### Karavaiev's blog

By Karavaiev, history, 2 years ago, Thanks for participating!

1521A - Nastia and Nearly Good Numbers

Tutorial
Solution

1521B - Nastia and a Good Array

Tutorial
Solution

1521C - Nastia and a Hidden Permutation

Tutorial
Solution 1

1521D - Nastia Plays with a Tree

Tutorial
Solution

1521E - Nastia and a Beautiful Matrix

Tutorial
Solution Tutorial of Codeforces Round 720 (Div. 2) Comments (90)
| Write comment?
 » Karavaiev can you give a proof or some intuition on why the greedy works in problem D ?
•  » » 2 years ago, # ^ | ← Rev. 6 →   We can keep for each subtree of r three states: 1) the minimal solution without r in the initial tree. x1 2) the minimal solution when we add an edge from the root of the subtree to r. x2 3) the minimal solution for (2) that disconnects the root of the subtree and r. x3 always x1 >= x2 >= x3; and x1 <= x3 — 1;for each subtree, if x3 == x1 we will run (3) else if x2 == x1 we will run (2) else, we will run (1) and remove the edge between r and the root of the subtree, which means to run (3).after we run this for each subtree, r is connected to his parent and to some bamboos. to calculate 1, 2, 3 just means to remove some arbitrary edges.x1 == x2 != x3 if and only if the degree of the root is lower than 2. Therefore, we won't remove the edge to the parent only if r is connected to less than 2 childrens and we receive the greedy solution.
•  » » (1) ensures that we do not break any linear chains (bamboos)(2) is the case of an inverted Y shape. One of the 3 edges needs to be broken.Let's take an edge between 2 nodes A, B: A — B. It can be noted breaking any edge from A, except A-B will not affect any decision on B's edges except A — B. Now, note that the 2 bottom nodes of the inverted Y will be having a degree of atmost 3, because of steps (2) and (3). So, by removing the edge to the parent, we get an inverted V shaped chain.(3) If a node has more than 2 children, all but 2 will have to be removed for a chain. The edge connecting the node and the parent will be removed based on the parent's degree, subsequently in the DFS.Using the independence mentioned above, we can remove any of C — 2 nodes. (C = no. of children) The strategy ensures that only forced/inevitable deletions are done, as an argument for optimality.
•  » » 2 years ago, # ^ | ← Rev. 2 →   Let's say we decide to remove some $k$ edges when we are at a vertex $v$. It is always beneficial to remove the edge from $v's$ parent to $v$ because — removing it can only decrease the answer for the remaining tree
•  » » I can prove why always performing operations on children first and then checking if it is required to break the edge between child and parent is optimal.(and not any other way like breaking arbitrary edges between adjacent nodes with maximum degree).Consider the example below- Example Let the root be node 1. The nodes 1 2 3 5 have degree 3.First of all, note that we first need to remove edges from the set {1-2, 1-3, 2-5} because it will decrease the degree of both nodes simultaneously.Now, which one to choose first? It can be seen that it is mandatory to remove edge 2-5 as node 5 has only this option. Similarly, for edge 1-3. Hence in 2 operations i.e removing edges 2-5 and 1-3 makes the degree of all nodes <=2. Notice that had we removed edge 1-2 first, then still we would have to remove edges 1-3 and 2-5. Hence it is always optimal to start removing edges from the end (children) to the top (root).Don't forget to upvote if it was helpful :).
 » Qs regarding problem D. So we need to remove x edges. But to remove x edges choose cant we use this greedy strategy: choose the vertex x with maximum deg (if its greater than 2). go over adj[x]-choose vertex y with maximum degree. Then let us delete the edge x-y. Continue this process till there are no vertices with degree greater than 2.
•  » » 2 years ago, # ^ | ← Rev. 2 →   Edges: a0-a1, a1-a2, a2-a3, a3-a4, a4-a5, a1-b1, a2-b2, a3-b3, a4-b4 Next vertexes have 3 degrees: a1, a2, a3, a4Optimal solution is to remove a1-a2 and a3-a4 But if you remove a2-a3 on the first step you will need to remove extra two.So you can't randomly pick vertexes with max degrees.
•  » » » Thank you-)
 » My Problem D solution is different, I am in the middle of writing a community editorial for it, will be released soon :)
 » My Solution to problem D: https://codeforces.com/blog/entry/90476
 » 2 years ago, # | ← Rev. 2 →   below is my (not the cleanest) implementation of solution 2 in the editorial of problem C. code here. i also searched for the minimum (or the index that had value 1) instead of the maximum. the idea is the same but the implemention is slightly different.EDIT: i made the code easier to read by removing my template
 » The solution of problem A can also be$A(B-1)+A(B+1)=2AB$since we have$gcd(B,B-1)=gcd(B,B+1)=1$
