### n0sk1ll's blog

By n0sk1ll, history, 8 months ago,

Author: wxhtzdy

Hint
Solution
C++ Code

# 1689B - Mystic Permutation

Author: n0sk1ll

Hint 1
Hint 2
Solution
C++ Code (Main solution)
C++ Code (O(n) solution)

Riblji_Keksic found the O(n) solution.

Author: n0sk1ll

Hint 1
Hint 2
Solution
C++ Code

Author: n0sk1ll

Hint
Solution
C++ Code

# 1689E - ANDfinity

Author: wxhtzdy

Stupid Hint
Hint 1
Hint 2
Hint 3
Solution
C++ Code

• +136

 » 8 months ago, # | ← Rev. 2 →   +45 Very fast editorial. Problems were good also.
•  » » 8 months ago, # ^ |   +11 Problem were really good, thanks [user:n0sk1||] and wxhtzdy and all the contributors of the contest. I was really a good contest for me.
 » 8 months ago, # |   +5 I was not even able to solve A :(
•  » » 8 months ago, # ^ |   +9 It's OK
•  » » 8 months ago, # ^ |   +3 Don't worry. I also felt that A was tougher than usual.
 » 8 months ago, # | ← Rev. 3 →   -21 Why DP in C? It's just overcomplication, isnt it?UPD: Idk, i just... Bruh
•  » » 8 months ago, # ^ |   +34 what's your approach?
•  » » » 8 months ago, # ^ | ← Rev. 5 →   +7 You can check out my solution https://codeforces.com/contest/1689/submission/160137279 . The idea is that we can make the infection infect only one vertex at a time, or non at all, If the vertex has two children, we delete one of them and make the infection spread to the other child, so both children die, and this process continues unless one of their children has only one child so infection can not spread anymore, then you just cut one source and infection can not spread at all.
•  » » » » 8 months ago, # ^ |   +3 What is the use of variable 'dis' in your code and why are you returning (dis+1) at some places, (dis+2) at other places, and just (dis) at some other places?Can you please explain a bit?
•  » » » » » 8 months ago, # ^ | ← Rev. 3 →   +3 It denotes the amount of vertex that dies, so if the vertex has two children, both of them die, so I do dis+2, if it only has one, only one dies, if it has none, then none dies and I just return dis.
•  » » » 8 months ago, # ^ |   0 You can just simply use recursion. My solution: https://codeforces.com/contest/1689/submission/160139911
•  » » 8 months ago, # ^ |   +1 ig we can just store subtree count of every node & later add by processing in valid manner
•  » » » 8 months ago, # ^ |   +6 yep, but is that not already considered dp?
•  » » 8 months ago, # ^ |   +6 we can solve c without dp.the approch is simply follow along the infected path along the binary tree using dfs/bfs,take minimum of the available infected paths and saved =(n-(infected)) my solution approch
•  » » » 8 months ago, # ^ | ← Rev. 2 →   0 Can anyone see why WA. 3rd Problem I'm storing the child counts in visited and then moving optimally along less children. 160139740
•  » » » » 8 months ago, # ^ |   0 you counter a case when the children is equal Thats the case when your approach doesn't work that's why we use dp to store both possible path and take the max
•  » » » » » 8 months ago, # ^ |   0 Thanks very much, I was just coming to this solution too.
•  » » » 8 months ago, # ^ |   0 I too have a similar approach it doesn't require dp just simple bfs and simple observation.
•  » » » 8 months ago, # ^ |   +1 Why do you multiply s by 2 here? mx=min(mx,(2*s)-1);
•  » » » 8 months ago, # ^ |   0 I am also solving problem C using same concept but I am using bfs instead of dfs. But I get tle in test case2. Can anyone tell why my solution is getting tle. https://codeforces.com/contest/1689/submission/160208992
•  » » » 8 months ago, # ^ |   0 can you please explain me the logic of 2*s -1 and 2*s in leaf node case and 2degree node respectively
•  » » 8 months ago, # ^ |   0 Yes it had much simpler solution
•  » » 8 months ago, # ^ |   +49 Agreed. For anyone who isn't aware, the non-DP approach is to let $v$ be the least deep vertex with at most one child. Then, the number of vertices that must be lost is $d(v) + c(v) + 1$, where $d(v)$ is the depth of $v$ (where the root has depth $1$) and $c(v)$ is the number of children of $v$.
•  » » » 8 months ago, # ^ |   0 I am probably being stupid, but why is d(v) being multiplied by 2?
•  » » » » 8 months ago, # ^ |   +3 For each two-child vertex down which the virus spreads, you lose both the child onto which the virus spreads and the other child, which you must shut down to keep the virus from spreading onto the other branch.
•  » » » » » 8 months ago, # ^ |   0 Got it, thank you
•  » » » 8 months ago, # ^ |   0 whats the proof for this?
•  » » » » 8 months ago, # ^ |   0 After reading Geothermal's second comment, I had to think carefully and visualize a tree that had layers of two-child vertices followed by a single- or no-child vertex. Then it became clear.
•  » » 8 months ago, # ^ |   0 Yeah, brute force worked, i also submitted dp solution later ,both solutions runtime was same.
•  » » 8 months ago, # ^ |   -11 I hate you, i really hate you people
 » 8 months ago, # |   +4 fastest editorial ever? nicevery fun, wish I could do more than 3
•  » » 8 months ago, # ^ |   +3 I don't think so there was recently a contest in which they update the rating and the editorial was out the minute contest and system testing ended. It was Instant no delay.
 » 8 months ago, # |   0 In problem C, wish there was a test case in the sample, where the input had an edge connecting from child node to parent node.Initially I assumed that, the edges were always from parent to child, and wasted time.I know it is my fault for making wrong assumption. But still :(.
•  » » 8 months ago, # ^ |   0 So true dude i got three RE and as soon as i saw the test case and made a little tweak it worked
•  » » 8 months ago, # ^ |   0 I wasted half of my time trying to code a greedy algorithm, and only realized halfway through that it was supposed to be dp, so that was kinda sad lol.
•  » » » 8 months ago, # ^ |   0 i also wasted alot of time on greedy and its implemetation,then in last 20 min all of the sudden observation came and coded it real quick and got ACed
 » 8 months ago, # |   +1 Cool
 » 8 months ago, # | ← Rev. 2 →   +4 O(n) solution for B.The smallest possible lexicographic permutation is 1,2,3,4... Assume that this is the answer. Now just check if any element of the answer array matches with input permutation. if yes, swap it with next element. It's easy to see that no conflict would arise in this manner. There's edge case for last index, we have to swap it with previous element.My submission- https://codeforces.com/contest/1689/submission/160104354
