bthero's blog

By bthero, history, 4 years ago, translation, In English

Several unexpected Kuhn solutions passed for D1F. Could you please discuss your solutions in the comments and prove its correctness or provide any counter-examples. Author's solution uses flows with Dinic.

Editorial is not completed yet. Problem D1F will be added later. Hope you enjoyed the problemset!

Editorial was/will be written by bthero and BledDest.

Our tester namanbansal013 has made amazing video-tutorials on YouTube for problems D2D/D1B and D2E/D1C. Make sure to check them out and show him some love!

Finally added the editorial for D1E. Currently it is very complicated and error-prone.

Div2A by bthero

Editorial
Code in C++ (BThero)

Div2B by nkamzabek

Editorial
Code in C++ (hugopm)

Div2C/Div1A by nkamzabek

Editorial
Code in C++ (BThero)

Div2D/Div1B by nkamzabek

Editorial
Code in C++ (BThero)

Div2E/Div1C by DimmyT

Editorial
Code in C++ (RedDreamer)

Div2F/Div1D by DimmyT

Editorial
Code in C++ (BThero)

Div1E by bthero

Editorial
Code in C++ (BThero)
Alternative solution code in C++ (hugopm)

Div1F by bthero

Editorial
Code in C++ (BThero)
  • Vote: I like it
  • +248
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it +13 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

»
4 years ago, # |
  Vote: I like it +12 Vote: I do not like it

thanks for instant editorial

»
4 years ago, # |
  Vote: I like it +21 Vote: I do not like it

D was really a good one... Thank you for such an amazing round :)

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

    Yep agreed 100%, I was thinking in terms of a linear combination of factors and stuff, later realized how amazingly they exploited the fact that we have 3 * n operations!

»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it

Thanks for the super fast editorial!

»
4 years ago, # |
  Vote: I like it +4 Vote: I do not like it

Can anyone explain C i still don't get it.

  • »
    »
    4 years ago, # ^ |
    Rev. 2   Vote: I like it +13 Vote: I do not like it

    Okay, here are some observations that might help you.

    • Consider element x, if they are at indexes 'i' and 'j'(consecutive occurrence of element x), then for a block of length [j — i — 1] or lower we cannot have that element as answer.
    • Also, if we have element x as answer for length 'L', then that element can be considered as answer for block of length >= 'L'.

    I think these two observations were enough for me to reach at solution.You can try too or I can explain if you are not able to reach to algorithm.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Please elaborate more. It will be very helpful.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +17 Vote: I do not like it

        Okay so here is what we can conclude from above observations.

        • As we are to check for consecutive occurrence of element x, It makes sense to make an array of positions for each element x from 1 to N.
        • So, now our question breaks down to finding maximum gap(or block of length that is invalid) between two positions for element x.
        • Do this for each element from 1 to N, and update their answer in array 'maxgap' which stores the minimum element x, that is valid answer for blocks of length > maxgap.
        • Now just traverse from 1 to N, print the minimum element you have stored till now for 1 to i'th in 'maxgap', to get answer and update the minimum element till now.

        Here is my code — Submission.

        I hope it helped.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    if x has to be the minimum number in all segments of length k then in input array between every occurrence of x and its previous occurrence there should not be another segment of length >=k. For instance in {1,2,2,1,1} for k=2 and x=1 we have a segment {2,2} of length two and hence not all segment s of length 2 have '1' in common. Note: We have to consider index -1 and n+1 also as value equal to chosen x.(segment from beginning and end);

    We can calculate this by maintaining a previous index for all the values we see traversing through array and updating the max distance between two same values. Then we can sort and find the min for every k.

»
4 years ago, # |
  Vote: I like it +9 Vote: I do not like it

Thanks for the quick editorial!

For div2b explanation, is the part "It is clear that f(X) = f(Y) = 0" a typo (since f(Z)=0, not f(Y))?

»
4 years ago, # |
  Vote: I like it +12 Vote: I do not like it

Loved Div2C. Purely algorithmic and appropriate difficulty.

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