•  » » Why do you need the gcd condition?
•  » » » 2 years ago, # ^ | ← Rev. 2 →   I think he added the gcd condition to prove that A(B-1) & A(B+1) are not divisible by AB and are nearly good
•  » » » » It directly follows since both are -A and A mod AB.
•  » » » » » Indeed. I added the GCD condition only because that was my first thought, thanks for your reminding!
 » Hey, can anyone tell what's wrong with my solution to problem B? what I have done is to check the gcd of each pair and continue in case its 1 and if its not 1 then replace the larger of the 2 consecutive numbers with the smallest prime number greater than the min of(ai,ai+1) and so on.I have also provided a case for those cases where the primes become equal after changing. In other words, I still can't find an error in my solution. Any help will be gladly accepted. my solution:115610004
•  » » Your first issue is that your 'b' array isn't big enough, as it potentially needs to store 2 * n many things, and therefore doesn't output everything it needs to.However in addition to that, your solution still fails when that is fixed on test cases such as 1 3 77 15 5 as the second element is changes to 7.
•  » » » 2 years ago, # ^ | ← Rev. 2 →   i have found an easy solution for B.AS we don't need to minimize the number of operations, hence we can think of replacing all the numbers by 2 consecutive prime numbers. As the element in the array can go upto 10^9 , our job is to find 2 prime numbers that are just greater than 10^9 which are 100000007 and 1000000009.so just replace the elements with these 2 primes alternatively. codevoid solve(){ int n=0,m=0,k=0,x=0; cin>>n; vi v(n); for(int i = 0; i < n ;i++) { cin>>v[i]; } cout<
 » Another approach for B: Observation : minimum element in the whole array wont be changed. Let the index of min element be 'mn'.Fact : Consecutive elements are always relatively prime.Approach : The idea is to make the array a sequence of alternate integers containing either a[mn] or a[mn]+1, such that a[i] != a[i+1]. There will always be N-1 such operations.eg: a[ ]={9 6 3* 11 15}; ('*' denotes minimum element)after all operations a[ ]={3 4 3* 4 3}. Here's the code.
•  » » I had the similar logic, but I started giving mn + 1 , mn + 2 , mn + 3... to the right as well as to the left of the min element.eg: a[ ]={9 6 3* 11 15}; ('*' denotes minimum element)after all operations a[ ]={5 4 3* 4 5}
 » In 1521A — Nastia and Nearly Good Numbers why a + a*(b-1)=a*b isn't working??
•  » » It does work, except when b is 2 because of the problem asking for 3 unique numbers. See my code for one way of getting around this.
•  » » change it to a + a*(2*b -1) = 2*a*bit solves the problem of 3 unique numbers
 » Hi, I have doubt for question A, I wrote that if B > 2, then z = AB, y = A, x = (B-1)A and if B = 2, I wrote x = A , y = 3A and z = 2AB, and for B = 1 is trivial. Is my solution wrong ?
•  » » z should be 4ab
•  » » » Where do you mean ?
•  » » » » look when b==2 , then x=A , y=3A so z should be x+y so 4AB (B because z should be mutiple of AB) hence when b is 2 so x=A,y=3A,z=4AB
•  » » » » » No even z = 2ab = 4a = a + 3a (since b = 2) is a multiple of AB = 2a
•  » » » » » » ohh sorry! , i didn't notice that , i did same thing as you are saying for b==2 , you can check that out
•  » » » » » » » 2 years ago, # ^ | ← Rev. 2 →   So if my solution is correct, then will I get any score(I am new to this site) ?
•  » » » » » » » » If I were you, I will probably first check the checker log and see if there is any issues with your solution. Also, your solution does not account for integer overflow (when the number exceeds the integer limit which is the case here as A*B can go up to 1e12), so that is why your solution got a WA. You should probably use long long or other 64bit equivalent instead of integer to fix this.
•  » » » » » » » » » Thank you for helping and am I allowed to check the 'checker log' during the contest ?
•  » » » » » » » » » No, it is a feature that is only allowed off-contest, so it would be a smart idea to practice a lot beforehand so that you won't make these types of mistakes.
•  » » I looked at your code and you've got variables of type int, because of that a*b gives you integer overflow, try using long long instead of int and note that instead of %d u should use %lld
 » Also for B, generating 2 primes bigger than the max of array and then replacing every adjacent pair whose gcd is not 1 with their minimum and a prime (one of those alternatively) would work. I find this idea more intuitive.