•  » » 8 months ago, # ^ |   0 I have a similar approach. https://codeforces.com/contest/1689/submission/160164830
•  » » 4 months ago, # ^ |   0 I wrote similar solution now, but Test 3 is incorrect I think, I sorted and if it matched I swapped and for n-1th index i swapped with previous element, but test 3 doesn't work.
 » 8 months ago, # |   +9 The problem IDs in the editorial are shown as the gym IDs (probably, some testing mashup). Please fix it.
•  » » 8 months ago, # ^ |   +8 Fixed, sorry.
 » 8 months ago, # | ← Rev. 2 →   -64 // My solution for A: #include "bits/stdc++.h" using namespace std; void solve(); int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int tc; cin >> tc; while(tc--) { solve(); } return 0; } void solve(){ int n, m, k; cin >> n >> m >> k; string a, b, c = ""; cin >> a >> b; sort(a.begin(), a.end()); sort(b.begin(), b.end()); int i = 0, j = 0, turn = 0; if(a[i] > b[j]) turn = 1; if(a[i] == b[j] && n > m) turn = 1; while(i < n && j < m) { if(turn == 0) { c += a[i]; i++; for(int t = 1; i
 » 8 months ago, # |   0 Very fast tutorial Very nice problems More contests like these please!!
•  » » 8 months ago, # ^ |   0 yes you are right
•  » » 8 months ago, # ^ |   0 Why didn't you give this contest then?
•  » » » 8 months ago, # ^ |   -22 I gave it from another ID my friend!!
 » 8 months ago, # |   +15 balanced round with good problems keep it up
 » 8 months ago, # |   +5 cool problems and well organized overall a very good contest.thanks:)
 » 8 months ago, # | ← Rev. 2 →   0 Problem C can be solved greedily. I just find the shortest path from root to the node which have less than 2 children and infected those node and saved all other nodes by deleting the first node of every subtree connected to these infected nodes. Codeint ans; int cnt; void dfs(int i,vi &vis,int dis,vi adj[]){ vis[i]=1; int sz=adj[i].size(); if(sz<3){ if(dis>n; vi adj[n+1]; for(int i=0;i>x>>y; adj[x].push_back(y); adj[y].push_back(x); } if(adj[1].size()==1){ cout<
•  » » 8 months ago, # ^ |   0 Nice Observation! What is cnt in your code?
•  » » » 8 months ago, # ^ |   +1 cnt represent that the last node has any child or not . If the last node has no child then there is no subtree connected to that node and in that case there is one less node to delete. That's why when cnt is 1(no child) the output is n-2*(ans+1)+1 which is equal to n-(ans+1)-ans and in the case where cnt is 2(has one child) the output is n-2*(ans+1)
•  » » 8 months ago, # ^ |   0 I solved C absolutely the same way as you
•  » » 8 months ago, # ^ |   0 what does this part of the code do? if(sz<3){ if(dis
•  » » » 8 months ago, # ^ |   0 If sz is less than 3 this means that the node has only one child or no child so the path ends here and I am just taking the minimum of all the path from root to the node having no or one child and cnt just stores that the last node has a child or not
 » 8 months ago, # |   0 Why is this getting MLE ? My code for C : 160135752
•  » » 8 months ago, # ^ |   +1 Your solve function is called recursively infinite times as it is calling its parent node in some test cases like the below one. Test Case: 5 2 3 5 1 4 2 1 2 
•  » » » 8 months ago, # ^ |   0 Fixed , thank you !Still , it is curious why it got MLE instead of TLE in this case.
•  » » » » 8 months ago, # ^ |   0 I think it would be TLE if it was an iterative loop, but recursively 3 seconds is more than enough to exceed the memory limit.
 » 8 months ago, # |   0 The hint 3 in problem E tells that answer is 0, 1 or 2. But we have an answer 3 in the example.
•  » » 8 months ago, # ^ |   +70 Perhaps they exclude the mandatory "+1" to the zeros initially
 » 8 months ago, # |   0 For B, lexicographicaly is supposed to be string ordering not integer ordering :((((((((((((
 » 8 months ago, # |   0 Can someone please explain problem C? Since it is a binary tree there will always be at max two edges from the root node. I calculated the indegree of both and subtracted the minimum to find the max nodes which can be saved but this approach is giving wrong answer on test 3. Pls Helphttps://p.ip.fi/4svQ
•  » » 8 months ago, # ^ |   0 I'm not sure what you mean but you can make more than 1 saving move
 » 8 months ago, # |   +1 they didn't thought that C can be solved using DFS?
 » 8 months ago, # |   +68 For D, another approach is to use the fact that $abs(x) = max(x, -x)$.Let $S$ be the set of black cell, then we need to minimize: $max(abs(i - x) + abs(j - y))$ for every combination of $1\leq i \leq n, 1\leq j \leq m, (x, y) \in S$.This is just $max(max(i - x, x - i) + max(j - y, y - j))$.Just expand the inner $max$ and we will have 4 cases to check, similar to the official tutorial.160104327I think this idea ($abs(x) = max(x, -x)$) is pretty common but still very powerful, probably would have taken much more time to solve D if I didn't know it.
•  » » 8 months ago, # ^ | ← Rev. 3 →   +18 When I tested the round, I immediately recognized the problem as one where you need to transform the coordinates in such a way that the Manhattan metric becomes the Chebyshev metric (which corresponds to rotation by 45 degrees and appropriate scaling). $|x| = \max \{x, -x\}$ is basically why that transformation works. I was also opposed to adding this problem in the contest because 1658E - Gojou and Matrix Game is a strictly harder version of the problem.
•  » » 8 months ago, # ^ | ← Rev. 2 →   0 In the 4 cases that we make on expanding the max, there is an underlying condition for every case right, for example, only when $i \leq x$ and $j \leq y$, we get the Manhattan distance as $x + y - (i + j)$, but in your implementation, you have directly chosen the maximum value of $x + y$, (say it is ${(x+y)}_{max}$) and you've taken the maximum of $cost$ and $(x+y)_{max} - (i+j)$ without checking if $i\leq x$ and $j\leq y$. Can you please explain the thought process behind this and why this works?Edit: I misunderstood what you meant by "expanding the inner max", I got it now, thanks.
•  » » » 7 months ago, # ^ |   +3 Yes, writing out the expansion more explicitly for anyone who doesn't see it, it is equal to $\max_{(x,y) \in S} \max(i-x+j-y,i-x+y-j,x-i+j-y,x-i+y-j)$ $= \max( \max_{(x,y) \in S} (i-x+j-y), \max_{(x,y) \in S} (i-x+y-j), \max_{(x,y) \in S} (x-i+j-y), \max_{(x,y) \in S} (x-i+y-j))$ $= \max(i+j + \max_{(x,y) \in S} (-x-y), i-j + \max_{(x,y) \in S} (-x+y), j-i + \max_{(x,y) \in S} (x-y), -i-j + \max_{(x,y) \in S} (x+y) ),$ and you can precompute each of the four terms $\max_{(x,y) \in S} (ax + by)$ for $a,b \in {-1,1}.$
•  » » » » 2 months ago, # ^ |   0 Can we use a similar method when we need to find the minimum Manhattan distance among all pair of points? Just replacing the outer MAX by MIN, whereas inner MAX remains same, as it corresponds to the 'abs' thing.
•  » » 3 months ago, # ^ |   0 I think a simpler solution is to transform the Manhattan distance to Chebyshev distance, and we only need to minimize $\max_{1\le i\le k} {\max(|a'-x_i'|,|b'-y_i'|)}=max(\max_{1\le i\le k}|a'-x_i'|,\max_{1\le i\le k}|b'-y_i'|)$, which is optimal when choosing the median among the $x$ and $y$ coordinates of given points.
•  » » » 3 months ago, # ^ |   0 Sorry, I didn't see that the tester above had already shared this solution.
 » 8 months ago, # |   +10 Problem D can also be solved by dp. But we have to maintain 4 dp tables. One table dp[i][j] stores max distance of a black point from i,j in top left of the matrix and other tables will store for other three part of matrix which is top-right, bottom-left and bottom-right . Max distance of a point from black point will be max of the value from all four table and then we can take minimum of all these and that will be our answer .
•  » » 8 months ago, # ^ | ← Rev. 2 →   +9 Even just 2 dp tables are sufficient... One storing max distance of a black cell with x coordinate < i & other with x coordinate >= i for a given (i,j)
•  » » » 8 months ago, # ^ | ← Rev. 2 →   +3 nice solution. I missed the idea of using first and last rows per column
•  » » » 8 months ago, # ^ |   0 can you explain more ? i didn't get what you mean by max dist. < i . Like what does this signify?
•  » » » » 8 months ago, # ^ | ← Rev. 3 →   +7 For each point (i,j), we want to know the max distance of a black cell from it. Once we know this, we can simply iterate over each (i,j) & find the one which is having min value. Now, for finding this, I define 2 dp tables :dp1(i,j) : Max distance of a black cell from (i,j) considering all black cells with coloum no. < j.dp2(i,j) : Max distance of a black cell from (i,j) considering all black cells with coloum no. >= j.Now, let's try to build transition for dp1(i,j), it includes all black cells with coloum no. 0 to j-1. As per definition of dp1(i,j-1), it includes all black cells with coloum no. 0 to j-2. So, now dp1(i,j) = max(1 + dp1(i,j-1), max distance of a black cell in (j-1)th coloum from (i,j)). Similarly, dp2(i,j) = max(1 + dp2(i,j+1), max distance of a black cell in jth coloum from (i,j)).Now, max distance of a black cell from (i,j) = max(dp1(i,j), dp2(i,j)). You can check out my code : here
 » 8 months ago, # | ← Rev. 2 →   0 I was thinking of applying a greedy approach for problem C, why is it not enough to find the closest path from root to leaf or a node which has just 1 children. after we find the path length we can just get the answer by (N — (x + (x-1)) + 1 ( 1 for the case if the last node found had 1 child).What i was thinking is for every step we have two choices either remove one branch or the other, when we remove one branch we also delete a node, thus (x + (x-1)), these are the nodes removed or infected, after that just subtract this from total N.The approach is wrong but i can;t figure out why, can someone help please?Okay, got the error, the approach was right, the problem was i was BFS so i had to take care of the fact that if there are two nodes in which one has only one child and there is other node which does not have a child, i will go with the one which does not have a child and in that case the formula will be n-(x+(x-1)) only
•  » » 8 months ago, # ^ |   0 From what I understand you are trying to say, your approach is correct! This is actually the same approach that Geothermal had: https://codeforces.com/submissions/Geothermal You may have had some calculation error. Here is what he had to say:"Agreed. For anyone who isn't aware, the non-DP approach is to let v be the least deep vertex with at most one child. Then, the number of vertices that must be lost is d(v)+c(v)+1, where d(v) is the depth of v (where the root has depth 1) and c(v) is the number of children of v."(Why is the depth multiplied by 2 in your code?) "For each two-child vertex down which the virus spreads, you lose both the child onto which the virus spreads and the other child, which you must shut down to keep the virus from spreading onto the other branch."
•  » » » 8 months ago, # ^ |   0 and make sure you check for the path to a 0 child node as well.
•  » » » » 8 months ago, # ^ | ← Rev. 3 →   0 Hey!!, i got that!! Thanks a lot.here is the code using bfs — https://codeforces.com/contest/1689/submission/160144859
 » 8 months ago, # |   +47 $O(n(log(max ai))^2)$ solution to E.
 » 8 months ago, # |   0 For what purpose there was this limitation in A, that "no character is contained in both strings."?
