Wansur's blog

By Wansur, history, 2 months ago, translation, In English

2013A — Zhan's Blender

First to solve: rob00

Solution
Code

2013B — Battle For Survive

First to solve: neal

Solution
Code

2013C — Password Cracking

First to solve: Pagode_Paiva

Solution
Code

2013D — Minimize the Difference

First to solve: edogawa_something

Solution
Code

2013E — Prefix GCD

First to solve: meme

Solution
Code

2013F1 — Game in Tree (Easy Version)

First to solve: EnofTaiPeople

Solution
Code with segment tree
Code in O(n)

2013F2 — Game in Tree (Hard Version)

First to solve: rainboy

Solution
Code
  • Vote: I like it
  • +101
  • Vote: I do not like it

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Problem E originally meant a solution without a gready, but what are rich in :)

And in F you need to separately figure out when the first / second player wins if he starts at his top, because otherwise it hurts a lot)

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I have another solution of $$$E$$$ and I wonder if it is intended.

    Enumerate $$$a_1$$$. Note all the divisors of $$$a_1$$$ as $$$d_1,d_2,\ldots,d_m$$$. We can check if there is $$$a_j$$$ such that $$$\gcd(a_1,a_j)=d_k$$$ for every divisors.

    Note $$$dp_{i,j}$$$ as the max sum when $$$\gcd(a_1,\ldots,a_i)=j$$$. We only accept transform $$$dp_{i,j} \rightarrow dp_{i+1,k}(k<j)$$$ so $$$i$$$ is small ($$$log(maxa)$$$).

    So the complexity is $$$log(maxa) \cdot m^2$$$ for an $$$a_1$$$.

    The maximum number of divisors may be $$$240$$$, but if we tag the calculated numbers and skip them, the average $$$m$$$ is around $$$10$$$.

    The final complexity is $$$O(n \cdot \log(maxa) \cdot \overline{m^2})$$$.

    • »
      »
      »
      2 months ago, # ^ |
      Rev. 2   Vote: I like it +3 Vote: I do not like it

      how do you check if there is a number that will turn N into one of its divisor D ?

      i thought of inclusion exclusion on the prime factors to determine if there exists such a number X that doesnt include any of the prime factors to turn N into D but it seems like u didnt use inclusion exclusion so how did u do it ?

      edit : seems like u only did it for one number

      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Let's assume $$$d_1<d_2< \cdots <d_m$$$.

        Note $$$cnt1_x$$$ as the total of multiple of $$$x$$$, and $$$cnt2_x$$$ as the total of $$$a_i$$$ such that $$$\gcd(a_1,a_i)=x$$$.

        For $$$i=m$$$ to $$$1$$$, do $$$cnt_2[d_i]+=cnt1[d_i]$$$, and $$$cnt_2[d_j]-=cnt_2[d_i]$$$ $$$(d_i=k\cdot d_j)$$$. The complexity is $$$O(m^2)$$$.

»
2 months ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

:< could someone explain why cout<<ceil(double(n) / min(x,y)); in A led to WA

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +21 Vote: I do not like it

    There are two reasons this may cause issue

    first (which is mostly the issue here), the output will be in scientific notation

    cout << ceil(1e9 / 2); // 5e+08
    

    this can be solved by casting the output to long/int

    cout << (long long)ceil(1e9 / 2); // 500000000
    

    Another issue which usually happens with large numbers is that double may not be precise enough, for example

    long long x = 1e18;
    x -= 2
    cout << (long long)ceil((double)x / 2) // 500000000000000000;
    

    Here the answer is off by 1 because double is not precise enough, a good solution for both these issues is to not use double for calculating ceil, instead you can calculate it using this

    $$$ceil(a/b) = floor((a + b - 1) / b)$$$

    Which can be written like this:

    long long a = 1e18, b = 2;
    a -= 2;
    cout << (a + b - 1) / b; // 499999999999999999
    
  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    use (long long)ceill(..) instead

»
2 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

My solution for problem C:

  • First binary search to find maximum consecutive one and zero's. You can binary search over array such as [0, 1, 11, 111, 1111 ...] for 1 and when result of binary search is 0 for 1 that means there aren't any 1 in password.

  • Now you can try both possible combination of max consecutive one and max consecutive zero. For ex let's say max_consec_one = 3, max_consec_zero = 4, so either 1110000 or 0000111 has to be a substring.

  • From the above example if max_consec_one = 3 and 1110000 is valid substring that means on left of this substring there has to be some amount of zero's and same logic for right. To find this cnt of zero's for left and one's for right you can again binary search.

  • You can repeat above step until string t reaches the size n of the original string.

I don't know how to prove that it is less than n * 2 queries, but I think it is. I don't know whether this approach is correct. I think my solution has some sort of implementation mistake. Here's my submission

