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

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

678A - Вася любит числа

Задачу предложил Әбдірахман Исмаил bash.

Нам нужно найти минимальное x, что x * k > n. Легко видеть, что . Для подробного знакомства с математическими функциями пола и потолка я рекомендую книгу авторов Грэхем, Кнут, Паташник "Конкретная математика". В этой книге есть отдельная глава, посвящённая этим функциям и их свойствам.

Решение на С++

Сложность: O(1).

678B - Такой же календарь

Задачу предложил Артур Яворски KingArthur.

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

Решение на C++

Сложность: O(1) — легко видеть, что количество итерация не превосходит небольшой константы.

678C - Мила и шоколад

Задачу предложил Sheikh Monir skmonir.

Легко видеть, что в оба цвета мы можем покрасить доски с номерами кратными lcm(a, b) — НОК чисел a и b. Очевидно, что эти доски выгоднее красить в более дорогой цвет. Таким образом, ответ равен: .

Решение на C++

Сложность: O(log(max(a, b))).

678D - Итерированная линейная функция

Задачу предложил Zi Song Yeoh zscoder.

В этой задаче можно было вывести формулу в качестве ответа: для этого нужно было посчитать сумму геометрической прогрессии. Далее формулу было легко посчитать с помощью бинарного возведения в степень.

Я опишу более сложное, но более общее решение. Если у нас есть некоторый набор переменных, который пошагово пересчитывается друг через друга с помощью линейной функции, то можно применить бинарное возведение в степень матрицы. Итак, в нашей задаче переменная была одна x. Новая переменная x' получалась по формуле A·x + B. Рассмотрим матрицу z = [[A, B], [0, 1]] и вектор v = [x, 1]. Умножим z на v слева. Легко видеть, что получится вектор v' = [x', 1]. Таким образом, чтобы сделать n итераций, мы просто должны n раз умножить слева матрицу z на вектор v. В силу свойства ассоциативности операции умножения матриц перемножение мы можем сделать бинарно.

В качестве упражнения можете попробовать выписать самостоятельно матрицу для чисел Фиббоначи и научиться их быстро считать. Под спойлером матрица и вектор.

Матрица и вектор для чисел Фиббоначи
Решение на C++

Сложность: O(logn).

678E - Очередной турнир ситхов

Задачу предложил и подготовил Алексей Дергунов dalex.

Давайте решать задачу динамикой. zmask, i — наибольшая вероятность выиграть Ивану, если джедаи из маски mask уже хоть раз сражались, а в живых остался только i-й джедай. Для подсчёта динамики переберём следующего джедая (ему придётся сражаться против i-го джедая): .

Решение на C++

Сложность по времени: O(2nn2).

Сложность по памяти: O(2nn).

678F - Лена и запросы

Задачу предложил AmirMohammad Dehghan PrinceOfPersia.

Посмотрим на задачу геометрически: пары чисел в множестве это просто прямые, задача по вертикальной прямой найти самое верхнее её пересечение с какой-либо прямой.

Разобьём все запросы на блоков. Рассмотрим те прямые, которые были добавлены до начала блока и не будут удалены в нём. Построим по этому множеству нижнее огибающее множество. Теперь, чтобы ответить на один запрос третьего типа нужно взять максимум по прямым нижнего огибающего множества и по запросам в блоке до текущего запроса. Последних не более , поэтому по ним мы можем пройти в лоб и обновить ответ. Теперь посмотрим на все запросы в блоке третьего типа, отсортируем их слева направо и будет искать оптимальную прямую в огибающем множестве с помощью двух указателей.

Решение на C++

Сложность: .

Разбор задач Educational Codeforces Round 13
  • Проголосовать: нравится
  • +32
  • Проголосовать: не нравится

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

Please write the editorial for E

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

В C же O(logC).

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

About problem E:

After some interesting discussion, I was wondering what exactly can we say about the optimal solution?

Let's assume that optimal sequence can be represented by a sequence a1, a2, ..., an of fighters in which a1 fights a2, then the winner fights a3, etc. Intuitively, the probability someone wins is higher the more to the right of the sequence it is: this implies an should be Ivan in an optimal sequence.

Now who do we want at the second to last position? That person will be given a greater chance to fight Ivan, so we want it to be the one that has the smallest chance to win against him.

Generalizing to all n players, we have the following O(n2) greedy solution: construct the sequence of fighters from the last to the first. For each pick, pick the available fighter that makes probability of Ivan winning in current sequence highest possible.

Code: 18489412

Of course, there's no such thing as "proof by AC", so I'm still curious if this solution is actually correct. If it is, I think it is quite interesting :)

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

    Some history: the setting was taken from Timus 1218. In 1218, we discovered a NlogN solution and included that problem into our contest at Petrozavodsk camp, where 7 teams out of 50 solved it.

    As my teammates just said, it became a tradition: all "Jedi Tournament" problems can be solved better than author initially thought. You could have done the same with your solution.

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

    Actually I've discussed with dalex that. And I thought about the same thing. But both of us agreed that greedy solution is incorrect here.

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

      If you discussed this before the contest, shouldn't you have included a test that fails the greedy solution?

      I'm also curious to know how you reached this conclusion.

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

        I thought about different greedy solution. This one passes random tests and must be correct.

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

        Oh you misunderstood. We have not a countertest, we just thought that greedy solution is incorrect.

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

Почему в E что-то вообще умножается на pji? Это же подразумевает, что побеждает джедай j, а пересчитываем мы для побеждающего i.

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

    В данной формулировке интересно не то, как состояние достигнуто, а то, какая наибольшая вероятность может быть получена из этого состояния. То есть в правой части выражения перебираются следующие бои и учитываются оба исхода каждого боя.

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

Another solution for problem F in O(N*log2N).

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

    Could u please go for more detail about it?? I have difficulty in reading and understanding ur code :P

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

    Do you use the technique with storing the blocks of the sizes 2k?

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

      Problem to find the topmost intersection of the vertical line with the lines from the set can be solved with Convex Hull Trick.

      I builded a segment tree of CHT over time interval.
      For ith insertion query update the segment tree with this line in range [ i, time till ith line exists ].
      For every query of 3rd type it is equivalent to point query at that point of time.

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

        Nice. But I think it's more complicated.

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

          During contest I tried with the same approach as mentioned in editorial (Submission). But it timed out because my complexity was O(N1.5 * logN). So I had to go this way but it seems that logN factor can be removed.

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

    I solved the problem using your idea but with complexity O(N*logN). Submission here: 18842789

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

      Insertion in logN nodes is log2N, right ?

      P.S: Your N*logN is slower than mine N*log2N.

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

        Actually if you insert the lines in sorted order the overall complexity for insertion is because you insert in nodes in total linear time. This was mnaeraxr and I did (using your idea, btw) 18845711. You probably didn't look deeper into mnaeraxr code.

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

Can anyone explain a little more about the recurrence relation in E?

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

Почему код решений такой плохой?

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

    А что именно плохо? Если вопрос в дефайнах или в сокращениях типа ld вместо long double, то в олимпиадном сообществе очень многие используют их.

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

Can someone explain the editorials for Problem E in a somewhat detail manner, it would be a great help.

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

    My approach. First observe that our jedi should fight last. Then we exclude him from the set of siths. Let mask be some subset of set of siths (without jedi) and i is a sith of this subset. Then dp[mask, i] is maximum (among all sequences of siths) conditional probability that Ivan wins tournament given that siths from mask already fought and i-th is a winner.

    We init our dp with full mask:

    for (int i = 1; i < n; i++)
        dp[all, i] = p[0, i];
    

    where all is full mask. That means, if all siths already fought and i-th is a winner then probability that Ivan wins tournament is equal to probability of win this sith. Then we loop over smaller and smaller mask's and calculating their values from previous calculations. To find dp[mask, i] use formula from editorial. Should be more clear now. If not I can explain in more detail.

    And the end answer will be maximum of dp[mask_i, i]. It is conditional probability that Ivan wins tournament given that i-th sith is the first participant in tournament.

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

      Could you explain more about the formula. I want to ask some specific questions:

      • z(mask,i) is when the i-th wins so why do they + z(mask U j,j)*p[j][i] as well.

      • z(mask,i) is the "maximal probability of Ivans victory if the siths from the mask already fought and the i-th sith left alive". So is Ivans necessarily be i or some bit 1 in mask or some other siths?

      This contest has been so long but if you could answer these, I would be really thankful. I have comtemplating about this problems for a week but still didn't figure it out. Thanks <3

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

Please ,explain me the solution of Another Sith tournament.Please explain me in words how that formula comes??

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

In above code for problem F, I want to know why blen is 2500, not sqrt(n). Please tell me.. my submission also TLE when i set blen sqrt(n), but accept when i set blen 2500. sorry for my fool english

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

    we need sorting all query in each block. so complexity is O(N * N / size + N * log2(size) + size * size). for best we choose size = 2500.

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

Can someone explain how is the complexity of solution of Problem E , in the editorial O(N^2 * 2^N) ? I think it is O(N^3 * 2^N) as for every O(n^2) starting pairs we have an O(n) loop to set the next winner.

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

Problem F 线段树分治+斜率优化可以做到O(NlogN)吧

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

Could you explain more about the formula in problem E. I want to ask some specific questions:

  • z(mask,i) is when the i-th wins so why do they + z(mask U j,j)*p[j][i] as well.

  • z(mask,i) is the "maximal probability of Ivans victory if the siths from the mask already fought and the i-th sith left alive". So is Ivans necessarily be i or some bit 1 in mask or some other siths?

This contest has been so long but if you could answer these, I would be really thankful. I have comtemplating about this problems for a week but still didn't figure it out. Thanks <3

  • »
    »
    5 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится
    • $$$z(mask, i)$$$ is not the probability that the $$$i$$$-th sith wins. Remember that we are calculating the probability of the $$$0$$$-th sith being the ultimate winner. It simply says that all siths in the mask have fought some match and the only sith alive out of those currently is the $$$i$$$-th sith.

    • Ivan corresponds to the $$$0$$$th bit. There are $$$2$$$ cases:

      $$$1$$$. $$$0$$$-th bit is $$$0$$$, which means Ivan hasn't fought yet.

      $$$2$$$. $$$0$$$-th bit is $$$1$$$. In this case, if $$$i \ne 0$$$, this means that Ivans fought but was killed. So, the answer for this state is $$$0$$$. Otherwise, Ivan is the survivor from all matches conducted so far and we proceed with the tournament.

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

678D - Iterated Linear Function How do we come from knowing that we have to find a matrix to the actual matrix? And what about the vector v, where that comes from?

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

    Here is a simple mathematical approach:

    After simplifying:

    gn(x) = (a^n)*x + b*( 1 + a + a^2 + a^3 ....... a^(n-1) )

    [ 1 + a + a^2 + a^3 ....... a^(n-1) ] forms a Geometric Progression, whose sum can be calculated as:

    S = b* (a^n-1)/(a-1)

    for the solution, see my submission 78952460

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

My solution to Sith Tournament (problem E) works without an extra index in DP. It is slightly different from the editorial.

Mask of (n — 1) bits represents which siths are still alive (as ivan will always stay alive, no need for keeping an extra bit for him). dp[mask] represents probability Ivan wins given that the siths in mask are alive. dp[0] is trivially 1 (as mask=0 means all other siths have died). We compute dp in increasing value of mask.

For computing value of dp[mask], we simulate the situation where Ivan has to choose two siths for a fight, and where one of them dies. We just run a loop through all pairs of distinct set bits (b1 and b2), and update our dp as follows:

probA = beats[b1][b2] * dp[mask ^ (1 << b2)]; // b1 beats b2
probB = beats[b2][b1] * dp[mask ^ (1 << b1)]; // b2 beats b1
totalProb = probA + probB;
dp[mask] = max(dp[mask], totalProb);

Before exiting, we also pair each sith with Ivan himself, updating our dp[mask] as follows:

dp[mask] = max(dp[mask], beats[1][bit] * dp[mask ^ (1 << bit)]

In the end, we print dp[(1 << (n - 1)) - 1].

AC Submission