•  » » 8 months ago, # ^ |   +12 If smallest character in s equals to smallest character in t, which should we choose?
•  » » » 8 months ago, # ^ |   0 Sorry, I still dont get it, what is wrong with this submission 160146764 ?
•  » » » » 8 months ago, # ^ |   +3 160162775 check this
•  » » » » » 8 months ago, # ^ |   0 omg... thanks.
•  » » » » 8 months ago, # ^ | ← Rev. 2 →   0 If you take a character from string a, you are not resetting the count for the other string to 0.Assume given strings are a = "aaacdd" and b = "bcde", and k=10. Your vector ab will be then ["ddcaaa", "edcb"].Initially, your cnt = [0,0] and ans is empty. After first three iterations, ans becomes "aaa", cnt = [3,0], and ab = ["ddc", "edcb"]. Now in fourth iteration, ans becomes "aaab" but cnt = [3,1]. It should become [0,1].
•  » » » 8 months ago, # ^ |   0 Can you please check my solution if that condition is not included: comment link
 » 8 months ago, # | ← Rev. 2 →   0 0
 » 8 months ago, # | ← Rev. 2 →   0 anyone plz discuss the approach of problem D. it will be very helpful for me, why it's maximize i+j and i-j, and , minimized i+j and i-j also.
•  » » 8 months ago, # ^ | ← Rev. 3 →   0 you can see an atcoder's problem in there. The official editorial has a detailed explanation
 » 8 months ago, # |   0 easy sol for B https://codeforces.com/contest/1689/submission/160137944
 » 8 months ago, # |   +1 Not figuring out definitely correct (strict $O(nm)$ complexity) solution for D, but use some tricks to get it passed.It is plausible to assume that $ans$ is close to the "center" of black cells (here I adopt $center=\frac{max-min}{2}$ for both x and y axis), then iterate over and move to adjacent cells util max Manhattan distance descend to optimum.I'm not sure if max Manhattan distance has the same property of monotonicity as Euclidean distance (a classical problem is covering points on the plane with smallest circle). If that property holds, binary search may also work.
•  » » 5 months ago, # ^ | ← Rev. 2 →   0 Yeah, I also thought of binary search, but the precomputation had to be done of diamond shapes of size k. Please share if you come across any such resources of doing the same.
 » 8 months ago, # |   +1 In problem C, can someone provide a smaller test case in which deleting the child with a higher subtree will lead to the wrong result? Thanks in advance!!
•  » » 8 months ago, # ^ | ← Rev. 3 →   0 171 21 33 43 52 66 7here root 1 : left child subtree (with root 2) has the same number of vertices that can be saved by right child subtree(with root 3).so if you cut left child subtree in the end answer will equal 2but if you cut right child subtree in the end will equal 3
•  » » » 8 months ago, # ^ |   0 For same number of subtrees, I deleted the one with higher number of children
•  » » » » 8 months ago, # ^ |   0 here both subtree of 2 and 3 have the same number of children
 » 8 months ago, # | ← Rev. 2 →   -15 The tests for A are very weak. I can see many solution hackable. I can't see the hack button. But here is the test case: 1 4 4 3 aaab aaad if this works swap the strings 1 4 4 3 aaad aaab  correct answer: aaaaaab, output: aaaaaad UPDATE: Almost every solution is hackable. Why I can't see hack button?
•  » » 8 months ago, # ^ | ← Rev. 2 →   +12 Testcases are not weak. Read the problem A again :)
•  » » 8 months ago, # ^ | ← Rev. 2 →   +17 Hey, same symbol cannot appear in both strings a and b!
•  » » » 8 months ago, # ^ |   0 Ah sorry
•  » » 8 months ago, # ^ | ← Rev. 2 →   0 Its wrong.
•  » » 8 months ago, # ^ |   +33
 » 8 months ago, # |   0 1689E - ANDfinity can be optimized to $O(n A^2)$, where $A=\log{\max a_i}$ We can count $cnt[i][j]$ how many times pair of bits $i,j$ was in all $a_k$ it's works in $O(A^2)$ per element and then check if this grpah connected To check if bit set just check $a[i][i] > 0$, if we have array $cnt$ DFS works in $O(A^2)$ So when we adding or subtracting 1 we can just update cnt we are doing it $O(n)$ times code: 160147889
 » 8 months ago, # |   0 Oh! Problem D had such simple solution. But I overkilled it with binary search.
•  » » 8 months ago, # ^ |   0 Can you please explain how you used binary search I thought of doing so, searching for optimal distance but got dtucked on how to verify if the rhombus around all black points intersect at some pointfor current mid
•  » » » 8 months ago, # ^ | ← Rev. 2 →   +3 There are four sides in rhombus. In all the cells of two opposite sides i + j remains the same and in all the cells in other two opposite sides i — j remains same where i and j are row and column number. So I divided them into two sets of ranges of two types where in first type, each range is of the form [i + j — mid, i + j + mid] and in other type, ranges are of form: [i — j — mid, i — j + mid]. Then just find the intersection of both type of ranges and iterate over every cell (i, j) to check if i + j lies in intersected range of first type of ranges and i — j lies in the intersected range of second type of ranges.
•  » » » » 8 months ago, # ^ |   0 Thnx
 » 8 months ago, # |   0 dang I was really close with D, but I wrongly thought that 4 squares shouldn't be sufficient and end up making convex hullB was too googlable, it was simply "minimum derangement" but overall the contest was nice!
 » 8 months ago, # | ← Rev. 5 →   -9 [DELETED]
 » 8 months ago, # |   0 Hi Guys! I need a little help with question C. my solution keeps getting a MLE verdict. I have no idea why. I would really appreciate it if you can tell me how to optimize it. thank you :).
 » 8 months ago, # |   0 just realized, i was printing -1 directly after reading in n == 1 without further reading in the elements of the array, and hence failing pretest 2 in B. :/
 » 8 months ago, # |   0 Can someone explain D please. I don't understand what 4 regions is getting created