•  » » This is exactly what I did.
•  » » Why do you need two primes?
•  » » » so that we don't replace two adjacent elements with the same prime number. consider the case 3 3 3
 » Another approach for problem B: Just replace elements at odd or even positions with 1e9 + 7, while maintaining the condition mentioned in problem.
•  » » I'm also doing the same thing, why this does not work?
•  » » » 2 years ago, # ^ | ← Rev. 3 →   Try: {2, 15, 6} You would actually shift '6' from 2nd index to 1st index, and then gcd(2, 6) > 1.
 » Can anyone explain how problem A gives yes when A=2 and B=2 ? I don't find a constraint in the problem that says the given integers are distinct.
•  » » one solution is 2 4 6 . 4 is divisible by (A*B)=(2*2). 2 and 6 are divisible by A=2.
•  » » 4 6 10 is a valid output for A = 2 and B = 2.A number being divisible by A and B does not imply that it will be divisible by A*B. Here 4 is divisible by A*B but 6 and 10 are not (Although they are divisible by B they satisfy the condition for being nearly good)
 » WHAT'S WRONG IN MY SOLTION FOR PROBLEM C ,IT IS GETTING IDLE LIMIT EXCEEDED.CAN ANYONE PLEASE HELP WITH IT https://codeforces.com/contest/1521/submission/115666166(HERE IS MY SUBMISSION)
 »
•  » » You skipped outputting 't'._
•  » » » thank you ,its's accepted now
 » 2 years ago, # | ← Rev. 2 →   My Solution to problem B was different from the editorial. since all Ai<=10^9 and x,y<=2*10^9So i filled MD=10^9+7 in alternate places. That way adjacent number always have gcd=1.let a1,a2,a3,a4....an be the array then print k=floor(n/2) lineseach line four integers i=1;i<=n;i+=2 : i i+1 min(a[i],a[i+1]) MDEg: 5 2 4 6 3 5OUTPUT 2 1 2 2 MD 3 4 3 MDfinal array 2 MD 3 MD 5
 » $C$ can also be done in $4$$\lfloor \frac {n} {3} \rfloor + 2 queries, though my solution uses 3 more queries •  » » 2 years ago, # ^ | ← Rev. 4 → Yes, I think my solution 115611578 also takes around \frac{4\cdot n }{3} in the worst case and n queries in the best case.I restore 3 elements in 4 queries but if I find position of element 1 or n, then I can easily find rest of the elements in 1 query per element. •  » » » omg orz i cant believe somebody actually wrote the bash sol  » problem (A+B) videoEditorial : https://youtu.be/eoG05DnVQik •  » » Isn't pupil a bit too early to create video editorials for others? I think you should wait some time and start doing those when you are very good at them, because only then you can create quality video editorials. •  » » » In fact he recorded the video in between the contest running. Its not a good strategy to just give up on contest when you still have 30 mins remaining with you.  » 2 years ago, # | ← Rev. 2 → in problem D, based on the question shouldn't the ans be just either 0 or 1? question in brief: In one operation: 1. remove any existing edge. 2. add an edge between any pair of vertices. minimum operations to get a bamboo from a tree. solution: case1: if tree is already bamboo ans is 0. case2: we can remove an edge from any leaf node and add an edge between vertices other than the leaf.hence, we got a bamboo(i.e leaf node) from a tree? •  » » we have to make bamboo using all vertices  » Can someone hack this solution for C? I think I have used 1.66n queries in the worst case, n for finding the position of 1 and 0.66n for the remaining elements. In some cases I have used random numbers. •  » » 2 years ago, # ^ | ← Rev. 2 → So I tried hacking it. Consider this TestcaseAt the end we have 2 1 those are the first two numbers you deduce. Then there is this pattern reapeating and increasing: 3 5 4 then 6 8 7 and so forth. This pattern forces your programm to always pass through i -= 3; in your for loop. The last if condition if (val > mn2) then randomly either does a second query or it doesn't. I then started 50 tests with this locally and got these query-amounts: Query Amounts15018 15038 15016 15007 14968 15003 15046 14995 15032 14979 15006 15056 15008 15005 15032 14970 15005 14975 15028 14976 14956 14980 14980 15027 15013 14983 14955 14986 15000 15029 14954 14930 15045 14955 14997 15032 15009 15007 14990 15028 15003 15043 14990 14989 15013 15004 15047 15020 14978 14986Some of the cases would've broken the 3n/2+30 limit. So 3n/2 seems to be some kind of worst case average of your algorithm and I am not sure how to further hack it. •  » » » Thanks. Maybe repeatedly trying to uphack with this test case can work. Also you can include the same case again in a test as the limit on sum of n over all test cases is 2 \cdot 10^4. •  » » » » 2 years ago, # ^ | ← Rev. 2 → Here you go, it's hacked now. :DAlthough I guess it is not a good test case per se, since there are those "+30" free guesses. •  » » » » » Thanks. Those +30 free guesses are there in all test cases, so why is this one not a good case?  » 2 years ago, # | ← Rev. 2 → I have a doubt in question A: Consider the case: 1 87 87 Won't it be impossible to generate three number such that exactly one is good and the other two are nearly good? All three numbers would simply be good?? Am I misunderstanding something?More simple I have doubt when A equals B, shouldn't the answer be NO? •  » » In this case 87 is nearly good. Or 2 \cdot 87. It is not good though, since it is not divisible by 87 \cdot 87$$87 \cdot 87$ is a good number. Or $2 \cdot 87 \cdot 87$So $87$, $(87-1)\cdot 87$ and $87 \cdot 87$ would be a valid solution.
