Блог пользователя komendart

Автор komendart, история, 8 лет назад, перевод, По-русски

617A - Слоник

Оптимально делать наибольший возможный шаг каждый раз. Поэтому слоник должен сделать сначала некоторое количество шагов на расстояние 5, а затем один или ноль шагов на меньшее расстояние. Следовательно, ответ равен .

Решение 15550796

617B - Шоколад

Нам дан массив, состоящий только из нулей и единиц. Мы должны разделить его на части, в каждой из которых ровно одна единица.

Особый случай: когда массив состоит только из нулей ответ равен нулю.

Рассмотрим общий случай. Во-первых нули на префиксе относятся к первому куску, нули на суффиксе относятся ко второму куску. Во-вторых, между каждой парой соседних единиц должно быть одно и только одно разделение частей. Между соседними единицами с индексами a < b всего b - a вариантов разделения. Поэтому мы должны перемножить эти значения для всех пар соседних единиц.

Бонус: каким является максимальный ответ при n ≤ 100?

Решение 15550806

617C - Поливка цветов

Первый радиус равен нулю или расстоянию от первого фонтана до какого-то цветка. Переберем все эти числа. Второй радиус будет равен максимальному из расстояний от второго фонтана до цветка, который не принадлежит кругу с первым радиусом. Теперь мы должны выбрать вариант с минимальным r12 + r22

Бонус: Я описал решение за O(n2). Можете ли вы решить задачу за O(nlogn)?

Решение за O(n2) 15550812

Решение за O(nlogn) 15550822

617D - Ломаная

Ответ равен одному, когда все координаты x или все координаты y совпадают.

Когда ответ равен двум? Переберем все пары точек. Пусть первая точка является началом ломаной, вторая концом ломаной. Только одна или две таких ломаных с двумя звеньями существуют. Они образуют прямоугольник с противоположными углами в первой и второй точке. Мы можем просто проверить принадлежность третьей точки прямоугольнику.

Иначе ответ всегда равен трем. Давайте построим вертикальные прямые через самую левую и через самую правую точки. Через третью точку построим горизонтальную прямую. Теперь, если мы удалим некоторые лишние лучи, получим подходящую ломаную.

Решение 15550843

617E - XOR и любимое число

У нас есть массив a

Давайте посчитаем массив (, ).

Xor подмассива равен .

Теперь запрос (l, r) заключается в подсчете количества пар i, j (l - 1 ≤ i < j ≤ r) .

Пусть мы знаем ответ на запрос (l, r) и знаем для всех v cnt[v] — количество вхождений v в .

Мы можем обновить за O(1) ответ и cnt если мы изменим правую или левую границу запроса на 1.

Поэтому мы можем решить задачу оффлайн за с помощью корневой эвристики (алгоритм Мо).

Решение 15550846

Разбор задач Codeforces Round 340 (Div. 2)
  • Проголосовать: нравится
  • +60
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится -19 Проголосовать: не нравится

Bonus in C — ternary search on first radius?

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +17 Проголосовать: не нравится

    Ternary Search won't work. I tried the same during contest and after it.

    What I had assumed was that the sum = r1^2 + r2^2 will first decrease as we increase r1 from zero and then increase after a certain "sweet spot". Turns out, that assumption was wrong.

    An example for that is say we have fountains at (0, 0) and (10, 0) and a flower at (0, 15). Now sum increases as r1 increases from zero, since r1 is increasing but r2 remains the same since it has to cover point (0, 15) till the time r1 can't cover it.

»
8 лет назад, # |
Rev. 5   Проголосовать: нравится +17 Проголосовать: не нравится

For problem D, did anyone else interpret

without self-intersections and self-touches

To mean that the kind of shape on the left would be invalid and that you would need at least three segments (like on the right) for the following example?

Because personally, a few of my fellow competitors and I found it very confusing which led to me being hacked and not knowing why.

Sorry for potato quality, let me know if you guys had the same issue.

Edit: These are the six valid line configurations that yield an answer of 2.

»
8 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

During last 3 minutes of the contest the server was very lag. Luckily I could submit again my solution for D at that time and got AC after the system testing. Anyway, this contest was very tricky and interesting :)

»
8 лет назад, # |
Rev. 2   Проголосовать: нравится +7 Проголосовать: не нравится

