### 676A - Nicholas and Permutation

All what you need to solve this problem — find the positions of numbers 1 and *n* in the given array. Let's this positions equal to *p* _{1} and *p* _{ n}, then the answer is the maximum of 4 values:

*abs*(

*n*-

*p*

_{1}),

*abs*(

*n*-

*p*

_{ n}),

*abs*(1 -

*p*

_{1}),

*abs*(1 -

*p*

_{ n}).

Asymptotic behavior *O*(*n*).

### 676B - Pyramid of Glasses

The restrictions in this problem allow to simulate the process. Let the volume of one wineglass equals to 2^{ n} conventional units. So the volume of the champagne surpluses which will stream to bottom level will always integer number. So let's pour in the top wineglass *q* * 2^{ n} units of champagne, and then we have following case: if in the current wineglass is more champagne than its volume, let's make *surplus* = *V* _{ tek} - 2^{ n}, and add *surplus* / 2 of champagne in each of the two bottom wineglasses.

Asymptotic behavior *O*(*n* ^{2}).

### 676C - Vasya and String

This problem can be solved with help of two pointers. Let the first pointer is *l* and the second pointer is *r*. Then for every position *l* we will move right end *r* until on the substring *s* _{ l} *s* _{ l + 1}... *s* _{ r} it is possible to make no more than *k* swaps to make this substring beautiful. Then we need to update the answer with length of this substring and move *l* to the right.

Asymptotic behavior *O*(*n* * *alphabet*).

### 676D - Theseus and labyrinth

It is easy to understand that we have only 4 states of the maze. How to solve this problem if there is no any buttons? It is just bfs on the maze (on the graph). Because of buttons we need to add to graph 3 additional levels and add edges between this levels. After that we need to run bfs on this graph and find the length of the minimum path if such exists.

Asymptotic behavior *O*(*n* * *m*).

### 676E - The Last Fight Between Human and AI

In this problem we have two main cases: *k* = 0, *k* ≠ 0.

Case when

*k*= 0. Then the division of the polynomial to the*x*-*k*depends only of the value of*a*_{0}. If*a*_{0}is already known then we need to compare it with zero. If*a*_{0}= 0 then the human wins, otherwise the human loses. If*a*_{ i}is not known then win who make the move.Case when

*k*≠ 0. Here we have two cases: all coefficients already known. Then we need to check*x*=*k*— is it the root of the given polynomial. Otherwise who will make the last move will win. Let we know all coefficient except one. Let this coefficient is the coefficient before*x*^{ i}. Let*C*_{1}is the sum for all*j*≠*i**a*_{ j}*k*^{ j}and*C*_{2}=*k*^{ i}≠ 0. Then we have the equation*a*_{ i}**C*_{2}= -*C*_{1}which always have the solution. If the human will make the last move he need to write the root to the place of the coefficient, otherwise computer will write any number, but not the root.

Asymptotic behavior *O*(*n*).

I crossed the road, walked into a bar, and changed a lightbulb.

Then I realized that my life was a joke...

just like this editorial

and like these problems

*these

need help from the red woman, post it with necklace

where are you from?..bar???

lmao

Thanks for fast editorial and the nice contest!

Can someone give an intuitive approach for problem C . I can't understand the editorial.

I thought this problem in this way: You have N numbers (a_i = {0,1}), find the maximum consecutive sum (only whit ones) if you can convert at most K zeros into ones. ?

It can be solved using two pointers. Now you can repeat this algorithm for each letter. I hope it helps you.. (Sorry for my poor english)

I'll explain C using the example: "abbaa" , k = 1

First, find out how many consecutive a's are possible in "abbaa" if we can swap no more than one 'b':

We're going to have "pointerLeft" and "pointerRight" describing the substring we're looking at during the execution. Both pointers start from -1.

We have now looked into all relevant substrings of consecutive a's. Next we would do the same thing for consecutive b's.

Thanks a lot!

Hey @baobab, I have implemented this problem using two pointers but I'm not able to understand how binary search will be used in this problem ?

I implemented it with two pointers only, haven't looked at the binary search solution.

