1

Editorial for Codeforces Round #919 (Div. 2)

 1 month ago
source link: https://codeforces.com/blog/entry/122560
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
By sum, history, 4 months ago, In English

Information about the round

Rating predictions (inspired by BucketPotato's editorial)
Who did what

Solutions

1920A - Satisfying Constraints
Hint 1
Solution
Code
1920B - Summation Game
Hint 1
Hint 2
Solution
Code
1920C - Partitioning the Array
Hint 1
Hint 2
Solution
Code
1920D - Array Repetition
Hint 1
Hint 2
Solution
Code (iterating over second type operations)
Code (repeated binary searches)
1920E - Counting Binary Strings
Hint 1
Hint 2
Hint 3
Solution
Code
1920F1 - Smooth Sailing (Easy Version)
Hint 1
Hint 2
Solution
Code
1920F2 - Smooth Sailing (Hard Version)
Hint 1
Hint 2
Hint 3
Solution
Code (small to large)
Code (LCA queries)

2 months ago, # |

Good round. Had fun solving A, B, C. Kudos for fast editorial!

2 months ago, # |

Thank you for the great contest, the DP recurrence for E was a bit trivial but OK for Div2E.

2 months ago, # |

Thanks for the fast editorial!

2 months ago, # |

Speed Forces!

2 months ago, # |

Thanks all for the super fast editorial

2 months ago, # |

light speed editorial

2 months ago, # |

Problem C: why we take GCD of all value? we can take m=2 to check instead?

  • 2 months ago, # ^ |

    It is possible that m=3 works while m=2 doesn't, for example [2, 3], [5, 6] are the same for m = 3 but not m = 2. So you have to use gcd to find the largest m that works.

    • 2 months ago, # ^ |

      Thank!

2 months ago, # |

was going to submit b part but time over..matter of seconds lol

2 months ago, # |

Can someone explain to me why O((n+logn)*max divisors of n) is fast enough to pass the tests?

  • 2 months ago, # ^ |

    upper bound fornumber of divisors is o(n ^ 1/3) then o(n + logn) * n ^ 1/3) which can be consdered o(n ^ 4/ 3) where the time limit is 3 seconds and n <= 1e5 thats fast enough

  • 2 months ago, # ^ |

    The sum of n over all tests does not exceed , and the maximum divisors a number less than or equal to can have is not more than (I think it is around or something). So in the end this is small enough to pass the problem.

  • 2 months ago, # ^ |

    You can practically check that for all numbers not greater 200000, the number of divisors is actually , so the author solution would not take too much operations

    • 2 months ago, # ^ |

      Rev. 2  

      0

      No, it's .

      • 2 months ago, # ^ |

        How can you prove this? Thank you in advance!

        • 2 months ago, # ^ |

          You can read details here: link

          • 2 months ago, # ^ |

            the link doesn't have a proof

            • 2 months ago, # ^ |

              Graph is a proof, lol. What proof do you want?

              • 2 months ago, # ^ |

                O(f(n)) has definition. You should prove that f(n) satisfy the definition.

                • 4 days ago, # ^ |

                  may be this is proof by example, they tested it over large number, found the relation between number of devisors verses N, it roughly approximate to O(N^1/3)

                • 2 days ago, # ^ |

                  There is no such thing as a proof by an example. There is only disproof by a counter example. I believe in the case above there is a proof, it's just not what is linked.

                • 2 days ago, # ^ |

                  density of primes for given N is 1/log(N) , that relations is also found by only by plotting the graph and there is no exact proof for it...., and we use it very often,

                  so this relation is also same way found I think...

                • 44 hours ago, # ^ |

                  Rev. 3  

                  0

                  There is a proof. Several of them. Google "prime number theorem" for more details. "The elementary proof of the prime number theorem: an historical perspective" (by D. Goldfeld) has elementary proof that is on pages 1 and 2 which is really really easy, but this statement is not the same as prime number theorem itself.

                • 14 hours ago, # ^ |

                  There's no sense of proofing it in the context of competitive programming. In every real case the precision of this approximation will be sufficient.

                • 9 hours ago, # ^ |

                  without proof it may be a lie. O() is fact, or not. You can't say it's O() if it's not, except if you ok with a lie. Regarding demands of proof: I didn't demand. I just wanted to stress out that the page doesn't have a proof. And claim that it has a proof is a lie.

  • 2 months ago, # ^ |

    it is about 200000*160=3.2*10^8 which can pass in 3 sec

2 months ago, # |

Thanks for fast tutorial.