Can someone help me to find out if my approach is incorrect or implementation?

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    I spotted a problem in your approach, check out this case:

    111010000

    here max_consec_one = 3, max_consec_zero = 4, yet neither 1110000 nor 0000111 are substrings of the original string

    • »
      »
      »
      2 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Thanks, btwn I upvoted you but someone else downvoted you it's kinda funny that you got downvoted for no reason.

»
2 months ago, # |
  Vote: I like it +18 Vote: I do not like it

can anyone explain problem D and E solutions for like why we did what we did . The intuition behind them.

»
2 months ago, # |
  Vote: I like it +1 Vote: I do not like it

You should add the binary search and prefix sum solutions to D as well.

As Sol2/Sol3.

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Please share the prefix sum solution of it

»
2 months ago, # |
  Vote: I like it +70 Vote: I do not like it

So in D you literally said "here is the solution" no explanation to the logic or why it works

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Waiting for the logic explanation! Someone who understood the solution please explain

»
2 months ago, # |
  Vote: I like it +9 Vote: I do not like it

can someone explain the solution to problem D

  • »
    »
    2 months ago, # ^ |
    Rev. 2   Vote: I like it +6 Vote: I do not like it

    The solution written in the editorial and the binary search solution of problem D are basically equivalent.

    If we always keep the array non-decreasing, then performing operations is not advantageous, which means we have the array we needed. So the problem becomes how can we keep the array non-decreasing when we continuously add elements to it. We can use binary search to search the left side of where we add new element, finding the longest interval that can be averaged using the operation that problem provide us. Equally, we can use a stack to finish the same work, just traverse forward(left) one by one. However, simply traverse forward one by one has a complexity of $$$O(N)$$$ that cannot accepted, that's why the editorial records the number of occurrences of duplicate elements.

    • »
      »
      »
      2 months ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      I dont understand the binary search solution. Can u illustrate more pls

      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it +6 Vote: I do not like it

        You can set the start place fixed at where we add the new element, then binary search the end place between 1 and the start place, a end place is legal with the same condition of the editorial says. And you can use prefix sum to calculate the interval sum in $$$O(1)$$$ complexity. The binary search is correct in that if an interval has a suffix that cannot be averaged, then it cannot be averaged, and this fact ensures the monotonicity that binary search required.

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          Can u pls provide a code for that

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
            Vote: I like it +3 Vote: I do not like it

          after you do binary search as you say, the value of prefix sum may change, and we may update it in complexity $$$O(n)$$$ that can not accepted. Is that rihgt?Is there something I misunderstand?

          • »
            »
            »
            »
            »
            »
            2 months ago, # ^ |
            Rev. 2   Vote: I like it 0 Vote: I do not like it

            You're right, maybe I have something misunderstand about the binary search solution. Thinking...

            • »
              »
              »
              »
              »
              »
              »
              2 months ago, # ^ |
                Vote: I like it 0 Vote: I do not like it

              I used binary search to find $$$alpha$$$ the lowest maximum obtainable and the $$$beta$$$ largest minimum obtainable with the operation. Then it can be shown that it is possible to build a solution that reaches both of these values. The answer is then $$$alpha-beta$$$

              • »
                »
                »
                »
                »
                »
                »
                »
                2 months ago, # ^ |
                  Vote: I like it 0 Vote: I do not like it

                After taking long time to read your editorial, i finally managed to slightly understand how the binary search approach works. And it seems there are some > or < wrongs and a 'is' is miss-spelled as 'it'? Sorry for my poor english btw.

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          I thought of the same approach but then while thinking couldn't resolve that how u are modifying the previous values from starting index to the adding index?? See what i mean that when we have a non decreasing monotonous array in our left side then we can use binary search on them to get where the new element fits in, then we can definitly take on the right side of that arrays sum by using prefix sum and then avg that part out.

          But my question is even though we can do this we dont have a method of changing the left portion of the array in O(1). Worst case in changing will turn out to be O(n). Hence the TC will ultimately turn out to be O(n^2), as per myself.

          The solution written above also states the same thing but they dont use the a sorted array instead they are using a stack, where they avg out the values. and keep count variable to indicate how many repetetive copies of it are existing in the left sorted section. This reduces the TC of our approach by a lot like they mentioned "since on each iteration, no more than 2 elements are added to the stack, and each element is removed at most once". Here i cant agree to the second point that each element is removed atmost once!! Like they are inserting more types of values than what are already present there, also the values m,ight be repetetive at different instances of index to be added.

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

sub link Can someone tell me why this is wrong? It's the same as the editorial, only difference being i wrote a simulation for the checking part

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Wait so long for the editorial

»
2 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

In problem C: What if there is a substring of the form both t+0 and t+1 in the original string?

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    You dont care u cant just take any of them and procceed until u hit the end of the string (neither t + 0 nor t + 1 is a substring) with this u will have a suffix of the string then start extending from the left (aka 0 + t or 1 + t until the length of t is n)