hey you can look into my solution : http://codeforces.com/contest/676/submission/30375778

i know that this is an easy problem but can't think of it in this way...after two hours i land on this solution :)

idea : first make blocks of a's and b's and then find presums for a and b separately(for_A and pre array represents these). Now, take the first a and find the position upto which you can go ..(this can be done with the help of binary search in pre array (for a) and for_a array(for b)) and then simply update the answer and at last take the max for the two cases.

complexity = NlogN

but the editorialist solution is really cool :)

can u give me ur solution link i liked ur way simple and easy to understand

Here: https://codeforces.com/contest/676/submission/18082074

hey man i am using a similar approach but it times out on 12 test case do i need to optimise it

Hey, I took a quick look at your code and it looks like you're sometimes decreasing pointer r. You want to only increase both pointers, never decrease them. That way you can guarantee O(n) time complexity.

thanks man

Thx, that was very helpful

Pick one of the alphabet (a or b in this problem) and do the following: - Consider every character other than the picked character as a bad character. You need to find the maximum subarray that contains at most k bad characters because we can replace them with the picked character. Finding Maximum subarray with at most k bad characters can be computed with two pointers

Check this submission

nice idea!

Me too, but I can give you alternative solution. Lets do binary search for answer — can we get "good" substring with such length. Left = 1, right = n + 1. In search we will look all substrings with middle = (left + right) / 2 length. At first we look at s[0:m — 1] and count "a" and "b" on it. Then we look at s[1:m] and so on, recounting "a" and "b". If we have min("a", "b") <= k at any moment, return true. Else return false. Answer is Left. O(n * log(n)). http://codeforces.com/contest/676/submission/18085847

Thank you m8! This solution is much more beautiful ( because I hate pointers )..

Thanks @CRAZY_POMIDOR , I was looking for a binary search implementation. Can you please explain it little more? I'm not able to understand counting from S[0-m-1] and then from S[1-m].

algo:

record the positions of the characters in different vectors( resizeable array). suppose,vector A for char 'a' and vector B for char 'b'.

base case: if the size of A or B vector <= K then answer is n

3. i) loop with k' th index of array A till the end of A and question one thing, " what is the maximum size if we change the previous k 'a' characters?"

ii)then, " what is the maximum size if we change the last k 'a' characters?"

Do 3 for array B also.

Maximum size is the answer.

C++ solution:18097109

You've to change k no. of same characters to optimise the substring length. Now suppose I take an array and assign 1 to the indices where character a occurs in the string and 0 where b occurs. Here marking the index as 1 implies we've changed an 'a' to 'b' .Now take the prefix sum of an array(array is a[]) . Considering two indices i and j (j >= i) , (a[j] — a[i-1]) represents the no. of characters changed for a substring starting from i and ending at j. so for every index i from 0 to n-1 find the upper_bound j such that a[j]-a[i-1] = k and the length of the string becomes j-i+1. Do this for all the b's also and take the max at each step.

Hope it helps!

I think my solution may be a little better and more elegant. :) Please take a look and leave your comment.

My solution used kind of greedy idea.

First, we record the possible places could be changed. By possible places, I mean the positions of the letter which appears less. For example, in "aabaabab", we record the positions of 'b's. (Without loss of generalization, we assume number of 'a' is always larger of equal to number of 'b'.) In this example, we record 2, 5, 7. Then we add -1 at the beginning and 8(the length of the string) at the end. So we get <-1, 2, 5, 7, 8>.

Then, we notice that, if we can change 'k' times, to get the longest string. These 'k' changes should be consecutive. In our example, let's say k = 2. Then, the change happens at either 2&5 or 5&7. It won't happen at 2&7 because this is like just change 2 or just change 7 when k = 1.

