### vovuh's blog

By vovuh, history, 4 years ago,

1454A - Special Permutation

Idea: MikeMirzayanov

Tutorial
Solution

1454B - Unique Bid Auction

Idea: MikeMirzayanov

Tutorial
Solution

1454C - Sequence Transformation

Idea: MikeMirzayanov

Tutorial
Solution

1454D - Number into Sequence

Idea: MikeMirzayanov

Tutorial
Solution

1454E - Number of Simple Paths

Idea: vovuh

Tutorial
Solution

1454F - Array Partition

Idea: MikeMirzayanov

Tutorial
Solution
Solution (Gassa)
• +134

| Write comment?
 » 4 years ago, # |   +39 Really liked problem E, great contest.
•  » » 4 years ago, # ^ |   +32 Overall contest was great especially the problem E. Thanks vovuh
 » 4 years ago, # |   0 great problems, thanks Mike and vovuh for setting div. 3s! much appreciated.
 » 4 years ago, # |   +14 did i get bonus point by succefully hacking someones code in this div3 contest? P.S : i am new in this codeforces platform
•  » » 4 years ago, # ^ |   +13 No. Bonus point can only be earned in regular Div.1 and Div.2 Round, or some Div.1+Div.2 Round like Global Round.
 » 4 years ago, # |   +40 The leaf trick for E is really neat , really liked it ... Nice contest
•  » » 4 years ago, # ^ | ← Rev. 2 →   +9 Can you pls explain how would you implement the straight-forward solution which is: "just extract and mark all cycle vertices and run dfs from every vertex of a cycle"? Thanks
•  » » » 4 years ago, # ^ |   +9 Start a dfs from any vertex and maintain prev of each element i.e the node before that node in the dfs tree. Now when you come across a visited vertex $v$ from the vertex $u$, then this means this vertex $v$ is part of a cycle and the cycle is $v, prev[v], prev[prev[v]], ... , u$.
•  » » » » 4 years ago, # ^ |   0 won't going to prev everytime take you to the root ? i guess you need to find the first common ancestor of u and v
•  » » » » » 4 years ago, # ^ |   0 oh my bad i am sorry
•  » » » » 4 years ago, # ^ |   0 Can you explain which vertices are the cycle vertices?And what does it mean by "trees hanged on cycle vertices". I am not clearly understanding the solution to E.
•  » » » » » 4 years ago, # ^ |   0 Since the graph is connected and number of vertices is equal of number of edges, there will a only one cycle. Now you can notice other vertices will form a trees with cycles vertices as roots. (Try drawing some pictures)
•  » » » 4 years ago, # ^ |   +18 Consider storing the graph as vector >, each vertex having a set of edges to adjacent vertices. Then we can efficiently remove an edge from the graph, by just removing it from the sets at both ends. In fact, here is a solution that does just that: 99510704
•  » » » 4 years ago, # ^ | ← Rev. 6 →   +3 I implemented it but can't find my mistake
•  » » 4 years ago, # ^ |   0 can you explain leaf trick bit more i didnt get that??
•  » » » 4 years ago, # ^ |   0 since the graph contains n edges that means it is a tree with one extra edge. This one extra edge will create some cycle in the tree. Now any note the following point 1) Any node in this cycle is of atleast degree 2 2) observe leaf trick -> we are picking the leaf nodes one by one and removing them and the edge between it and it's parent after processing. And after this removal either the parent node could either be of degree 1 (a new leaf), or (some node with more descendents present which would eventually be removed by the leaf trick). Or this parent node could be in the cycle. after removal of all the children nodes only nodes present in the cycle will be left in the queue.
 » 4 years ago, # | ← Rev. 4 →   +8 Can anyone tell me, in problem F's solution provided by Gassa: In the expansion part, "we can pick the side of expansion after which the value min(u,v,w) is larger, and if these are equal, pick any". I can't understand why in the case of equal, we can pick any. Wouldn't that affect afterwards?