»
2 months ago, # |
  Vote: I like it +5 Vote: I do not like it

Regarding E's time complexity as $$$O(n\log^2W)$$$ may be better.

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In F1, I was trying a solution with simultaneous BFS (from 1 for Alice, and from u for Bob). It doesn't work, but I don't know why. I would appreciate if someone could point out the edge case. At each step, Alice goes to EVERY unseen node in her frontier, marking it as 'seen', after that the neighbours of each of these nodes become her next frontier. Then Bob does the same thing. If at any point a player's frontier is empty, or only have 'seen' nodes, and its that players turn, the player loses.

  • »
    »
    2 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    See if this may help you: 282194464. It's a simple backtracking solution using DFS, but I don't know why it doesn't TLE (since backtracking usually has exponential/factorial time complexity).

  • »
    »
    2 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it
    1
    8
    1 2
    2 3
    1 4 
    4 5
    4 6
    6 7
    6 8
    8 8
    

    In this test case, Bob would win, but your algorithm outputs 'Alice' ?

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    This is also my initial thoughts, since the previously shared test didn't fail my program I changed it to make it fail mine, expected output is still Bob:

    Test
»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Wansur I have a practice submission for problem D which was accepted, but I believe it shouldn't, as it has $$$O(n^2)$$$ time complexity. Here's the submission 282154960, and here's a test generator that should make it TLE:

C++

I'm posting this here because there isn't a way to hack my own submission to a past contest.

»
2 months ago, # |
  Vote: I like it +65 Vote: I do not like it

For those of you who don't understand what the tutorial of E is saying:

We want to prove that $$$F(a_1,a_2,\cdots,a_n,x) \ge F(x,a_1,a_2,\cdots,a_n)$$$ where $$$F$$$ is the sum defined in the problem and $$$x$$$ satisfies $$$x < a_1$$$. If this is true, there always exists an optimal solution where is the smallest element is re-arranged to the first position. Here is the proof:

$$$F(a_1,a_2,\cdots,a_n,x) = (\color{red}{a_1}) + \gcd(a_1,a_2) + \gcd(a_1,a_2,a_3) + \cdots + \gcd(a_1,a_2,\cdots,a_n,x)$$$

$$$F(x,a_1,a_2,\cdots,a_n) = (\color{red}{x + \gcd(x,a_1)}) + \gcd(x,a_1,a_2) + \gcd(x,a_1,a_2,a_3) + \cdots + \gcd(x,a_1,a_2,\cdots,a_n)$$$

Because $$$x < a_1$$$ and gcd is always smaller or equal the the difference of two numbers, we have $$$\gcd(x,a_1) \le a_1 -x \implies x + \gcd(x,a_1) \le a_1$$$.

For the rest of the terms, it is easy to observe that the term below is always less than or equal to the corresponding term above since $$$x$$$ is added in the calculation.

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +7 Vote: I do not like it

    "It can be observed that the gcd will reach 1 in at most 10 iterations." can you please explain it for me?

    • »
      »
      »
      2 months ago, # ^ |
        Vote: I like it +9 Vote: I do not like it

      $$$a_1$$$ has at most $$$\log(a_1)$$$ (not necessarily distinct) prime factors. In each iteration, at least one of them should be gone, or the $$$\gcd$$$ is already the minimum possible.

      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        but why in each time one of them gone? if the left of array are same ,ans they are different from others , it wont go even one. And by the way,qingczha's provement int F(x,a1..an) is wrong ,because in fact for array 3 2 2 2 is wrong,but i dont know why

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          becauze if u don't have any element which is less than last, it means that every left elements are equel to each otehr, and you can stop your loop

    • »
      »
      »
      2 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      At first, we divided every $$$a_i$$$ by $$$g = gcd(a_1,a_2,...,a_n)$$$. This means that the gcd of some prefix of $$$a$$$ will now eventually reach $$$1$$$ instead of $$$g$$$.

      We are greedily building our new array, with every new element it is guaranteed that the new gcd will be strictly less than the previous (until we reach $$$1$$$ obviously). And since $$$a_i ≤ 10^5$$$, any $$$a_i$$$ can have at most $$$6$$$ distinct primes in its factorization, so we can safely say that the gcd will be reduced to $$$1$$$ in at most $$$10$$$ iterations.

      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        i know at most $$$log_{2}a_i$$$ not necessarily distinct primes, but why $$$6$$$ distinct primes?

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          The minimum number that has $$$q$$$ distinct primes is just the product of the smallest $$$q$$$ primes.

          $$$2×3×5×7×11×13=30030$$$

          $$$2×3×5×7×11×13×17=510510$$$

          $$$30030$$$ and $$$510510$$$ are the smallest numbers that have $$$6$$$ and $$$7$$$ distinct primes, respectively. Maximum possible $$$a_i$$$ is $$$10^5$$$ which is bounded by these two numbers meaning that any $$$a_i$$$ can have at most $$$6$$$ distinct primes.

  • »
    »
    2 months ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    Could you tell me how to explain the greedy in the tutorial? That means how to prove that $$$x,y,a_1,a_2,a_3,\cdots $$$ is not worser than $$$x,a_1,a_2,a_3,\cdots ,y$$$ if $$$\gcd(x,y)\le \gcd(x,a_1)$$$?

  • »
    »
    5 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    "For the rest of the terms, it is easy to observe that the term below is always less than or equal to the corresponding term above since x is added in the calculation.". I can't observe it. Could would explain further

    • »
      »
      »
      5 weeks ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      $$$\gcd(x,a_1,a_2) = \gcd(x,\gcd(a_1,a_2)) \le \gcd(a_1,a_2)$$$ because the gcd is a divisor and hence must be smaller or equal to each of the input.