Haven noticed above two points, we can do the iteration with different k = 0~maxK. (In fact, only use maxK is enough. I didn't realize this when I was implementing it but now it seems true to me.)

The question left is, how can we quickly get the result after we made 'k' changes? Suppose we changed the i'th position in all possible changes(Namely, the vector <-1, 2, 5, 7, 8>). Then, the answer is vi[j+k] — vi[j-1]. Namely, we changed the ith position, the (i+1)th, ... (i+k-1)th. Then the break happens at (i+k)th and (i-1)th position, for i = 1 ~ ((i+k) < vi.size()).

Submitted code here. The complexity is O(vi.size()^2). The code can be further improved as I mentioned use only maxK. Thus can be reduced to O(vi.size()) = O(n).

Please leave your comment.

I like to think about two pointers this way:

Without the time limit, we could solve the problem by testing each of the n possible solutions, each one starting from each position of the string. This would give us O(n^2) complexity with the naive approach.

However, we can find the solution for a given position with the solution of the position before. How? Well, the first difference between the two solutions is the first characters. By removing it from the first solution it relaxes the constrictions of the second. It is obvious that every character of the first solution will also be present in the second. That means that, after removing the initial character, we just need keep inserting the following until it breaks the condition.

We can implement this solution with two pointers, one for the beginning and one for the end of the string. Note that each one of them will only increase, moving to next position, never regressing. This gives us O(n) complexity.

My approach :-> Let us assume that if we are given beauty 'x' , can we find a sub-string by changing the K characters in the string , if we can find it using 'x' — beauty then we can also find using a beauty value of x-1 or for any y such that y<=x. So we can binary search the answer.

The sub-problem is now defined as for a given value x can we find a desired sub-string by allowing k changes. this sub-problem can be solved in linear time by using sliding window and maintaining the count for letter a and letter b separately.

https://codeforces.com/contest/676/submission/51955698

Please correct me if i am wrong.

Nice editorial, clear explanations!

Todays C was same with 660C - Hard Process problem.

In problem A, the statement,

Print a single integer — the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performingexactlyone swapExactlyseems to imply that one swap is necessary, so shouldn't answer for the case31 2 3be 1.You can swap 1 and 3.

Oh! missed that..Thanks

I did exactly same mistake, I thought answer should be 1 if n = 3 and 2 is in middle..I think it was my only mistake in solution :P

I had a nice contest today because the problem C was like 660 C and 660 C is the problem that I made it for the 11th educational round. I wish such good things for u in the next contests. :D

in problem E how to check if k is a root of the given polynomial? this is pretty much the hardest part in the problem :3

You have to check if f(k) = 0. First consider a0: it must be divisible by k otherwise f(k) != 0 because all the other terms are multiples of k. So you can add a0/k to a1. Now consider a1: it must be divisible by k otherwise f(k) != 0 because all other terms are multiples of k. So you can add a1/k to a2... and so on. Finally when only a_n is left, check that it is equal to 0.

Code: 18087228

very intersting :D

Let the answer mod a large prime. If it is hacked, mod more primes.

i used 280 prime modulos and it is still not passing

Edit

320 mods gives WA too

Edit

taking mod with 2 ^ 63 too passes

this is pathetic! just like my submission

If you use specific primes in the codes, others always can hack you.

For example, You use primes 7,11,and 13.

Then I can calculate the value of product of all primes 7*11*13=1001. And hack you by following data:

3 10

1

0

0

1

And if you use 11, 13, and 17. I get 11*13*17=2431.

Then I can hack you with following:

3 10

1

3

4

2

I used integers in range [2e9, 2e9 + 200) as mod, and got accepted ;)

18092407

You got lucky :-) Here is a hack: http://pastebin.com/XZ2za9Xw It should say No, but you say Yes.

Basically the product (and lcm) of the numbers are still in the range of a degree 10000 polynomial. Either you need more numbers, larger numbers (why not 1e17,1e17+200?), or random numbers that the hacker can't easily take the lcm of.

You have to check if

`f(k) = 0`

as mentioned. However,`f(k)`

may be very large and thus cannot be stored. I used a slightly different approach to calculating`f(k)`

.Finally, check if

`done`

is zero. The comparison with`10000000000LL`

works because of the following. When`i = 0`

,`abs(done)`

must be less than`10^4`

, since the problem specifies that`abs(a[0]) < 10^4`

and their sum must be zero. Now, when`i = 1`

,`abs(done)`

must be`< 2 * 10^4`

