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

Автор dalex, 9 лет назад, По-русски

540A - Кодовый замок

Для каждого символа посчитаем, в какую сторону выгоднее вращать диск. Это можно сделать либо формулой: min(abs(a[i] - b[i]), 10 - abs(a[i] - b[i])), либо даже двумя циклами for: в прямом или обратном направлении.

540B - Школьные оценки

Посчитаем количество оценок, меньших y. Если таких больше штук, то мы не сможем удовлетворить второму условию (про медиану), и ответ -1. Иначе получим ровно столько оценок y, чтобы количество оценок, больших или равных y, было как минимум штук (возможно, это уже выполняется). Это минимальное необходимое действие для удовлетворения второго условия.

Теперь, чтобы не нарушить первое условие, сделаем оставшиеся неизвестные оценки как можно меньше — единицами, и проверим сумму. Если она больше x, то ответ снова -1, иначе требуемые оценки найдены.

540C - Ледяная пещера

Я выделил здесь три случая, хотя некоторые из них можно объединить.

  1. Если начальная и конечная клетка совпадают, посмотрим на количество целых соседей этой клетки. Если есть хотя бы один целый сосед, то пойдем туда и сразу же вернемся обратно, выполнив задачу — в этом случае ответ YES.
  2. Если начальная и конечная клетка являются соседями, то посмотрим на тип конечной клетки. Если конечная клетка треснувшая, то ответ YES. Иначе для положительного ответа необходимо, чтобы у нее был хотя бы один целый сосед — пойдем на конечную клетку, затем на этого целого соседа, а потом вернемся обратно.
  3. В наиболее общем случае проверим, существует ли путь по целым клеткам от начальной клетки до конечной. Если нет, то ответ NO. Иначе посмотрим на тип конечной клетки. Если она целая, то для существования ответа необходимо наличие у нее двух целых соседей — по одному мы придем в нее, а второй используем как промежуточную точку, а если конечная клетка треснувшая, то у нее должен существовать один целый сосед.

540D - Остров невезения (мой код: http://pastebin.com/3s6dRK3A)

Будем считать величину dp[r][s][p] — вероятность возникновения ситуации, когда в живых осталось r камней, s ножниц и p бумаг — для всех возможных значений r, s, p. Начальная вероятность равна 1, а для подсчета остальных необходимо сделать переходы.

Пусть у нас имеется r камней, s ножниц и p бумаг. Найдем для примера вероятность того, что в этой ситуации камень убьет ножницы — остальные две вероятности считаются симметрично. Количество случаев, в которых кто-нибудь умрет, равно rs + rp + sp, а количество случаев, в которых умрут ножницы, равно rs. Так как все случаи равновероятны, нужная нам вероятность равна . Именно с этой вероятностью мы перейдем в состояние dp[r][s — 1][p], где ножниц станет на 1 меньше.

В конце, чтобы получить вероятность, что, например, камень выживет, надо просуммировать все величины dp[i][0][0] для i от 1 до r (аналогично для остальных видов).

540E - Бесконечные инверсии (мой код: http://pastebin.com/QFEMRbNP)

Запомним, на какой позиции какое число будет стоять после выполнения всех swap-ов. Теперь будем считать ответ. Ответ состоит из двух частей. Первая часть — это инверсии, образованные исключительно теми элементами, которые поучаствовали в swap-ах. Их можно посчитать одним из двух стандартных способов: mergesort-ом или с помощью сжатия координат и дерева Фенвика. Вторая часть — это инверсии, в которых один из элементов пары участвовал в swap-ах, а второй — нет. Для простоты рассмотрим тест:

2
2 6
4 8

Перестановка будет выглядеть так: [1 6 3 8 5 2 7 4 9 ...], а массив swap-нутых элементов так: [6 8 2 4].

Давайте поймем, с какими элементами будет образовывать инверсии число 8. Очевидно, такими элементами могут быть лишь те элементы, которые находятся между начальной позицией числа 8 (где сейчас число 4), и текущей его позицией. Вот этот подотрезок: [5 2 7]. Чисел на этом подотрезке, которые не участвовали в swap-ах, две штуки: 5 и 7. Число 2 учитывать не надо — ведь оно участвовало в swap-ах, и мы его посчитали на первом шаге решения.

Таким образом, надо взять количество чисел между начальной и конечной позицией числа 8 в глобальной перестановке (т.е. 8 - 4 - 1 = 3), и вычесть из него количество чисел между позициями числа 8 в массиве swap-ов (т.е. 4 - 2 - 1 = 1). Чтобы избавиться от дополнительного вычитания единицы, можно просто из правого индекса вычитать левый. Так мы получим количество инверсий, образованные элементом 8 и элементами глобальной перестановки, не участвовавших в swap-ах. Для завершения второго шага надо лишь посчитать эту величину для всех чисел, участвовавших в swap-ах. Все операции второго шага можно выполнить при помощи сортировок и бинарного поиска.

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

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

Задача С очень понравилась! Спасибо автору!

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

Пора учить теорию вероятностей заново :( Не смог догадаться до этой очевидной формулы.

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

    Обидней когда придумал, и не закодил.

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

      Не спорю. Но придумать — уже половина дела.

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

      Это ещё что по сравнению с тем что придумал, закодил, не успел отладить, контест закончился, на дорешивании исправил пару символов и сдал.

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

      Обидно, когда придумал, закодил, но не догадался, что в ответ пойдёт сумма :(

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

Well, I think, it would be great if the meanings of 'global sequence' and 'swaps array' is made clear in E's explanation (in paragraph 4 if the test case isn't counted). Do they mean 'the permutation' and 'the swapped elements' in the second paragraph...?

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

Thanks for the editorial! If I may ask quickly about question B, I'm still a bit confused as to how the (n-1)/2 check works for the median. For example if given original grades 3, 5, 6 and minimum median of 6, with value k=50 and x=999, wouldn't it be easy to add 50 values to {3, 5, 6} such that the median exceeds 6 and sum<999? Yet with the editorial it says if at least (n-1)/2 marks are less than the median ie: (3-1)/2 = 1, marks are <= median (which there are since 3, 5, and 6 are <=6}, how does it mean we can return -1?

Thanks, sorry if this is a dumb question, I'm just really confused.

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

    Seems like you mistook n and k.

    In the example where Vova needs 49 (the problem says it's an odd number) tests and finished 3, n = 49, and k = 3. Therefore, (n — 1) / 2 is 24 instead of 1. Then, of course, the answer is -1 if there are 24 marks that are less than y, instead of 1 :)

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

    Oh... I see now, the variable "n" was referring to ALL the course marks and not just the ones that were currently given... I didn't read the question very well; but hoping to do better next time, thanks for the problems!

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

    The number 3 in your formula (3-1)/2 is k, but it must be n, I think that's where you are wrong.

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

Посчитаем количество оценок, меньших или равных y. Если таких больше штук, то мы не сможем удовлетворить второму условию (про медиану), и ответ -1.

Вроде строго меньших. Медиана должна быть больше либо равна y.

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

Edit: No need to read this. I have caught my mistake. A reading error :) One more Question for Problem B. If suppose the input is n=5 and k=3 and the minimum median is 4 and the given input is 444. So this fails the (n-1)/2 condition, but still 44444 for example is a solution (assuming sum is large enough). Sorry if it is dumb question(hopefully it is not) :) Did not read the solution carefully. My mistake. No need to reply to this.

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

    This mistake was fixed about 30 minutes ago, maybe you haven't updated the page since that time? Now that statement says about elements less than y.

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

      Yes, I just refreshed and saw that. Then I updated my post, thinking I read wrong. But thanks, I did not read wrong and now it has been corrected. :)

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

In problem D, if all the meetings are equiprobable the probability that we have minus one scissor would not be instead of . Why we don't count the meetings between the same kind?

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

    It's a conditional probability: the probability of the fact that rock kills scissors, given that somebody dies.

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

      But the question D says any two random individuals meet so why isn't 2 people from whole set included as said above by Empty.I mean why is that wrong if we consider the whole people left as our sample space for choosing two people.

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

        If two of the same types are chosen, we are back with the same state as before: nothing changes. We just go again, and we keep going until different types are chosen. Until that happens, nothing changes so the same state is preserved.

        As dalex said, we only calculate probabilities of the different events given that something changes.

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

          But, it will not affect the result of the probabilities?, it would be interesting to see a math proof to show how it works.

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

            What's confusing is that we are conditioning this on the fact that a single type wins, and also we are not at all interested in the number of trials this takes. Meaning, we aren't checking the probability of the case that all three types remain (ie: they keep meeting each other).

            So now, given that after some number of trials, a single type remains, we can effectively ignore all the trials where the same type meets.

            Again, we could not do this if we were calculating things like:

            1) number of trials until a specific type wins 2) probability that a single type will win given the possibility of an eternal tie

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

              I get the same meaning like Empty said.I can't get the correctly example answer in my way.I think in most cases, you should read the problem without ambiguity or less.

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

            math proof can be following:

            first, lets say that

            Crsp — all possible permutations of r s and p pairs.

            Crr, Css, Cpp — all possible permutations between (r and r), (s and s), (p and p) pairs respectively.

            Crs, Csp, Crp — all possible permutations between (r and s), (s and p), (r and p)

            (note that Crs = r *s, Csp = s * p, Crp = r * p)

            it's evident that

            Crsp = Crr + Css + Cpp + Crs + Csp + Crp

            now lets say that

            Prsp — is a probability for [r, s, p]

            Pr1sp — is a probability [r — 1, s, p]

            Prs1p — is a probability [r, s — 1, p]

            Prsp1 — is a probability [r, s, p — 1]

            note that meetings between r and r, s and s, p and p doesn't remove anything, so:

            Prsp = (Prsp * (Crr + Css + Cpp) + Pr1sp * Crp + Prs1p * Crs + Prsp1 * Csp) / Crsp

            multiply the equation by Crsp and move Prsp * (Crr + Css + Cpp) to the left part:

            Prsp * (Crsp — Crr — Css — Cpp) = Pr1sp * Crp + Prs1p * Crs + Prsp1 * Csp

            but Crsp = Crr + Css + Cpp + Crs + Csp + Crp, so:

            Prsp * (Crs + Csp + Crp) = Pr1sp * Crp + Prs1p * Crs + Prsp1 * Csp

            or:

            Prsp = (Pr1sp * Crp + Prs1p * Crs + Prsp1 * Csp) / (Crs + Csp + Crp)

            finally we know that Crs = r *s, Csp = s * p, Crp = r * p, so:

            Prsp = (Pr1sp * (r * p) + Prs1p * (r * s) + Prsp1 * (s * p)) / (r * s + s * p + r * p)

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

              Nice. We obtain a recursive relation for Prsp. I mean Prsp = A * Prsp + something, a seemingly infinite recursion.

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

        I didn't use the conditional probability at all. See my code:10949419. I'm considering all possible pairs of meeting (the sample space is n*(n-1) / 2). However, I still got the same result. When 2 people of the same species meet, no one will die. This will lead to an infinite geometrics series when you calculate the probability that someone dies.

        [Edit] So, both methods are fine. If you do it without the conditional probability, but get a different result, you're calculating the probability wrong.

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

          p[i — 1][j][k] += ppp / (1 — ppp2); can you please explain what i am doing by this ppp / (1 — ppp2); ?

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

            Let's say we're interested in P[a rock dies].

            Case 1: a rock dies in the first meeting. P(1) = i * k / space(i + j + k)

            Case 2: no one dies in the first meeting, then a rock dies in the second meeting. P(2) = P[no one dies] * P(1).

            Case 3: no one dies in the first 2 meetings, then a rock dies in the third meeting. P(3) = P[no one dies]^2 * P(1).

            ...

            P[no one dies] = (space(i) + space(j) + space(k)) / space(i + j + k) = ppp2.

            So, P[a rock dies] = P(1) + P(2) + ... = P(1) + ppp2 * P(1) + ppp2^2 * P(1) + ppp2^3 * P(1) + ... = P(1) / (1 — ppp2).

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

        the question is intended to make people make WA by making statement of question vague. Dont go hard on this question. Its best to down vote the editorial and announcement

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

    Hey, why can't we use this recurrence relation instead: Considering dp[i][j][k] to be a struct with member functions r,s,p

    dp[i][j][k].r= 1/3.0 *( dp[i][j][k-1].r + dp[i][j-1][k].r + dp[i-1][j][k].r);

    Why is this logically incorrect?

    EDIT: Got it. All are taken different. I was taking all the rocks as same.

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

Для чего в задаче B нужен параметр p во входных данных?) Чтобы запутать нас? :)

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

    Да, Такое достаточно часто бывает, но если бы не было условия y <= p, то можно было бы скосить некоторую часть решений, т.к. нужно было бы брать оценку min(y, p), а не просто y. Лично я, не дочитав условие, написал min(y, p). Но из здравого смысла, действительно, медиана не может быть больше максимальной оценки, иначе — безысходность :С

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

Why my solution for D print wrong answer? I don't see anything different compared to the author's code.

10958659

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

can someone help me to correct my algorithms for Problem-B(School Marks)

My SoutionSolution

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

    I just want to give you an advice (because I'm not familiar with Java). Your code is a bit complicated, to make it simpler, put the answer(s) to the problem into an array (or a vector). It is much easier to read, and of course, to write the code.

    Here is my C++ solution (with comments) for reference: pastebin

    Good luck!:)

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

Thanks for the fast tutorial :)

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

can anyone please explain how to calculate the probability in problem D?

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

In problems C this case 7 1 X . . . X . . 5 1 3 1 Will fall at the beginning, and will not come up So the answer should be NO, but why the answer is YES Can you explain it ?

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

Umm i may have grossly misunderstood problem C here. Probably the word 'side adjacent' or 'fall down'. Help me out here. I used the BFS in a grid technique to get my answer. However, my code gives me 'YES' for example testcase 2. According to my logic, that should right. Here is the case:

5 4 .X.. ...X X.X. .... .XX. 5 3 1 1

We can go to 1,1 from 5,3 as follows:

(5,3)->(4,3)->(4,2)->(3,2)->(2,2)->(2,1)->(1,1)

Here is my code: http://ideone.com/JS4OAU

What's the flaw?

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

    When you reach (1, 1) for the 1st time, the ice from 'intact' become 'cracked', so you can't fall down yet. You must step on (1, 1) another time to fall down, but there's no room to do this, so the answer is 'NO'.

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

ALright so i've applied the concept of a BFS in a grid but my code keeps failing at Test case 21:

2 2 .. .X 2 2 1 1

Any ideas as to why it fails?

submission: http://codeforces.com/contest/540/submission/10967359

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

    Ok, I've had a lot of submissions and i'm thinking this cannot be done by BF Ssince there is not way of determinig whether the adjacent edges have been stepped on or not. They may have been discovered but no way to determine that they have been stepped on i believe. Not unless i find the actual shortest path using BFS and backtrack. I'm completely lost. Could someone help me? Is this solvable with BFS?. Here's a C++ code:

    http://codeforces.com/contest/540/submission/10968998

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

      The insight is that you just need to find if the destination is reachable or not. It doesn't matter which path you take. Then at the destination, if you need an extra step on that, you just look around the 4 neighbors to see if at least two of them are dots. So you can move to one dot and move back again (assuming that you might step on another dot, while getting to the destination). There is also an edge case where you start from one of the 4 neighbors. In this case, you only need one dot.

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

        And at least a neighbor dot have visited to ensure it reachable from start point

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

          No need. We already check if the destination is reachable or not. If it's reachable, it already guarantees at least a neighbor dot has been visited or the starting point is a neighbor.

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

            Can you please tell me what will be the answer for this case? 3 1 X . X 1 1 2 1

            I think answer will be YES. Path: (1,1)->(2,1)->(1,1)->(2,1)

            Accepted codes give NO.

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

              you cannot go back to (1,1) because it's already cracked and you'll fall down.

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

A task I really liked thanks to its author, it moymu was easier than C. When I read the task E I said that it's light and wrote the code as it passed a retest on the system it is testing 22 test gave TL here is my code http://codeforces.com/contest/540/submission/10950774 — I solved this problem by Algorithm Fenwick. Many thanks to Maxim Akhmedov and Alexei Dergunov preparation for such an interesting round.

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

Can anyone tell me why am I getting WA on test 55 problem C? flag=0 if destination cell is intact, else it is 1. Solution

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

Can anyone please explain problem E in detail? I m not able to understand anything

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

    Which part are you unable to understand. Do you understand the question clearly?

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

      I tried to understand his code. CODE

      Can you please tell me what he is doing in the last for loop of the main function and what is the function bs doing.

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

        let me explain you the general approach. suppose you have the input as: 2 1 1000000000(10^9) 100 200000000(2*10^8)

        you obviously cannot create an array of size 10^9. so you create an array with only the elements which were swaped. So the array : arr[] = {1 , 100 ,200000000,1000000000 } we then compress this array as arr[] = {1,2,3,4} (100 is replaced with 2,200000000 with 3,1000000000 with 4) now apply the swaps then we get arr[] = {4,3,2,1} now we need to do 2 things 1) Count the inversions in the compressed array 2) Count the inversions in the original sequence which contains all the elements. Add the results of 1 & 2 you get the answer. How to solve 1 ? We can use merge sort : http://www.geeksforgeeks.org/counting-inversions/ or using a fenwick tree : http://pavelsimo.blogspot.in/2012/09/counting-inversions-in-array-using-BIT.html. ans = 0 number of elements less that 4 and to its right = 3. ans = 3 number of elements less that 3 and to its right = 2. ans = 5 number of elements less that 2 and to its right = 1. ans = 6. so the answer for the first part is 6.

        Now, How to solve the 2nd part ? (this is the last loop in the editorial solution) Getting back to our original sequence after swaping. seq = 1000000000,2,3,4,...98,99,200000000,101,102.........999999998,999999999,100,1 now how many inversions for 10^9 ? it's original position — current position so 999999999 but we have already counted the inversion made by 200000000,100,1 in the first part where they were compressed, so subtract 3.

        now inversions for 2*10^8 is also calculated in the same way.

        Now add the results of the 2 parts. Please go thorough the editorial code. the above is an explanation of that code. It is easy to understand.

        also have a look at http://codeforces.com/blog/entry/17643#comment-225956 that is what the last loop is for

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

        Here's my code that uses fenwick trees (Binary Indexed Trees) and lower_bound to solve this question.

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

Can some one explain why we need to do the second part in question E. Why cant we simply count the no. Of inversions using merge sort or a fenwick tree?

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

    I understood it after understanding the question and solution clearly.

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

    Because you will miss cases where first number is a moved one and the other one did not move.

    look at first input:

    after swaps it looks like:

    2,4,3,1,5....

    if you just consider pairs in which both elements have moved from original you will get:

    2,4,1

    this will give you 2 pairs (2,1) and (4,1) but what about (4,3) ? you will only get this, by the second method that has been explained.

    You cannot construct the complete tree and expect to iterate through it in timelimit that is set.

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

is it just me or anyone else?

I wanted to practice on this round but find the image in Problem C is a dead image... http://codeforces.com/predownloaded/5b/ff/5bff99f4731b22c9ea00f830072ddfe7040ed80d.png

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

I am trying to understand the following solution 10945934 for 2 days already.
I don't get the key part of the solution:

for (int i = 0; i < m; i++)
{
    int x = a[i];
    int pos = mapchik[x];
    ans += abs(b[i] - x) - abs(pos - i);
}

Could, someone please explain in as much detail as possible, how does this part of the code work?

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

In problem D , i cannot understand the meeting probability . According to tutorial it's r*s / (r*s + s*p + p*r) for rock species meets/kills scissors species when they meet . Now i'm giving my view , i want to know whether it's correct or not .

Suppose at any situation we have r rocks, s scissors and p papers .

Now , let's find the probability to choose 1 rock species and 1 scissors species . say it's P(x)=(r/(r+s+p))*(s/(r+s+p-1)) . That means P(x)=(r*s)/((r+s+p)*(r+s+p-1)) .

again for 1 scissors species and 1 paper species . say it's P(y)=(s*p)/((r+s+p)*(r+s+p-1)) .

again for 1 paper species and 1 rock species. say it's P(z)=(p*r)/((r+s+p)*(r+s+p-1)) .

Now the probability of rock kills scissors = P(x) / (P(x)+P(y)+P(z)) .

it's equal to (r*s) / (r*s + s*p + p*r) . exactly the same as tutorial . Plz let me know whether i'm correct or not .