»
2 months ago, # |
  Vote: I like it +1 Vote: I do not like it

Your proof for problem C seems incorrect to me.

In your proof, you mentioned However, after this iteration, we will make only 1 query. But what if that iteration does not exist? For example, you coincidentally reach a suffix of size $$$n - 1$$$ for $$$t$$$, which may take $$$2(n-1)$$$ queries. And after $$$2$$$ more queries, you realized that your $$$t$$$ has reached the end of $$$s$$$. So you need $$$1$$$ additional query to know whether the first character is '0' or '1'. In total, this is $$$2(n - 1) + 2 + 1 = 2n + 1$$$ queries.

In your reference implementation, this case does not actually happen but you may need to address it in your proof.

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I was thinking the same thing. I tried out few test cases and maybe this will clear answer you question —

    Not every operation will cost you 2 queries. Say you start your query with "0", if there is no substring "0", then we are looking at a string "11..11" as answer and this will take exactly 2*n queries. On the contrary, one can argue that answer string can be of the form "011..11", then too if you start your query with "0", you only take one query to get the one substring 2 queries for each character in the other "11..11" part.

    Basically, your suffix of size n-1 will take 2*(n-1) queries only if they are the opposite of the character that you are querying for first( example- answer string — "100000" and you query first for t+"1" and then t+"0" ). But if the first character of answer string is the same as the character you are querying first then you get the whole string and not the suffix ( your answer builds as "10.." )

    I hope I was able to explain!

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    If the first characters costs 2 queries, it means the the whole string consists of 1 only(assuming you are querying in the order of 0 and 1). In this case, exactly 2n queries will be used to figure the string out.

»
2 months ago, # |
  Vote: I like it +5 Vote: I do not like it

why is the problem D explained without explanation?

»
2 months ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

someone explain solution for task D in a bit elaborate manner.the tutorial is of no use

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In case you still don't understand the tutorial of D:

The key observation here is: If two consecutive elements $$$a_i > a_{i+1}$$$, it is always not bad to "mix them up", i.e. assign $$$a_i := \lfloor{\frac{a_i+a_{i+1}}{2}}\rfloor$$$ and $$$a_{i+1} \to \lceil{\frac{a_i+a_{i+1}}{2}} \rceil$$$. For instance, (10,1) -> (5,6) and (8,4) -> (6,6). The reason is that: 1. The answer is not worsen since the range is smaller. 2. If in the optimal operation sequence the value of $$$a_i$$$ is transferred to some element of large index instead of $$$a_{i+1}$$$, it is always valid to transfer it from $$$a_{i+1}$$$(Why?).

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    what do you mean by transferring ai? can you explain pls

    • »
      »
      »
      2 months ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      simply $$$a_i \to a_{i}-1$$$ and $$$a_j \to a_{j}+1$$$ as defined in the problem

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I got this but I am not sure how to simulate all of this?

    I can only think of an O(n^2) solution where you do it n times to get a sorted array.

    I dont get the stack implementation in the editorial :(

    • »
      »
      »
      2 months ago, # ^ |
      Rev. 2   Vote: I like it +8 Vote: I do not like it

      Let's say you have a sorted array $$$a,\cdots,a,b,\cdots,b,c,\cdots,c$$$ where $$$a<b<c$$$ and now you want to append a $$$d$$$ and keep it sorted.

      Firstly, what the stack stores is an efficient representation of the elements in the current array, i.e. $$$[(a,cnt_a),(b,cnt_b),(c,cnt_c)]$$$. Now to add $$$d$$$, we firstly mix it up with $$$c$$$. The result can be calculated in $$$O(1)$$$ because we know the sum and the total count. One slight tricky point is to split the "floor" part and the "ceil" part. For example, we have $$$(10,7)$$$ (7 tens) and mix it up with a $$$1$$$, we know that the sum is $$$10*7+1 = 71$$$ and the count is $$$7+1=8$$$. The result should be $$$[(8,1),(9,7)]$$$. (Try to figure out how $$$1$$$ and $$$7$$$ are calculated.)

      If mix-up with currently largest element(i.e. $$$c$$$) would cause the the result to be smaller than the second largest element(i.e. $$$b$$$), the first mix-up is actually not needed and we include $$$(b,cnt_b)$$$ in the mix-up as well. We keep the inclusion until the result satisfies the sorted-ness.

      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Ohh got this, we can do the 7,1 by the sum and average value or something.

        Thanks a lot!!

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Problem C can also be solved with O( n + 2 * log(n) ) complexity. Use binary search to find the longest continuous string of 0's using queries. Then we can build the right side of the string with 1's and check with queries. If it's not a substring we replace the 1 with 0 and continue until we reach fill the string or we end up with more 0's consecutively than what we found to be the longest. Next we use binary search to query how many of the ending 0's are also apart of the confirmed substring we know from the last query section. This will finish constructing the right side of the string. To find the answer, we now add 1's to the front of the string and query, if it's not a substring then the answer is to replace the 1 with a 0.

»
2 months ago, # |
Rev. 4   Vote: I like it +30 Vote: I do not like it
  • My solution for problem D :
Solution
  • »
    »
    2 months ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Cool solution understood that better than in the editorial

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Wait isn't min going to change when min > mx — y? a[i+1] += (a[i] — (mx-y)) a[i] = mx-y

    • »
      »
      »
      2 months ago, # ^ |
      Rev. 2   Vote: I like it +1 Vote: I do not like it
      • min might change , but the min wont decrease , I am not saying that min wont change , min might change but the change is that min does not decrease , it will always either remain same or increase .
      • So reducing the maximum element will not decrease the min ,
      • so the value = max(a1,a2,..an) — min(a1,a2,...,an) . here when we are reducing the max then , the min might increase or remain the same , so it is always optimal to reduce the max . if min increases that means it is coming closer to the max hence the value is decreasing .
      • Also initially I have stated the assumption : Suppose it is possible to make maximum element of the array A from mx to mx-y .
      • for example a = [18 , 9 , 12 ,18 , 6]
      • initially mx = 18 and mn = 6;

      • now let us just make mx to mx-2 , 18 to 16
      • a = [16 , 11 , 12 , 16 , 8]
      • Do you see that in this newly formed array ,mx = 16 and mn = 8 , here mn is increasing , and mx is decreasing , so the overall value will decrease . from initially value = 18-6 = 12 to value = 16-8 = 8.
      • I think from above example you are able to get the idea that decreasing the maximum element wont decrease the mn , but min might increase or remain same . since max is decreasing and min is increasing overall the value is decreasing . is this helpful ?
      • »
        »
        »
        »
        2 months ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        what i mean is that what if mx — y gets smaller than min

        • »
          »
          »
          »
          »
          2 months ago, # ^ |
          Rev. 2   Vote: I like it 0 Vote: I do not like it

          That is not possible , mx is changed to mx-y and mx-y < mn (you are saying this) You can look at the last element = a[n] , a[n] >= minimum(mn), we are making all the elements a[i] <= mx-y ; since the last element = a[n] >= mn , the last element can only increase . so you can not make a[n] to mx-y which is mx-y < mn . So the condition you mentioned can never happen , is this helpful ?

          • »
            »
            »
            »
            »
            »
            2 months ago, # ^ |
              Vote: I like it 0 Vote: I do not like it

            thx, yes it was helpful, thats indeed good solution, bro what's your real rating

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    perfect explanation, thanks you

  • »
    »
    2 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    This is what I want to do but I have difficulty coming up with binary search part. Thank you.

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Why the code of F1 can solve the problem in O(n)? Thank you!

»
2 months ago, # |
  Vote: I like it +3 Vote: I do not like it

Problem D. I saw a solution that we can binary search upper and lower bounds simultaneously. And I had tried this and got AC. But I'm very confused that how to prove this two independent operations is correct?

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In the case of a buffed up C , how to get to the answer in less than 2*N queries?

»
2 months ago, # |
  Vote: I like it +9 Vote: I do not like it

I wrote a more detailed editorial for problem D, if anyone is interested https://mirror.codeforces.com/blog/entry/134292

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In the D problem, in authors solution as we are putting any element in stack only if it is larger than the previous one, as result max is at the top of stack and min should be at bottom, so taking minimum of all elements of stack(first element) should also give minimum but it is giving wa on tc3. Also, since the tc is large i cant work it out, any idea as to what might be the problem. WA_solution

Thanks in advance

  • »
    »
    2 months ago, # ^ |
      Vote: I like it +3 Vote: I do not like it
    1. wrong answer 1st numbers differ, the first case is not very large(n = 20)
    2. $$$1\le a_i\le 10^{12}$$$ & const ll INF = INT_MAX/10;
    • »
      »
      »
      2 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Thanks alot, it was a total blunder by me :(

»
2 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

[DELETED]

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Could anyone share the DP solution for E? Please brighten me :))

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it
#include <bits/stdc++.h>
using namespace std;