, since`abs(a[1]) < 10^4`

. Continuing so on,`abs(a[n]) < 10^5 * 10^4`

if`n = 10^5`

.Note that, for the same reason, simply using storing

`done`

as a`long double`

works. You have sufficient precision to store numbers <=`10000000000LL`

. If it exceeds and becomes too large, you can't store the number perfectly, but it is good enough that it won't be equal to zero, so you can just check if`done == 0`

.One way to do it is the following: Notice that you can calculate the value of the polynomial as follows:

x_{ n}=a_{ n}kx_{ n - 1}= (x_{ n}+a_{ n - 1})k...

x_{1}= (x_{2}+a_{1})kThe value is then

x_{1}+a_{0}. Now notice that if any of thex_{ i}is too big in absolute value, thenx_{ i - 1}= (x_{ i}+a_{ i - 1})kwill also be too big and so on. Thus thenkcannot be a root in this case. If none of the intermediate results are too big, all of them will fit in a 64-bit integer and we can just check whether we get zero in the end.The precise condition for 'too big' can be found to be the following:

x_{ i}| ≥ 10000|k| / (|k| - 1)Note: here I've considered only the case when |

k| ≥ 2. When |k| ≤ 1, things are trivial.could someone please explain problem B more clearly. Thank you.

I replied to comment under, I explained "my" solution (actually I took idea, but I coded it later xD)..So if you are interested go and see..

Can anyone give a nice explanation for problem B ? please...

I had problems with understanding it, but I solved it after looking some other codes.. Here is my solution; Make array 10 x 10 and let array[0][0] be the top Glass. Give it value 2048 * (t -1) Now you ask: Why the hell 2048 * (t-1)?! Because you dont want to play with doubles,to every "child glass" you will add half of vine from its parents, so when you do operation /2, you dont want to lose precision, thats why you put 2048 ( 2048 = 2 ^ 10, you will always get integer). Then, array[1][0] is child with only one parent, array[0][0], so you set array[1][0] = array[0][0] /2 -2048 ( you substract 2048 because you save values which will be added to childs). Also, array[1][1] has same one parent so you will do same.. So you just go through matrix and fill needed cells by adding half of parents values to childs! If child is array[x][y] then there are two cases; 1. It can have only one parent ( if x == 0 or y == x, or by words if it is most left or most right glass in row) 2. It can have two parents — all other cells.. Also, if you get negative value in child, that means it wont be filled, so when you go through matrix you just ++counter when cell is >=0..

I hope I explained well, But I dont think so xD

`2048 = 2^11`

Oh...Anyway, it does not really mattern, only thing that matters is that it will be enough to be sure we will get only integer values..

Actually, doubles is okay. I solved the problem without multiplying everything with 2048.

Code: 18096043

Thankyou very much for the explanation :)

I dont get this: (you substract 2048 because you save values which will be added to childs) edit: I got it, thanks !

Here is a way to solve it. It doesn't involve doubles.

Let's say our current glass is located at row i and col j.

Obviously if a glass ever gets full then it will add water to the two corresponding glasses below it:

glasses located at (i+1,j) and (i+1,j+1)

Now for each time we water a glass, we can simulate the process by watering to the top glass, and then the ones below it and so on.

However, there is a problem, we need to know when a glass is full, so we can push water to the level below it. ( It can easily be done by a recursive code).

If you trace it with the pen and paper for few samples, you can find that a glass is full when it is watered ( 2^(lvl) ) times. (The lvl is zero based ).

So basically you need to maintain a 2D array, where arr[i][j] corresponds to how many times the cell located at arr[i][j] was watered.

Set counter to 0.

When you are watering a cell, if after watering it becomes full, increment the counter.

If it doesn't get full, do nothing.

If it is full before you water it, then water glasses below it. (i+1,j+1) and (i+1,j).

Again, the formula of 2^lvl gets very clear why it works if you trace it with a pen and paper.

Sample Code : http://codeforces.com/contest/676/submission/18082377

A glass might be full even before the 2^(level) times water is poured due to the filling of the upper-level glasses getting filled and water reaching from the overflowing of these cups. 2^(level) times water is needed to completely fill all the cups in a given row.