2 months ago, # |

Wow, Problem C and Problem D are pretty cool. Loved the questions. Thanks !!!!!!!!

  • 2 months ago, # ^ |

    Absolutely Correct!!

2 months ago, # |

Loved task B, Thanks for this high quality round.

  • 2 months ago, # ^ |

    #include <bits/stdc++.h>
    using namespace std;
    
    int main()
    {
        int t;
        cin >> t;
        while (t--)
        {
            int n, k, x;
            cin >> n >> k >> x;
            vector<int> a(n);
            for (int i = 0; i < n; i++)
                cin >> a[i];
    
            sort(a.begin(), a.end());
    
            long long s = 0;
            for (auto it : a)
                s += it;
            if (k == x)
            {
                if (k == n)
                    cout << 0 << endl;
                else
                {
                    vector<int>b=a;
                    while (k != 0)
                    {
                        // k--;
                        // cout<<k<<endl;
                        b.pop_back();
                        k--;
                        // cout<<k<<endl;
                    }
                    reverse(b.begin(), b.end());
                    for (int i = 0; i < x; i++)
                        b[i] =b[i] * -1;
                    int s = 0;
                    // for(auto it:b) cout<<it<<" ";
                    // cout<<endl;
                    for (auto it : b)
                        s += it;
                    reverse(a.begin(),a.end());
                    for(int i=0;i<x;i++) a[i]=a[i]*-1;
                    int s1=0;
                    for(auto it:a) s1+=it;
                    cout << max(s1,s) << endl;
                }
            }
            else if (k < x)
            {
                while (k != 0)
                {
                    a.pop_back();
                    k--;
                }
                int s = 0;
                for (int i = 0; i < a.size(); i++)
                    s += a[i];
                cout << -s << endl;
            }
            else if(k>x)
            {
                vector<int>b=a;
                vector<int>c=a;
                reverse(b.begin(),b.end());
                reverse(c.begin(),c.end());
                vector<int>ans;
                // for(auto it:b) cout<<it<<" ";
                // cout<<endl;
                int i=0;
                // 3 3 3 7 15 32
                bool flg=false;
                while(i<k){
                    int s1=0,s2=0;
                    if(i+x>=n) {ans.push_back(0);break;}
                    for(int j=i;j<i+x;j++){
                        s1+=b[j];
                    }
                    for(int j=i+x;j<b.size();j++){
                        s2+=b[j];
                    }
                    ans.push_back(s2-s1);
                    s1=0;s2=0;
                    i++;
                    
                }
                sort(ans.begin(),ans.end());
                // for(auto it:ans) cout<<it<<" ";
                // if(flg) cout<<0<<endl;
                // else 
                cout<<ans[ans.size()-1]<<endl;
    
                // int l=k;
                // while(l!=0)
    
                
            }
        }
        return 0;
    }
    

    Hi can u help me out in rectifying the error in this code

2 months ago, # |

if there are more than one occurence of type 3 constraints with the same x,some solutions may be hacked!!

  • 2 months ago, # ^ |

    "no two constraints are the exact same." So there can't be more than one occurence of the same type with the same x

    • 2 months ago, # ^ |

      i misinterpreted in hurry..thanks

2 months ago, # |

Do you expect people to know that the number of divisors of is small in Div2C? It took me a while to realize that you can just check each divisor in , I bet there were a lot of people who just submitted it without understanding why it works fast

  • 2 months ago, # ^ |

    It's a pretty common idea in problems and well known enough

    I think most people at least know that the number of divisors is at most 2sqrt(n), and even if you use this extreme bound, O(n sqrt(n)) still passes under the constraints

    • 2 months ago, # ^ |

      Oh, forgot about bound, yes that makes much more sense... I'm now even more ashamed of spending so much time on this problem

      • 2 months ago, # ^ |

        For future reference, most of the time it's ok to assume max # of divisors is around N ^ (1/3)

        • 2 months ago, # ^ |

          Thanks! I already knew that but apparently not well enough..

        • 2 months ago, # ^ |

          Rev. 2  

          0

          You can get the exact bound by finding the number of divisors of the greatest highly composite number less than the constraint. You can find these numbers in this series on oeis https://oeis.org/A002182. These could also be useful when writing tests/hacks for problems.

        • 2 months ago, # ^ |

          Okay, I'll bite. how cube root?

      • 2 months ago, # ^ |

        What is this 2 root(n) bound about , I am still confused

        • 2 months ago, # ^ |

          If then either or is (since ) so there are no more than divisors that are and no more than divisors that are

