### vovuh's blog

By vovuh, history, 4 years ago, All ideas belong to MikeMirzayanov

1203A - Circle of Students

Tutorial
Solution

1203B - Equal Rectangles

Tutorial
Solution

1203C - Common Divisors

Tutorial
Solution

1203D1 - Remove the Substring (easy version)

Tutorial
Solution

1203D2 - Remove the Substring (hard version)

Tutorial
Solution

1203E - Boxers

Tutorial
Solution

1203F1 - Complete the Projects (easy version)

Tutorial
Solution

1203F2 - Complete the Projects (hard version)

Tutorial
Solution Tutorial of Codeforces Round 579 (Div. 3) 579, Comments (88)
| Write comment?
 » Thanks for the great editorial ! The tutorial for the problem F2 seems to be unavailable for me. I get the following error "Unable to parse markup [type=CF_MATHJAX]".
•  » » vovuh Can you check the editorial for F2, thanks
•  » » 4 years ago, # ^ | ← Rev. 2 →   Has the problem been fixed yet? It works fine on my device. •  » » » Yes ! It's fixed now.
 » Can someone elaborate how to handle case when b_i is negative in problem F. Why are we setting a_i = max(a_i,-b_i). Why sorting in the order of a_i+b_i works?
•  » » a_i = max(a_i, -b_i) — u delete variants, when yours current rating plus b_i < 0. For example: r = 10, a_0 = 9, b_0 = -20. U can take this project, but yours rating will be negative. And I don’t know, why the sort a_i + b_i works.
•  » » 4 years ago, # ^ | ← Rev. 3 →   First, let me tell you why we are setting ai = max(ai, -bi):let's talk both the situations: ai >= -bi and ai < -bi , if ai >= -bi, that means ai doesn't change, when ai < -bi, the problem let us ensure r > 0, when we do this project i, r will be r + bi(bi if negative), so it's obviously why we let ai be max(ai, -bi), we must ensure r+bi > 0, that means we let ai = -bi(the case 2), we can decrease the judgement.Second, why sorting in the order of ai + bi can work? This problem trouble me for a long time at first, when we let ai be max(ai, -bi), we can ensure ai >= -bi, that means ai + bi is not negative, but it can be zero, if we can't do project i, for j (aj + bj < ai + bi) we must can't do all of this, too.That is because aj is greater than ai or not, if aj >= bi , we can't do project j, if aj is smaller than ai, and aj + bj < ai + bi, we can't do project i that means r < ai, when we do the left thing, r will be smaller, that means we can't do project i, either. So this can work.
•  » » I think that you should think about this array like “how much rating I need, to make i-th order”.
•  » » 4 years ago, # ^ | ← Rev. 10 →   Let's try to determine the optimal order to complete all the projects.Let's first focus on two adjacent projects $i$,$j$ in the current arrangement (supposing $j=i+1$), and see when we should swap them.(Obviously, the swap will not affect other projects.) That's to say, we should see which way will make completing both projects "easier".$I.$ If we can take both of them by taking $i$ first, that means our initial rating $r$ satisfies both $r \ge a_i$ & $r + b_i \ge a_j$, which is equivalent to $r \ge max(a_i , a_j - b_i)$.$II.$ If we can to take both of them by taking $j$ first, that means our initial rating $r$ satisfies both $r \ge a_j$ & $r + b_j \ge a_i$, which is equivalent to $r \ge max(a_j , a_i - b_j)$.We wonder which constraint is weaker. We already have $a_j - b_i > a_j , a_i - b_j > a_i$, so we just need to compare $I.$ $a_j - b_i$ and $II.$ $a_i - b_j$. The smaller, the weaker. Note that $I. < II.$ <=> $a_j - b_i < a_i - b_j$ <=> $a_i + b_i > a_j + b_j$. So, for every pair of adjacent projects, we should determine whether to swap them or not by the value $a_i + b_i$. In other words, we have the sequence sorted in the order of $a_i + b_i$.(I hope thinking this way can inspire and help you.)(Thank Bekh for better formatting! I'm new to writing comments, but I'll keep trying.)(Looking forward to others' better, shorter, clearer answers!)
•  » » » 4 years ago, # ^ | ← Rev. 2 →   And an amazing thing that I sort the projects with negative b[i] use this also pass. bool cmp2(mp A,mp B){ // A.first means a[i] A.second means b[i] // B.first means a[j] B.second means b[j] int OK1,OK2; OK1=B.FIR-A.SEC; OK2=A.FIR-B.SEC; return OK1
•  » » » »
•  » » 4 years ago, # ^ | ← Rev. 2 →   Why sorting in the order of $a_i+b_i$ works? Assume there are two projects:$X$,$Y$, with $a_x+b_x>a_y+b_y$, and our remaining rating is $r$. If we can't complete $Y$ after finishing $X$, that means $r+b_xa_y+b_y$ and $r+b_x  » 4 years ago, # | ← Rev. 14 → For problem F2,I have a solution in complexity：$O(n^2)$. My solution is similar to the writer's.The only difference is that I let$dp[i][j]$be after you choose j in the first i tasks , the maximum rating you have.Then we can simply solve this problem using dynamic programming and the complexity is$O(n^2)$.Here is my code.Sorry for my poor English. •  » » 4 years ago, # ^ | ← Rev. 2 → I also thought of that optimization; code to compare •  » » Can you please elaborate? From your definition of dp state, if you initialise dp as rating obtained from the positive part, the dp won't be updated as maximum rating possible is the case where you do not take any negative rating change elements. •  » » » 4 years ago, # ^ | ← Rev. 5 → It can be updated for sure. We can do these transitions :$dp[i][j]=dp[i-1][j]$and if$j>=1$&&$dp[i-1][j-1]>=a_i$&&$dp[i-1][j-1]+b_i>=0$then$dp[i][j]=max(dp[i][j],dp[i-1][j-1]+b_i)$At last,we just need to find the maximum number$i$that satisfy$dp[n][i]>=0$•  » » » » Thanks for the elaboration. I understand it now. Dp[i][j] is the max rating you can have considering first i tasks and must taking j of them. Once you force to take j tasks the updates become clear.  » Can anyone please help me to understand the problem E? I dont understand the problem for a while. It would be really helpfull. Thanks in advance. :) sorry for my poor english. •  » » In simple words we have to maximize number of distinct elements in an array either by keeping the element as it is or increasing it by 1 or decreasing it by 1. •  » » » Thanks a lot understood. :)  » 4 years ago, # | ← Rev. 2 → Can you please check my submission 58732857 for problem C. It is the same as editorial but it timed out. Is using python such a big problem ? •  » » You can see many participants use Python with AC •  » » Hello. I got AC with ur code when use Python 3. https://codeforces.com/contest/1203/submission/58817204 •  » » Try using PyPy3, which is an alternative implementation of Python3. It generally runs much faster. •  » » » I actually submitted on PyPy3 and it still errored out but it is getting accepted in Python 3. This doesn't seem right. •  » » » » There are some changes in the "fractions" module implementation of PyPy3. It's slower. Try the same solution, but import gcd from "math" module rather than "fractions". •  » » » » fractions.gcd() is deprecated since version 3.5. Use math.gcd()  » why the problem F2 Tutorial is Unable to parse markup [type=CF_MATHJAX]  » I use a different cmp function for sort in problem f1: look at my cmp2 in the solution https://codeforces.com/contest/1203/submission/58799244  » 4 years ago, # | ← Rev. 2 → why do we sort by a + b in decreasing order for negative value in F1 •  » » I've tried to explain main idea behind it there  » Can someone help me with problem D1 code. Where am i going wrong logically? It's giving me WA on test case 5. •  » » We are in the same boat friend :( Can someone plzz elaborate what to do for passing testcase 5. •  » » 4 years ago, # ^ | ← Rev. 2 → Your code only takes into consideration the case of matching s2 with s1 as early as possible. You also have to this from the back side of the string s2. than you will have to consider all the possible breaking point of the string s2(break s2 into two parts) find the max difference(no. of characters between them).Here is my code 58800190. I hope this will clear your doubt. •  » » Another interesting example is "aabb" and "ab".Your code matches as ( a a b b ) and returns 1.It is possible to match as ( a a b b ) and the answer is 2.  » 4 years ago, # | ← Rev. 6 → Do your tester program check if participant find solution though jury can't find it?58820595There is just comparator and my solution find order though author's answer is NO.I could check it by myself but I can't see full test case. Where is my mistake?P.S. Found mistake. Too late to delete this comment.P.P.S. 58821318 Maybe not found. At each step I checking if r >= ai and r >= 0 after each step. So I think that in test #11 I found correct order to take all projects.P.P.P.S. Sorry now I really found mistake.  » i can't prove gcd(...(gcd(gcd(a,a),a,)...)a[n])=gcd(a,a,...a[n]) in problem C •  » » 4 years ago, # ^ | ← Rev. 3 → We have$a, b, c$let's denote$gcd(a, b, c) = g$and$gcd(a, b) = z$for convenienceWe want to prove that$gcd(gcd(a, b), c) = gcd(a, b, c)$After substituting some terms you get$gcd(z, c) = gx|y$reads x divides y and means$y\%x = 0$or in english$x$is a divisor of$yg|z$and$z|a$then$g|a$Same way$g|z$and$z|b$then$g|b$and$g|c$is true anyway so$g|a$and$g|b$and$g|c$are true That's for the divisibility. How do you know that it's the greatest?Assume$gcd(a, b, c) = g$and$g > z$. Since$g|a$and$g|b$.$gcd(a, b)$would've given$g$not$z$which is the greater divisor.In other words$gcd(a, b, c)$is either gonna be$gcd(a, b)$or one of its divisors. and you can keep doing the same to generalize to more then three numbers... prove$gcd(a, b, c, d) = gcd(gcd(a, b), c, d) = gcd(z, c, d) = gcd(gcd(z, c), d) ...$and so on.If something is not clear, please ask.There are more formal proofs out there on the internet too. •  » » » thank you, i will more research  » Task F, isnt unique: https://acmp.ru/index.asp?main=task&id_task=572 •  » » How would one go about solving the task u mentioned? I mean the constraints are high, and creating dp array for knapsack would go out of memory. •  » » » Two ideas: In the code in the editorial the first dimension of dp is neg.size() + 1. This simplifies the code, but actually it only uses dp[i] to calculate dp[i+1], so one only ever needs to store two dp rows at a time. The rows of the dp array will have many repeated values, one might be able to reduce storage by just storing the start and end indexes of each group of repeated values. Note that I have not tried writing code using either of these ideas.  » Can anyone tell me why problem B,s case 2 output is YES and why case -3 output is NO. Thanks in advance. :) •  » » 4 years ago, # ^ | ← Rev. 4 → T.C — 2 : -> 10 5 2 10 1 1 2 5->R1 — sides a1 = 10,b1 = 1 and there is extra 10,1 also possible for opposite sides. ->R2 — sides a2 = 5, b2 = 2 and similar hereas a1.b1 == a2.b2 .Hence Yes.T.C — 3:-> 10 5 1 10 5 1 1 1-> R1 — sides a1 = 10,b1 = 1 and there is extra 10,1 also possible for opposite sides. ->R2 — sides a2 = 5, b2 = 1 and similar hereas a1.b1 != a2.b2 .Hence No.  » I have another solution for problem F1(cannot contribute to problem F2, but has a more obvious correctness). First, deal with the projects with positive b values greedily.Then, calculate the rating after all projects are completed. If it's negative, terminate the program. Otherwise, consider to process the projects in a reversed order, beginning with the calculated "final" rating R. Each time we choose a project i such that R — b_i >= a_i, and update R by R — b_i. So the rating R will be increasing during the reversed process. Then it's easy to determine if it's possible to complete all the tasks. •  » » Very easy to understand the "obvious" correctness as you stated.Thanks. •  » » 3 years ago, # ^ | ← Rev. 2 → Upd:this solution can contribute to F2 in fact. We focus on the projects with negative b values only.Assume we have finished processed all the projects we selected with a remaining final rating R0. Then consider to process the projects in a reversed order with R0 as the initial rating. We can process a project i iff R-b_i >= a_i, so we can store these available projects in a priority_queue and one by one greedily choose the project with the smallest -b_i(rating change) to process, thus yielding the minimum initial rating required to finish a certain number of projects with final rating R0. It's easy to maintain the available projects with the rating increasing in O(n), and priority_queue is O(nlogn). The final rating R0 ranges from 0 to the biggest a_i+b_i (a larger R0 doesn't make sense since this is sufficient for us to choose the projects freely at the reversed "beginning"), a O(r) range.The above process doesn't require the real initial rating r, so with this approach we can also answer queries about multiple initial ratings efficiently.Overall Complexity(single query): O(nrlogn)Overall Complexity(multiple query): O(nrlogn + nq) (q:number of queries) •  » » Woah. This is just amazing and doesn't even require a proof because it is just so obvious.  » orz xk  » 4 years ago, # | ← Rev. 3 → Hi, I tried solving the question D1, but I was getting WA on test 5. Editorial also suggest the use of brute force. I am not able to figure out if I have missed some boundary condition.In short, what am I doing: I am calculating all possible indexes for a substring in the main string. After getting all possible indexes, I am just finding the case which removes the most characters from the main string.The code: def checker(mainstr, substr, index): pos=[] for i in substr: temp = mainstr.find(i,index) if(temp == -1): return [] else: pos.append(temp) index = temp+1 return [pos, pos[-1]] def logicmain(mainstr, substr): size = len(mainstr)-1 index = 0 allpos=[] while(True): first = checker(mainstr, substr, index) if(len(first) == 0): break else: allpos.append(first) index = first+1 maxdrop=0 for i in allpos: val = max(i, size-i) maxdrop = max(maxdrop, val) return maxdrop def main(): mainstr= input() substr = input() ans = logicmain(mainstr, substr) print(ans) if __name__ == "__main__": main()  •  » » Even mine solution was same using bruteforce and got WA on tc-5. Can't figure out why.https://codeforces.com/contest/1203/submission/58756135  » Hi, I just want to know what 1ll in the solution of the 1st problem ? •  » » 4 years ago, # ^ | ← Rev. 3 → 1ll is the number 1 but of type long long not int. It is used to avoid overflow. because the result of the multiplication will be of type int since the array a is an array of int, and therefore it could overflow. Using 1ll makes the result of the multiplication of type long long rather than int.  » 4 years ago, # | ← Rev. 2 → Proof for F1: Take array of the projects with negative$b_i$(sorted as given in the tutorial). Let’s complete the projects in this order. If we get stuck at index$k$, then:$ r + \sum_{i
 » In problem B i stored the number and occurrence in a map . If the occurrence of any number is odd then this Case would be "NO" else i check from i from 1 to n that a[i]*a[n] and then i++ and n-- . if all the area is equal then it's "YES" . I don't know what is problem it's getting wa. this is my submission 58846470 And sorry for bad english :)