•  » » 4 years ago, # ^ | ← Rev. 3 →   0 We can prove that if there is an answer, this approach won't lose it.Assume the maximum on left segment is $u$, the minimum on middle segment is $v$, the maximum on right segment is $w$ and there exists a partition makes $u = v = w = x$.For all the second segments that satisfy the condition, there is a biggest one include all the others, let it be $[L, R]$. (Easy to see if another segment $[L', R']$ also makes $u = v = w = x$ and neither of them includes the other, $[min(L, L'), max(R, R')]$ will be the one includes them both.)Because after every move $min(u, v, w)$ will only be smaller or stay the same, and $[L, R]$ is the biggest segment makes $u = v = w = x$. So for a partition $[l, r]$, if $l < L$ or $r > R$, $min(u, v, w) < x$. (Otherwise $[l, R]$ also satisfy the condition and it's bigger than $[L, R]$.)Initially, $[l, r]$ is included by $[L, R]$. When will we lose the answer? Only when $l = L$ and we make $l$ decrease or vice versa. But if we do so, $min(u, v, w)$ will be smaller than $x$ as we mentioned above, but in the other choice $min(u, v, w) >= x$, so the algorithm will pick the other and will not lose the answer.
 » 4 years ago, # |   0 Can someone tell me what's wrong in my code for Problem D My Codemap < int , int > cnt;bool cmp(int a, int b){ return cnt[a] > cnt[b]; }vector factorize(int n) { vector res; for (int i = 2; i * i <= n; ++i) { while (n % i == 0) { res.push_back(i); cnt[i]++; n /= i; } } if (n != 1) { cnt[n]++; res.push_back(n); } return res; }signed main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int test; cin >> test; while(test--){ int n; cin >> n; vector < int > fact = factorize(n); bool isThere = false; for(auto i : cnt){ if(i.second > 1){ isThere = true; break; } } if(!isThere){ cout << 1 << "\n"; cout << n << "\n"; }else{ vector < int > ans; sort(all(fact), cmp); for(int i = 0; i < (int)fact.size(); i++){ if(fact[i] != fact[i+1]){ int pu = 1; while(i < (int)fact.size()){ pu *= fact[i]; i++; } ans.push_back(pu); }else{ ans.push_back(fact[i]); } } cout << (int)ans.size() << "\n"; for(auto i : ans) cout << i << " "; cout << "\n"; cnt.clear(); } } return 0;}
•  » » 4 years ago, # ^ |   0 use long long
 » 4 years ago, # | ← Rev. 4 →   +8 I have a simple approach for F:(to avoid misunderstanding, I will count the array from index 1)First, we will create an array $left$ and $right$ satisfy these condition:a) $1 \leq left_i \leq i \leq right_i \leq n$b) $A_i = min(A_{left_i}, A_{left_{i + 1}}, A_{left_{i + 2}}, ..., A_{right_i})$c) $right_i - left_i$ is maximum.We can build this array using deque, as I indicated in my submission.Then, we will try to find out two index $x$ and $y$ such that $x \geq left_i - 1$ and $y \leq right_i + 1$. (why?).To find out $x$ and $y$, we will maintain 2 more arrays: prefix maximum and suffix maximum. And the rest part could be done easily with binary search.Finally, we can partition the initial array into 3 parts: $x$, $y - x - 1$, and $n - y + 1$.My submission: 99517001
•  » » 4 years ago, # ^ |   +3 Very nice approach. Saved me the effort of learning RMQ.
»
4 years ago, # |
-47

can anyone help me why my B question do not get accepted although my idea was same but failed particular testcase ~~~~~

# include<bits/stdc++.h>

using namespace std; typedef long long ll; typedef std::vector vi;; typedef pair<ll, ll> pi;

int main() {

# ifndef ONLINE_JUDGE

// for getting input from input.txt
freopen("input1.txt", "r", stdin);
// for writing output to output.txt
freopen("output2.txt", "w", stdout);


# endif

ll t;
cin >> t;
while (t--) {

ll n;
cin >> n;
ll a[n];
ll b[n] = {0};
ll mx = 0;

for (ll i = 0; i < n; i++) {
cin >> a[i];

b[a[i]]++;

mx = max(a[i], mx);
}

bool flag = true;
ll g;
for (ll i = 1; i <= mx; i++) {
if (b[i] == 1) {

flag = false;
g = i;
break;
}

}
if (n == 1) {
cout << 1 << "\n";
}
else if (n == 2) {
if (a[0] == a[1]) {
cout << -1 << "\n";
}
else if (a[0] > a[1]) {
cout << 2 << "\n";
}
else if (a[0] < a[1]) {
cout << 1 << "\n";
}
}
else if (flag == true) {
cout << -1 << "\n";
}
else {
for (ll i = 0; i < n; i++) {
if (a[i] == g) {
cout << i + 1 << "\n";
break;
}
}
}

}


}