•  » » » Ohh I missed that, I just assumed that A.B meant it should be divisible by A and B both, didn't notice it should be divisible by their product too :(Thanks.
 » for the 2nd problem could a possible logic be that we find the gcd of two consecutive numbers and if it is not 1 then we replace a[i] with the minimum of the two values and a[i+1] with the next smallest prime after a[i]. So for eg if a = 9 6 3 11 15 then after the 1st iteration, we get 6 7 3 11 15, i.e. selecting the 1st two since gcd(9,6)!=1 and then replace it with the min i.e. 6 and the next with 7 (smallest prime after 6). This logic is showing the wrong answer. Can anyone pls let me know the fault?
•  » » Consider the array : [ 2, 9, 6, 3, 11]gcd(2, 9) = 1, therefore continue: gcd(9, 6) != 1, therefore according to your logic it would be replaced with (6, 7)But then, A=2 and A=6 would have a common factor!
•  » » » Here,you can replace 9 as A=A*A+1 but it showing wrong ans,why? https://codeforces.com/contest/1521/submission/115629013
 » hey,can anyone tell what wrong with my solution https://codeforces.com/contest/1521/submission/115629013 Firstly,I take starting of 2 no and if one of them is minimum,let 1 no is minimum than 2 no change to first no +1 but if 2 no is minimum than first no change to x*y+1 where y is 2 no and x is previous no that came befor 1 no in array.
 » 1521A: If A%B==0 then two other numbers which are divisible by A is also divisible by B then all three are good,is that case not considered. Please help if i missed something
•  » » if X%(A*B)==0 then x is good, not if x%b=0 let x=4 a=4 b=2 here, X%(A*B)!=0 x%(4*2) not equal to 0 but x%4=0
 » 2 years ago, # | ← Rev. 2 →   Another easy approach for B is that to change every odd index to the left and right to the minimum element to a prime which is greater than 1e9 . Every element of the array is less than 1e9 and the constraint for choosing x and y is 1 < x,y <= 2e9 .
•  » » thanks,i got it
 » For the task D, editorial gave a nice greedy solution. I did it using DP. But I see flows mentioned in the tag. Can someone explain how do we do it using flows? Thanks.
 » 2 years ago, # | ← Rev. 2 →   Proof of problem $D$ greedy solution:Starting from the deepest nodes, if we have a node $x$ having parent $p$, where $x$ has $k$ leaf children where $k>1$, we know that $x$ at the end should have at most $2$ adjacent nodes anyway, so we give priority to first removing the edge to $p$, as this edge may give the opportunity for $p$ in its turn to remove less edges, while the edges to $x$'s children are guaranteed to not give any such future opportunities. So removing the edge to $p$ will sometimes be better, and in the worst case will be similar to removing one of the children edges. This logic continues to be applicable as we go up the tree.