2 months ago, # |

Rev. 2  

+31

This was my FIRST Contest ever , I only managed to solve problem A , I tried solving B but could not figure out how would alice calculate which element to remove and which to not? At the end i got frustrated and left.

Honestly I loved the experience.

2 months ago, # |

Who can explain the Kruskal tree method of problem F2, I thought of it for a long time but I don't know how to maintain.

  • 2 months ago, # ^ |

    The KRT is a way to solve the subproblem in the editorial where you want to find the largest minimum edge on a path from (x, y, 0) to (x, y, 1). The graph you build on the nodes is exactly the same (each cell should have two nodes corresponding to the number of times you cross the ray). Then you will run Kruskal's MST algorithm before performing any queries and make a KRT as normal, and the queries will then be the LCA on the KRT between nodes (x, y, 0) and (x, y, 1).

2 months ago, # |

Rev. 2  

0

Why does this not work for B? Am I stupid or is this not n log n? Sorry if it's unreadable did the prefix sum backwards.

def solve(k,x,nums):
    nums = sorted(nums, reverse=True)
    s = sum(nums)
    pref = [s]
    for num in nums:
        s -= num
        pref.append(s)
    biggest = func(x,0,pref)
    for i in range(1,k+1):
        curr = func(x,i,pref)
        if curr > biggest:
            biggest = curr
    return biggest

def func(x,i,pref):
    x = min(x + i, len(pref)-1)
    return pref[x] — (pref[i] — pref[x])

2 months ago, # |

Thanks for the fast editorial and a wonderful contest!

2 months ago, # |

Damn thought about gcd in C but could not get it. I need to work on my Maths skills lol. Problem B was good.

2 months ago, # |

Explain please, why everyone thinks A, B, C were good? I admit D was nice, though too hard for me. C was unnecessarily hard after incredibly stupid A and a little over-time-consuming B.

  • 2 months ago, # ^ |

    Felt the same way for B problem, was kinda of hard for me. Looks like a need some more practice.

2 months ago, # |

Rev. 4  

0

In problem C, for the 3rd sample test case (5 11111), the answer given is 2. But the tutorial code gives answer as 1.

We can make a single group of size 5 which will be counted as 1 point. Also we can groups of size 1 and take m as 2, which will also be counted as 1 point.

So,answer should be 2 points. Hence, I think tutorial code is wrong

  • 2 months ago, # ^ |

    It gives me 2 when I run it

    • 2 months ago, # ^ |

      My bad. Sorry

  • 2 months ago, # ^ |

    Rev. 3  

    +1

    arsi[i-1]*(b+1)>=1000000000000000001 i think this can lead to overflow

    • 2 months ago, # ^ |

      So I added other constraints (ars[i-1]*(b+1)<ars[i-1]) too.. Can that also lead to overflow..?

      • 2 months ago, # ^ |

        I think ars[i-1]<=1e18/(b+1) is better than ars[i-1]*(b+1)<ars[i-1] .When you calculate ars[i-1]*(b+1) then it already overflow at some cases and it is possible that ars[i-1]*(b+1)>=ars[i-1]

      • 2 months ago, # ^ |

        Yes, it may in some cases like in my submission: 241476717. you better use 1e18/(b+1) >= ars[i-1]. I still don't know why ars[i-1]*(b+1) < ars[i-1] can overflow, any explanation is appreciated!

        • 2 months ago, # ^ |

          Try to run this code:

          long long a = 922337203685477632;
          cout << (a * 21);

          It overflows, a < 1e18 and result > a. Basic way to find out a similar to this is to solve: Solution is: I picked and python with its precision errors:

          >>> int((2**64)/20)
          922337203685477632

2 months ago, # |

Fast Editorials :)

2 months ago, # |

Rev. 2  

0

Here's an alternate solution to problem C without GCD. Observe that if we need to pick some m such that a set of numbers are all congruent to each other modulo m, m is at most as large as the second smallest element in the set. The bound on m is small enough to bruteforce all k and all m and it somehow works.

Code: 241481077

  • 2 months ago, # ^ |

    Excuse me but somehow your submission may TLE when the input is like :

    1
    200000
    30030 30030 30030 ... 30030 1

    (I wont submit since it's the same as the hack input for #241489844 )

    • 2 months ago, # ^ |

      Thanks, good to know! Actually, my solution did get hacked. Seems like the system tests were weak.

  • 2 months ago, # ^ |

    I'm not able to observe. Could you please elaborate a bit more on why this works?

  • 2 months ago, # ^ |

    Someone send me this solution link in my live stream solution discussion.
    I hacked it live there :)
    The hack part starts at 1:01:16

    Since, you are iterating on all nos until upper, I chose thing = 2*p and upper = p, where p is a prime.