#ifdef LOCAL
// #include "..\debugging.h"
#endif

#define int long long
using vi = vector<int>;
using vc = vector<char>;
using vb = vector<bool>;
using vd = vector<double>;
using vs = vector<string>;
using pi = pair<int, int>;
using vvi = vector<vector<int>>;
using vcb = vector<vector<bool>>;
using vvc = vector<vector<char>>;
using mi = map<int, int>;
using si = set<int>;


#define endl "\n"
#define all(x) begin(x), end(x)
#define sz(x) int((x).size())
#define fmap(name, x) mi name; for(auto it:x) ++name[it]
#define F first
#define S second
#define elif else if
#define PB emplace_back
#define MP make_pair
#define REPi(a, b) for (int i = a; i < b; i++)
#define REP(i, a, b) for (int i = a; i < b; i++)
#define REPO(a) for (int i = 0; i < a; i++)
#define vvl(ab, r, c, v)  vvi ab(r, vector<int>(c, v))
#define dbg(v)  cout << #v << " = " << (v) << endl;

const long long mod = 1000000007ll, mod2 = 998244353ll;

int dist(vvi &tree, int p, int node, int p2 = -1) {
    int ans = 1;
    for(int c: tree[node])
        if(c != p && c != p2) {
            ans = max(ans, dist(tree, node, c )+1);
        }
    return ans;
}

void path(vvi &tree, int node, int target, int p, vi &ans) {
    for(int i: tree[node]) {
        if(i == p)
            continue;
        ans.PB(i);
        if(i == target) {
            return;
        }
        path(tree, i, target, node, ans);
        if(ans.back() != target)
            ans.pop_back();
    }
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;

        vvi tree(n);
        for(int i=1; i<n; ++i) {
            int u, v;
            cin >> u >> v;
            --u, --v;
            tree[u].PB(v);
            tree[v].PB(u);
        }

        int u, v;
        cin >> u >> v;
        --u, --v;

        vi adist(n, 0), bdist(n, 0), p = {-1, 0};
        path(tree, 0, u, -1, p);
        p.PB(-1);

        int m = p.size()-2;
        vi dp(m);

        for(int i=1; i<m+1; ++i)
            dp[i-1] = dist(tree, p[i-1], p[i], p[i+1]);


        vi a(m), b(m);
        for(int i=m-1; i>=0; --i) {
            a[i] = dp[i] + i;
            b[i] = dp[i] + m-i-1;
        }

        vi suffdp(m, b.back());
        vi predp(m,a.front());
        for(int i =1 ;i<m-1;i++){
            predp[i] = max(a[i],predp[i-1]);
        }
        for(int i=m-2; i>=0; --i)
            suffdp[i] = max(suffdp[i+1], b[i]);

        // dbg(p);
        // dbg(a);
        // dbg(b);
        // dbg(dp);
        // dbg(suffdp);
        // dbg(predp);


        int start = 0, end = m-1;
        int counter = 1;
        while(start < end){
            if(counter && a[start] > suffdp[start+1] || !counter && b[end] > predp[end-1] ){
                counter = !counter;
                break;
            }
            if(counter)
                start++;
            else
                end--;

            counter = !counter;
        }

        if(start == end)
            counter = !counter;
        cout << (counter?"Bob" : "Alice") << endl;
    }

    return 0;
}

can someone explain why this is wrong for F1.

Basically I tried to find the path from 1 to u. For every path value I found Dp(max depth not on path)

then I checked for early exit. If this makes sense

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

I wonder in problem E.Is there a dp in The right time complexity ? Like "wuhudsm"we can Note dpi,j as the max sum when gcd(a1,…,ai)=j.But at least it cost O(n*n),because enumerate i cost N,and State transition cost N. It is at least O(N*N)

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

So can we have a rigorous mathematical proof for the solution of problem B?

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

the $$$A$$$ and $$$B$$$ in E's editorial are sequences, or elements, or the gcd of a sequence?

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Can anyone find the issue with my approach to Problem D?

https://pastecode.io/s/e7awhp5j

»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

problem E is god tier. loved it

»
7 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

I really struggled to understand 2013F2, which I guess makes sense because it's rated 3500 for a reason.

tldr; the idea is, for each node $$$x$$$ Bob starts at, we can compute the earliest turn at which Alice beats Bob and Bob beats Alice. If Alice's "win turn" is <= Bob's "win turn" then Alice wins, otherwise Bob wins.

After studying the code and attempting it myself for several days I'd like to offer a somewhat different and more detailed explanation of F2 that I think is more direct. The $$$(l_j, r_j)$$$ stuff is correct but I think makes the logic look harder than it is.