~~~~~

•  » » 4 years ago, # ^ |   +4 u know right, You will get downvoted for pasting code rather than posting the submission link?
•  » » » 4 years ago, # ^ |   +20 sorry this was first time i tried to interact in editorials...next time i will keep in mind ..my bad
 » 4 years ago, # | ← Rev. 3 →   0 Anyone help me where i am getting wrong for problem F 99476252 or is my logic incorrect?UPD: got AC (just because i wrote log() inplace of log2()).
 » 4 years ago, # |   0 Can anybody explain why my solution https://mirror.codeforces.com/contest/1454/submission/99483191 for D is giving TLE
•  » » 4 years ago, # ^ |   0 i*i <= n causes integer overflow and leads to increased iterations of the for loop. Changing int to long long should work.
 » 4 years ago, # |   0 can someone explain problem 2 in detail??
•  » » 4 years ago, # ^ |   0 You have to print the index of the minimum element of all the elements that occur only once in the given array. Hope this makes it clearer.
 » 4 years ago, # |   0 Can anyone familiar with C++ please explain this, In the editorial of Problem C, std::unique returns a forward iterator to the end of the modified vector right? Are we typecasting that to an int here ?
•  » » 4 years ago, # ^ |   +8 We are getting the size of the array after modification, i. e. removing consecutive duplicates. As vector iterator is a random access iterator, so we can just subtract vector::begin(), to get the total number of elements from the beginning of vector to the end of the modified vector
 » 4 years ago, # |   +8 is E solvable for more than n edges?
 » 4 years ago, # |   0 Why system testing happens in Contests having open hacking phase , meaning it shows Accepted then what is the need of system testing
•  » » 4 years ago, # ^ |   +1 It is rejudged with hack cases. If someone's solution gets hacked, the author decides if he wants to include the hack case (i think) and everyone's code is tested again.
 » 4 years ago, # |   +3 my solution for question 2 is same as written in tutorial, but it was hacked , Why :( solution link https://mirror.codeforces.com/contest/1454/submission/99428157
•  » » 4 years ago, # ^ |   0 Maybe you get TLE because for each test you are resetting arrays flag and ind to 0. Thus the time complexity is $O(4 * 10 ^ 9) = ~4s$.
•  » » » 4 years ago, # ^ |   +3 if i use vector insted of array ,i got ac?
•  » » » » 4 years ago, # ^ |   0 No it's not that. Just at the first for don't go through all the elements. Go through the first n+1 and it will be fine.
•  » » » » » 4 years ago, # ^ |   +3 for(int i=0;i<200005;i++) flag[i]=0,ind[i]=0; for(int i=0;i>m,flag[m]++,ind[m]=i+1; int x=-1; for(int i=1;i<=n;i++) { if(flag[i]==1) {x=ind[i]; break;} }this loop is also go through (n+1)
•  » » » » » » 4 years ago, # ^ |   0 Yes but if n is a small number then you go through positions that you don't need to use. So if you change 200005 to n+1 it should be fine. PS: If you want you can make flag and ind vectors and assign them to the size of n.
•  » » 4 years ago, # ^ |   +1 Because you fill arrays with zeros from 0 to $2*10^5$ for each test, so it becomes $4*10^9$ in total. You can just change your “for” from 0 to n.
•  » » » 4 years ago, # ^ |   +8 https://mirror.codeforces.com/contest/1454/submission/99432026 can you tell why this is giving tle for b??
•  » » » » 4 years ago, # ^ |   -8 You are creating a map of size 10^5 for every test case. There can be 10^4 test cases so number of operations could be 10^9
•  » » » » » 4 years ago, # ^ |   +8 so creating map will add to complexity??
•  » » » » » » 4 years ago, # ^ |   +8 You are initializing an array of size 200005 every time. The time complexity of array initializing is O(N). Thats why you were getting TLE.
 » 4 years ago, # |   +2 My solution for $E$ to find all nodes which belongs to cycle or not: Use bridge finding algorithm, and if an edge is not a bridge then two nodes connecting this edge will be in cycle, so mark them. code. PS : Simple dfs would have worked, but almost always i end up in an infinite loop, when writing dfs code to find nodes that are in cycle.
 » 4 years ago, # |   0 Can somebody help me understand how this submission got hacked? Is it some Java stuff?