2 months ago, # |

Rev. 5  

-26

A[n] — 2*A[min(i+x,n)] + A[i] is the Subarray sum. That saves time from O(n^2) to O(n).Prefix sum concept is used.

  • 2 months ago, # ^ |

    -2* is because the sum added it already so he needs to subtract it once to get it normal (like without being added to the whole number) without the Bob things, and another time so it gets *-1.

    • 2 months ago, # ^ |

      Yes! first X elements are removed from A[n] and bob decrease the sum by negatively adding those x elements again in the sum. But, why does A[i] added again?

      • 2 months ago, # ^ |

        the other elements before it? it's a prefix sum. if you basically subtract a number you're subtracting everything before it as well

        • 2 months ago, # ^ |

          now I got it. Thank you. i removed elements are not considered to be negatively added again.basically,right x elements of removed elements is bob's negative contribution. Now, I understand it.

2 months ago, # |

I had the idea for B but my implementation was just terrible

  • 2 months ago, # ^ |

    Same, took me much time to realize that using a for loop is way better than a while ;-;

2 months ago, # |

Rev. 3  

0

was WA on pretest 3 on D meant to catch any known error or just a random case? ;( not able to find my mistake

2 months ago, # |

Rev. 4  

+5

Alternate Solution to problem C.
For a given divisor of N, its sufficient enough to check if there exists any prime which satisfies the given conditions ( Not so hard to prove why it is so ) . Since there are not many primes under 2.1e5 the solution easily passes for the given constraints . Submission 241489844. Edit: Lmao TL hacked

2 months ago, # |

I have a question how problem C O(n2) solution is being getting accepted ?

  • 2 months ago, # ^ |

    I think you mean O(n*(2Sqrt(n))? if you're talking about the gcd.

    • 2 months ago, # ^ |

      No, I have seen many solutions which are O(n2) as well. They are getting accepted. How ? They are directly running for loop for findings divisors as well.

      • 2 months ago, # ^ |

        241481930 that's my submission, otherwise it's impossible to get accepted I think ;-;

        • 2 months ago, # ^ |

          No Worries :) Thank you for sharing your solution

      • 2 months ago, # ^ |

        Can you link one such solution which got accepted?

          • 2 months ago, # ^ |

            damn I thought you were trolling lol, how did this get accepted jfl (he's an lgm tho)

            • 2 months ago, # ^ |

              I am also shocked b/w the time limit given was 3 seconds. I think it can get accepted due to that as well.

              • 2 months ago, # ^ |

                No that's at most 3e8 I think, turns out it was If(n%k==0) lol

          • 2 months ago, # ^ |

            There is a check if(n%k==0) inside the loop, so the complexity is the same as in the tutorial.

            • 2 months ago, # ^ |

              Damn fr ;-; so it's O(n*2Sqrt(n))?

              • 2 months ago, # ^ |

                Nice :) You are correct Now I observed this thing :) Thanks to you guys !!

          • 2 months ago, # ^ |

            Rev. 2  

            +13

            This is not .

            The inner loop runs only if is a factor of , i.e. times, where is the number of factors of .

            The inner loop does iterations; each iteration calls gcd once which seems like it would be in total, but since we calculate gcd with the previous result, the total runtime is (check this).

            Since the above is done times, the time complexity is . For , is at most (this is reached for ; you can verify it yourself if you wish). This is fast enough.

          • 2 months ago, # ^ |

            there's the check part n%i

2 months ago, # |

can any one give me explanation of problem B?

  • 2 months ago, # ^ |

    You need to find the maximum possible answer, after both alice and bob playing for one round, Alice, will try to remove K numbers at most to maximize the answer, and Bob will make X numbers negative to minimize the solution thus he'd choose the greatest numbers cause their negatives is the smallest.

2 months ago, # |

can someone explain ans = max(ans, A[n] — 2 * A[min(i + x, n)] + A[i]); in part b?

  • 2 months ago, # ^ |

    Since he added the sum, and wants to subtract it for bob part. he multiplied it by 2 so it subtracts not just not do anything... and he is getting the max, since Alice (Idk if I am saying the names flipped lol) wants to maximize the solution

    • 2 months ago, # ^ |

      y why does he multiply by 2?

      • 2 months ago, # ^ |

        Cuz he got the sum the first time Let's you have two numbers 1 and 2, if you want to multiply 2 by -1 after you takte the sum, the sum being 3. 3-2=1--> this is the first time you didn't multiply 2 by -1 you her just got back to the starting point 1-2 (multiplication by 2) = -1.

2 months ago, # |

Here is an alternative solution for F1 (in practice: 241489058).

First, run a multi-source BFS from all volcanoes to determine the distance from every square to the nearest volcano.

Now, given a query, we run another kind of BFS from the given square. Let be the distance from this square to the nearest volcano. Instead of one queue, we maintain queues: the squares reachable when the minimum distance to the volcanoes is . Initially, the -th queue contains our starting square, and we process the queues in the order from highest to lowest.

The remaining issue is to detect when we made a turn around the island. For that, pick an arbitrary square of the island in advance. For each visited square, maintain a real value: how the polar angle changed when getting to that square. When the square was not yet visited, just record the current value. When we arrive at an already visited square: if the difference between the old and the new value is close to zero, do nothing; but if it is not (most probably close to then), we just found a round trip. What remains is to record the greatest possible distance from volcanoes when this happened.

2 months ago, # |

Can someone please explain in problem B why nlogn is passing? Because number of testcases are 1e4 and n is 1e5 and k<=n so when k=1 and n=1e5 and t=1e4 will the nlogn solution will be accepted?

  • 2 months ago, # ^ |

    It is guaranteed that the sum of over all test cases does not exceed .

    • 2 months ago, # ^ |

      Oh got it thanks

2 months ago, # |

Am I the only one who found majority of the problems in this contest to be filler?

2 months ago, # |

Rev. 2  

+11

F2 can be solved in with offline LCA.

2 months ago, # |

I think the data for Problem C might have been a little weak. The following testcase:

1
100000
99997 99997 .... 99997 49998

Can hack solutions which use the heuristic that the GCD should be = 1 (if more than 1 then that GCD value itself works), and also that the only valid answer is 49999 (which is a large prime). Some solutions try all numbers from and that should usually be too slow, I think.

Thanks!

  • 2 months ago, # ^ |

    precompute divisors SMH

2 months ago, # |

Thanks for the clear and short conditions!

2 months ago, # |

I personally think C is harder than D. Maybe swap them is better?

2 months ago, # |