F1 variant: the game simplifies to the following:

  • there is a simple path connecting Alice and Bob, Alice at $$$1$$$ and Bob at $$$m$$$
  • the graph is a tree and no backtracking is allowed
  • therefore if Alice or Bob ever walks off the path at node $$$i$$$ into a subtree then they can't return. Therefore they have moves equal to the max height of that tree plus 1 moves remaining, and their opponent has free reign to explore the rest of the path. Alice can get up to $$$i-1$$$ and Bob can get down to $$$i+1$$$

Let's start with the F1 version where we only need to find the winner for a single start vertex. The solution proceeds as follows, let $$$m$$$ be the number of nodes in the $$$1$$$ to $$$u$$$ path:

  • if Alice can walk off the path at $$$1$$$ and have more moves than Bob walking off anywhere in $$$2..m$$$ then Alice wins. Otherwise Alice steps forward
  • if Bob can walk off the path at $$$m$$$ and have more moves than Alice walking off anywhere in $$$2..m-1$$$ then Bob wins. Otherwise Bob steps forward
  • iterate this until someone wins by stepping off, or runs out of moves. Use a segment tree to make the max on the ranges fast.
  • whichever player has the earlier "win turn" wins, if there is a tie then Alice wins because she moves first on each turn.

F2 variant: this one is harder because Bob can now be at any position on the simple path between $$$u$$$ and $$$v$$$. As the editorial says this path is a subset of the union of $$$1..u$$$ and $$$1..v$$$ so we can solve for all nodes on both of those paths, and then iterate over the $$$u$$$ to $$$v$$$ path at the end and print the answers.

The idea is the same as the F1 version, but this time we need to compute Alice and Bob's win turns for each of Bob's positions.

Alice win turns: if Alice turns off the path at $$$i$$$ then she has $$$t_i \equiv h_i + 1$$$ moves remaining. She will beat Bob at

  • $$$i+1$$$ right now if $$$a_i > t_{i+1}$$$
  • $$$i+2$$$ as well if $$$a_i > \max(t_{i+1}+1, t_{i+2})$$$, because Bob can go off the path at $$$i+2$$$, or can take one step to $$$i+1$$$ and then step off
  • as noted in the editorial we can find the latest position $$$r$$$ using binary search because the right-hand side increases monotonically in $$$r$$$; $$$r+1$$$ increases the the moves at $$$i+1..$$$ and also adds a new option for Bob turning off
  • given that Alice is at $$$i$$$ this means $$$i$$$ turns have elapsed; Bob's starting positions are at $$$2*i+1 .. i+1+r$$$
  • and now we know that Alice will win at turn $$$i$$$ against Bob at those positions
  • there will be multiple $$$i$$$ that win against each starting position $$$x$$$ for Bob. These positions are equivalent to turn numbers. Alice obviously wants to win as soon as possible so we'll record the minimum Alice "win index" $$$i$$$ for each Bob start position $$$x$$$

Bob win turns: similar logic to Alice's win turns. The idea is the Alice win turns are correct, but they assume that Bob has not already won. So we do another loop from Bob's perspective to find his earliest win turn at each index; if they're the same or lower then Bob wins. The idea of finding a win turn of ranges of Bob start positions is the same, but the details are a bit more complicated:

  • if Bob turns off at $$$i$$$ then he'll win against Alice if $$$t_{i} \geq t_{i-1}$$$, this time it's $$$\geq$$$ because Alice must move first, e.g. if she has 1 move remaining, and Bob has one move remaining, then Alice loses at the top of turn 2.
  • he'll also win against Alice if $$$\max(t_{i-2}, t_{i-1}+1) <= t_i$$$
  • again this turns into a binary search on the left bound $$$l$$$ such that Bob, if he reaches $$$i$$$, will win against Alice if she's at $$$l..i-1$$$
  • and again this means that $$$l..i-1$$$ turns elapsed for Alice to get there. So Bob turning off at $$$i$$$ means he started at $$$i+l-1 .. 2*i-2$$$ in $$$l-1..i-2$$$ turns, respectively
  • the turn number varying over $$$l-1..i-2$$$ makes it hard to update an efficient structure later. Instead, we notice that the earliest turn number comes from the latest $$$i$$$ where Bob descends. If Bob descending at $$$i_1$$$ and $$$i_2$$$ both result in victory for Bob if he starts at $$$x$$$, then the earliest turn is $$$x - \max(i_1, i_2)$$$. So we record the maximum turnoff index $$$i$$$ for each starting position $$$x$$$.
  • finally, having record the max $$$i$$$ for each starting position $$$x$$$, at the end we can compute the win turn from $$$x-i$$$. In other words, if Bob starts at $$$x$$$ and can win against Alice at positions $$$i_1, i_2, ..$$$ then he'll pick the latest one because that's the fewest moves, earliest turn.