Bonus C: use set to store points, that are currently belong to second circle, sorted by distance to the centre of the second circle (from the farthest to the nearest). Sort all points by their distance to the centre of the first circle (from the nearest to the farthest). Now iterate over this points: you should erase current point from set and try to update your answer (it will be min(ans, dist(*st.begin(), r2) + dist(a[i], r1)).

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +13 Проголосовать: не нравится

    Yes, you're right.

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    I don't think I understand your explanation.

    Are you saying to map each point to the circle which is closest to it? Some form of greedy approach?

    • »
      »
      »
      8 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      Ehmm, not really. You should just keep two sets of points, which belongs to appropriate circle. This can be done by storing one set of points in std::set and another set of points in a sorted vector.

      Here's my code: http://pastebin.com/wT5t0etA

      P.S. Sorry for my poor english ;(

»
8 лет назад, # |
  Проголосовать: нравится +6 Проголосовать: не нравится

nlogn solution for C. http://codeforces.com/contest/617/submission/15538579

Store the distances of each flower from fountain1 in a vector. Sort this vector, let D1. It stores the prospective values of R1. Store the maximum values of Suffixes of distances of flowers from Fountain2. Now iterating over the distances in D1 vector, it is easy to see that if R1 is equal to D1[i], it means that Fountain1 can cover all of 0..i flowers. So now we need the value of R2 needed to water flowers i+1...n-1. R2 is the max distance of any of these flowers from F2. (obtained from the suffix maximum we stored earlier)

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Bonus B: 3*2^48

»
8 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

Would someone mind clarifying, in O(n2) solution to C, what the significance of the line dist.push_back({0, 0}) is? It is required for AC.

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

B can be also solved using DP with state f[i] representing cuts ending at position i. Solution 15522284

»
8 лет назад, # |
  Проголосовать: нравится +9 Проголосовать: не нравится

I solved C in nlogn ! my solution is like this , for every point store two distances , distances1 from fountain1 and distance2 from fountain2 . sort the points on basis of distance1 in decreasing order and now for every i do this solution=min(solution,distance1[i]+maxvalue_of_distance2_upto_i)

»
8 лет назад, # |
  Проголосовать: нравится +26 Проголосовать: не нравится

How to solve E in O(n*polylog)?

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    I know how to reduce my problem to counting cnt[v] * cnt[v] but don't know what to do next.

    Let .

    • »
      »
      »
      8 лет назад, # ^ |
      Rev. 4   Проголосовать: нравится 0 Проголосовать: не нравится

      We can consider following:

      So we have two arrays ai and . We need to count number of l ≤ i, j ≤ r such that , i.e. ai = cj. Any ideas what to do with it?

»
8 лет назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

Anybody did n^2 dp for problem B?

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

for problem D: in the following case,Why shouldn't the answer be 2 ?

A     B
    -----.-----.
   |
   |
   . C
»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Could someone explain Problem — E ? The editorial is not easy to understand.

  • »
    »
    8 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +18 Проголосовать: не нравится

    In the editorial, prefix[i] = prefix[i — 1] ^ A[i] (^ means xor) and cnt[v] = number of elements with prefix[i] = v, where i lies in the current mo's windows. So now, in mo's algorithm, you push the queries in sqrt(N) blocks according to left pointer, and then sort each block of queries according to right pointer. Now when you add an element to the window, suppose element A[x] is inserted in the window, where x is the indice added and y = prefix[x] ^ k, then ans += (cnt[y]). We do this because cnt[y] stores all the elements in the current window having prefix xor equal to y. And if we do xor of prefix[x] with any of these elements then the resultant xor will be k. While adding and removing you also need to constantly update cnt[] array.

    See the editorial code for a clearer view.

»
8 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

Русского разбора нету, придётся переводить(

UPD: Спасибо за русский разбор.

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Can someone explain problem D? I had a look at the solution and cannot understand what's the need of the function is_between()? 617D - Polyline

  • »
    »
    8 лет назад, # ^ |
    Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

    Given three points you have to find whether any three points satisfy the properties as given.Here's how to solve . Three conditions have to be considered:

    1. All points are collinear , answer is 1 (All points are in a straight line) .

    2. All points are not collinear , answer is 3 :) .

    3. Only two points lie in a same axis , This is the case we have to think about :

    i> If all points form a pythogorean triplet , answer is 2 .

    ii> If axes( Either X or Y coordinate ) of a two point are equal , we check whether the other third point come strictly bellow or above the other pair. In this case the answer is 2 . Else if it comes between the two points , the answer is 3 .

    • »
      »
      »
      8 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      In the 3rd point : - There is no need to check for the pythogorean triplet. Only checking if the third point lies strictly below or above the other pair or if it lies in between the points is enough. I got it accepted without checking for a pythogorean triplet

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Автокомментарий: текст был переведен пользователем komendart (оригинальная версия, переведенная версия, сравнить).

»
8 лет назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

for problem C we can also make a binary search on the answer here is my code : 15552813

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

почему xor на [l...r] равен pref[l-1] xor pref[r]?

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Если , то .

    Подставим a = pref[r], b = pref[l - 1], c = xor[l...r]

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится +10 Проголосовать: не нравится

    В отличие от AND или OR эта операция обратима. Поэтому . Отсюда следует, что .

»
8 лет назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

why do we have to use the pref[i] = pref[i-1]^a[i]; instead of just testing with the normal number?

  • »
    »
    8 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Because we are interested in number of subarrays such that A[i]^A[i+1]..A[j-1]^A[j] is equal to k. A[i]^A[i+1]..A[j-1]^A[j] = pre[j]^pre[i-1]

»
8 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Could someone explain the following case for the problem 617D — Polyline: (1, 1) (2, 2) (3, 3).

Aren't we need 4 segments to construct the polyline?

»
7 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

Can anyone make me understand this line written in problem E?

Let we know answer for query (l, r) and know for all v cnt[v] — count of v in a[l - 1...r]. We can update in O(1) answer and cnt if we move left or right border of query on 1. So we can solve problem offline in with sqrt-decomposion (Mo's algorithm).

»
6 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

in problem E(xor and favourite number),what does cnt[v] of the following line mean: "Let we know answer for query (l, r) and know for all v cnt[v] — count of v in a[l - 1...r]. "