.

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

    Okay, so let's make an observation if, for each distinct element, I know it's indices (could be stored by using a map to a set/vector), so let's say my current element is 'a' and it's distributed in the following manner in my array

    x x x a x x x x a x x a x a x x x

    (where x is an arbitrary element (x!=a) and a is our desired element)

    so now let's compute the maximum difference between consecutive indices and the distance of first 'a' from the start and the distance of last 'a' from the end.

    The consecutive differences are

    [4 (dist. from start), 5, 3, 2, 4 (dist. from end)]

    now the max diff from the above array is 5, so now for every sliding window of length 5 & more, I can ensure that at least one 'a' is present in each of the sliding window. (Can easily be visualized)

    Thus, now as in an ordered_map, it's sorted according to its keys, so for each element, when I calculate the max diff for the indices of this element (let's say it's y), I can mark the answer for all length from y to n, as my current element. In the above loop (used for marking my answer), I would iterate only till a point where my answer isn't marked (as whenever I encounter a marked index, all the indices from that index to n would already be marked & as it's a map, it would definitely be marked with a smaller element!), and thus after that, I break the loop.

    For all the indices that aren't marked, the answer would be -1.

»
4 years ago, # |
Rev. 3   Vote: I like it +43 Vote: I do not like it

Isn't the solution for 1B missing something ? The statement says that after each operation, all elements of the array should be non-negative. Edit: I now see that $$$a_1 \ge i-1$$$ at the $$$i$$$-th iteration.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +16 Vote: I do not like it

    I think that this solution takes that into account. All array elements start greater or equal to 1. If we start accumulating the sum at $$$a[2]$$$, then we are guaranteed to at least add 2 to $$$a[1]$$$, meaning $$$a[1] \geq 2$$$. Then even if $$$a[3]\mod 3 \equiv 1$$$, it is guaranteed that we are able to add 2 to bring it to a multiple of 3, and turn $$$a[3]$$$ into 0. In this way the entire sum can be moved into $$$a[1]$$$.

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

Dimmmy must've used his time travel capabilities again to bring such a fast editorial!

»
4 years ago, # |
Rev. 3   Vote: I like it +49 Vote: I do not like it

Div2D/Div1B

"Otherwise, we have to make it divisible by transferring i−(ai mod i) from a1 to ai. Note that this operation does not break a condition on non-negativity because all ai are initially positive."

Why does this not break the condition? How are we guaranteed that a1 >= i-(ai mod i)?

EDIT: just figured it out after posting this comment. Since we iterate in increasing order of i, each element we've seen will contribute at least 1, so by the time we are at index i, a1 will have at least (i-1).

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

    Imagine you are at position pos and have successfully accumulated all 2..pos-1 piles into the pile at position 1. Since v[i] for all i is at least 1 you'll have at least pos-1 value in the first position. Notice that v[pos]%pos can be at max at pos-1. (although pos-(v[i]%pos) can be equal to pos but that case is handled separately). Hence if we iterate from left to right it'll always be possible to do this.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Basically at each 'i' , subtract at max (i-1) from 1, and add atleasr 'i' at 1 , hence a[0]+= (1 or more for each i). Then as robinz62 edit.

»
4 years ago, # |
Rev. 2   Vote: I like it -34 Vote: I do not like it

i think that In Div2E/Div1C editorial let's construct a trie on our array integers, trie is typo and tree is correct meaning.

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

That was too fast. Thanks!

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Solved C quickly but failed on B. I think it a rare condition in this round.

»
4 years ago, # |
  Vote: I like it +16 Vote: I do not like it

The elegancy of the solutions made me happy.

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Div2C is a very elegant solution

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

In Div2D/Div1B, is it possible to use a ternary search to find the value we want all the elements in the list to assume?

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

    That value is already known, say it's x. After every move, array sum will remain constant so, in the end sum = nx, x = sum/n. That's why sum%n == 0 is a necessary condition.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

"Otherwise, there always exists a solution which uses no more than 3n queries." What is the solution of [0,1,1,1,2], please? sum=5,divisible by n=5.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Read statements carefully: "You are given an array a consisting of n positive integers"

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

Div2D

Why can't we just take $$$\frac{a_i}{i} * i$$$ from each $$$2 \leq i \leq n$$$, making values equal to $$$a_i := a_i\mod i$$$ and transfer it to $$$a_1$$$, using exactly $$$n - 1$$$ operations, then transfer needed values back from $$$a_1$$$ to all elements, using another $$$n-1$$$ operations?

I've desperately tried to find some counter-exapmle during last 1.5 hours, but I couldn't.

UPD: Got it, thank you all

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

    It's wrong if there is i and a[i] % i > sum / n

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    $$$a_i$$$ can become more than the target value in this case but still less $$$i$$$

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

    1 1 2 2 3 3

    First phase wont change any values, so you dont have enough in a[1] for second phase

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can anyone explain div2C problem in simpler way with some example

  • »
    »
    4 years ago, # ^ |
    Rev. 3   Vote: I like it 0 Vote: I do not like it

    Consider the distance between 2 positions (j > i), as d = (j — i — 1).

    For each number x that may be present in the array, calculate the following distances:

    1- Between the first element of the array and the position of the first occurrence of x.

    2- Between pairs of positions (j > i), such that a [i] = x and j is the position of the element equal to x closest to i on right.

    3- Between the last element of the array and the position of the last occurrence of x.

    Now take the largest of these values for each x value, consider this value equal to k.

    The number x appears in all subsegments of size >= k.

    then we have the answer :)

    my code: https://mirror.codeforces.com/contest/1417/submission/93998385

»
4 years ago, # |
  Vote: I like it +25 Vote: I do not like it

Nice div1C

»
4 years ago, # |
Rev. 3   Vote: I like it -8 Vote: I do not like it

Also, thanks for strong pretests <3

.

UPD: I really don't understand this contests with 3 pretests.

UPD2: I actually understand why we don't have full tests. But when we have so weak pretests, contests are just BlindForces. Why don't remove all pretests at all in this case? At least participants will get same experience, IMO

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    RIP.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +40 Vote: I do not like it

    They do that when the problem allows many tests per test file to make the queue faster.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it -13 Vote: I do not like it

      It is very cool, but they can at least make them stronger. Why in problems with several testcases they make pretests with only 1 testcase per pretest? BTW, my two problems failed because of typos, so stupid typos, that I am not sure how this passed event 3 pretests. That is the point in doing many-testcase input, if pretests are actually 1 test-case? I thought they do test-case input to speed up testing process.

»
4 years ago, # |
Rev. 2   Vote: I like it -7 Vote: I do not like it

Tutorial for Div2C is hard to understand. I solved Div2C, maybe the way the tutorial explains it, I am not sure.

So I think if somebody did not solve it, it is completly not understandable. What is meant by "we can update the suffix [some formular]..."?

  • »
    »
    4 years ago, # ^ |
    Rev. 3   Vote: I like it 0 Vote: I do not like it

    For every array element x, they compute the minimum window size k which is guaranteed to contain x. If the minimum k contains x, then all window sizes greater than k also contain x. Then, they sort the array elements in increasing order. For every array element, they have computed a minimum k which it covers. So we try to update the suffix [k..n] with this array element. If we find some k' in the suffix [k..n] which is already updated, then we don't need to update any further because every element in the suffix [k', n] has already been updated by a smaller array element because we're iterating through the elements in increasing order.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      How to update "the suffix", whatever it is?

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

        We make an array which maps the window size k to the smallest number which occurs in all windows of size k. For example if the array size is 3, then we will have 3 window sizes. So, let the array(1-indexed) "K" be [-1, -1, -1]. Then, we sort the array given in the problem in non-decreasing order. Let's say the array given in the problem is [1, 2, 3](already sorted). If it wasn't, then sort it.Let's also assume that we have computed the smallest window size k for each of these elements. For 1, this window size is 3. For 2 this window size is 2. For 3 this window size is 3.

        Now, we will update the suffixes of the "K" array while iterating through the array we sorted.

        When iterating through the array we sorted, we will run into 1, 2, 3 in that order. For 1, the smallest window which works is 3. So, we will update each k >= 3 in the K array with 1. Now the K array is [-1, -1, 1].

        Then we'll run into 2 while iterating. The best minimum window size which works is 2. So, we'll update the "suffix" with indices [2..3] in the K array with the value 2. But, when we try to update position 3, we see that it has already been updated. So, we can stop and we don't need to go any further. Now the "K" array is [-1, 2, 1].

        Then we run into 3 while iterating. The smallest window which works is 3. So, we can update the suffix [3..3], but it has already been updated by a smaller value 1. So, we can stop.

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

Can someone tell me how I passed pretest and managed to get runtime error on test "1" during system testing?

here is my submission: 93984302

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Usually this is undefined behaviour, some index out of bounds. But I cannot see in which line.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      But I at least passed pretest(which had 4 tests). Very confused, hope I don't get ruined by some mysterious problem.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        I compiled and run it on my computer, it is a out of bounds.

        Error message

        You could try to use compiler options which make your code fail in such cases.

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          nah I re-submitted and got AC, idk

          • »
            »
            »
            »
            »
            »
            4 years ago, # ^ |
              Vote: I like it -7 Vote: I do not like it

            That is the "undefined" in undefined behaviour. Sometimes it works, sometime it does not.

            • »
              »
              »
              »
              »
              »
              »
              4 years ago, # ^ |
                Vote: I like it +5 Vote: I do not like it

              Hmm, very interesting. I guess I will prompt to static arrays more to avoid this kind of problem(maybe will help? idk).

              Anyway, thank you for trying my code.

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

                Why would using static arrays help?

                It may sound rude and it is rude
                But people who don't understand what UB is should not code in c++. It should literally be repeated on every c++ lesson

                • »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  4 years ago, # ^ |
                    Vote: I like it 0 Vote: I do not like it

                  I will try to study what UB is. It is correct that I didn't take C++ lesson though.

                • »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  4 years ago, # ^ |
                    Vote: I like it 0 Vote: I do not like it

                  Don't take my comment personally

                  It just happens again and again.

                  People create posts or comments and always ping Mike or contest authors regarding "It passes locally but fails with the same example in tests" or something like that. Though it is completely normal for their language Really painful.

                  Also it is not the only ub you can get. There are plenty of other options to run into it.

                • »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  4 years ago, # ^ |
                    Vote: I like it 0 Vote: I do not like it

                  What is ub?

                • »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  »
                  4 years ago, # ^ |
                    Vote: I like it 0 Vote: I do not like it

                  Undefined Behavior

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

            Yes you did get AC from undefined behaviour, but you may get RE during systests. To avoid that, compile with -D_GLIBCXX_DEBUG. This will catch all out of bounds accesses(in stl containers), and you will therefore not get any UB for that reason at least.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    DimmyT asking for help

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      xD I don't know what to do... Maybe MikeMirzayanov can help? In every problem, pretests are prefix of all tests.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        yes but I surely passed pretest so I don't know why...

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Yeah I submitted the exact same code again and got accepted, MikeMirzayanov sorry to bother but please help me TAT

»
4 years ago, # |
  Vote: I like it +6 Vote: I do not like it

This contest made me purple for the first time :) Thanks for the good problems

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