•  » » 4 years ago, # ^ |   +3 Change the size of your cnt array from 200001 to n+1. Because if number of test cases is 20000, total no. of operations will be 4∗10^9 which will result in TLE
 » 4 years ago, # |   +4 Anyone use random shuffle to solve A?
•  » » 4 years ago, # ^ |   0 Yes you
•  » » 4 years ago, # ^ |   0 did random shuffle passed test cases
•  » » » 4 years ago, # ^ |   0 Random shuffle till find a valid solution passed.
•  » » » » 4 years ago, # ^ |   +9 This solution is not wrong. We only need a few random shuffles to get the correct solution.What the problem asks (find a permutation such that P_i != i for all i) is basically to find a derangement of the permutation.More about derangement can be found here.The probability of getting a derangement from all permutations of length N is !N / N!. The value of !N / N! approaches to 1 / e = 37%Let's say we want to do random shuffle X number of times such that the probability of getting a derangement is at least 99%.Then, (0.37)(1 — (1 — 0.37)^X) / (1 — (1 — 0.37)) >= 0.99 This gives us X >= 10, so doing 10 random shuffles already gives us 99% chance of getting a valid derangement.We can increase X to 50 to increase the odds. We can also just random shuffle until we find a valid solution like you did, which can be expected to use at most 50 shuffles.This gives us a O(50TN) solution which gives accepted.An example demonstration of using 50 random shuffles here
 » 4 years ago, # | ← Rev. 2 →   +4 problem C got weak testcases. Someone from the Egyptian Olympiad in Informatics(so I know him) passed problem C with a wrong solution so I hacked him. Surprisingly after system testing, I found that this is the only case that made him fail and if I didn't hack him, he was going to pass system testing. Oh, and also I found out that around 12 people also failed on the case(My case: Case#7). So around 12 people were going to also unfairly pass.
•  » » 4 years ago, # ^ |   +5 what is your test case??
•  » » » 4 years ago, # ^ |   +6 My testcase was a randomly generated array of length $2*10^5$. The elements in the array were from $10^5$ to $2*10^5$. A lot of people have done the mistake of doing a frequency array of size $10^5$ or $10^4$. Now you wonder, why they did the frequency array so small that would give runtime error or wrong answer? Here is my answer:1)Some people didn't notice the mistake. They were gonna pass unfairly.2)Other people who didn't use memset or a fast method of memory allocation in each testcase, the person got TLE with $2*10^5$. So the person decreased the allocation to $10^4$ surprisingly, it passed system testing and was going to pass all system testing.
•  » » » » 4 years ago, # ^ |   +5 great
•  » » 4 years ago, # ^ |   +5 A stress test was missing in the pretests... An array of largest size with all elements equal was an easy hack for my solution (TLE but could be easily fixed if I TLEd a pretest). Was pretty happy that I did ABCDF then got hacked on C :/
 » 4 years ago, # | ← Rev. 2 →   0 can anyone pls tell me at which test case my code is failing.link of my solution : https://mirror.codeforces.com/contest/1454/submission/99488821
 » 4 years ago, # |   +5 I solved F using segment trees and binary search in O(nlog² n). Submission. Code#include #define int long long using namespace std; int range_max(int t[], int l, int r, int n) { // max on interval [l, r) int res = 0; for(l += n, r += n; l < r; l >>= 1, r >>= 1) { if(l & 1) res = max(res, t[l++]); if(r & 1) res = max(res, t[--r]); } return res; } int range_min(int t[], int l, int r, int n) { // min on interval [l, r) int res = INT32_MAX; for(l += n, r += n; l < r; l >>= 1, r >>= 1) { if(l & 1) res = min(res, t[l++]); if(r & 1) res = min(res, t[--r]); } return res; } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--) { int n; cin >> n; int mintree[2 * n], maxtree[2 * n]; for(int i = 0; i < n; i++) { cin >> mintree[n + i]; maxtree[n + i] = mintree[n + i]; } for(int i = n - 1; i > 0; i--) maxtree[i] = max(maxtree[i << 1], maxtree[i << 1 | 1]), mintree[i] = min(mintree[i << 1], mintree[i << 1 | 1]); int i; for(i = 0; i < n; i++) { int a, b, c; a = range_max(maxtree, 0, i + 1, n); int beg = i + 1, end = n - 2, mid; while(beg <= end) { mid = beg + end >> 1; b = range_min(mintree, i + 1, mid + 1, n); if(b == a) { c = range_max(maxtree, mid + 1, n, n); if(c == a) { cout << "YES\n"; cout << i + 1 << ' ' << mid - i << ' ' << n - mid - 1 << '\n'; goto end; } else if(c < a) end = mid - 1; else beg = mid + 1; } else if( b < a) end = mid - 1; else beg = mid + 1; } } end: if(i == n) cout << "NO\n"; } } 
 » 4 years ago, # |   +7 How to approach E if there were more than N edges ?