•  » » 2 years ago, # ^ | ← Rev. 4 →   I had a trouble understanding how "giving priority to removing the parent-facing edge" also works when a node $x$ has non-leaf children; I cannot believe my intuition. Now, I understand it systematically after reading your comment many times.Let's define the problem as finding the set of edges to remove that is of minimum size. Of course, there are multiple optimal solutions. $SS_0$ is the set of such solutions.Starting with the original tree $T_0$ and its nodes that have only leaf children, applying "giving priority to removing the parent-facing edge" on each node $x$ gives us a forest consisting of bamboos and a smaller tree, $T_1$. We now have the set of edges removed from this phase, $R_1$. There exists $S_1 \in SS_0$ such that $R_1$ is a subnet of $S_1$. Why?: For each node $x$ from above, consider the $T_0$ as two trees separated by the parent-facing edge ($e \in R_1$) of $x$. If all $S \in SS_0$ does not contain the $e$ (meaning the $e$ has survived from removal), we can always delete* the $e$ and restore any child-facing edge of $x$, keeping these unchanged, the degree of $x$ and the total number of edges removed. (*Here, delete is meant to "delete from a tree", not "delete from a set") Repeating it, we can transform any $S$ into $S_1$. Let's denote the set of all such $S_1$'s as $SS_1$. For $T_1$ and $SS_1$, we can apply similar reasoning. The only difference is that we pick nodes whose children are linear chains or leaves. A linear chain acts like a leaf.Repeat until $T_i$ reaches the empty tree. We eventually get the optimal solution $S = \bigcup R_i$.
 » Problem D reminds me of a Vietnamese fairy tale — The hundred-knot bamboo :))I'm wondering if anyone of the problemsetter have read this :))
 » i have found an easy solution for B.AS we don't need to minimize the number of operations, hence we can think of replacing all the numbers by 2 consecutive prime numbers. As the element in the array can go upto 10^9 , our job is to find 2 prime numbers that are just greater than 10^9 which are 100000007 and 1000000009.so just replace the elements with these 2 primes alternatively. codevoid solve(){ int n=0,m=0,k=0,x=0; cin>>n; vi v(n); for(int i = 0; i < n ;i++) { cin>>v[i]; } cout<
 » I think Problem E doesn't need to sort. We only need to fill the most frequently occurring numbers x first. Because the order of other numbers doesn't matter. It's easy to prove.my solution
 » 2 years ago, # | ← Rev. 2 →   Can someone explain to me why I am getting TLE in this question. Here is my solution:-https://codeforces.com/contest/1521/submission/115881089I broke all edges as given in the tutorial and then applied bfs to find the endpoints of the small bamboo trees.
 » i dont really think i've understood the editorial of problem D.according to the statement, cant we hack it with the following? 1 10 2 8 2 5 2 4 8 1 8 7 5 6 5 3 4 10 4 9 but the std to D has run correctly.could anybody pls explain it to me? thank you and sorry for my poor English and maybe impolite wording :)
 » How to solve problem E using DP
 » 2 years ago, # | ← Rev. 2 →   With quite a bit of trouble I managed to solve 1521E - Nastia and a Beautiful Matrix. First I solved a different problem(because I'm dumb and can't read problem statements). The original one asks for both the main and the off diagonal to have different numbers or a number and a hole(0 is not treated as a number). Now m, k, and a_i elements be the same and for the 2x2 submatrixes you have the following rules: The 2 elements of the main diagonal are different. 0 is a number not a hole. At least 1 element is 0. This one also has a constructive solution. This one 116955492. If you solved the original one try to solve this one without looking at the solution. It has a more subtle solution in the sparse case.
 » in the 2nd problem the ans also can be for test case 4 5 4 5 4 3 4 5 4 5 ....but the soln says that we have to increment all the time i think it is not necessary so the soln of that part you have to add in soln
 » regarding the problem A:If A is divisible by B (A % B == 0), then how the solution works?e.g. A = 10, B = 5 so now AB = 50 and A(B+1) = 60 which is divisible by both A and B, so all 3 numbers are good!
•  » » true did you get why this works if yes please explain
•  » » i think they didn't mentioned that for nearly good integers b&2 != 0 i.e it is okay for nearly good integers to be divisible by b.
 » HI guies i** have a simple doubt on the question** 1st of the contest 1521A — Nastia and Nearly Good Numbers There are 2 cases:if B=1 , then the answer doesn't exist. Here we cannot get the nearly good numbers at all.Otherwise, we can construct the answer as A+(A-A*B)=A*B does not work in the question please clearify with valid reason .
 » 32 hours ago, # | 0 .ComplaintFrame { display: inline-block; position: absolute; top: 0; right: -1.4em; } .ComplaintFrame a { text-decoration: none; color: #ff8c00; opacity: 0.5; } .ComplaintFrame a:hover { opacity: 1; } ._ComplaintFrame_popup p, ._ComplaintFrame_popup button { margin-top: 1rem; } ._ComplaintFrame_popup input[type=submit] { padding: 0.25rem 2rem; } ._ComplaintFrame_popup ul { margin-top: 1em !important; margin-bottom: 1em !important; } Can Any one explain In question A if a%b==0 then how solution exists as all the "nearly good" integers will be "good" integers too ?