On this contest I had big troubles with problem E. I used the idea with the mergesort + checking every bit of answer from last to first. It uses O(30 * n * logn) time, and with n = 3e5 it is approximately 1e8, is it really that slow for time limit = 2 seconds? If anyone can get AC with my code, please share my mistake. (94018657)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    My solution was with almost the same idea as yours and also got TLE on test case 12, when I optimized my code it runned locally on 3 seconds for the worst test case.

    However I think you should use long long for computing the amount of inversions.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

a great contest but very weak pre test for B (div 2)

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Div2-B my code What's wrong in this I'm unable to figure it out. If anyone could help me. Initially it is assigning all the elements of array as '0' and putting current index(j) in map if it's not making 'T' with another previous element i<j, but when it founds a[i]+a[j]==T 'j' is assigned to 1.

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

Testcases were very weak for Div2 C. I saw a lot of submissions where the test case 1 1 3 would fail, but somehow got accepted. I submitted my code at 1h 6 mins(all pretests passed). Went on ahead to try D, but at 1h 52 mins, I realised, that I've missed the case for n = 1, So I resubmitted it. Turns out they didn't have a basic case like n = 1. My ranking fell from expected 1200 to 1765. Please do something about the resubmission rule.

»
4 years ago, # |
  Vote: I like it +13 Vote: I do not like it

When you submit solution in the last min and net fucks you up and then you submit that after contest and it ACs. FML

»
4 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Weak Test cases for problem (div.2)A. A soluion with 10^7 operations(in worst case) in java, it just has 3 test cases which are also randomly made i guess. look at this solution. I know its just problem A but still it decreases the quality of contest.

»
4 years ago, # |
  Vote: I like it +68 Vote: I do not like it

"Several unexpected Kuhn solutions passed for D1F. Could you please discuss your solutions in the comments and prove its correctness or provide any counter-examples. Author's solution uses flows with Dinic."

Don't worry, it is almost impossible to hack Kuhn (especially on those, specific graphs). Even if it is possible, it is VERY hard. Of course, I don't have any proof of my words, but I know it from my experience.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +32 Vote: I do not like it

    This is a strange question, but: how to solve this problem with Kuhn? I don't doubt its time efficiency, but I don't know how to find the maximum matching which saturates some given set of vertices without using circulations (which is the model solution).

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +52 Vote: I do not like it

      Alright, so you need to find the matching that covers some set of vertices.

      • Using Kuhn in proper order, find any maximum matching that covers all vertices of the left part from the set, let's say that the set of covered vertices of the left part is $$$L$$$ (some vertices from the set + something else).

      • Using Kuhn in proper order, find any maximum matching that covers all vertices of the right part from the set. Similarly, define $$$R$$$.

      The claim is: there is a maximum matching on the set of vertices $$$L \cup R$$$.

      You can prove it using alternating paths.

      And then you can just leave only those vertices and find the maximum matching.

      Note: this algorithm also can be used for solving the maximum vertex-weighted matching where you have weights on both parts. I will leave it to you as an exercise.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +12 Vote: I do not like it

        That's really cool (though I need some time to make sure I understand why this is correct). Thank you!

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +32 Vote: I do not like it

        which Kuhn's algorithm is this and what does it do? He has too many...

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it +41 Vote: I do not like it

          Oh, excuse me! In Russia, we call the 'Kuhn's algorithm' a DFS-like approach for maximum matching in the bipartite graph, which goes like that: for $$$v \in L$$$ in some order, run $$$dfs(v)$$$ (i.e. simplified and faster version of Ford-Fulkerson, which appears to be quite powerful).

          Here is the Russian (unfortunately) page with code and description of this algorithm (you can use a translator if you really want): e-maxx..

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        So u use that claim just to cut down the number of vertices and edges? Or am i missing something?

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Can you please explain how to find maximum weighted max matching? I know about fast Kuhn, but I always thought that it can’t be used for finding maximum weighted matching.

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +53 Vote: I do not like it

      Another way (I didn't participate today, though, so I'm not 100% sure). We can model our subproblem (given a bipartite graph, find a matching covering a given subset of vertices) as a maximum-cost flow: connect a source with all vertices of one side of the bipartite graph with oriented edges with capacity 1 and cost 0 or 1 (1 if the vertex must be covered by the matching). We analogously connect all vertices of the other part of the graph with the sink. Now, if we need to cover $$$R$$$ vertices, we can easily see that we are looking for any flow with cost $$$\geq R$$$.

      But running a maximum-cost flow algorithm naively is probably too slow. In order to cope with that, we need to understand how the simplest maximum-cost flow algorithm works on our network:

      • In the first phase, the algorithm iteratively finds augmenting paths with a total cost of $$$2$$$. We can convince ourselves that this is actually equivalent to finding the maximum-size matching on the subgraph induced by all required vertices (and no other vertices). We can do just that using Kuhn's algorithm.
      • In the second phase, the algorithm iteratively finds augmenting paths with a total cost of $$$1$$$ in the residual network created after the first step; hence, we are looking for alternating paths connecting an unmatched required vertex with an unmatched non-required vertex. This is equivalent to running the Kuhn's algorithm on the graph above (with the matching found in the first phase), only that we only search for alternating paths originating from a required vertex (remember that the origin can belong to either part of the graph).
      • No further augmenting paths in the max-cost flow algorithm will increase the cost of the flow, so we're done — we found a matching covering as many vertices as possible.
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Hi, Can anyone please tell me the time complexity of my code for D2B, according to me, it is approximately O(N log N). But it gave TLE on the system tests, which shows that I have approximated the complexity incorrectly. Here is the link to my submission:

https://mirror.codeforces.com/contest/1417/submission/93976053

Thanks in advance!

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

    If input looks like $$$a = [x,x,x,...,y,y,y,...]$$$ and $$$x + y = T$$$, every time your program sees a $$$x$$$ it will go through every positions of $$$y$$$ and set the answer, then the run time becomes $$$O(n^2logn)$$$

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

For problem D how can it be told for sure that a[1] wont be negative after the operation. lets say if a[i]=8 and i=7 then it would take 7-(8%7)=6 at least 6 but if a[1] is less that that how what will happen then? what am i missing?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Even I have the same doubt

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    Because he did the operation from i=2 to i=n

    you can see that the when we are doing from i=k, a[i] is at least k-1 since a[1]~a[k-1] is all greater than zero, thus the method will work.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Aaaaaaaah! That feeling when a solution passes after contest by changing just ONE CHARACTER!!!!

Nice contest!

»
4 years ago, # |
Rev. 2   Vote: I like it -7 Vote: I do not like it

please someone help what's wrong in my code in div.2(B)? It failed in system testing(test#4). https://mirror.codeforces.com/contest/1417/submission/93983911

why I am downvoted why it's not right of the "pupil" to ask doubts

»
4 years ago, # |
  Vote: I like it +37 Vote: I do not like it

My solution for Div1 D using small-to-large merging passed in 1.4s. 94011971

The idea is that we simulate small-to-large merging for edges in reverse order and save which values were in a smaller set, so we could simulate the process in reverse order by removing the smaller set from the larger set.

  • »
    »
    4 years ago, # ^ |
    Rev. 2   Vote: I like it +13 Vote: I do not like it

    You don't even need to use a set of pairs to answer queries.

    With the same idea you can maintain the vectors during the small-to-large merging and sort them afterwards, then you can simply rollback the edges which you are supposed to erase. To answer queries you go from the back of the vector and pop elements which are already deleted (equal to 0) or aren't in the same disjoint set anymore. So for all queries you get O(n) amortized (After sorting for NlogN of course).

    This made my code run in about 650ms.

    Submission

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +5 Vote: I do not like it

      Wouldn't there be $$$O(NlogN)$$$ elements in total which we need to sort? Therefore the complexity would still be $$$O(Nlog^2N)$$$, but with a better constant.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        Yeah, i didn't notice that, you're correct.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +26 Vote: I do not like it

        You can get the complexity down to $$$O(N \log N)$$$ if you sort all vectors using counting sort (consider all vectors that contain 1, then all vectors that contain 2..., and proceed like this to reconstruct all vectors in the correct order). See 94166796

        • »
          »
          »
          »
          »
          4 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          Cool. I spent day to optimize this solution with vectors to $$$O(n log(n))$$$ and didn't come up.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In DIV2B , why can't we just put all pairs whose sum add up to the target into different multi sets?

 for(int i = 0 ; i < n ; ++i){
        
        int curr = arr[i];
        int val = tar - curr;
        
        if(freq.count(curr) <= 0) continue;
        --freq[curr];
        if(freq[curr] <= 0) freq.erase(curr);
        
        if(freq.count(val) == 0){
            ms1.insert(curr);
            continue;
        }
        
        if(ms1.count(val) > ms2.count(val)){
            ms1.insert(val);
            ms2.insert(curr);
            --freq[val];
        }
        else{
            ms1.insert(curr);
            ms2.insert(val);
            --freq[val];
        }
        
        if(freq[val] <= 0) freq.erase(val);
        
        
        
    }
»
4 years ago, # |
  Vote: I like it +11 Vote: I do not like it

Was O(nlog(n)log(max(A[i]a)) not intended for div2E or does my solution just have poor constant/ bad implementation on that time complexity?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    My O(n log A) with hashmap failed on pretests so I assume that anything slower than O(n log A) wasn't intended but I might be wrong

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

    The time limits were tight here. My solution failed with map too. Unordered_map barely passes (but I needed a custom hash function — they may have some anti-hash test cases).

    EDIT: Actually your complexity can work (for example see tourist's solution), But constants matter a lot here.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Otherwise, we have to make it divisible by transferring i−(aimodi) from a1 to ai. Note that this operation does not break a condition on non-negativity because all ai are initially positive. I don't know why this sentence is true. If a1 is small, isn't it a negative number? Or am I too stupid?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +15 Vote: I do not like it

    Since we are considering the indices $$$i$$$ in ascending order, and all $$$a_i > 0$$$, when we start dealing with $$$a_i$$$, $$$a_1 \ge i - 1 \ge a_i \bmod i$$$.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Rating changes working correctly? 2000 rank made me a specialist again

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Dropped to specialist before, seems like 2000 rank is not enough for a steady blue title.

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

Can any one give a formal proof for Div 2 A?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Can someone please explain div2b, how we can separate array a in white and black balls based on given unlucky integers T?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Some video solutions (for 2A-F), in case you like those

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I might be wrong here, but isn't your solution for D wrong with an input of:

1
8
0 0 2 0 0 0 0 6

The second operation from your code 1 3 1 would reduce the first element by 1 and increment the third element by 1, but the first element is still 0 at that stage.

16
2 1 0
1 3 1
... // snipped here, got the output from a custom invocation call
»
4 years ago, # |
  Vote: I like it +7 Vote: I do not like it

For Div1C / Div2E I have another solution without using a trie.

Here is my submission: 94030812

Explanation:

Spoiler
  • »
    »
    4 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    Cheers, I tried a mergesort solution after the contest but it would always be too slow, your submission + explanation was a nice reference :)

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    I did think of the solution on these lines but couldn't come up with a concrete proof of why it would work... good to know it works

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Your solution's time complexity is O(30*n*log(n)) right ? I have made similar submissions but they all got TLE, did you use any optimization ?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

can someone tell me what is wrong with my solution....what i did was take input as pairs(to remember the index after sorting by value) and loop until i find two index that gives the sum "k" and the remember the indices of the two value. Now just make half of the subarray 1 and others zero then sort by indices to finally print the answer. submission : 94032531

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

For div2 B it shows WA, My solution was to divide them like this: paint X white and T-X black if it exists and distribute all x=T/2 equally to black and white. What is wrong with this approach.

My Solution: https://mirror.codeforces.com/contest/1417/submission/93987002

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    maybe trying not declaring big arrays in main? that sometimes causes WA

»
4 years ago, # |
  Vote: I like it +29 Vote: I do not like it

Div1 C TL not friendly :( My solution with hash table didn't pass.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Is div2D solution wrong? consider 1 1 1 1 3 3 4 the sum is divisible by 7, but it seems to be unsolvable...... pls help me with this case :)

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

    1 1 1 1 3 3 4 >>> 0 2 1 1 3 3 4 >>> 2 0 1 1 3 3 4 >>> 0 0 3 1 3 3 4 >>> 3 0 0 1 3 3 4 >>> 0 0 0 4 3 3 4 >>> 4 0 0 0 3 3 4 >>> 2 0 0 0 5 3 4 >>> 7 0 0 0 3 4 >>> 4 0 0 0 6 4 >>> 10 0 0 0 0 4 >>> 7 0 0 0 0 7 >>> 14 0 0 0 0 0 >>> 12 2 0 0 0 0 0 >>> 10 2 2 0 0 0 0 >>> 8 2 2 2 0 0 0 >>> 6 2 2 2 2 0 0 >>> 4 2 2 2 2 2 >>> 2 2 2 2 2 2 2

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Oops i gave the wrong data......

      0 1 1 1 3 3 5

      should this be unsolvable or not ?

      thx

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +10 Vote: I do not like it

        0 1 1 1 3 3 5 is not a valid testcase

        A[i] should be larger than 0

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

          Oh thx for the fastest reply i ever seen......

          I should make sure that i am able to read problem statements carefully for every contest :( it's so hard since i'm in gmt+8 and codefroces contests are often held late at night

          anyway thanks @..vince

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In Div2B if we consider this test case

5 9
1 3 3 3 8

According to solution provided it would be 0 0 0 0 1

But optimal solution would be 0 0 0 1 1

Am I correct nkamzabek ?

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    What are you asking for?

    Both coloring you gave have f(c)+f(d)=0

»
4 years ago, # |
  Vote: I like it +45 Vote: I do not like it

In Div1 B , the condition:"$$$a_i\geq 1$$$" is really important.At first,I ignore it,so I am stuck for a very long time.

Compared to B,Div1 C is much classical.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I made an unnecessary resubmission for missing that. I found out about that constraint when I wanted to hack someone.

»
4 years ago, # |
  Vote: I like it +6 Vote: I do not like it

According to problem Div2D: Number 1 is the most powerful number :))

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Construct a Trie to solve Problem E. I can never think such a great idea! Here's my solution: 94045226 without using trie. Code may be a little long, but it got accepted!

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

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

Div 2B: Even after reading editorials I don't see any error. Can someone plz tell me what's wrong with my code? Solution B. My solution was to divide them like this: paint X white and T-X black if it exists and distribute all x=T/2 equally to black and white.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Is the rating change unusual this time for everyone or only me?

»
4 years ago, # |
Rev. 2   Vote: I like it +31 Vote: I do not like it

We (me, gyh20, Time_tears) have a totally different (and much easier, we think) solution to D1D.

First add the edges from the last operation to the first, and at the same time use disjoint-set-unions (with merging the small one into the big one) to add the numbers a connected component contain into a vector and keep the total size under $$$n\log n$$$.

After getting done with the vectors, sort each of them from small to big. Let $$$bel[i]$$$ be the connected component the point with value $$$i$$$ is now in. For all $$$i$$$ from $$$1$$$ to $$$n$$$, let $$$bel[a_i]\leftarrow getfather(i)$$$. (getfather is the dsu function)

Then we answer the queries:

  • If this operation is a deleting operation, let's assume that we delete (x,y). If deleting the edge doesn't affect connecting components, ignore it. Else let $$$getfather(x)\to x, getfather(y)\to y$$$. Assume that $$$size[x]<size[y]$$$ (size of connected components after deleting). For all points $$$i$$$ in x's component, let $$$bel[a_i]\leftarrow x$$$. Also change the father of $$$x$$$ to itself.
  • Else, let $$$getfather(x)\to x$$$. Consider from back to front in its vector: if the number is printed, pop it (use pop_back). If it's $$$bel$$$ isn't x, pop it. Else print it.

The solution runs a lot faster than the author's. Without any optimizes, it only uses 452ms. Also it doesn't need any data structures.

My code is here: 94056232

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

can anyone explain what does this line in editorial for DIV2 F mean, If the current query is of first type, remember the "boss" of the corresponding vertex. How is the question transformed to subtree-maximum query on DSU tree ?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

why my O(n*30) solution in E give TLE

94058521

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

Can Someone please tell me what's wrong in my solution for div2-B

https://mirror.codeforces.com/contest/1417/submission/94138194

I have simply changes the color (k — number) to opposite value of the (number). This also ensures that all the n/2 numbers are equally distributed but still getting wa on test 4

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

    Got my mistake. For any one doing same mistake as me consider the test case

    4 8

    8 0 4 4

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

      Thanks, bro! It was really messing up with my head, didn't realize that I am just plain dumb :)

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

The editorial of Div1E is missing. Could anyone share the idea of its solution?

»
4 years ago, # |
Rev. 3   Vote: I like it +93 Vote: I do not like it

Since the editorials of problem E and F are missing, I will share my approach to solve them:

E:

Observation 1
Observation 2
Observation 3
Observation 4

F:

Observation 1
Observation 2
Observation 3
Observation 4
  • »
    »
    4 years ago, # ^ |
      Vote: I like it +18 Vote: I do not like it

    Thank you. Was waiting for this.

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

In the editorial of Div2E/Div1C,there's something I can't understand. In the tutorial, $$$a, b$$$ are the children of $$$v$$$, and $$$v$$$ has a depth of $$$k$$$. Then $$$a, b$$$ have a depth of $$$k-1$$$, and the highest bit which differs in both should be the $$$k-1$$$-th highest bit. So I think only the $$$k-1$$$-th highest bit of X is toggled, lists $$$S(a)$$$ and $$$S(b)$$$ will change their relative order, not $$$k$$$-th. Can anyone explain it?

»
4 years ago, # |
Rev. 2   Vote: I like it +16 Vote: I do not like it

Edit: has been fixed.

The maxn (4e6 + 100) in the code of Div2E/Div1C is small and can be hacked by this generator:

#include <bits/stdc++.h>

using namespace std;

const int mx = 1e9;
const int n = 3e5;

int main() {
   cout << n << endl;
   int cnt = 0;
   for (int i = 0; (i << 12) <= mx; i++) {
      if (i > 0) {
         cout << " ";
      }
      cout << (i << 12);
      cnt++;
   }
   for (int i = 0; cnt < n; i++) {
      cout << " " << ((i << 1 | 1) << 11);
      cnt++;
   }
   cout << endl;
   return 0;
}
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Nice contest. I'm new to the technique of adding fake node to build dsu tree where used in Div2F/Div1D problem. Is there any relevant problem can be solved by this technique?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

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

Div2 A. The statement "any operation which increases the value of $$$min(a_1,a_2,…,a_n)$$$ is unoptimal" (the proper English word is non-optimal) is false. Besides, it is meaningless since not every operation that preserves the minimal value is optimal.

1
2 3
1 2

You can copy once regardless of whether you copy from $$$a_1$$$ to $$$a_2$$$ or from $$$a_2$$$ to $$$a_1$$$.

  • »
    »
    4 years ago, # ^ |
    Rev. 5   Vote: I like it +8 Vote: I do not like it

    Why has it been downvoted? Is anything stated there incorrect? It referred to the original text of the editorial which has since been edited.

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

Thanks for Editorial

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

seeing space complexity for the first time in editorial!! one of the best round.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by bthero (previous revision, new revision, compare).

»
4 years ago, # |
  Vote: I like it +8 Vote: I do not like it

I am thrilled after understanding div2 F's solution

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In the problem Div2 D, the editorial said that transfering i-(a[i]%i) from a[1] to a[i] does break the non-negative rule. How about the case that a[1] < i(a[i]%i)? Will the a[1] become negative?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In Div2E/Div1C we can convert all numbers to binary. Then we start with the whole array of n elements and look at the most significant bit. Iterate over the array, counting inversions and antiinversions along the way. (Inversions are 1-0 pairs and antiinversions are 0-1 pairs, 0-0 and 1-1 pairs are neither.) Split the array into two subsequences, placing the elements with a 0 bit in this position to one of them and elements with 1 bit to the other, while preserving order within each subsequence. Repeat the same procedure recursively on each of the subsequences, with the next most significant bit. Inversions (as well as antiinversions) at the same recursion depth should be added up. Recursion stops, after processing the least significant bit. At the end we have the total number of inversions and total number of antiinversions per recursion level i.e. per bit position. Now we can construct the required x, setting its bits to 1 at positions where the number of inversions is strictly larger than the number of antiinversions and to 0 in the others. Complexity is O(n logn).

»
4 years ago, # |
Rev. 9   Vote: I like it +18 Vote: I do not like it

Unofficial Div1F editorial (Dinic's maxflow solution):

Note that a satisfactory solution can be produced as follows: for every cell, exactly one of the following must be true:

  • It points to a neighbor of lower value than it that doesn't point back, and its cost will be the difference between the values.
  • It points to a neighbor of equal value that points back to it. The sum of their costs will be equal to their shared value (division can be arbitrary, e.g. $$$(1, x-1)$$$ or $$$(\lfloor x/2 \rfloor, \lceil x/2 \rceil)$$$)

Note that the second condition resembles the bipartite matching problem that arises from domino-tiling an arbitrarily-shaped chessboard (e.g. this problem from AtCoder). In fact, it can be framed as a bipartite matching, but with only a subset of nodes being mandatory participants for the matching. A node is mandatory iff its cell has no neighbors of lower value, otherwise it's optional.

Recall that to use Dinic's maximum flow to solve a bipartite matching, there are source-edges to one of the parts (the "white" cells on a chessboard), sink-edges from the other of the parts (the "black" cells), and directed edges from the first part to the second part based on potential matchings (i.e. between cells with equal value). To model mandatory nodes, we add a "demand" to its source or sink edge, modeling demands by the transformation detailed in this tutorial.

The answer is yes iff all demands are met by the flow. The solution can be reconstructed by matching cells by the second condition if there is flow between them. If a cell isn't matched this way, the first condition can be fulfilled instead; this is always possible as the node would have been marked mandatory otherwise.

Beware: Dinic's algorithm implementations that pass many other flow problems fine may TLE here due to a subtle bug. In particular, ensure your adjacency-list pointers (ptr in the author's solution, or next in my solutions [recursive | iterative]) only increment if its edge is exhausted, i.e. the search in that node hasn't fulfilled its flow limit yet.

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

In problem 1D, the given solution code runs about 1.3s (GNU C++17(64)) and the TL is 1.5s?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

All spoilers are broken. Please fix this.

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

I have alternate solution for div-2 F which has same TC as the editorial's solution, but slightly worse space complexity, $$$(O(n + q)\log{n})$$$.

Firstly, store all the queries, and delete all the edges given in the type-2 queries. Now, in this new graph, unite all the nodes in connected components into one dsu set each.

Now we will basically try to simulate the process in reverse. We can do it like this: Iterate from the last query to the first. Now all the type 2 queries are essentially unite queries (as we are going backwards), so store the set representatives of both the ends of the edge that was to be deleted in this query. Also, store the smaller set.

Now we will iterate from first to the last query, and answer queries too.

  1. For type 1 queries: simply check max in current dsu set of given vertice, set its value to 0, and update dsu set accordingly.
  2. For type 2 queries: we had earlier stored the smaller set that was merged into the larger set. So now we must separate that smaller set from the larger one. But some elements of the smaller set might have changed in the prior type-1 queries. So we can just check the new value of each element before adding stuff back into the smaller set.

Implementation: link