•  » » 4 years ago, # ^ |   +5 that problem has no known polynomial time solution. try googling
 » 4 years ago, # |   0 Can someone explain why my submission is showing wrong answer on test case 4 even though it is right? https://mirror.codeforces.com/contest/1454/submission/99475597
•  » » 4 years ago, # ^ |   +5 The return; statement should be inside if(cnt==-1||cnt==1){...}
 » 4 years ago, # |   0 Alternative solution for F. Lets iterate through all values, and try to make each value minimum of second block. If we are trying to make $a_i$ minimum, we should find first value left to i, such that $a_k  » 4 years ago, # | +8 I came up with simple approach in F.First we will build min and max sparse table so that we can get min and max values in O(1).Its easy to observe that as we increase length of a segment, maximum value increases , and minimum value decreases. Using this observation : For every possible X from 1 to n-2, we will find lower bound(l) and upper bound(u) of possible value of Y. This can be done using binary search. The third segment ,if possible, will lie in between (l+1) to (u), and this can also be found using binary search.If at any point we are able to find first, second and third segment, We will print it. Else No possible answer is there.Using this approach, we can further extend the problem to calculate all possible X,Y,Z which satisfy the given conditions.Time Complexity -> O(nlogn). Submission link -> https://mirror.codeforces.com/contest/1454/submission/99541373 •  » » 4 years ago, # ^ | +3 That is exactly what I've done but I used seg trees for min and max xD but it worked. And yep, I agree that the idea of that solution so simple. I got the idea in only 10 minutes(and 30 minutes implementing and debugging due to the fact that I don't have a segment tree template :c).  » 4 years ago, # | ← Rev. 3 → -6 deleted •  » » 4 years ago, # ^ | ← Rev. 2 → 0 You should paste the link or put your long code into the spoiler Like thisYou can highlight it too !   » 4 years ago, # | 0 In F solution by gassa why u=min(x[lo-2],a[lo-1]) i.e why x[lo-2] is here? •  » » 4 years ago, # ^ | +3 The maximum on the updated left segment, [0..lo - 1), is just stored in x[lo - 2]. The middle segment just got a[lo - 1] added to it, so it can contribute to the minimum on the middle segment.  » 4 years ago, # | +8 Question D is very good  » 4 years ago, # | 0 Can someone explain problem D for me? I am having a hard time understanding the explanation •  » » 4 years ago, # ^ | +19 Never mind guys,i just saw neal's discussion stream.Its clear now.stream link  » 4 years ago, # | 0 When we do cnt * (n-cnt), arent we counting some edges multiple times? Lets say we have two vertices on the cycle each with a tree of size k. Then for both vertices we do k*(n-k). So, arent the paths between both trees counted twice? Can you please correct me where I am going wrong. •  » » 4 years ago, # ^ | 0 I also think you are correct. I think there's a typo in the editorial for E and answer should be: for all cnts in cycle: cnt * (cnt — 1) + (cnt * (n-cnt) / 2) where the division is not integer division. •  » » » 4 years ago, # ^ | 0 I'm an idiot, I should've thought about it more before commenting. What you're saying is true, the paths do look like they are being counted twice. You would normally expect it to be divided by 2. However, each time a node from a tree finds a path to another node that's in another tree, there are two ways to get there; it can either go clockwise around the cycle, or go anti-clockwise. This means this multiply-2 from going clockwise-anticlockwise cancels out the divide-2 from the paths being counted twice. So in the end, it's cnt*(n-cnt). •  » » » » 4 years ago, # ^ | 0 Thanks for clearing up  » 4 years ago, # | ← Rev. 2 → 0 can anybody tell me what's wrong with my code problem C got WA, D got TLE sorry for bad quality because I coded those in a rushUPD: i knew my problem D code was wrong because i didn't check all primes possible but why was that TLE'ed C: 99488693 D: 99475141  » 4 years ago, # | 0 Can someone explain why did this solution TLE's? My Solution •  » » 4 years ago, # ^ | 0 It's giving TLE on test 2 which has 2e4 testcases. Now, in your code, you are running this loop: for(int i = 0 ; i < ARR+2 ; i++) lastocc[i] = -1; where ARR = 2e5+2. Hence, in total you are doing computations more than 2e4*2e5=4e9, which is causing TLE.  » 4 years ago, # | ← Rev. 2 → +8 Interesting fact: author's solution problem D have time complexity$O(\sqrt{t\cdot N})$, where$N$is sum$n$for all test cases ($N <= 10^{10}$). Proof: SpoilerLet$N = \sum_{i=1}^t n_{i}$, where$n_i$is number in$i$-th test case.Complexity solution is$O(\sum_{i=1}^t \sqrt{n_i})$. Prove that$\sqrt{t\cdot N} \ge \sum_{i=1}^t \sqrt{n_i}$:$ \sqrt{t\cdot N} \ge \sum_{i=1}^t \sqrt{n_i}\\ t\cdot N \ge {(\sum_{i=1}^t \sqrt{n_i})}^2\\ t\cdot \sum_{i=1}^t n_i \ge \sum_{i=1}^t{n_i} + 2\sum_{i=1}^t{\sum_{j=i+1}^t{\sqrt{n_i\cdot n_j}}}\\ (t - 1)\cdot \sum_{i=1}^t n_i - 2\sum_{i=1}^t{\sum_{j=i+1}^t{\sqrt{n_i\cdot n_j}}} \ge 0\\ \sum_{i=1}^t{\sum_{j=i+1}^t{(n_i - 2 \cdot \sqrt{n_i \cdot n_j} + n_j)}} \ge 0\\ \sum_{i=1}^t{\sum_{j=i+1}^t{(\sqrt{n_i} - \sqrt{n_j})^2}} \ge 0\\ $Last line is sum square of number. It's always not negative value. All transformations in the proof were valid, which means that$\sqrt{t\cdot N} \ge \sum_{i=1}^t \sqrt{n_i}$. So, time complexity of solution is$O(\sqrt{t\cdot N})$.  » 4 years ago, # | ← Rev. 5 → 0 can someone explain to me the problem 3? i don't get the editorial.also, i have a different approach of the problem, i don't know why it doesn't work.the main idea of my solution is that for each element, we split the integers according to the element and and get the minimum size of the splitted integers. so in the last test 11 2 2 1 2 3 2 1 2 3 1 2 if i split the 3, i get 2 2 1 2 2 1 2 1 2 which is equal to 3 •  » » 4 years ago, # ^ | 0 In fact it works, with a little improve.let x be the value we are trying. (For each value we only do it once) We need some way (you can think about it) to help us get to the next position NXT in the array that a[NXT]==x in O(1). Instead of go though all the array and find.so the total time need is O(n) after the improve.There are some parts need to be careful, It is easy to write wrongly. •  » » » 4 years ago, # ^ | 0 then i don't know why my code doesn't work. is it because i made the array into string? here is my code: int n=sc.nextInt(); String ns=""; Set sets= new HashSet<>(); for(int i=0;i list = new ArrayList<>(Arrays.asList(nArr)); list.removeAll(Arrays.asList("", null)); if(list.size() •  » » » » 4 years ago, # ^ | ← Rev. 2 → 0 I don't know much about java but I think the split() function take O(n) time to split the array, so the total is still O(n*n). If there is no problem with the time we can use string, it's easy to write. But I don't suggest to use string to often. //In c++ there are lot of string operator are not O(1), but greater than it. string s=""; s+='a'; //this is O(1); s='a'+s; //this is O(length of s); //if we do s='a'+s n times, it is O(1+2+3+...+n) = O(n*n) We need to use a list or array to save where the next number is. For example. a[] = {1,3,2,4,4,1,2}. nxt[1][]={0,1,5,8} nxt[2][]={0,3,6,8} nxt[3][]={0,2,8} nxt[4][]={0,4,5,8} we add a '0' in the beginning and a 'n+1' at the end. Then for each number check throw nxt, to calculate the answer.we don't have space so save a array size[2e5][2e5]. So use a list or vector.  » 4 years ago, # | 0 Can someone explain to me how the proposed solution for D didn't send TLE when in the worst case scenario you'd have to check if the numbers are divisible by any of all values up to 10^5? And here I was thinking of how to optimize it to reduce it to sqrt(10^5) and only checking with prime numbers using a sieve lol.For reference, using the method above, it takes way more than 10 seconds when testing the number 9999999769, which could perfectly fit into a test case.This is my first time competing in codeforces, which probably explains my confusion. Anyways, any help with my doubt is appreciated :) •  » » 4 years ago, # ^ | 0 If you can put you code I can see the problem. I'm not that good at English.Here is some of my understanding.First you only need to check the prime number from 2 to sqrt(n). Why? Because if we check from 2 to sqrt(n) and there is no prime number that n%P==0. We can confirm that n is a prime.So there is no need to check the rest of it.If the smallest prime factor of n is greater then sqrt(n) then n is a prime. Because if there is P1>sqrt(n) and P2>sqrt(n) there is no way P1*P2<=n.Here's how I divide a number in to prime factors cin>>n; int tmp=n; for(int i=2;i*i<=n;i++) { while(tmp%i==0) { cnt[i]++; tmp/=i; } } if(tmp!=1) cnt[tmp]++; Of course tmp can be very big, it need to be write like this cin>>n; int tmp=n; for(int i=2;i*i<=n;i++) { if(tmp%i==0) p[++tot]=i; while(tmp%i==0) { cnt[tot]++; tmp/=i; } } if(tmp!=1) p[++tot]=tmp,cnt[tot]++;   » 4 years ago, # | 0 Hi all. in problem d i have made certain observation. if the number is prime we cant do much we print the number itself if the number is not prime then i observed and did this -> count all the prime factors and the frequency. The maximum frequency will be the length.-> what i observed is only 2 3 5 and other prime numbers are the only prime factors of a number. for example 65=5*13 8=2*2*2 and so onnow what i did in my code. first i checked whether a number is prime or not if it is then i did step 1 and if not i count all the 2s 3s 5s and other prime numbers if any after all the counting if the max freq is 1 then printing the number itself ,if not then printing the minimum prime factor according the max frequency now my problem is that my code is giving TLE like hell because my code for checking prime number is inefficientso i want to know if my concept and approach is correct at all and if so how to optimize my code? •  » » 4 years ago, # ^ | ← Rev. 6 → 0 I sorry to say that you way is half correct.If the number is small, you solution can solve it.The way you check prime number and the way you calculate all the prime factors is a bit slow.here's how I get prime factors. cin>>n; for(int i=2;i*i<=n;i++) { while(n%i==0) { cnt[i]++; n/=i; } } if(n!=1) cnt[n]++,n=1; the most improtant part is i*i<=n. you only to check O(sqrt(n)) time.the if after is also necessary.For example n=21, first you get 7 after /3. Then quit the loop. But 7 is a prime factor. So if n!=1 after the loop then n must be a prime factor and it only appeared once.You can try some number and have a deeper understanding.This solution is O(sqrt(n)). There are faster solution but you need to learn more. Like how to get prime number from (1 to n) in O(n).I hope this will help you.  » 4 years ago, # | ← Rev. 3 → 0 RESOLVEDIn problem A, I wrote for (int i = 0; i < n; i++) { cout << (i + 2) % n << " "; } instead of  for (int i = 0; i < n; ++i) { cout << (i + 1) % n + 1 << " "; } as shown in the editorial, but get output : 0 1 \n 2 3 4 0 1 for the input: 2 2 5 I think the codes are implementing the same thing. I have looked through c++ reference for the error, and searched "Modulo error" to find the reason, but I don't get anything useful. Can I have any hint or any keyword to search on Google about why this is happening?Thanks! •  » » 4 years ago, # ^ | +1 They are obviously not the same thing$(5+2)\operatorname{mod}7=0(5+1)\operatorname{mod}7+1=6+1=7$•  » » 4 years ago, # ^ | 0 I don't know whether this is you problem.In the first way, 0<=(i+2)%n  » 4 years ago, # | 0 For E Is there proof that it will have always 1 cycle? •  » » 4 years ago, # ^ | 0 use n-1 edges to build a tree first (link u[i] to v[i] if they are not connected) (or u[i] to v[i] is the 'last edge')then transform the un-root tree to a root treethe 'last edge' is from u to vthen the cycle is (root to u),(u to v),(v to root) •  » » » 4 years ago, # ^ | 0 Thanks  » 4 years ago, # | 0 The O(n) solution of promble F is very valuble.Here is my solution .I improve it from the O(nlogn) solution. let L be the left point, R be the right point. we can find that when L is increasing R decrease. also we can find that for one L there is only one R may be the answer.(there can be several but they are all the same.)let lmax[L] be the maximum value from 1 to L, rmax[R] be the maximum value from R to n.(lmax[L]==rmax[R])if there is k that (rmax[k]==rmax[R] && L  » 4 years ago, # | 0 but there is another approach without any graph algorithms that works very well for such kind of graphs vovuh Is the leaf trick that you mentioned in the editorial of problem E, a particularly classic known idea / algorithm ? •  » » 4 years ago, # ^ | 0 I don't know if it's really well known approach in general but it works very well for me when you need to calculate something on functional graphs.  » 4 years ago, # | 0 I am applying seg tree+ 2 pointers in problem F ,but it gives WA on test case 2 (case 721) . Could anyone pls help me ? Here's my code :99797628  » 4 years ago, # | 0 Can somebody please help me with my code, its for problem E, I keep getting MLE and i just cant understand why? 100473133 •  » » 3 years ago, # ^ | 0 Did it get resolved?  » 3 years ago, # | ← Rev. 3 → 0 In problem E, why does a normal BFS/DFS lead to MLE on test 2?The memory limit seems to be sufficient. I even tried declaring global arrays and with a maximum size of 100 to at least pass test 2, it still resulted in MLE. vovuh can you explain please?PS: Solved it finally but had to rewrite from scratch (without using any boiler plate code). Not getting what's the problem with the previous one. Will using one/two extra vectors of$O(n)\$ size make any difference?
 » 2 years ago, # | ← Rev. 2 →   0 I have solved F with segment trees and the two-pointer algorithm. So I have a start(== 0) and end(== N-1) variable. I have segment trees to query maximum from ([0, start], [end, N-1]) and minimum from ([start+1, end-1]). Now my segments are [0, start], [start+1, end-1] and [end, N-1]. My aim is to increase max1([0, start]) and max2([end, N]) as gradually as possible. Now in our while loop if max1 == max2 == min(from [start+1, end-1]) then we have found a solution otherwise we have to update start and end.So if(max1 < max2) or (max1 > max2) I will start++ or end-- accordingly. But if max1 == max2 then I will compare A[start+1] and A[end-1] and if they too turn out to be equal then I will compare A[start+2] and A[end-2]. So even if I have a case where start+1 and end-1 point to equal elements I will make sure that the increase in [0, start] and [end, N-1] is gradual. 142372335 ~~~~~ Your code here... ~~~~~ ll N; cin >> N; vector A(N); for (ll i = 0; i < N; i++) cin >> A[i]; vector segmentMin(4 * N, LONG_LONG_MAX), segmentMax(4 * N, LONG_LONG_MIN); buildMin(0, 0, N - 1, A, segmentMin); buildMax(0, 0, N - 1, A, segmentMax); bool possible = false; ll start = 0, end = N - 1; while (start + 1 < end) { ll max1 = queryMax(0, 0, N - 1, 0, start, segmentMax); ll max2 = queryMax(0, 0, N - 1, end, N - 1, segmentMax); ll min1 = queryMin(0, 0, N - 1, start + 1, end - 1, segmentMin); if (max1 == max2 && max1 == min1) { possible = true; break; } if (max1 < max2) start++; else if (max1 > max2) end--; // max1 == max2 else { // we want to slowly increase max1 and max2 if (A[start + 1] < A[end - 1]) start++; else if (A[start + 1] > A[end - 1]) end--; // ultimate slow increaser else if (start + 2 <= end - 2 && A[start + 2] < A[end - 2]) start++; else end--; } } if (possible == false) { cout << "NO\n"; continue; } cout << "YES\n"; cout << start + 1 << " " << end - start - 1 << " " << N - end << "\n";
 » 3 months ago, # | ← Rev. 5 →   0 problem c 101 5 2 5 6 5 10 10 7 1 2how is this going to be 1 !?????????????????????I wasted 2 hour and it seems that I can't even get what the problem want