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

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

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
  • Проголосовать: не нравится

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

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

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

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

»
11 лет назад, скрыть # |
 
Проголосовать: нравится +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...?

»
11 лет назад, скрыть # |
 
Проголосовать: нравится 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.

  • »
    »
    11 лет назад, скрыть # ^ |
    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 :)

  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится +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!

  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 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.

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

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

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

»
11 лет назад, скрыть # |
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.

»
11 лет назад, скрыть # |
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?

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

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

    • »
      »
      »
      11 лет назад, скрыть # ^ |
      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.

      • »
        »
        »
        »
        11 лет назад, скрыть # ^ |
         
        Проголосовать: нравится 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.

        • »
          »
          »
          »
          »
          11 лет назад, скрыть # ^ |
          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.

          • »
            »
            »
            »
            »
            »
            11 лет назад, скрыть # ^ |
             
            Проголосовать: нравится 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

            • »
              »
              »
              »
              »
              »
              »
              11 лет назад, скрыть # ^ |
               
              Проголосовать: нравится +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.

          • »
            »
            »
            »
            »
            »
            11 лет назад, скрыть # ^ |
             
            Проголосовать: нравится +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)

      • »
        »
        »
        »
        11 лет назад, скрыть # ^ |
        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.

  • »
    »
    11 лет назад, скрыть # ^ |
    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.

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

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

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

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

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

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

10958659

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

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

My SoutionSolution

  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 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!:)

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

Thanks for the fast tutorial :)

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

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

»
11 лет назад, скрыть # |
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 ?

»
11 лет назад, скрыть # |
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?

»
11 лет назад, скрыть # |
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://mirror.codeforces.com/contest/540/submission/10967359

  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 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://mirror.codeforces.com/contest/540/submission/10968998

    • »
      »
      »
      11 лет назад, скрыть # ^ |
       
      Проголосовать: нравится 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.

»
11 лет назад, скрыть # |
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://mirror.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.

»
11 лет назад, скрыть # |
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

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

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

»
11 лет назад, скрыть # |
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?

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

    I understood it after understanding the question and solution clearly.

  • »
    »
    11 лет назад, скрыть # ^ |
     
    Проголосовать: нравится 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.

»
11 лет назад, скрыть # |
 
Проголосовать: нравится 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://mirror.codeforces.com/predownloaded/5b/ff/5bff99f4731b22c9ea00f830072ddfe7040ed80d.png

»
9 лет назад, скрыть # |
 
Проголосовать: нравится 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?

»
6 лет назад, скрыть # |
 
Проголосовать: нравится 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 .