I got it. Thanx. Wonderful answer brother !!

Regarding the "two pointer algorithm", what is a necessary and sufficient condition for the "two pointer algorithm" to work (as opposed to check all subsequences in

`O(n^2)`

)? My guess is if a longer length can only improve a solution if it is feasible and vice-versa but I have not been able to formalize this.Monotonicity, i.e., right pointer increment increases the function value and left pointer increment decreases the function value.

You can easily prove the two pointer technique in monotonic function works with contradiction.

Maybe we are saying the same things but I think your formulation is too strict. I think all we need is that

`f`

must be monotonic in length (i.e. for a longer length, the value is maximized if the value is defined). In slightly more precise terms, it would be something like the two pointer algorithm takes in an integer`n`

and a partial function,`f`

from interval to A where A is comparable and returns the largest interval in`[0, n)`

at which f is defined and maximized.Also, I think the algorithm would work if we loosen the restriction on

`f`

a bit more too — I think it would still work if`f`

is monotonic for overlapping intervals i,e. if f is defined at two intervals`i`

and`j`

and`i`

overlaps`j`

and`len(i) <= len(j)`

implies`f(i) <= f(j)`

Does it also imply that whenever a problem can be solved with two-pointers, it can almost surely be solved with binary search also ?

can someone please explain E "we have the equation ai * C2 = - C1, it will always have solution" more specifically. — — I think -C1 can not be divided by C2. Thanks in advance.

Even with a given explanation I can't turn task B into code. Can someone show your solution, please?

I think use queue to simulate the pouring operation is a good way. to avoid floating number, I use the 2^10 as the whole glass. My Submission

I use a 10*10 matrix look at my comment below this comment.

In problem D, can anyone explain this "Because of buttons we need to add to graph 3 additional levels and add edges between this levels."..What are these 3 levels ?

One for each rotation

Each rotation is new level-every element changes(except '+' and '*'). So you need to make 3d array: matr[k][i][j], where k is current level(0<=k<=3)- there are 4 levels.And then you need to fill all array levels with changed elements('>' --> 'v', for example). Finally, just use bfs, where you can go to upper level or to closest neighbour cell(check if you can go there)

Can someone explain me problem D in detail , i didn't understand the rotation part: Thanks in advance ..

In probelm D, at the second testcase, my output is 4 in my visual studio. But system says my output is -1. Could anyone please explain why my output is different? http://codeforces.com/contest/676/submission/18111486

At a glance, try if changing variable types of stx,sty,edy,edx to int works.

My code for problem B is 18097517 I realized this approach later in the contest so I couldn't get AC during contest. But my basic idea is to use a 10*10 matrix and put t units on the top glass then take t-1 out of it and distribute to the glasses beneath.

My code for Div2-C-Vasya_and_String gives correct result on ideone and my system. ideone solution

But, codeorces gives WA verdict on the same code on very 1st test case. My solution on CF[Both ideone and codeforces code are same]

Can somebody help me debug my code, if there is any ?

hey can anyone look at my code for 676c...it is giving wrong ans on 12th case I'hve used binary search approach. http://codeforces.com/contest/676/submission/18114269

A question out of the blue: Can we solve problem D using Dijkstra approach on a 2D distance array?

you can solve it using Dijkstra on a 3D distance array this is my solution :

https://codeforces.com/contest/676/submission/55204169

in problem B how does one conclude that 2^n should be the volume for each glass. Like in the editorial it mentions that so that the water that flows down in integer. but how do i conclude this in general during similar questions. in other words how to come up with such a strategy during contest

I think editorial's solution is not the only solution there. I just used brute force approach to solve it.

Problem D: My solution is O(4*n*m) and it is judged as TLE on test case 24. Can someone please have a look and suggest what's wrong? My Code

The tag for problem C div2 says dp. How can it be done with dp.

I've tried it using binary search and two pointers separately. How with DP? Kindly help !!

Can you help me with dp solution for 676C — Vasya and String. Thanks

How to solve problem C using Binary Search