676A - Николай и перестановка
Все, что нужно сделать в этой задаче — найти индексы в массиве чисел 1 и n. Пусть это будут p1 и pn соответственно, тогда ответом на задачу будет максимум из следующих значений:
Асимптотика решения O(n).
676B - Пирамида из бокалов
Ограничения в задаче были таковы, что можно было просто промоделировать процесс. Предлагаем вам следующий вариант: заведем емкость бокала равную 2n единиц. Утверждается, что тогда излишки шампанского, которое польется на уровень ниже, будут всегда соответствовать целому числу. Итого, выльем в самый верхний бокал t * 2n единиц объема, а далее действуем следующим образом: если в текущем бокале больше шампанского, чем его емкость, то surplus = Vtek - 2n, а еще нужно не забыть добавить surplus / 2 шампанского в два бокала на уровне ниже.
Асимптотика решения: O(n2).
676C - Вася и строка
Эта задача хорошо решается методом двух указателей. Пусть указатель на левую границу l, а на правую r. Тогда для каждой позиции l будем двигать правую границу до тех пор, пока на подстроке slsl + 1... sr можно провести не более k операций замены, чтоб эта подстрока была симпатичной. Для проверки потребуется завести частотный словарь размером с алфавит строки, который будем пересчитывать вместе со сдвигом границ.
Асимптотика решения: O(n * alphabet).
676D - Тесей и лабиринт
Можно легко понять, что состояний лабиринта всего 4. Допустим, в этой задаче нет никакой кнопки, как ее решать? Ответ очевиден: это обычный поиск в ширину на гриде. Что нам дает наличие кнопки? Нам нужно дополнить наш граф еще 3 дополнительными уровнями, а нажатие на кнопку сассоциировать с переходом на следующий "уровень" лабиринта. Вертикальные переходы необходимо зациклить. Тогда запустим бфс уже на таком трехмерном гриде и выберем минимум из значений по уровням в клетке с Минотавром, либо поймем, что пути до этой клетки нет.
Асимптотика решения: O(n * m).
676E - Последняя битва человека против ИИ
Пожалуй, самая интересная задача этого раунда. Необходимо разобрать два случая: k = 0, k ≠ 0.
Случай k = 0. Тогда делимость многочлена на x - k будет определяться лишь значением коэффициента a0. Если a0 уже известен, то нужно сравнить его с нулем. Если a0 = 0, то это уже победа человека, иначе поражение. Если же a0 еще не известен, то все зависит от того, чей сейчас ход. Кто ходит — тот и выигрывает, поставив на позицию a0 нужное ему значение.
Случай k ≠ 0. Тогда опять же есть два случая: все коэффициенты уже известны, и нам нужно проверить, является ли x = k корнем получившегося многочлена (например схема Горнера), или есть неизвестные коэффициенты. Если есть неизвестные коэффициенты, то поймем почему выигрывает при оптимальной игре тот, кого последний ход. Допустим известные все коэффициенты, кроме одного. Пусть при xi. Тогда обозначим за C1 сумму по всем j ≠ i ajk j, а за C2 = k i ≠ 0. Тогда уравнение ai * C2 = - C1 относительно ai всегда имеет решение. Если ходит человек, то в качестве коэффициента ему нужно вписать корень, а если ходит компьютер — что угодно, лишь бы не корень.
Асимптотика решения 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
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.
can u give me ur solution link i liked ur way simple and easy to understand
Here: https://codeforces.net/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.
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.net/contest/676/submission/18085847
Thank you m8! This solution is much more beautiful ( because I hate pointers )..
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 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.
А можно более подробно про проверку корня алгоритмом Герона?
Видимо, в описании ошибка, скорее всего, имелась ввиду схема Горнера
действительно, имелась ввиду именно она!
В задаче E я просто сравнивал по модулю в лоб, но использовал простой модуль порядка 10^13 и оно зашло. Проверял после контеста 1е9+7 и он валился на 62-м.
Есть решение без модулей)
Я уже видел у топов)
Как же хорошо в див2, решения с константным модулем не хакают :)
Не то слово :D
можно в последнюю секунду засылать и тебя не хакнут
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 performing exactly one swap Exactly seems to imply that one swap is necessary, so shouldn't answer for the case
3
1 2 3 be 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 calculatingf(k)
.Finally, check if
done
is zero. The comparison with10000000000LL
works because of the following. Wheni = 0
,abs(done)
must be less than10^4
, since the problem specifies thatabs(a[0]) < 10^4
and their sum must be zero. Now, wheni = 1
,abs(done)
must be< 2 * 10^4
, sinceabs(a[1]) < 10^4
. Continuing so on,abs(a[n]) < 10^5 * 10^4
ifn = 10^5
.Note that, for the same reason, simply using storing
done
as along 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 ifdone == 0
.One way to do it is the following: Notice that you can calculate the value of the polynomial as follows:
xn = ank
xn - 1 = (xn + an - 1)k
...
x1 = (x2 + a1)k
The value is then x1 + a0. Now notice that if any of the xi is too big in absolute value, then xi - 1 = (xi + ai - 1)k will also be too big and so on. Thus then k cannot 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:
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
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.net/contest/676/submission/18082377
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 integern
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 iff
is monotonic for overlapping intervals i,e. if f is defined at two intervalsi
andj
andi
overlapsj
andlen(i) <= len(j)
impliesf(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 ?
Я не согласен с решением задачи B
В условии парень выливает объем одного бокала в секунду, а в решении ты выливаешь все сразу. И поэтому порядок наполнения сбивается. Центровые бокалы наполняются быстрее: они начинают уже переполнятся, в то время как крайней на том же уровне пирамиды еще недоконца наполнены.
Может кто объяснит...
Центровые бокалы будут наполняться быстрее и в случае, если лить по одному
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
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)
Господи, последняя задача — просто позорище, div2E уже не торт. Мне одному показалось, что это задача шутка? P.S. Какая ещё схема Горнера, что за стёб? Многочлен делится на (x-k), если k является его корнем — теорема Безу, алло!
У меня для вас плохие новости!
А как проверить, что k является корнем многочлена?
По нескольким модулям посчитать
Это, конечно, хороший прием, и знать его полезно, но в самом тупом варианте он здесь легко взламывается, а вычисление по нескольким рандомным модулям требует написания большого количества кода. У Горнера и кода мало, и взломать нельзя.
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.net/contest/676/submission/18111486
At a glance, try if changing variable types of stx,sty,edy,edx to int works.
Наконец-то руки добрались http://codeforces.net/contest/676/submission/18131834
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.net/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
В Е плохие тесты. Я такую фигню придумал и реализовал. Было пару ошибок в логике и реализации, но в итоге я добился ацептеда, подсматривая тесты. А потом прочитал разбор, и понял какой я глупец... Как минимум моё решение отдельно рассматривает все участки разделённые хотя бы двумя нулями. Поэтому моё решение на тест
1 1 1 0 0 ?
приk = 100
выдастNo
.How to solve problem C using Binary Search
89604997