•  » » 8 months ago, # ^ |   +3 The regions are top-left rectangle, top-right rectangle, bottom-left rectangle and bottom-right rectangle, which are created by lines parallel with coordinate axes passing through our yellow point.I'll add this in the editorial.
•  » » » 8 months ago, # ^ |   0 what does i+j, i-j signify can you explain it more?
 » 8 months ago, # |   0 in D, As per editorial, we are selecting 4 points with different cases. Now what if you find answer to a point which is not able to belong to the correct case. I mean case1 is for both positive but is not getting achieved. explain plz?
 » 8 months ago, # |   -29 Please tell me why my BFS code is not working on Prob C. #include #include #include using namespace __gnu_pbds; using namespace std; using ll = long long; #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define sz(a) (int) ((a).size()) #define pb push_back #define fi first #define se second #define f0r(i, a, b) for(int i = (a); i < (b); ++i) #define f0rr(i, a, b) for(int i = (a - 1); i >= (b); --i) #define trav(i, v) for(auto &i : (v)) template using V = vector; template using P = pair; template using VP = vector>; template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; template T pow(T a, T b) { T res = 1; f0r(i, 0, b) res = res * a; return res; } template void ckmax(T &a, T b) { a = max(a, b); } template void ckmin(T &a, T b) { a = min(a, b); } int dx4[] = {0, 1, 0, -1}; int dy4[] = {1, 0, -1, 0}; int dx8[] = {-1, -1, -1, 0, 1, 1, 1, 0}; int dy8[] = {-1, 0, 1, 1, 1, 0, -1, -1}; const ll linf = 1000000000000000000; const int inf = 1000010000; // <===================================================================================================> vector > g; vector subTree, vis; void dfs(int u) { vis[u] = 1; trav(v, g[u]) { if(vis[v]) continue; dfs(v); subTree[u] += subTree[v]; } vis[u] = 0; } int main(){ cin.tie(nullptr)->sync_with_stdio(false); int tt = 1; cin >> tt; f0r(T, 1, tt + 1) { int n; cin >> n; subTree.assign(n, 1); vis.assign(n, 0); g = vector> (n); f0r(i, 0, n - 1) { int u, v; cin >> u >> v; u--, v--; g[u].pb(v); g[v].pb(u); } dfs(0); int ans = 0; queue que; que.push(0); while(true || !que.empty()) { int u = que.front(); que.pop(); vis[u] = 1; vector ver; trav(i, g[u]) if(!vis[i]) ver.pb(i); if(sz(ver) == 0) break; if(sz(ver) == 1) { ans += (subTree[ver[0]] - 1); break; } if(subTree[ver[0]] > subTree[ver[1]]) { ans += (subTree[ver[0]] - 1); que.push(ver[1]); } else { ans += (subTree[ver[1]] - 1); que.push(ver[0]); } } cout << ans << "\n"; } return 0; } 
•  » » 8 months ago, # ^ |   +1 Please use spoiler to write your code. SpoilerI mean this way
 » 8 months ago, # | ← Rev. 2 →   0 Prob A is not diffcult, but cost me 48 minutes to solve it, becaue I add multi characters to string c in one operation. o(╥﹏╥)o
 » 8 months ago, # |   0 Can someone tell me in 1689D - Lena and Matrix why taking average of leftmost and rightmost row and column (i.e. x=avg of(max row i+ min row i) and y=(max column j+ min column j) and taking all pssible value of (x,y) by taking ceil and floor value(i.e. 4 case) and checking which gives minimum distance for all black co0rdinates is giving wrong answer.(160145986). Any counter example to show this method is wrong??
 » 8 months ago, # | ← Rev. 4 →   0 I have a doubt the code given for A gives wrong answer for16 4 2aaaaaaaaaagiven_answer:aaaaaaaaexpected:aaaaaI was thinking that we should also consider whether string a is small or stering b at a moment when both has same smallest character. Please correct me.
•  » » 8 months ago, # ^ |   0 you have to stop when any of the string is empty and since "a" is lexographically smaller than "aa" so its better to empty the second string first to get optimal string
•  » » » 8 months ago, # ^ |   0 yaa exactly but many submissions including the editorial one gives the wrong answer as answer should be aaaaa. Correct me plz
•  » » 8 months ago, # ^ | ← Rev. 2 →   +3 Actually in given question same character does not appear in both strings. But lets say we allow same character to occur, then the answer in your case would be $aaaaaaaaa$ (9 times $a$)
•  » » » 8 months ago, # ^ |   +3 Oh okay got it forgot to read that.Why the answer should be 9 times a we take 2 aa from string b then one a from string a and again 2 aa from string b. Now b is empty hence answer should be aaaaa.But yaa I have to read the problem more carefully
•  » » » » 8 months ago, # ^ |   0 Yes you are right here, lexicographically smaller string should be smaller!
 » 8 months ago, # |   +3 The editorial's solution for problem D 1689D - Lena and Matrix may be too slow for languages like Python. I found a small speedup that allows Python code to pass the time limit.Instead of "iterating over all squares in the matrix and finding the most distant black square", not all squares in the matrix actually need to be checked. For example, points outside the black diagonal rectangle (as shown in the editorial) clearly can't be optimal, and hence don't need to be checked.Intuitively, points near the middle of the black diagonal rectangle have the best chance of being optimal and should be checked. I'm not sure how to prove that this is sufficient other than "Proof by AC" ;)The time complexity is still O(nm) but maybe with a smaller constant factor.Slow version, where all squares are checked (TLE in Python): https://codeforces.com/contest/1689/submission/160175658Fast version, where only 4 middle squares are checked: https://codeforces.com/contest/1689/submission/160175205
 » 8 months ago, # | ← Rev. 4 →   +3 A more complicated but mathematical(?) solution for D via direct analysis of manhattan distance.First note that if any black square is between two other black squares in the same row or column then in the optimal configuration the longest distance will not be to that square. This can be shown by computing the manhattan distances to an arbitrary point directly. One of the squares on its left/right side will have greater distance. So removing those squares we have $O(n+m)$ black squares left.Now fix some row $a.$ We find the optimal column(s) $b$ that minimize the distance for squares in this row. Thus, we want to minimize $\max ( |a-x_i| + |b-y_i| )$ for $b \in [1,m].$ Each of the $|a-x_i|$ are constants, so we have functions of the form $c + |x - d|.$ It's easy to see (by looking at the graphs) that the maximum of two such functions $\max(c_1 + |x - d_1|, c_2 + |x - d_2|)$ is another such function $c_3 + |x - d_3|.$ It follows that the function $f(b) = \max ( |a-x_i| + |b-y_i| )$ is bitonic, and we can binary search to find the optimal $b$ value(s) for this row.Solution runs in $O(n^2 \log n)$ because for each of $n$ rows binary search takes $\log n$ and and each one we check we compute $O(n)$ numbers to find $f(b)$ at that column $b.$163193116
•  » » 8 months ago, # ^ | ← Rev. 3 →   0 not only can we binary search we can solve a system of equations to get exactly an x and y that will minimize the manhattan distance! this is done by noting that the maximum distance for a number of points would be max( a-xi + b-yi, xi-a + b-yi, a-xi + yi-b, xi-a + yi-b ) where i is the ith black squarethen we can see that we can compute the max manhattan distance is max( a+b + max(-xi-yi), b-a + max(xi+yi), a-b + max(-xi+yi), -b-a + max(xi+yi))to minimize the maximum manhattan distance would be the equivalent of solving a+b + max(-xi-yi) = -b-a + max(xi+yi)b-a + max(xi-yi) = a-b + max(-xi+yi)though the problem with this is that a and b are not always integersin my submission i checked the four nearest integer points ¯_(ツ)_/¯ couldn't think of a better solutionhttps://codeforces.com/contest/1689/submission/160184723
 » 8 months ago, # |   0 In D, we are checking 4 points. But for each point we are checking, there should be 4 cases for signs. What if the points we have chosen can only make 3 sign cases and cannot make the 4th sign case. Explain please.
•  » » 8 months ago, # ^ |   0 Even if we have just one B all 4 cases will be covered.
•  » » » 8 months ago, # ^ | ← Rev. 2 →   0 I mean while checking for a certain white element, the black which we considered giving maximum or minimum for (let's say) case 3(+-) is not being in case 3 with the current white we are checking.We take a black (2,3) with min i-j = -1 (case 3). When we are checking for white at (0,0) 0-2 = -2, 0-3 = -3, it belongs to case 4. So we should have chosen a different point which could have given a good case 3 with this pointActually the solution is correct and maybe it requires some extra proof. That's what I am asking
 » 8 months ago, # |   0 Hehe finally got my O(nm + number of black points) solution for problem D to work :) just in case of a harder problem in which n = 10e9, m = 10e9, and only the black points are given https://codeforces.com/contest/1689/submission/160184723
 » 8 months ago, # |   0 Can anyone explain why the maximum answer can be 2 for E?
•  » » 8 months ago, # ^ | ← Rev. 4 →   0 maximum 2 operations after all the 0s have been turned into 1sfor example100000100010=> 100011001000the algorithm in general would befind maximum ai & -ai and two numbers that ai & -ai = max(ai & -ai)add 1 to one such numberminus 1 from another one such numberthe minus 1 would become 11111110the add one would become 10000001since largest ai & -ai all other (ai & -ai) < max(ai & -ai) would be connected to 1111110then 10000001 would connect to all ai & -ai == max(ai & -ai)
•  » » » 8 months ago, # ^ |   0 Got it. Thanks!!!
»
8 months ago, # |
-37

O(N) solution

# include <bits/stdc++.h>

using namespace std;

int main() { int t; cin>>t; while(t--){ int n; cin>>n; vector a(n); for(int &y:a) cin>>y; if(n==1){ cout<<-1<<endl; continue; } int prev,minm; minm=1; unordered_map<int,int> m; vector ans; int flag = 0; for(int i=0;i<n;i++){ if(a[i]!=minm){ ans.push_back(minm); m[minm]=1; minm++; while(m.find(minm)!=m.end()&&minm<n){ minm++; } }else{ prev = minm; if(minm<n) minm++; while(m.find(minm)!=m.end()&&minm<n){ minm++; } ans.push_back(minm); m[minm]=1; minm = prev; } } if(a[n-1]==ans[n-1]){ swap(ans[n-1],ans[n-2]); } for(int y : ans){ cout<<y<<" "; } cout<<endl; }

return 0;

}

»
8 months ago, # |
-32

can someone tell why this code is not giving correct answer on test case 88 expected 3 but found 2

# include <bits/stdc++.h>

using namespace std;

//Speed

# define Asquare cout.tie(NULL);

//Aliases using ll= long long; using lld= long double; using ull= unsigned long long;

//Constants const lld pi= 3.141592653589793238; const ll INF= LONG_LONG_MAX; const ll mod=1e9+7;

//TypeDEf typedef pair<ll, ll> pll; typedef vector vll; typedef vector vpll; //typedef vector vs; typedef unordered_map<ll,ll> umll; typedef map<ll,ll> mll;

// Macros

# define rv(v) v.end(),v.begin()

// Utility functions template void prll(T &&t) { cout << t << "\n"; } void prllarr(ll arr[], ll n){fl(i,n) cout << arr[i] << " ";cout << "\n";} template void prllvec(vectorv){ll n=v.size();fl(i,n)cout<<v[i]<<" ";cout<<"\n";} template ll sumvec(vectorv){ll n=v.size();ll s=0;fl(i,n)s+=v[i];return s;}

// Mathematical functions ll gcd(ll a, ll b){if (b == 0)return a;return gcd(b, a % b);} //__gcd ll lcm(ll a, ll b){return (a/gcd(a,b)*b);} ll moduloMultiplication(ll a,ll b,ll mod){ll res = 0;a %= mod;while (b){if (b & 1)res = (res + a) % mod;b >>= 1;}return res;} ll powermod(ll x, ll y, ll p){ll res = 1;x = x % p;if (x == 0) return 0;while (y > 0){if (y & 1)res = (res*x) % p;y = y>>1;x = (x*x) % p;}return res;}

//Graph-dfs // bool gone[MN]; // vector adj[MN]; // void dfs(ll loc){ // gone[loc]=true; // for(auto x:adj[loc])if(!gone[x])dfs(x); // }

# define printv(vec) for(auto x: vec){cout<<x<<" ";}cout<<"\n";

//Sorting bool sorta(const pair<ll,ll> &a,const pair<ll,ll> &b){return (a.second < b.second);} bool sortd(const pair<ll,ll> &a,const pair<ll,ll> &b){return (a.second > b.second);}

//Bits string decToBinary(ll n){string s="";ll i = 0;while (n > 0) {s =to_string(n % 2)+s;n = n / 2;i++;}return s;} ll binaryToDecimal(string n){string num = n;ll dec_value = 0;ll base = 1;ll len = num.length();for(ll i = len — 1; i >= 0; i--){if (num[i] == '1')dec_value += base;base = base * 2;}return dec_value;}