•  » » 4 years ago, # ^ | ← Rev. 3 →   Try out this test case [1,2,2,2,3,3,3,6]. Your algo would return yes but answer is no ans there are no 2 1s or 2 6s to make a rectangle. Just wnsure that the value occurs in pairs. It should pass. Hope it helps!
 » In B: I get a WA on test case 8 here is my codecan someone please elaborates how to do :(
•  » » 4 years ago, # ^ | ← Rev. 2 →   At least your condition (n!=1) is problemTry (it is impossible to create rectangle)111 2 3 4
 » 4 years ago, # | ← Rev. 3 →   For problem B, I tought that if we sort the array and check that if for every i (1 to (n*2)-1) (i use v*v[n-1] for checking) is equal to v*v[n-1]. Where is my wrong? I couldn't find it. Please help. (I got wrong in 8th test.)
•  » » You should check, whether the number of sticks of the same length is even, and in for(ll i=1;i<(n/2)-1;i++) , you should write i<=(n/2)-1, because you would miss a pair. This way, your solution works.
 » Can anyone tell me why my java solution for problem c exceeding time limit?
•  » » int overflow in this loop:  for(int i=1;i*i<=c;i++) { eventually i*i will overflow before getting to c
 » Can someone give me an intuition for the D2 problem? Why are we creating a prefix and a suffix array? What is the purpose of that?
 » 4 years ago, # | ← Rev. 2 →   why is sorting by $a_i + b_i$ is optimal for negative projects in F1?
 » Regarding problem C solution provided in the editorial ; please consider the expression/condition in the following IF block(the following is as given in the solution);i.e if (i != g / i) { ++ans; } .Now when I tried using if ((i*i) != g ) { ++ans; } in my solution ; I received a Wrong Answer Verdict.Can someone please help me out where am i going wrong.?
•  » » because if ((i*i) != g ) { ++ans; } could be overflow because i is integer, change it to if ((i*1ll*i) != g ) { ++ans; } and you will get AC
 » Can someone help find out why the hell am i getting runtime error,(problem F1) my submisssion https://codeforces.com/contest/1203/submission/58887999
•  » » Comparison function must have strict weak ordering. I was doing the same mistake. For more info read here : https://stackoverflow.com/questions/34446443/segmentation-fault-because-of-comparison-functionGot it to pass your code till test case 36. This is your submission with correction. Now you can work on to remove the bug from your implementation.
•  » » » Thanks a ton brother
 » Can anyone please explain editorial of problem D2 ?
•  » » Let me try to explain my approach. Consider these examples first: $s=efgcbaec$ $t=bac$ $s=beaac$ $t=bac$ $s=beaafgc$ $t=bac$ I guess it must be clear till now that our longest substring in $s$ can lie between any $2$ characters of $t$. Hence, to maximize this we will store first and last occurrence of each character of $t$ in $s$(which can be done easily by iterating $s$ and $t$ from left to right and vice-versa).Now we will do $ans=max(max,last[i]-first[i-1])$ for $i \in [1,|t|]$.Link to Code
•  » » » 4 years ago, # ^ | ← Rev. 3 →   let s = baabca t = bacfor each character of t: {"b": {first_occurence: 1, last_occurence: 4}, "a": {first_occurence: 2, last_occurence: 6}, "c": {first_occurence: 5, last_occurence: 5} }according to you answer is maximum distance between adjacent characters of t:max_dist = last_occurence["a"] — first_occurence["b"](i.e. 6 — 1 = 5) which is wrong in this case, correct answer is 2
•  » » » » If you take last occurrence of $b$ as 4 then you won't be able to make $t$. The occurrences should be valid as well.
•  » » » Thankyou so much for your hint.
•  » » I have written a blog on the solution to this problem. Here's the linkI hope it is of some help :)
•  » » » It helped me. :)
 » Thanks for the great editorial!
»

the common divisors problem code is still saying that time limit exceeded on test case 3 here is the code below... if any one could find the solutions please tell me why its giving time limit exceeded..... thanks in advance .....

# include <bits/stdc++.h>

using namespace std; long long int gcd(long long int a,long long int b) { if(a == b) return a; else if(a>b) return gcd(a-b,b); else if(b>a) return gcd(a,b-a); } int main() { long long int count = 0; long long int n; cin >> n; long long int a[n]; long long int i; for(i = 0;i<n;i++) cin >> a[i]; long long int GCD = a; for(i = 0;i<n;i++) { GCD = gcd(GCD,a[i]); } for(i = 1;i*i<=GCD;i++) { if(GCD % i == 0) { count++; if(GCD/i != i) { count++; } } } cout << count << endl; return 0; }

•  » » Instead of going from gcd(a,b) to gcd(a-b,b), try gcd(a%b,b). It is the same thing, essentially, just faster, because if a is much larger than b, you can skip many a-b-b-b...-b by doing a%b.Imagine if a = $10^{12}$ and b = $1$, your gcd(a,b) will have to make $10^{12}$ recursive calls!
•  » » » many many thanks to you!!!
 » Can someone explain me solution to D2 that How are the iterators i and pos working? I did the easy version but don't have a clue how to optimize it. The editorial seems harder than the problem itself
 » I can't understand why my solution is giving wrong answer for D2(testcase 6).Can someone help me? int main(){ string s,t; cin>>s>>t; int I=0,J=SZ(s)-1; REV(i,SZ(t)){ while(s[J]!=t[i]) J--; J--; } int ans=++J; int id=0; REP(i,SZ(t)){ while(s[id]!=t[i]) id++; id++; } uax(ans,SZ(s)-id); REP(i,id){ if(s[i]==t[I]){ I++; J++; while(J
 » Someone could explain why problem B actually work with the editorial solution?
 » 4 years ago, # | ← Rev. 2 →   F2 is solvable in O(N log N) as it's equivalent to the deadlines and durations scheduling problem: https://cp-algorithms.com/schedules/schedule-with-completion-duration.html
 » 3 years ago, # | ← Rev. 2 →   In problem E in test case 3: Spoiler10 8 9 4 9 6 10 8 2 7 1 why the answer is 10? shouldn't it be 9?
•  » » 3 years ago, # ^ | ← Rev. 2 →   Lets see the array in sorted order : 1 2 4 6 7 8 8 9 9 10 10Um operations selection like this would conclude the answer to be 10 : 1 2 4 5(6 — 1) 6(7 — 1) 7(8 — 1) 8 9 10 11(10 + 1)There maybe some other permutations for the same but hope this would clear ur query !
 » 14 months ago, # | ← Rev. 2 →   Oh no，I applied preSum for question D2 and ignore the order of lettersmy code: import java.util.*; import java.io.*; import java.math.*; import java.text.*; public class Main{ public static void main(String args[]) throws IOException { Read sc = new Read(); String s = sc.next(); String t = sc.next(); List list1=new ArrayList<>(); List list2=new ArrayList<>(); for(int i=0,j=0;i=0;i--){ while(s.charAt(j)!=t.charAt(i)){ j--; } list2.add(j); j--; } Collections.reverse(list2); int ans=Math.max(list2.get(0),s.length()-list1.get(t.length()-1)-1); //System.out.print(ans); for(int i=1;i
 » For D2, you may want to consider this greedy trick I have seen a few times: left and right.For each index i in t, get the leftmost index j of S where t[:i] is a subsequence of S[:j].For each index i in t, get the rightmost index j of S where t[i:] is a subsequence of S[j:].The answer can be:1) the n-1-(leftmost index of S where t is a subsequence of S[:ans])2) the rightmost index of S where t is a subsequence of S[ans:]3) for some index of i from 0 to t.size()-2, take the rightmost index r of S where t[i+1:] is a subsequence of S[r:] and the leftmost index l of S where t[:i] is a subsequence of S[:l] the candidate can be r-l-1; `#include using namespace std; int main() { string a, b; cin >> a >> b; int n = a.size(), m = b.size(); vector lb(m, 0), rb(m, 0); int tmpb = m-1; for(int i = n-1; i>=0; i--) { if(b[tmpb]==a[i]) { rb[tmpb--] = i; } if(tmpb<0) break; } tmpb = 0; for(int i = 0; i