This last point is where the mysterious fa[x] <= x-fb[x] comes from in the sample code (the code uses $$$i$$$ in place of $$$x$$$; I used separate symbols for current position $$$i$$$ versus starting position $$$x$$$ to hopefully reduce confusion).

The code uses an interesting multiset approach for finding the minimum win index. If an index is valid for a range of Bob start positions $$$x1..x2$$$ then $$$i$$$ is put in add[x1] and rem[x2]. These record when to add and remove candidate indices as we iterate over x values. The multiset makes it easy to find the min and max after doing the updates. At x we add all indices in add[x], find the min/max, then process rem[x] because the x1..x2 intervals are inclusive.

Instead of the clever multiset you can use a min segment tree for Alice's win turns and a max segment tree for Bob's win turns (technically Bob's win indices as discussed above). Same linearithmic runtime but easier copy-paste if you have a reference segtree implementation handy (I think copy-paste from a personal repo is acceptable here but idk for sure).

»
7 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Hey, for the solution shared for 2013F1 — Game in Tree (Easy Version), the last paragraph mentions that it can be proven that instead of using a segment tree or sparse table, one can simply iterate through all vertices on the segment and terminate the loop upon finding a greater vertex. This approach will yield a solution with a time complexity of O(n).

I am unable to prove this, so was hoping if someone could help me out with it. Thanks!

  • »
    »
    6 weeks ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

    The more I think about it, the more I think the statement is correct. Here's my proof:

    The worst case is if the current player, to find the other player's best number of countermoves with a loop in O(n), has to run that loop more than O(1) times.

    Suppose the current player is Alice, and at her current position i, she has a side path off the Alice-Bob path that has a lot of moves, such that we'll do O(n) iterations to find Bob's best counterplay on i+1..j (Bob is currently at j). That's O(n) iterations for Bob's max — but Alice will only be at position i once.

    We we find Bob's best counterplay by iterating from i+1..j then each loop starts with i+1, which has O(n) countermoves — because the i+1..j path is O(n) nodes long, plus whatever nodes of off node i+1. Suppose Alice has k different locations where she can step off the Alice-Bob path such that we'll do O(n) iterations.

    By starting at i+1 for Bob's counterplays with O(n) moves, to do more than one iteration, Alice must have access to O(n) moves.

    Therefore Alice must encounter at least O(k*n) nodes on side paths. There are only O(n) nodes total, and therefore k must be O(1).

    The above proof can be generalized a bit to say Alice and Bob are d nodes apart, there are k places where Alice and Bob can step off that trigger O(d) iterations. The loops would take O(k*d) iterations. But they'd also require having O(k*d) = O(n) nodes in total. Therefore k*d is order n so the total loop time is O(n).

    And similarly the proof is the same for Bob basically, except Bob's "counterplays loop" has >= instead of > for Alice.

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

I am curious about the trivial solution presented for question F1. It's claimed that the time complexity of trivial loop is $$$O(n)$$$, but I cannot see why. (Though I have to admit that, to me it really looks like the trivial solution has linear time complexity)

  • »
    »
    6 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    See my earlier comment for a proof.

    The idea of the proof is that suppose Alice and Bob are separated by O(k) nodes. Then to do O(k) iterations in each of Alice's and Bob's loops, they have to have access to at least k nodes in a subtree off the current path. Therefore to do O(k**2) iterations there must be O(k) nodes in subtrees at O(k) locations, O(k**2) total nodes. Therefore the max iterations done in the loops is bounded by the number of nodes which is O(n).

    In other words each iteration done in the loop over the other player's turn requires a node in a subtree. Thus the total iterations is bounded by the number of nodes in the tree which is O(n).

»
6 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Another solution to D:
1) $$$max = max$$$ of all possible suffix average ceil.
2) $$$min = min$$$ of all possible prefix average floor.
3) $$$ans = max - min$$$.
ref: https://mirror.codeforces.com/contest/2013/submission/285605752

  • »
    »
    6 days ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Could you please explain this solution?

»
6 days ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

I tried to code for E but failed on Hidden Test Case .Can Anyone tell me what's wrong with solution //this is the codde ~~~~~ int n; cin >> n; vector vec(n); for (int i = 0; i < n; i++) { cin >> vec[i]; } sort(vec.begin(), vec.end());

// map<int, int> mpp;
    vector<pair<int, int>> sortedMap;
    for (int i = 1; i < n; i++) {
        int temp = __gcd(vec[i],vec[0]);
        int x=vec[i]/temp;
        int y=vec[0]/temp;
        sortedMap.push_back({vec[i],x%y});
        // mpp[vec[i]] = x % y;
    }



    sort(sortedMap.begin(), sortedMap.end(), sortByValue);
    // sort in descending order


    int ans = vec[0], temp = vec[0];
    for (const auto& it : sortedMap) {
        int gcd = __gcd(temp, it.first);  
        temp = gcd;
        ans += temp;
    }

    cout << ans << endl;

~~~~~