//Check bool isPrime(ll n){if(n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(ll i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} bool isPowerOfTwo(ll n){if(n==0)return false;return (ceil(log2(n)) == floor(log2(n)));} bool isPerfectSquare(ll x){if (x >= 0) {ll sr = sqrt(x);return (sr * sr == x);}return false;} //Code by Abhinav Awasthi

# define vll vector

//#define vs vector

# define yes cout << "YES\n"

using namespace std; void inpv(vl& a,ll n){ fl(i,n){ ll te; cin>>te; a.pb(te); } }

# include<math.h>

using namespace std;

# define ll long long

vector size1; vector parent; vector<vector>graph(10);

vectorlength;

ll dfs(ll node,vb & visited,ll last){ if(visited[node]){ return length[node]; } visited[node]=true; for(ll i=0;i<graph[node].size();i++){ // cout<<graph[node][i]<<" "<<node<<endl; if(graph[node][i]==last){ continue; } length[node]+=dfs(graph[node][i],visited,node);

}
return length[node];

} ll sol(ll node,ll last){ if(node==1){ if(graph[node].size()==2){ if(length[graph[node][0]]>length[graph[node][1]]){ return length[graph[node][0]]-1+sol(graph[node][1],1); } else{ return length[graph[node][1]]-1+sol(graph[node][0],1);

}
}
else if(graph[node].size()==1){
return length[graph[node][0]]-1;
}
else{
return 0;
}
}

else if(graph[node].size()==2){
if(graph[node][0]!=last){
return length[graph[node][0]]-1;

}
else{
return length[graph[node][1]]-1;

}

}
else if(graph[node].size()==1){
return 0;
}
else if(graph[node].size()==3){
if(graph[node][2]==last){
if(length[graph[node][0]]>length[graph[node][1]]){
return length[graph[node][0]]-1+sol(graph[node][1],node);
}
else{
return length[graph[node][1]]-1+sol(graph[node][0],node);

}
}
else if(graph[node][1]==last){
if(length[graph[node][0]]>length[graph[node][2]]){
return length[graph[node][0]]-1+sol(graph[node][2],node);
}
else{
return length[graph[node][2]]-1+sol(graph[node][0],node);

}

}
else{
if(length[graph[node][1]]>length[graph[node][2]]){
return length[graph[node][1]]-1+sol(graph[node][2],node);
}
else{
return length[graph[node][2]]-1+sol(graph[node][1],node);

}

}
}

}

int main() { fast_io int tt; cin>>tt; ll c=0;

while(tt--)
{
c++;

ll n;
cin>>n;
graph.clear();
graph.resize(n+1);
length.clear();
length.resize(n+1);
vector<ll>gg(n+1,1);
length=gg;
ll root=-1;

fl(i,n-1){
ll a;
ll b;
cin>>a>>b;

graph[a].pb(b);
graph[b].pb(a);
}

vb visited(n+1,false);
ll ans=dfs(1,visited,-1);

// cout<<ans<<endl;
ll ans1=sol(1,-1);
cout<<ans1<<nl;

}

}

 » 8 months ago, # |   -27 whats wrong in this..? giving WA on test 2ll dfs(ll node,vb & visited,ll last){ if(visited[node]){ return length[node]; } visited[node]=true; for(ll i=0;ilength[graph[node][1]]){ return length[graph[node][0]]-1+sol(graph[node][1],1); } else{ return length[graph[node][1]]-1+sol(graph[node][0],1); } } else if(graph[node].size()==1){ return length[graph[node][0]]-1; } else{ return 0; } } else if(graph[node].size()==2){ if(graph[node][0]!=last){ return length[graph[node][0]]-1; } else{ return length[graph[node][1]]-1; } } else if(graph[node].size()==1){ return 0; } else if(graph[node].size()==3){ if(graph[node][2]==last){ if(length[graph[node][0]]>length[graph[node][1]]){ return length[graph[node][0]]-1+sol(graph[node][1],node); } else{ return length[graph[node][1]]-1+sol(graph[node][0],node); } } else if(graph[node][1]==last){ if(length[graph[node][0]]>length[graph[node][2]]){ return length[graph[node][0]]-1+sol(graph[node][2],node); } else{ return length[graph[node][2]]-1+sol(graph[node][0],node); } } else{ if(length[graph[node][1]]>length[graph[node][2]]){ return length[graph[node][1]]-1+sol(graph[node][2],node); } else{ return length[graph[node][2]]-1+sol(graph[node][1],node); } } }}int main() { fast_io int tt; cin>>tt; ll c=0; while(tt--) { c++; ll n; cin>>n; graph.clear(); graph.resize(n+1); length.clear(); length.resize(n+1); vectorgg(n+1,1); length=gg; ll root=-1; fl(i,n-1){ ll a; ll b; cin>>a>>b; graph[a].pb(b); graph[b].pb(a); } vb visited(n+1,false); ll ans=dfs(1,visited,-1); // cout<
 » 8 months ago, # | ← Rev. 2 →   0 Can someone point out my mistake in C!? What I did is: At each level of BFS, I found the node with largest number of nodes in subtrees. Added that amount to result and continue BFS with rest nodes of that level. My Solution
•  » » 8 months ago, # ^ |   0 Well, that does not work. The optimal solution is not to allways choose the bigger of the two subtrees. Instead, we have to choose the one where we can stop the infection at the earliest step. That is, where the path to the first vertex with less than two childs is shortest.
 » 8 months ago, # |   0 For 1st problem I tried a test case 1 5 5 2 aabbc aabbd The correct answer for this should be aaaabbbbc, but even their solution is giving aaaabbbbd. If someone is getting correct answer please check by reversing the string order and please correct me if a I am going wrong somewhere.
•  » » 8 months ago, # ^ |   0 The question stated: no [same] character is contained in both strings.
 » 8 months ago, # | ← Rev. 3 →   0 Hi guys, can someone explain why this code doesn't work. I'm stuck in this problem and keen on to solve it with this logic, here is code and i think easy to understand. https://codeforces.com/contest/1689/submission/160231154 C problem
 » 8 months ago, # |   0 Can we do D in O(K) where K denotes the number of black squares?
 » 8 months ago, # | ← Rev. 2 →   +23 I think there is an $O(n$ $log(max(a_i))$ $+$ $log^2(max(a_i)))$ solution for problem E. Details is as follows:First of all, the current solution can be sped up to $O(n$ $log^2(max(a_i)))$ by using dynamic connectivity or creating a spanning tree which connects all the nodes for every $a_i$, updating it for every $+1$ or $-1$ operation and running DSU to check if the bits are connected. That way, the precomputation part will be $O(n$ $log(max(a_i)))$, and the checking part can be done in $O(log^2(max(a_i)))$.For the second optimization, I claim that only checking $log(max(a_i))$ times is sufficient for us to determine whether there exists a construction for answer $=$ $1$.First of all, we have to precompute the connectivity of the 30 bits in the given configuration (after adding $1$ to every $a_i$ $=$ $0$) using DSU. Then, we store the index of the LSB (least significant bit) of every connected component in a set (which I'll call $R$). To check answer = $0$ we simply have to check if $|R|$ $=$ $1$.Lemma 1: $+1$ operations only work if $|R|$ $=$ $2$ and $min(R_i)$ $=$ $0$. Proof of Lemma 1Case 1: $a_i$ is evenAdding $1$ to $a_i$ means connecting the current component with the $0$th bit, which reduces the no. of components by at most $1$.Case 2: $a_i$ is oddAdding $1$ to $a_i$ means possibly disconnecting some parts of the current components, and connecting the current component with $1$ bit (can be any bit except for $0$). For this operation, the best case reduces the no. of components by $1$ as well, so $|R|$ $=$ $2$ must be true.Furthermore, observe that the current component $a_i$ is in has the $0$th bit, which must be the LSB of the component. Therefore, we can add $1$ to an element from the other component instead and achieve the same result.Lemma 2: $-1$ operations only work when LSB of current value $\geq$ $max(R_i)$ and the current component doesn't disconnect after the operation. Proof of Lemma 2A $-1$ operation means removing an edge between the component and the LSB (hence possibly disconnecting them) and adding an edge between it and every bit less than the LSB.We can prove this lemma by contradiction. Assume there exists a $-1$ operation on an element $a_i$ with LSB $<$ $max(R_i)$. Obviously, that element won't be in the component $max(R_i)$, and after the $-1$ operation, it still won't be connected with that component as all the bits affected aren't in that component. Therefore, it won't be possible if the LSB of the current value $<$ $max(R_i)$.Even if some $a_i$ satisfies the first condition, the component $a_i$ is currently in might disconnect after performing the operation, so we have to check whether the component is connected using the $O(log^2(max(a_i)))$ checking method above.(Side note: There might be some faster methods for checking as we only have to check whether a component is disconnected or not. If you have any ideas, please comment below!)Lemma 3: We will find a solution after checking at most $log(max(a_i))$ distinct values that has LSB $\geq$ $max(R_i)$. Proof of Lemma 3Notice that in order for a component to disconnect after the $-1$ operation, the edge that was removed must be a bridge in the graph. In a graph, there will be at most $n-1$ bridges, where $n$ is the number of nodes. Therefore, in our graph, there will be at most $log(max(a_i)) - 1$ bridges, and we will find a valid configuration after at most $log(max(a_i))$ tries.Note that for values with a single bit (a perfect power of 2), only $a_i$ $=$ $2^{LSB}$ might not be valid, and the rest must be valid.Hence, we can find the answer with overall time complexity $O(n$ $log(max(a_i))$ $+$ $log^2(max(a_i)))$. The $O(n$ $log(max(a_i)))$ is from the precomputation for the graph, and $O(log^2(max(a_i)))$ is for the queries.Here is my implementation of the above solution. If you spot any flaws in my solution, please comment below; I would very much appreciate it. Also, sorry for my bad English ._.
 » 8 months ago, # |   0 how B can be optimized to O(nlogn)
 » 8 months ago, # |   0 B- Mystic Permutation's O(n) solution was awesome :)
 » 8 months ago, # |   0 https://codeforces.com/contest/1689/submission/160132878 Can anyone help with the test where my solution to C gets runtime error.
 » 8 months ago, # | ← Rev. 3 →   0 Problem C can be solved using a simple preorder traversal, with only an adjacency list as extra memory. Essentially: dfs(current, current_kill, &min_kill): if current has 0 child: min_kill = min(current_kill, min_kill); else if current has 1 child: min_kill = min(current_kill+1, min_kill); else: dfs(current.left, current_kill+2, min_kill); dfs(current.right, current_kill+2, min_kill); If the current node has no children, then the infection has reached it's end, and the current killed node count can be compared to the global min_kill count.If the current node has one child, it can be stopped by pruning that one child. This ends the infection, and increases the kill count by 1 extra, so we compare current_kill+1 instead.If the current node has 2 children, we will try pruning each child. This causes the child to die, and the other node to be infected, so dfs is called again with current_kill+2.This strategy will explore every path that the infection can take and store the minimum killed nodes in a single variable.
 » 8 months ago, # |   0 I tried the approach of Manhattan distance and rotating technique for problem D.Many people have solved this problem by DP. Can any one please explain your DP appraoch?Thank you in advance for helping.
 » 8 months ago, # |   0 n0sk1ll, How to prove the solution for B?
 » 8 months ago, # | ← Rev. 2 →   0 Is there rigorous proof for question D?
 » 8 months ago, # |   0 I have some questions about the solution to problem A. What if I have taken all the characters in string A but there is still more than k characters in string B?
 » 7 months ago, # | ← Rev. 3 →   0 My Approach for problem C:D0 = distance of closest leaf node from root.D1 = distance of closest 2 degree node from root (Also consider root if degree of root = 1)Answer = min(n - 2*D0 - 1, n - 2*D1 - 2)`Idea: we want minimal infection spread, therefore we will force the spread of infection to nearest cut-off point and that can only be a leaf node or a 2 degree node.My Solution
 » 6 months ago, # |   0 For problem E, there exists easier way to check if graph is connected.Repeat $log$ $max$ $a_i$ times following : If $a_0$ $\text &$ $a_i>0$ set $a_0$ to $a_0|a_i$ Finally if there exists some $a_i$ that $a_i$ $\text&$ $a_0=0$ then graph is disconnected.
 » 5 months ago, # | ← Rev. 2 →   0 Didn't quite liked the editorial....as if the question was less of a pain....can't even understand editorial of A. Downvoting