I misunderstood E's "substring" as "subsequence" and wrote a wrong DP.Now feeling I'm a noob :(

  • 2 months ago, # ^ |

    it happens (I'm actually a noob)

2 months ago, # |

Can someone kindly help with any simple test case for Problem D, for which my solution fails? Or, help me identify what mistake in my code (in Java — 241492905) ?

2 months ago, # |

Negative time to editorial publish

2 months ago, # |

For problem C: I Need some help to figure out what the complexity of this solution is: 241500814

It might be around O(N*log(N)) I guess, but I am not sure.

So, what I did is to first arrange all factors of n in a 2D vector (let's say V) s.t.

in any vector if the elements are like {a,b,c... x,y} then it holds that b%a=0, c%b=0.... y%x=0.

Once we have such arrays we can binary search on each of them to find out for how many of the factors in an array m>1 exists.

So if the size of this 2D vector is X, then the complexity would be something like: O(N*log(N)*X), but what will be the upper bound on X??

  • 2 months ago, # ^ |

    Rev. 2  

    0

    n^1/3

2 months ago, # |

C was a bit standard, but great contest overall.. thank you.

2 months ago, # |

Its not necessary to use prefix sum for problem B ryt?

2 months ago, # |

Rev. 3  

0

This was a good round, but the only issue I had was that D had repeated occurrences of indices. I know it was never stated in the input that the indices had to be distinct, but I felt like it was obvious enough to assume haha. Well, at least I learned to be a lot more careful.

I do think that at least one of the examples should have featured repeated indices though.

  • 2 months ago, # ^ |

    you cant expect samples to cover everything, and in this case, repeated indices isnt an edge case for 99.9% of solutions

    Today's contest had way stronger samples than usual (and imo way stronger than should be)

2 months ago, # |

Rev. 2  

0

Please Anyone help me Find out Why my Solution is failing on some testcases! Problem D — My submission — 241508049

2 months ago, # |

Rev. 2  

0

Please, someone, i beg you, tell me why this C++ solution fails Problem D test 3 241505744 . The same exact solution works in python. There were size issues in the beginning but i addresses them. Now I just don't know what it could be and i've been trying to fix this for over 3 hours. (the python was almost correct more than 3 hours ago, but after realizing the potential size of the accumulated array can be >>>>> 10**18, i made a small adjustment and it worked). But the c++ just won't and i'm just super frustrated... please :(

I'll just say briefly, there is a "recursive" class that holds the old array before multiplying (type 2 operation) by a factor, and it also holds the additions (type 1 operatoin) that happened since the last multiplication.

2 months ago, # |

241515808 please tell why is it giving run time error

2 months ago, # |

Rev. 2  

0

Excellent round. C is good and standard. However I stuck in the gap between C and D so the round go speedforces for me :(((((

2 months ago, # |

1920B — Summation Game Follow this step. I think it will help to you : Input Handling , Sort, Calculating Initial Sum, Iterating to Maximize Sum and output here code -> https://ideone.com/kXKZYF

2 months ago, # |

use GCD for c number problem

  • 2 months ago, # ^ |

    yep you are right i also done this problem using __gcd. Thank You for sharing your idea

2 months ago, # |

That was an amazing contest with some cool problems like C and E

2 months ago, # |

Problem C was cool, I learned so much

2 months ago, # |

Rev. 2  

0

Good round!

2 months ago, # |

Can anyone explain why calculating gcd of series of numbers take n+logn and not nlogn time

Although i solved ABC but i wasn't aware of this

  • 2 months ago, # ^ |

    Rev. 2  

    +11

    If or , the gcd algorithm will be . Furthermore, when we do cumulative gcd of all the numbers, our current gcd can only decrease times (if it doesn't decrease, we have the case previously mentioned which is constant), which is why the check function runs in .

    • 2 months ago, # ^ |

      Rev. 3  

      0

      Thanks for the reply

      Problems were good hope to see more contests from you in future

2 months ago, # |

Problem C but with better time complexity. Haven't proved it mathematically but I think time complexity is n*log(n). Uses the fact that if 1, 2, 4, 8, ... are factors of 2^k == n than in worst case we need to check no more than 2^k + 2^(k-1) + 2^(k-2) ... which is 2*n numbers. And assuming gcds check are log(n) hence ig n*log(n). But math gets complicated when n is not pure power of any prime. So ig I will leave it for someone else.

https://codeforces.com/contest/1920/submission/241529452

  • 2 months ago, # ^ |

    Rev. 2  

    0

    Complexity analysis
    • 2 months ago, # ^ |

      Thanks For the analysis <3

2 months ago, # |

Damn, I didn't see the constraints for 1920B - Summation Game and solved by considering negative numbers as well XD, submission.

2 months ago, # |

First approach of problem D is really new learning to me. Thanks.

2 months ago, # |

Can anyone explain what is wrong in this code for D 241534324

2 months ago, # |

The editorial for F2 says that the time complexity of parallel binary search solution is . Here the should from path compression in dsu, but I think we cannot use path compression since we need undo the operations, or can we?

  • 2 months ago, # ^ |

    My parallel binary search solution just uses a regular DSU. You do rounds of incrementally adding all potential edges between neighbours at the right times. At a certain point in this sweep you do one connectivity query for each of the queries, no need for undoing: 241434298 The only thing that does not quite achieve this time complexity is some sorting I call inside the parallel binary search, but it can of course easily be fixed.

    • 2 months ago, # ^ |

      That makes sense. Thanks very much.

2 months ago, # |

Problem C

For people who didnt get why taking the gcd of difference of nos at all those positions works (found it a pretty cool idea):

Consider all the first nos from all partitions as:

a1, a2, a3, a4, .. , ak

Now if they have a difference which is multiple of a common number G, they can be written as: (say)

a1, a1+3G, a1-4G, a1+103G, .. , a1+7G

Now for m = G you get the same remainder for this sequence: a1%G

Now for the same no to appear at all such positions in all partitions, the required m will be the gcd of differences at all such positions.

I hope it makes sense now!

2 months ago, # |

Can someone please explain the formula used in B solution in the editorial? I cannot wrap my head around it. Thanks in advance.

  • 2 months ago, # ^ |

    Apparently goes like this. Let e be the element of the arr, r be the rest of the sum.

    To find the difference of sum. S = e+r S' = -e+r

    S'-S = (-e+r)-(e+r)= -2e

    • 2 months ago, # ^ |

      thanks alot!

2 months ago, # |

in problem c can someone tell that cant we just find all prime number lenghts(k) satsifying the condition (i.e m>=2) and then like we do in sieve find all the multiples of those lenghts and that will be the ans,TC of it will be n logn but idk why this approch 241560669 is failing

  • 2 months ago, # ^ |

    [1,1,2,2,1,1,2,2] can't be split on any primes, but does split on k = 4.

2 months ago, # |

Rev. 2  

0

https://codeforces.com/contest/1920/submission/241572267

Can someone explain why this solution of task D gets accepted on visual c++ 2017, and gets a time limit on g++20?

2 months ago, # |

Hey! can someone please help me out with how to calculate the time complexity for Problem C. My doubt is why is not the code in the solution given not throw TLE, The code looks like a O(n^2) solution

  • 2 months ago, # ^ |

    When we check some divisor , it will take time since we are taking cumulative gcd of numbers. The reason why the code does not take is because the number of divisors can have if is pretty small, around 160. So the actual time complexity is closer to .

2 months ago, # |

Had a doubt regarding problem D, would appreciate any help I could get for the same!

In the editorial I can see that they have used 2e18 as the upper limit, but since the max length index is 1e18, having (1e18+5) would work as well right?

I did something similar during the (virtual) contest, but initially gave 1e18+5 as the upper limit, which failed. then I gave 2e18+5 as the upper limit, and voila! it passed! Funny thing is that the test case it failed on didn't fail on my local with 1e18+5 limit!

Now I know that happens alot that a solution would fail on one IDE and pass on another, but I was unable to figure out why that happened in this case, any pointers would be highly appreciated!

Failed solution — https://codeforces.com/contest/1920/submission/241579138

Accepted solution — https://codeforces.com/contest/1920/submission/241583879

( PS : I know my both my solutions should have given TLE for a particular edge case, but I guess CF problem setters didn't think someone would be as stupid as me :P )

  • 2 months ago, # ^ |

    1e18 will work for python, but cpp compiler cant precise the float value after big division(in my case), ex 1223333444333332.13 gives something like 12.23e14 or something, so the condition falls for that limit, so u have to take more bigger value

2 months ago, # |

What's the time complexity in C?O(n*n)

2 months ago, # |

Rev. 3  

0

can anyone help me with my approach for problem d ?
for op 2 I incremented x by x=(x-1)*(a+1)+1 (index of the next element) for op 1 I put the value in map map[x]=value and used lower bound to find the index in map and if not found then used while loop until found edit: solved it, didn't use the limit of 1e18 here is ac code 241701574

2 months ago, # |

Can someone tell my why my Python code is getting a TLE for C. The logic seems identical to the C++ answer

from math import gcd
cases = int(input())

for _ in range(cases):
    n = int(input())
    nums = [int(x) for x in input().split()]

    ans = 0
    for k in range(1, n + 1):
        if n % k == 0:
            g = 0
            i = 0

            while i + k < n:
                g = gcd(g, abs(nums[i + k] - nums[i]))
                i += 1

            if g != 1:
                ans += 1

    print(ans)

2 months ago, # |

https://codeforces.com/contest/1920/submission/241625518 Can anyone tell what is the problem with this submission? It is giving correct answer in my PC. But i guess while checking overflow there is a problem.

2 months ago, # |

Rev. 2  

+11

  • 2 months ago, # ^ |

    Here is parity version: 241636798

2 months ago, # |

Rev. 3  

0

How does the editorial for problem F2 account for a case like this?

https://imgur.com/a/W2gRkVa

  • 2 months ago, # ^ |

    Round trip is a loop. We consider only loops. In vertical segment you have on pic, you would have to go up and down, or down and up, thus there is 3 intersections of round trip on the pic (if it's cycle).

    • 2 months ago, # ^ |

      Rev. 2  

      0

      Thank you for your reply. I'm still confused about how there are 3 intersections to the right of the island — aren't we just counting how many blocks cross the dotted line? Additionally, how are we keeping track of if a component forms a round trip (or polygon) ?

      • 2 months ago, # ^ |

        Long explanation
        • 2 months ago, # ^ |

          very helpful!

2 months ago, # |

in Problem C ,if m is gcd of m1,m2,... then all the divisor of m will also satisfy the condition of partitioning the array, then why we have only added 1 to our answer, we should add the count of divisor of m. If I am wrong please correct me?

  • 2 months ago, # ^ |

    All the divisors of m also satisfy the condition, but that is only for a particular k. We add one point for each k for which there exists m >= 2.

2 months ago, # |

I have another solution to F2 in that doesn't use small to large or LCA.

My solution follows the editorial up to drawing the imaginary line. Then, I process all of the edges except those that cross the line in order of decreasing .

After adding each edge, create a graph where the components in the DSU are nodes. For each edge that crosses the line, add an edge between the corresponding nodes. If there is a cycle of odd length in this graph, then that cycle and all nodes connected to it form a round trip (basically the same observation as in the editorial). We can now merge all of these nodes and make a note that this component is a round trip in the DSU.

If we choose our line correctly (either horizontally or vertically), this solution runs in . My code passes in 580 ms.

2 months ago, # |

Rev. 3  

0

In D if solving by repeated binary search according to the editorial why is there dp[i]=((v+1)>2e18)? (ll)2e18: dp[i-1]*(v+1);

if i am doing dp[i]=dp[i-1]*(v+1) directly its giving wrong answer. can someone explain.

2 months ago, # |

For B a more verbose sol. 242411746

Only reason "" pref[n] — 2 * pref[min(i+x,n)] + pref[i]"" works is because the prefix array starts with 0.

I hope someone finds it helpful. Because I got bricked reading that.

2 months ago, # |

The LaTeX rendered like this, initially I thought it was something nobody bothered to fix.

Recently I found out that it is a Chrome issue — https://affinemess.quora.com/A-brief-PSA-about-reading-math-on-Quora

2 months ago, # |

Can anybody the problem with my solution for Problem C ?

#include <bits/stdc++.h>
#define int long long
using namespace std;

set<int> fac(int n)
{
	set<int> ans;
	for(int i=1; i*i<=n; ++i)
	{
		if(n%i == 0)
		{
			if(n/i == i)
				ans.insert(i);
			else
				ans.insert({i,n/i});
		}
	}
	return ans;
}

void solve()
{
	int n; cin >> n;
	vector<int> arr(n);
	for(auto &x : arr)
		cin >> x;

	set<int> fct = fac(n);
	int ans = 0;

	for(auto &x : fct)
	{
		int cnt = 0;
		for(int i=0; i<n/x; ++i)
		{
			int val = 0;
			for(int j=0; j<x-1; ++j)
				val += abs(arr[((j+1)*(n/x))+i] - arr[(j*(n/x))+i]);
			cnt = __gcd(cnt,val);
		}

		ans += (cnt!=1);
	}

	cout << ans << "\n";
}

signed main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);cout.tie(nullptr);
	int tc; cin >> tc;
	while(tc--)
		solve();
}

7 weeks ago, # |

Can anyone please tell me why my code for problem D isn't working , it's working for small test cases but gives wrong answer for the 3rd example test case with big integers

#include<bits/stdc++.h>
using namespace std;
#define ll long long 
long long find(long long idx,vector<ll> &b,vector<ll> &x,ll* sizes,int n){
   
    
    int val=(lower_bound(sizes+1,sizes+n+1,idx)) -sizes;
   
    if(b[val]==1) return x[val];
    else{
        // return find(idx%(sizes[val-1]),b,x,sizes,n);
        if(idx%sizes[val-1]){
            return find(idx%(sizes[val-1]),b,x,sizes,n);
        }
        else{
            return find(sizes[val-1],b,x,sizes,n);
        }
    }

}
void solve(){
    ll n,q;
    cin>>n>>q;
   
    vector<ll> b(n+1);
    vector<ll> x(n+1);
   // vector<ll> sizes(n+1);
   ll* sizes=new ll[n+1];

    sizes[0]=INT_MIN;
    sizes[1]=1;
    cin>>b[1]>>x[1];
    for(int i=2;i<=n;i++){
        cin>>b[i]>>x[i];
        if(b[i]==1) {
            if(sizes[i-1]+1>(ll)(2e18)){
                sizes[i]=sizes[i-1];
            }
            else{
                sizes[i]=sizes[i-1]+1;
            }
        }
        else{
            //sizes[i]=sizes[i-1]*(x[i]+1);
            if((x[i]+1)>=((ll)(2e18)/sizes[i-1])){
                sizes[i]=sizes[i-1];
            }
            else{
                sizes[i]=sizes[i-1]*(x[i]+1);
            }
        }
    }

    //cout<<"The final size is :  "<<sizes[n-1]<<endl;
    vector<ll> queries(q);
    for(int i=0;i<q;i++){
        cin>>queries[i];
    }
    cout<<"The answer is:-   ";
    for(int i=0;i<q;i++){
        int idx=queries[i];
        cout<<find(idx,b,x,sizes,n)<<" ";

    }
    cout<<endl;
}
int main(){
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int t;
    cin>>t;
    while(t--){
        solve();
    }
    return 0;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK