2

Codeforces Round 921 (Div. 1, Div. 2) (Partial) Editorial

 7 months ago
source link: https://codeforces.com/blog/entry/125137
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.
neoserver,ios ssh client
By JaySharma1048576, 3 days ago, In English

I hope you enjoyed the round. Here is the editorial for some of the problems. The hints and tutorial for the rest of the problems will be added soon. Do provide your feedback on each problem so that we can improve upon them the next time.

2A. We Got Everything Covered!

Author: JaySharma1048576

Hint 1
Tutorial
Solution
Feedback

2B. A Balanced Problemset?

Author: JaySharma1048576

Hint 1
Hint 2
Tutorial
Solution
Feedback

2C/1A. Did We Get Everything Covered?

Author: JaySharma1048576

Hint 1
Hint 2
Tutorial
Solution
Fun fact
Feedback

2D. Good Trip

Author: yash_daga

Hint 1
Hint 2
Hint 3
Tutorial
Solution
Feedback

2E/1B. Space Harbour

Author: yash_daga

Tutorial
Solution
Feedback

2F/1C. Fractal Origami

Author: mexomerf

Hint 1
Hint 2
Tutorial
Why unusual modulo?
Solution
Feedback

1D. Balanced Subsequences

Author: yash_daga

Hint 1
Hint 2
Tutorial
Solution
Feedback

1E. Paper Cutting Again

Author: yash_daga

Tutorial
Solution
Feedback

1F. Anti-Proxy Attendance

Author: JaySharma1048576

Hint 1
Hint 2
Hint 3
Hint 4
Tutorial
Harder bonus tasks
Solution
Feedback

2 days ago, # |

Rev. 6  

-36

I guess people don't like to see what I wrote, and unfortunately I can't delete the comment (no option to do so), Treat this as a DELETED COMMENT.

  • 41 hour(s) ago, # ^ |

    I don't really get why I was being downvoted initially (and even now)
    I am genuinely interested in knowing that, if someone can politely point out the reason. It will be much appreciated. (will take care about it next time I say something, feel free to see previous revisions).

    • 37 hours ago, # ^ |

      what was your comment?

      • 37 hours ago, # ^ |

        You can press the <-Rev. 6
        button to see the previous revisions (i.e. what my comment was).
        Thank you for your time.

        • 36 hours ago, # ^ |

          now i wonder too what made you have so many downvotes

2 days ago, # |

C was tough!!

  • 41 hour(s) ago, # ^ |

    It seems interesting, it's quite easy when find this greedy way in A but harder in C.

2 days ago, # |

I resent working solution on C an hour after AC attempt. Ask questions.

2 days ago, # |

JaySharma1048576 dario2994 kevinsogo Are code or explanations available for the 1F bonus tasks?

  • 2 days ago, # ^ |

    The moment, when the greats despaired

  • 36 hours ago, # ^ |

    I can only provide their codes here because I don't fully understand them (My rating doesn’t allow me to understand it).

    dario2994's solution (70 queries)
    kevinsogo's solution (55 queries)
    • 36 hours ago, # ^ |

      dario2994's solution is roughly what I expected (split into up to 8 equal segments, then reduce to two segments).

      Not sure what kevinsogo is doing for though — would appreciate a proof regarding the total number of queries if there is one. It's also not clear to me why the find function never asserts false.

      • 20 hours ago, # ^ |

        Rev. 4  

        +16

        It seems you have pinpointed the most crucial part of my code :)

        When I derived this algorithm, I had no proof that find would work, just empirical evidence that I tried it for many random tests and couldn't find a breaking case. (And I guess I proved it for small just by checking.) But now after you asked, I spent some more effort proving it, and I think I have come up with something that might work.

        Roughly, it seems to me that we need to show some sort of variation of the Borsuk-Ulam theorem.

        Let's make the array circular, and consider its half-open subarrays , with appropriate wraparounds, i.e., is to be understood mod , and . Note that the complement of is .

        Then I defined a cost function from subarrays to 2D vectors satisfying the following:

        • near-continuity property: whenever . (The in the former uses Manhattan distance.)
        • antipodal property: .
        • boundary condition: for all and .

        And the goal is to show that has a near-zero, i.e., some such that . (In my code, you can see the definition of in the comments: its two coordinates are scost and bcost.)

        We can think about a continuous version of this, where the indices and are now allowed to have fractional values, and extend into a continuous function in a somehow "tame" way. The claim is that this extended has a zero. If this is true, then I'd think that the original, discrete version of must also have a near-zero nearby (...maybe, haha; alternatively, maybe the proof of the continuous version can be adapted to the discrete one) which is what we want.

        Thus, we seem to need to know the topology of "subarrays of a circular array". Well, I think it's a sphere! Map the subarray to the point on the sphere with longitude and latitude . Then we can check that:

        • This respects the fact that only makes sense mod (because replacing with doesn't change things);
        • and map to antipodes;
        • empty subarrays map to the north pole, so the boundary conditions are satisfied. (Their complements map to the south pole.)

        So Borsuk-Ulam applies, and (the extended) has a zero.

      • 20 hours ago, # ^ |

        Rev. 2  

        +16

        Now, for a proof of the number of queries, we have two quantities at every step:

        • The number of indices such that . Let's call this .
        • The number of indices such that . Let's call this .

        Here, we only consider "alive" indices, i.e., those that may still contain the target value. Initially, and are .

        Then, assuming that we are always able to perform a query on a subarray such that:

        • it kills roughly half the indices;
        • it splits the indices roughly equally into the two kinds;

        then we have the recurrences and . (This is what the find function accomplishes; it looks for a subarray that will do this.)

        This then means that the sum decays with a factor of roughly at each step.

2 days ago, # |

Can anyone accurately explain what is asked in Div2 D? I am not getting what probabilities do here since it is about summing values. Also at the start of each excursion are we summing all f or just the pair involved in that excursion?

  • 2 days ago, # ^ |

    Expectation is one of the core application of probability.

  • 2 days ago, # ^ |

    You could sum up all the values time their probabilities respectively to get the expectation value.

  • 42 hours ago, # ^ |

    Rev. 2  

    0

    They asked us to sum up the pairs involved in the excursion. The question is so poorly worded that I had the same doubt during the contest.

  • 38 hours ago, # ^ |

    I don't get it either. I get 7/9 but how does it relate to 777777784?

    • 38 hours ago, # ^ |

      They want you to kind of find exact values of p and q in p/q. There might be a possibility that you simulate the process and find average according to it or something (then you get the approximate answer by remaining well within the constraints or something). They don't want that, they want you to use math to find the expected value and not implement the selection process in it's entirety.

      • 38 hours ago, # ^ |

        Yeah, so what should I output? It says calculate p/q mod (1e9+7) but p/q is a fraction, and according to my knowledge the modulo operation is only valid between two integer operands. Btw based username :)

        • 37 hours ago, # ^ |

          You are to output modulo of times Modular inverse of .

          • 36 hours ago, # ^ |

            Thanks, I'm new here. I thought -1 was an exponent.

            • 20 hours ago, # ^ |

              It kind of is, if p/q were an integer less than 1e9+7, It will be equivalent to p/q.

2 days ago, # |

div2D another solution.

let X be the sum over all friendship values and N be the number of pairs (which is n * (n — 1) / 2). now consider taking random pair of people from 1 to k. what is the expected friendship value at iteration 1? obviously, it is X / N. what happens then? with probability p = m / N we will take a pair of friends, so we should add +1 to our X, with probability 1 — p we will take a pair of people who aren't friends, so we add +0 to our X. it means that we should increase our X by p * 1 + (1 — p) * 0 = p and continue iteration.

you can check my submission here: https://codeforces.com/contest/1925/submission/243687166

  • 47 hours ago, # ^ |

    Much concise and clearer than the tutorial, thank you for your explanation!

  • 39 hours ago, # ^ |

    Concise and efficient!

2 days ago, # |

Rev. 2  

0

Can anyone explain the intuition for the GCD properties given in problem B. I got the idea by realizing that for a number k that divides x, you can divide the Ks x/k times over the n spots. Therefore, the answer is the maximum divisor k such that x/k>=n.

  • 2 days ago, # ^ |

    It took me a while to see it too. But I guess if you have a,a,a,a,a...a,(x-(num)*a), we want the last term to be a multiple of a. Then you can kind of see that a has to be a factor of k

  • 46 hours ago, # ^ |

    Rev. 5  

    +5

    You can think like this: You want to split into so as to maximise subject to the constraints that and .

    Let , then . Hence must divide . So, you can basically iterate over all factors of in time complexity, and take if , as each , so . Where, is just the residual when is divided by .

    Here's my submission for reference :)

    • 18 hours ago, # ^ |

      what is k in your solution , k1+k2...kn , i didn't understand that

      • 17 hours ago, # ^ |

        Oops, I missed it in my explanation:

        So, if is of , that means (definition of a divisor). Also, since , this gives us the condition . I hope, it is clear now :)

        You can ask if you have any other doubts.

2 days ago, # |

Rev. 6  

+142

As the solution of D1C is currently missing, I'd like to explain my solution:

Consider the paper lying flat on a table. The paper has two sides, gray and orange (according to the picture), with gray being originally on top. On every move, the crease lines we make are valleys, but for all layers with orange on top, these valleys actually become mountains once unfolded (since gray ends up on top).

After the first fold, at every point in time and at every point in the paper, there are an equal number of gray and orange layers on top of each other. This is because after the first fold, exactly half of the single gray layer was folded to orange and now there is one layer of both. After every subsequent fold, the balance will stay as all layers are treated equally.

Since an equal length of crease lines is created on each layer of the paper, this means that every round of folds after the first one creates an equal total length of new valleys and mountains. The length of valleys created in the first round of folds is . Thus, always holds.

What is the total length of crease lines created on iteration ? Each crease line is times the length of a crease line on the previous iteration, but the number of layers of paper doubled. Thus, the total length of created crease lines is multiplied by every iteration. Thus, on iteration , the total length of added crease lines is . Exactly half of this, i.e. , is the total length of added mountains (and also the length of added valleys).

On each subsequent round, we add times more mountains than the previous round. Let . Now, for fixed , we have and .

The remaining part of the solution is boring: We can notice that the value of is a geometric sum, we can calculate its value with the formula , where is the first term, is the ratio between consecutive terms and is the number of terms. This also solves as . We need to represent the values of , and finally in a form like with . To do this, we will have to get rid of square roots in denominators. This can get tedious, so the formula can be very helpful. Exact details are left as an excercise to the reader. Splitting even and odd will be useful.

Derivation of the previous formula:

PS, Why is the mod ? Are there some cases where the answer isn't defined modulo or modulo ?

  • 2 days ago, # ^ |

    Very intuitive explanation. I saw the question and thought there must be a numberphile videos on this.

  • 2 days ago, # ^ |

    Yeah I did the same. I also wrote a struct to store which was very convenient and easy to debug.

    struct node{
    	int x,y;
    	node(){x=y=0;}
    	node(int xx){x=xx;y=0;}
    	node(int xx,int yy){x=xx;y=yy;}
    	node inv(){
    		node z;
    		z.x=x;
    		z.y=(mod-y)%mod;
    		int a=x*x-2ll*y*y%mod;
    		a=(a%mod+mod)%mod;
    		a=poW(a);
    		z.x=z.x*a%mod;
    		z.y=z.y*a%mod;
    		return z;
    	}
    	friend node operator +(node x,node y){
    		node z;
    		z.x=(x.x+y.x)%mod;
    		z.y=(x.y+y.y)%mod;
    		return z;
    	}
    	friend node operator *(node x,node y){
    		node z;
    		z.x=(x.x*y.x%mod+x.y*y.y*2ll%mod)%mod;
    		z.y=(x.x*y.y+x.y*y.x)%mod;
    		return z;
    	}
    	friend node operator /(node x,node y){
    		y=y.inv();
    		return x*y;
    	}
    };
  • 2 days ago, # ^ |

    is the largest prime number under under which is a quadratic non-residue.

    • 45 hours ago, # ^ |

      I might be missing something very simple, but why do we want 2 to not be a quadratic residue? Why would the existance of "sqrt 2 under modulo" be a bad thing?

      • 44 hours ago, # ^ |

        Answer is not defined if sqrt 2 exists (a + b root 2 can be written with other values of b)

        • 44 hours ago, # ^ |

          But the statement doesn't say "find , for which ", it says "find , for which ". The fractional value of is well defined regardless of the modulus used since it is defined by equality, not congruence under modulo. This means that the value of under modulo is well defined unless , where , and .

          If instead, your argument is that "sqrt 2 doesn't exist under modulo it is harder to misunderstand the problem", then I think I can agree with that. But I still wouldn't change the modulus to something non-standard for this reason.

          Or am I wrong?

          • 41 hour(s) ago, # ^ |

            You are correct, idk the reason either now

            • 37 hours ago, # ^ |

              Rev. 2  

              +11

              Maybe because (the denominator) can be ?

          • 36 hours ago, # ^ |

            This means that the value of under modulo is well defined unless , where , and .

            So let's test this theory. If you take the math to its natural end you will find out that the value of such that is exactly, with no modulo reductions:

            Where and . Since is always either or it's easy to check that no big prime can divide both and , and thus no big prime can divide both the numerator and the denominator either. So we require to never be divisible by for our modulo of choice . Assuming is nonzero modulo this gives

            So there you have it, as long as $2$ is a quadratic non-residue modulo we are guaranteed to be able to compute the answer. Since is a quadratic residue for both standard choices and , this seems to me like a good enough reason to change the modulo.

            However, you might argue that even if is a quadratic residue, that doesn't mean that the answer is impossible to compute. After all, and are something specific and not whatever you want them to be. So let's go a bit further. I'll focus on the case where is even and therefore . Then

            And so we want

            To never happen. We know $8$ is a quadratic residue for the usual primes since is, so choosing for either modular square root of fails. But wait! is not equal to just any number, it must be equal to for some . So in fact we need

            Clearly this is much better, there's nooooo way a power of $2$ just happens to give one of these two random values modulo for both of our standard primes. Unfortunately it just so happens that for both and the order of modulo is , and so passes through every single quadratic residue modulo .

            But there's still some hope! There's no reason both values of have to be quadratic residues... Aaaand it's dead, for and we have that is a quadratic residue. But wait! Both of the choices actually turn out to give quadratic non-residues modulo ! Surely these silly authors should have just gone with that instead of their weird modulo...

            Nope, recall that is only one of the possibilities, we also need to discard . Doing similar math we find that the bad case here is

            Significantly less clean than the previous case, but equally solvable. We now need to check the square roots of $2$ modulo and see if the resulting expression is a quadratic residue. For this turns out to be a non-QR, and for ... wow! also a non-QR! Very unexpected!

            So in summary, while is a no-go, it turns out that the authors could have safely chosen and kept the answer computable. My question for you now is, if you were the author, would you rather go with the non-standard modulo that clearly works, or the standard modulo that basically only works because we won four coin flips in a row and could have easily sent contestants with more number theory experience on a wild goose chase like the one I just sent you on?

            • 35 hours ago, # ^ |

              My question for you now is, if you were the author, would you rather go with the non-standard modulo that clearly works, or the standard modulo that basically only works because we won four coin flips in a row and could have easily sent contestants with more number theory experience on a wild goose chase like the one I just sent you on?

              Now that I understand the reasoning behind it, I would definitely choose the non-standard modulo.

              Your comment seems a little passive aggressive, possibly because of my comments about "this is not a good enough reason to change the modulo", and I don't really like that. I wasn't trying to critisize the problemsetters' choices of modulo; I was just looking for a good explanation for that, and your comment managed to do that. Before your explanation, I didn't know why having 2 be a quadratic non-residue was desirable — now I know.

              Anyway, thanks for the explanation!

              • 35 hours ago, # ^ |

                Sorry if it came off that way, it's definitely a good and valid question and I was mostly trying to emphasize that one of the standard modulos working seems very unlikely at a glance.

2 days ago, # |

Someone pls help me with my submission for C div 2 ... pls help me with the test case being failed ..

i am just checking for every character till kth place , ahead of its first index there must be present at least n-1 characters of each type for an answer..

243690556

  • 2 days ago, # ^ |

    If you are just checking for n-1 occurences of each character ahead it might fail for abcaaabbbccc , n=4 , k=3 a,b,c, all have n-1 occurences ahead of them, but the string can't make all subsequences. I have not checked your code, but this might be the problem in your approach

  • 2 days ago, # ^ |

    Rev. 3  

    +1

    oh,Your approach is the same as mine during the contest, both wanting to use this method to check if there are n abcs This kind of arrangement string. However, this idea is problematic

    For example, aaabbbcccaaabbb

    You will find that there is no substring like CBA, but the result obtained using the above approach will be YES.

    So the correct way should be to use greed to check.like this

  • 2 days ago, # ^ |

    I think I might used a similar approach and just came to know what was the problem with this approach. if I understand correctly you are checking that if the freq of the character you have right now is let's say x then every character must be present n-x times in its suffix, but the problem is that we are not considering the order of the characters in this approach, that's why this will give the wrong answer.

2 days ago, # |

Rev. 2  

0

Can I solve B without divisors way?

2 days ago, # |

Hi for D cant we just directly put the values and answer in O(1).

Using pnc we get expected value = [((k*f)*(nC2) + (k*(k-1))*m/2]/(nc2)^2 ?

  • 2 days ago, # ^ |

    I was getting wrong answer for test case 6. I think the limits just go boom. Can someone check the code and point where is the thing going wrong?

    • 3 hours ago, # ^ |

      Do all the math in this problem with long long instead of int. Otherwise you WILL have overflow in the multiplications.

      • 3 hours ago, # ^ |

        Ah i defined int as long long. I didn't take mod for f sum so it overflowed

2 days ago, # |

Rev. 2  

+4

I have a dp solution for 2C/1A.

Let dp[i][c] be the largest n such that any string of length n ending with c is a subsequence of s[1…i].

We have two relations

dp[i][c] = dp[i-1][c] for c != s[i]

dp[i][s[i]] = max(dp[i-1][s[i]], min(dp[i-1][c]) + 1); c = a, b, …

Now we know the answer is “NO” if and only if there exist c such that dp[m][c] < n. Choose that c as the last character in our answer, and continue doing this again. Now we can construct the solution from the back, then reverse it to get the answer.

  • 2 days ago, # ^ |

    I also came up with same idea but got stuck at printing the non occuring subsequence . But finally again tried an hour ago and solved it.

2 days ago, # |

Can anyone explain the formula in Div2D?The tutorial is like not writing it.

  • 46 hours ago, # ^ |

    Rev. 2  

    +15

    Expectations can be tough to think about. Here is a mathematical proof for Div2D [Note that it requires basic understanding of probabilities and expectations]:

    Let pair 1 occur times, pair 2 occur times pair occur times in the excursions. Let be the total contribution of pair to the total friendship. Hence, if total friendship is

    subject to . Here, each is a random variable which takes value in the range .

    Clearly, using linearity of expectation [even though 's are contrained]. This is the power of linearity of expectation.

    What is ?

    If pair occurs times in the excursion. So, the contribution is . Which can be simplified to .

    It is easy to find = .

    How to simplify this?

    For each the answer is just =

    Note that .Idea, is that there are places. You have to reserve places. In each of the places, where you place the pair the probability is and in the remaining places where you don't, the probability is . You can then multiply be . And, also is .

    So, for each the answer can be expressed as where and can be precalculated as they don't depend on .

    This gives the proof behind expression used in the editorial.

    Submission: here

2 days ago, # |

Div2 is pretty good for me, though why is Div2C reused as Div1A? I think that's a pretty cheap move, you know...

  • 2 days ago, # ^ |

    ain't that always how it is for same round but separate division?

    • 2 days ago, # ^ |

      Oh wait, I didn't realize this. Tks

2 days ago, # |

my submission Logic I am trying to make blocks which have k smallest character greedily.

It's failing on test case 2, can anyone tell me what's wrong with my logic, code is self explanatory

  • 2 days ago, # ^ |

    int pos = find(all(v),1)-v.begin();
    ans += pos+'a';

    bro this part is wrong you should add last character of the block but you adding the first character from block which has count 1,let for k=3 block is "abbc" you should add 'c' but you adding 'a'. replace above two lines with

    ans += s[i] ;
    • 47 hours ago, # ^ |

      Thank you, but adding s[i] means that this character will definitely have a frequency of 1, but I am adding the character that also have a frequency of one,so how does it affect the final answer.This part is not clear by me. Can you please explain this, or just give me counter test case it would be much helpful.

      • 47 hours ago, # ^ |

        Let n=2 , k=3 , s="abbcab" In this 1st block will be "abbc" and 2nd block which is incomplete will be "ab" In 1st block you adding 'a' instead of 'c' , because 'a' also have count 1 and find function returns iterator of first matched element. Your logic giving ans "ac" but it is present and ans should be "cc".

        • 47 hours ago, # ^ |

          Thank you so much!

2 days ago, # |

In div2B "The maximum GCD that can be achieved is always a divisor of x" . Can anyone please explain why is that? I'm not getting this point.

  • 2 days ago, # ^ |

    gcd(a1,a2,a3...an)=gcd(a1,a1+a2,a1+a2+a3,...,a1+a2+a3..+an) so at the end we get sums of all sub problems which is just x so answer is gcd(a1,a1+a2,....,x) so ans is always divisor of x .

  • 2 days ago, # ^ |

    Consider an array of numbers .

    Let be the greatest common divisor (gcd) of all these numbers.

    Since every number is a multiple of , we can express each number as follows:

    where are positive integers.

    The sum of these numbers is:

    Therefore, should be a factor of .

    And here all 's are positive integers so hence we have to find smallest factor of that is greater that or equal to ,say

    Then is our required

2 days ago, # |

Why div2 D must take the probability modulus, and can not be expressed as a decimal like normal problems, and give a precision requirement?

2 days ago, # |

Rev. 2  

-10

Why so many math problems

  • 39 hours ago, # ^ |

    It's a math website

2 days ago, # |

For 1D,I have a easier solution.243652894

  • 2 days ago, # ^ |

    By the way; it is 2D. Can you please explain your solution?

    • 2 days ago, # ^ |

      We can treat each pair of friends separately. Regardless of the pair of friends, the probability of selecting them is .

      At the jth excursion, if the ith pair of friends is selected, then its contribution to the answer is , where is the expected value of having selected the ith pair of friends earlier, and we get . Then if we are not sure if the ith pair of friends was selected (the probability of selection is ), the contribution of the ith pair of friends to the answer in the jth tour is .

      Combining the contributions to the answer from the i-th pair of friends in the kth excursion, the

      After the contribution of the ith pair of friends to the answer has been counted, the answer is obtained by adding up the contributions of each pair of friends to the answer.

      This is the result.The time complexity is $O(t\log MOD + m)$.

      Look here.It's my new solution.243708880

2 days ago, # |

In Problem "2D. Good Trip" Tutorial,

Shouldn't it be "x Choose k" inplace of "k Choose x"?

2 days ago, # |

Can someone help me in finding what did i do wrong in 2C

243641202

i was trying to make the ith letter x by checking is every combination of previous letters is possible or not

2 days ago, # |

Rev. 3  

+4

For Div2D, each excursion increases the expected friendship value of every (non-zero) friendship pair by , where = . So the expected friendship value of the -th pair after excursions is . So the expected friendship value of the pair picked after excursions (i.e. for the -th excursion) is .

Using this, we can come up with a straight-forward formula for the answer:

Which simplifies to:

Code : 243709626

2 days ago, # |

Rev. 3  

0

For C I created a dynamic programming solution : Can someone verify as I am getting TLE on test 3..

dp[i][L] = 1 (if we can make all possible strings of length L using characters 'starting' from index i) else 0 Now we can loop over every character find the smallest index greater than i where it occurs using a character-set map . Say,the smallest index greater than i is ind, (if it doesnt occur we can make dp[i][L] =0) . So, if dp[ind+1][L-1] is true that means we can make all strings possible starting with the character I am currently checking.

As the time complexity is 26*26*O(m) , it wont pass however I was interested in its correctness.

243709963

2 days ago, # |

Why does the submission for 2C TLE? 243710719 Isn't the time complexity which should pass within the time limit?

  • 2 days ago, # ^ |

    The sum of m over all test cases is mentioned to have an upper bound of 10^6 so it wont pass

2 days ago, # |

Problem B

Can someone kindly explain why the condition for the loop is i*i<=x?

  • 2 days ago, # ^ |

    Rev. 3  

    0

    we want to check divisors . for each divisor , we also check , because it will be another divisor of , and we don't need to check any divisor , all of them were already checked.

  • 2 days ago, # ^ |

    To Reduce TC:

    if i is a factor then x/i is also a factor, similarly for sqrt(x).We need to loop till sqrt(x) because all factors after it had already been taken [ by (x/i)]

2 days ago, # |

i thought in div2c we have to print string which contains all the subsequence which is not present in original string

2 days ago, # |

Can some please explain why the following solution doesn't work for problem C

Your code here...

#include <bits/stdc++.h>

#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds; 
  
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> 


using namespace std;

#define ll long long

const int mod = 1e9 + 7;

template<typename A, typename B>
ostream& operator<<(ostream &os, const pair<A, B> &p) {
    return os << '(' << p.first << ", " << p.second << ')';
}


template<typename T>
ostream& operator<<(ostream &os, const vector<T> &v) {
    if (!v.empty()) {
        os << v[0];
        for (int i = 1; i < v.size(); i++) {
            os << ' ' << v[i];
        }
    }
    return os;
}


template<typename T>
istream& operator>>(istream& is, vector<T>& v) {
    int n;
    is >> n;
    v.resize(n);
    for (int i = 0; i < n; i++) {
        is >> v[i];
    }
    return is;
}


template<typename T>
vector<T> readList(int n) {
    vector<T> values(n);
    for (int i = 0; i < n; i++) {
        cin >> values[i];
    }
    return values;
}

void check(string& s, int n, int k) {
    int sz = s.size();
    
    vector<vector<int>> memo(sz, vector<int>(k, 0));

    memo[0][s[0] - 'a'] = 1;

    for (int i = 1; i < sz; i++) {
        for (int j = 0; j < k; j++) {
            memo[i][j] += memo[i - 1][j];
        }

        memo[i][s[i] - 'a'] += 1;
    }

    set<char> visited;

    for (int i = sz - 1; i >= 0; i--) {
        if (visited.count(s[i])) continue;

        visited.insert(s[i]);

        for (int j = 0; j < k; j++) {
            if (memo[i][j] < n - 1) {
                cout << "NO\n";

                char ch = j + 'a';

                string result(n - 1, ch);

                result += s[i];

                cout << result << "\n";
                return;
            }
        }
    }

    cout << "YES\n";
}

void solve()
{
    int n, k, m;

    cin >> n >> k >> m;

    string s;

    cin >> s;

    vector<int> count(k);

    for (char ch : s) {
        count[ch - 'a']++;
    }

    for (int i = 0; i < k; i++) {
        if (count[i] < n) {
            cout << "NO\n";

            char ch = i + 'a';

            string result(n, ch);

            cout << result << "\n";
            
            return;
        }
    }

    check(s, n, k);
}


int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;

    cin >> t;

    while (t--)

    solve();
}
 

46 hours ago, # |

Observation in div2. D: all the sums of expected values of every friendship increases in a pattern: if n = 3, m = 1 and there is a bond of 1 between 1 and 2, in the first turn the expected value is 1 * 1/3 = 3/9. In the second turn, 2 * 1/9 (increased) + 1 * 2/9 (still) = 4/9. On the next turns it goes like 5/9, 6/9 and so on. The contribution of every bond can be calculated in O(1).

45 hours ago, # |

Solution for Div-2 C is giving wrong answer in test case: 1 4 3 12 abcaccabcabc

Output: NO aaaa

As it is clearly visible 'aaaa' is a possible subsequence

  • 45 hours ago, # ^ |

    Output is NO cbba

45 hours ago, # |

243618528 can someone point out as to why this is failing on pretest 2? My thought process was that since we need atleast n occurences of a character in a string to count that , also there could be a case where a character may not be present in the string at all. So i found which characters among the first k were present.

45 hours ago, # |

There should be at least one testcase in the pretest which can cause TLE or a large testcase should be added on the pretest. I got passed in the pretest section of B simply on the first attempt and didn't came with another try for optimized solution, which caused tle on the system testing.

45 hours ago, # |

problem B is a subproblem of problem 803C - Maximal GCD.

45 hours ago, # |

E's solution k got declared as int while the bound is <= 1e12. Even in the test case there is some test with k >= 1e10. I submitted the code and it actually worked ?

  • 45 hours ago, # ^ |

    Oh sorry didn't see your #define there

45 hours ago, # |

Rev. 3  

0

Hi, I don't know if it's legitimate to ask for this but yesterday I got a tle on the div2 E 243653603

However, submitting the exact same code in C++ 64bits makes it ac (in 1sec). 243744788

Please, would it be possible to get a rejudge ? Also if anyone knows why C++ 64 bits is that much faster, I'll gladly take it (the last time I used C++ 64 bits, I got tle because of it...).

Thanks by advance for the help

JaySharma1048576

  • 45 hours ago, # ^ |

    Iirc when you're doing many operations with 64-bit integers, 64-bit compilers are significantly faster. I believe 64-bit compilers are faster (or at least not slower) most of the time. Where did you get tle with 64-bits and ac with 32-bits?

    Also, this has happened to quite a few people before and I don't think anyone has gotten a rejudge, so you're probably out of luck.

    • 44 hours ago, # ^ |

      Rev. 3  

      0

      Thanks for your answer, it sounds like a reasonable explanation.

      In this problem 1250B - The Feast and the Bus I got tle in C++ 64 (243748301) and ac in C++ 17 (243748727). I also have a friend who got tle for similar reasons on a shortest path problem I think ? I'll try to find it but it was a long time ago

      By the way, if the runtime can change that much, during the testing phase, can't they try to submit solutions in both C++ 64 bits and 32 bits to avoid such things happening ?

      • 44 hours ago, # ^ |

        Here is your code with removing #define int long long and chaning one int to ll https://codeforces.com/contest/1925/submission/243752795

        Gets an AC with C++ 17, not very strong though (because there are still a lot of lls)

        • 43 hours ago, # ^ |

          Oh thanks ! I wouldn't have thought that changing only a few ints to long long would make such a difference as most of the operations are in the segtree

44 hours ago, # |

What is wrong with my logic for div 2D?

Each of the pairs of friends has a probability of being chosen times over the excursions. Then, the expected value can be calculated by summing for all . (This is by using sum of arithmetic series).

  • 43 hours ago, # ^ |

    Rev. 2  

    0

    You are looking for the probability of a pair being chosen a fixed number of times (probability that the pair gets selected i times).

    What you are doing is just like, wrong

    I would recommend you to learn a bit about expected value (definition, linearity) and to do things more formally. You want E(S) where S is the sum of friendship values of all k pairs chosen for the excursions.

    S = X1 + ... + Xm where Xm is the sum of friendship values of pair i (over all the excursions it was chosen for).

    By linearity: E(S) = E(X1) + ... + E(Xm)

    Now, to compute E(Xi) you can fix how many times the pair i has been chosen and you end up with a simple sum to compute (which is a bit similar to what you sent, except you need some binomial coefficients for the probabiltiy).

    • 42 hours ago, # ^ |

      First of all, thank you for the reply. Sorry, but I don't understand what you mean by "fix how many times the pair i has been chosen". Could you provide an example of calculating using "binomial coefficients for the probability"?

      Thank you very much.

      • 40 hours ago, # ^ |

        Rev. 7  

        0

        So let's consider pair i.

        (I technically skipped a step here, but overall it's just partitioning the events depending on how many times the pair i was chosen).

        And (which has a closed form that you pointed out in your original comment)

        Now, you are looking for which actually follows a binomial law.

        If you don't know what that is, I'll just try to explain intuitively: - you have probability for the pair i to be chosen at a fixed excursion

        • so if you fix the excursions at which the pair i is chosen, the probability to be chosen exactly at these excursions is

        • you have ways to chose the excursions at which the pair will be chosen

        So overall,

        • 33 hours ago, # ^ |

          can u explain div1 B ?

44 hours ago, # |

Problem D can also be solved in . See here.

44 hours ago, # |

Rev. 2  

0

2 line Solution for Div 2D

Code

43 hours ago, # |

C is really hard for me. Frustrated : (

42 hours ago, # |

2D has a direct formula.

Let , which denotes the number of pairs of children, and , which denotes the sum of friendship among each pair of friends in the beginning.

In each round, the probability of choosing a pair who are friends is .

Then, after rounds, the expected value of increase is , so the expected value of sum of friendship among each pair of friends is . Then, the expected value of friendship of the chosen pair in the -th round is .

Therefore, the answer will be . It can be calculated using constant time.

  • 42 hours ago, # ^ |

    Great solution. I didn't notice that sum of is bounded in the problem statement. So although I came up with an ( is the modulo) solution, I didn't think it could pass and did not submit. So I tried to transform my original formula (which is similar to the expectation of a binomial distribution) into a direct formula through an algebraic way during the whole contest. Of course I failed. Now I realize that I should use an alternative explanation to form another simpler formula instead of transforming the original formula directly.

42 hours ago, # |

I have just done D to upsolve, should have read that in contest. I recently solved a problem 1761F1 - Anti-median (Easy Version) and used this as a subproblem to get sequences in which there will definitely exists a k regular bracket as subsequence. :(

42 hours ago, # |

Anyone using sqrt decomposition to solve div2 problem E? I divide the sequence into blocks, with each block at most length (the last block is cutoff to a lower size). Then for each insertion of harbour, I find its left harbour and right harbour and then update the blocks in ; for each query , I also retrieve the information in blocks in . I think it should cost and should get passed. However I got time limit exceeded: https://codeforces.com/contest/1925/submission/243770890. Could anyone help?

  • 23 hours ago, # ^ |

    is too large for this problem because and the constant is not small enough.

    It is much better to process a problem with interval assignments and interval queries using a segment tree which has time complexity than a block array which has time complexity .

    • 23 hours ago, # ^ |

      Thanks!

41 hour(s) ago, # |

I have to admit this was a great contest. Unfortunately in Div 2 B i forgot to check sqrt(n) and only checked everything else , noticing this costed me 40 minutes but im glad i solved it anyway.

41 hour(s) ago, # |

Can anyone please explain div2E?

Thanks in advance.

  • 32 hours ago, # ^ |

    Rev. 3  

    0

    Spoiler
    • 25 hours ago, # ^ |

      thanks bro

40 hours ago, # |

Can anyone give a counterexample or explanation why this solution doesn't work? https://codeforces.com/contest/1925/submission/243789503

  • 26 hours ago, # ^ |

    Rev. 3  

    0

    Input
    2
    3 2 6
    babbaa
    2 1 3
    aaa
    
    Expected
    NO
    aab
    YES
    
    Produced
    YES
    YES

38 hours ago, # |

Nice explanation

38 hours ago, # |

Can somebody please provide an inductive proof for Case 2 of 1D?

35 hours ago, # |

Rev. 2  

0

Problem E: My submission (WA on test 8)

My approach:

▶ Calculate the initial cost for each N ship and build a segment tree on it.

▶ Say a new harbour is built at position and value . Say The nearest left neighbour is and the nearest right neighbour is . Then the cost of ships in the segment is decremented by , and the cost of ships in the segment gets multiplied by .

▶ I used lazy propagation for range multiplication/division and addition.

Can someone point out the mistake?

  • 26 hours ago, # ^ |

    Take a look at Ticket 17298 from CF Stress for a counter example.

    • 23 hours ago, # ^ |

      Thanks. Why is this one failing?

      • 20 hours ago, # ^ |

        Take a look at Ticket 17306 from CF Stress for a counter example.

  • 20 hours ago, # ^ |

    how are differentiating whether addition was performed first or multiplication ?
    order matters here right?

    • 18 hours ago, # ^ |

      Rev. 2  

      0

      I am storing the lazy values for each node of the segment tree, which means that we must multiply the value at that node with first and then add (r — l + 1 is the length of the segment covered by node) to it, i.e., . Now let's say we are pushing the lazy information of a node, say to its child with lazy information then we can observe that becomes . Hence, we can accordingly modify the lazy_multiply and the lazy_add values. ( NOTE: The identity for lazy_multiply and lazy_add are 1 and 0 respectively. Since we also need to do the division operation, there is also a lazy_div for each node in actual implementation. )

      • 13 hours ago, # ^ |

        t[l].lazy_add = (t[l].lazy_add / t[id].lazy_div) * t[id].lazy_mul + t[id].lazy_add
        You are rounding values here. t[l].lazy_add may not be divisible by t[id].lazy_div

        • 12 hours ago, # ^ |

          Observation: is always of the form and t[id].lazy_div is always a divisor of so there will be always an exact division.

  • 12 hours ago, # ^ |

    it works i do it in same way. code

    • 12 hours ago, # ^ |

      Thank you for letting me know that it's correct.

      How did you handle division without a lazy value for division? And why did you take mod? The original problem wasn't asking us to print the answer modulo M.

      • 12 hours ago, # ^ |

        I guess the problem in your solution is that the lazy division values can overflow if multiple updates are stacked on top of each other without pushing further. tmpzlp's solution uses a big prime modulo larger than the largest possible answer, and this solves all of your problems:

        • Since the modulo is larger than the largest possible answer, the value reduced modulo will be correct.
        • Since the modulo is prime, we can perform division via multiplication by modular inverse. Now we don't need a separate lazy division variable (since division is now multiplication) and the values won't overflow since we reduce them in modulo, though __int128 needs to be used for multiplication.
        • 113 minutes ago, # ^ |

          Got it. Thank you, sir. Btw, such a cool usage of __int128 ^w^

35 hours ago, # |

Can anyone explain in 2B, why we need the condition n <= i? I'm not knowing what case it works for

  • 32 hours ago, # ^ |

    Rev. 2  

    +5

    We are just walking from 1 to sqrt(x)

    When x divides i, that means there are 2 divisors of x, not just one -> i , x / i

    The first condition handles the first divisor and the second handles the second

    • 13 hours ago, # ^ |

      so the factors of x that are greater than sqrt(x) are just the same product we have seen before sqrt(x) but written vice versa?

      like if we have seen (a*b) before square root it's the same numbers repeating again but in reverse like b*a?

      • 13 hours ago, # ^ |

        Exactly.

        If it's a new concept for you, you should study number theory.

        • 13 hours ago, # ^ |

          Sure, will do

28 hours ago, # |

How to solve Div2E/Div1B? Still waiting for the editorial :\

  • 26 hours ago, # ^ |

    Rev. 2  

    +6

    My solution:

    For each harbor I keep the sum of distances of every ship between this harbor and the next harbor. I can do it using a std::set maintaining the positions of all available harbors. Now i put the mentioned value for a harbor at position x inside a Fenwick tree ( the xth number in the Fenwick tree, if there is a harbor at position x, contains the value of that harbor). Now let's talk about answering each query, in each query i First take the sum of all values of harbors inside that segment. It's really easy to see that there are some ships in the segment that I'm not counting their distance but I should, and there are some ships outside that I'm counting their distance but I shouldn't. I can calculate these missing/extra values using the std::set we maintained above. It is a bit mathy, so I recommend taking a look at my implementation to understand it better: 243623915

    • 23 hours ago, # ^ |

      Your method doesn't require lazy propagation. Great.

      Can you please tell me if this approach will work? (Although it is a bit messy to implement)

27 hours ago, # |

Can anyone tell me what's wrong with my code on Problem C. I compared it with the editorial and think they are the same, but I got WA. https://codeforces.com/contest/1925/submission/243847499

24 hours ago, # |

For the Div2 D, for considering the incremental sum of pairs, why they have assumed that for a excursion only 1 pair can be repeated and they only accounted that pair repeated k x times, and multipled the whole by m? Why can't 2 or more pairs be a part of excursion considering that sum and probabilites would change and the final solution would also, right?

21 hour(s) ago, # |

Can someone tell me how to determine the time complexity of div 2 b?? according to the constraints if feels like O(n) solution to work since n<=1e8 but my O(n) solution gives tle?? here is the solution 243588276

  • 19 hours ago, # ^ |

    You have to consider the number of test cases also

    • 15 hours ago, # ^ |

      I haven't had any problems like this before and i have never considered the number of test cases before as well, is this because in most problem there is a statement like:- "It is guaranteed that the sum of n and sum m over all test cases does not exceed 1e5 and the sum of k over all test cases does not exceed 2⋅1e5." While this question didn't??

      • 14 hours ago, # ^ |

        Yep that's exactly the reason

15 hours ago, # |

Please help me in identifying the mistake in my code. Do you have any counter example for this? Getting wrong answer on test case 3639 of test 2. Submission

14 hours ago, # |

Will we see solutions?

  • 8 hours ago, # ^ |

    The editorial for 1C has been added. Unfortunately, there was an Indian ICPC Regionals contest the very next day of this contest and all three of us were judges for that contest. We didn't get any time on Sunday to write the formal tutorials in the editorial and the author of 1B and 1E was busy today. Hence, the delay.

13 hours ago, # |

I think there is a little mistake in the constants in d1F editorial.

Div1F spoilers
  • 8 hours ago, # ^ |

    Rev. 2  

    +10

    Yeah, you are right. I probably messed up something while writing the editorial. But it was an editorial-only bug. The constraints in the problem are correct and according to the better bounds found by you. You can check that which is according to the value of and not .

    And yeah, the solution works only after rounding. There is a buffer of just query between the constraints and the calculated bound so you have to be quite precise.

    • 8 hours ago, # ^ |

      Actually, surprisingly my solution with the incorrect constant passes the tests when always rounding down (243937391), even though theoretically it should fail. I guess it is hard to kill solutions with slightly suboptimal constants at high values of , as sometimes you'll get lucky and get 3 queries when the worst-case is 4.

13 hours ago, # |

Rev. 2  

0

unable to understand why they are doing this in div2B

if(n<=i){ ans=max(ans,x/i); }

edit: nvm for anyone with the same doubt check this explanation https://codeforces.com/blog/entry/125137?#comment-1111266

13 hours ago, # |

Problem C's solution was very nice, but may be very difficult to prove. But, it made me wonder if authors prove their "greedy" solutions or not? And this is NOT to criticize the editorial. I was wondering if there have been cases where an author came up with a problem, which had an obvious greedy solution but later came out to be wrong because someone came up with a test-case where it didn't work. Maybe experienced participants can tell.

Otherwise, if every author proves their greedy problem I believe they should post their proofs as well. It will benifit others a lot. Since, greedy is something which doesn't come naturally to everyone and a lot of competetive programmers struggle with it. If something reduces to some standard greedy, then it's okay. But in other cases a proof should always be present in my opinion. That would at least guarantee that someone doesn't hack the author's solution

  • 13 hours ago, # ^ |

    Rev. 2  

    0

    I was wondering if there have been cases where an author came up with a problem, which had an obvious greedy solution but later came out to be wrong because someone came up with a test-case where it didn't work.

    This probably happens every now and then during the problemsetting process — usually this would be noticed during stress testing. But sometimes shit happens and these mistakes aren't caught, even with stress testing. For example Codeforces Round 846 (Div. 2) had a problem C with an intended greedy solution, but it turned out to be incorrect. The round got unrated and the problem was deleted as it was unsolvable with the given constraints.

  • 75 minutes ago, # ^ |

    Well, I do have a proof for 2C/1A. It is easy and intuitive so I felt it unnecessary to explain in the editorial.

    Let the counter-case we are building using the greedy until we reach the end of be and the final counter-case be . There are two things that must be proven:

    1. If , then is not a subsequence of .
    2. If , then all possible strings of length formed using the first English alphabets are a subsequence of .

    Firstly, notice that the greedy algorithm divides the string into some blocks with each block (except possibly the last one) containing all the first English alphabets and where the last character appears exactly once in the block in the end.

    So, if you are aware of the well-known greedy algorithm to check if a given string is a subsequence of another string or not, you can notice that the first character of must match to the last character of the first block of since there is no better choice for it, the second character of must match the last character of the second block of because there is no other choice between the first chosen character and the last character of the second block and so on. Now if , the first character that is in and not in is not present in the last remaining block (possibly empty) of . So, the string subsequence matching algorithm fails and is not a subsequence of .

    Now, if , we already know that is a subsequence of . Now, the character in is the last character of the block of , If you replace it with any other character, it will still be present in the block of since these blocks contain all the first English alphabets. So, no matter what changes you do to the string , it will still remain a subsequence of . This proves the second part.

12 hours ago, # |

Rev. 2  

0

Can someone help me guessing test case where this test solution failed [submission] I have tried all test cases that everyone has commented in the comment boxes

105 minutes ago, # |

In DIV2C / DIV1A while building the counter-case, why is it always optimal to pick the first character as 'the one whose first index of occurrence in the given string is the highest'?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK