Привет, Codeforces!
10 февраля 2016 года в 18:00 MSK состоится седьмой учебный раунд Educational Codeforces Round 7 для участников из первого и второго дивизионов.
<В прошлый раз эти абзацы всё-таки изменились>
О формате и деталях проведения учебных раундов я писал уже ранее. Также об учебных раундах вы можете прочитать здесь.
Раунд будет нерейтинговым. Соревнование будет проводиться по немного расширенным правилам ACM ICPC. На решение задач у вас будет два часа. После окончания раунда будет период времени длительностью в один день, в течение которых вы можете попробовать взломать абсолютно любое решение (в том числе свое). Причем исходный код будет предоставлен не только для чтения, но и для копирования. Таким образом вы можете локально тестировать решение, которое хотите взломать, или, например, запустить стресс-тест.
Если у вас есть идеи каких-то задач, которые вам кажутся интересными, или может есть уже что-то почти готовое, что вы по каким-то причинам не можете дать на раунд (злой координатор сказал, что задача БАЯН), официальное соревнование (жюри не хочет переграбливать соревнование), можете писать мне.
</В прошлый раз эти абзацы всё-таки изменились>
Большое спасибо Aleksa Plavsic allllekssssa, который предложил задачи D и E, и Ивану Поповичу NVAL, предложившему задачу F. Также благодарю Mohammad Nematollahi Deemo он предложил задачу, которую мы сильно упростили и решили дать в качестве задачи C.
Подготовкой задач как всегда занимался я (Эдвард Давтян). Благодарю MikeMirzayanov мы вместе придумывали задачи A, B и C. Спасибо Маше Беловой Delinur за проверку английских текстов условий. Также большое спасибо Aleksa Plavsic allllekssssa и Ивану Поповичу NVAL за тестирование задач.
На этом раунде вам по традиции будет предложено шесть задач. Мы постарались сделать задачи не очень сложными, но при этом интересными. На мой взгляд задачи чуть более математизированы, чем обычно. Надеюсь комплект задач вам понравится и вы хорошо их порешаете!
Good luck and have fun!
UPD1: Первая фаза соревнования закончена. Можете взламывать решения других участников.
UPD2: Разбор задач готов.
UPD3: Раунд закончен. Результаты окончательные.
Thanks a lot for the rounds. I like that each problem is meant to illustrate a specific algorithm. I just have one question: Is it possible that you will make educational rounds rated soon? especially that the problems in the last couple rounds are new and not from some previous contests?
Some of the problems were not new.
Please don't downvote :(
At first it wasn't new, but in the last couple rounds I see the announcement saying that the problems are new. (I think they are new because the announcement started to say the names of people who suggested the problems).
If it's first time you see a problem it doesn't mean it's new or not standard
and those people who are mentioned in the announcement are just mentioned because they suggested standard problems not original problems
Sorry, but I suggested new and for me not so standard tasks :P
Normally that doesn't mean someone didn't invent something similar before.
Ok maybe you did, but it's supposed that people suggest standard/old problems not new as it's mentioned in the announement
I really don't think the quote you mentioned means that the problems were not new. It says if you prepared problems "that you can't use in rounds".
Sorry for the questions if you don't like it, it represents my opinion only. I just asked because in MikeMirzayanov's first announcement he said that the series will be unrated (for now).
Unrated (perhaps for now);
it's not that I don't like it I didn't mean to offense, I just wanted to say that the idea of educational round is to present problems that are standard (not like what you said the problems were new), so it can't be rated because of that.
and about "that you can't used in rounds" I'm not sure what reasons that a problem can't be used in rounds other than because it's already used somewhere or it's too standard
Well, I can not agree with you :P
I had several rounds in the last half year and I can not organize every 15 days one contest. Also I invented a lot of tasks soon(at least 20), so for me it is much easier option giving it now to Edvard which prepares everything and on that way help to CF ;)
I know you didn't talk about me, but I suppose here is many guys which will do the same thing!
поздравляем за Вашу полностью заслуженную награду! надеюсь, что Ваши тренировочные раунды будут продолжатся! собственно мне они очень нравятся! P.S. у того, кто фотографировал награду хорошая прическа)
Thanks Edvard for mentioning me!
I think the task for this round are more 'educational' than any other time :) Also I am sure that everyone will find something interesting and solvable.
About my tasks, I think they aren't standard and I would happy to see such task on some contest where I am participant... Several times they were on line to be used for my regular competition :)
Good luck and any feedback about tasks after round will be valuable :)
Say whaaaat? O.o
Gratz!
Поздравляю!
The Educational rounds have been excellent in featuring algorithms that are otherwise uncommon. Also, they let contestants experiment with the contest environment without fear of rating deduction, so trying new problem solving sequences and the such. I hope that these rounds will continue to be excellent :D
Mathematical problems are the best. kudos to Edvard
I think Educational round is at its best. Don't make it rated as it helps us to do/learn fearless coding at a competitive level. Thanks to MikeMirzayanov for polygon n all. Keep it up guys!
Clash with IIIT hyderabad's Codecraft contest tomorrow.
clash with IIIT hyderabad, Codecraft contest tomorrow.
Do both :)
Thanks a lot for the round Edvard.
I think that the round will be interesting and cool!
Codeforces is an amazing community! Like none other. This place is supposed to be competitive, but instead, its such a supportive community. People are not just sharing their knowledge, they're doing so without any immediate tangible incentive in return! May God bless you MikeMirzayanov, may god bless all problem setters, editorialists, people who share their solutions in blogs, coordinators, and everybody involved in the process. Sometimes, people willingly encourage others who feel defeated and demotivated. I think the money the setters earn is nothing compared to what they give, and a lot many people share their approaches without any payment whatsoever. :) I feel humbled by you all, and I feel happy everytime I come here. I wish to become great programmers like you, and also great human beings like you. God bless codeforces!
You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.
Does this also mean that you can hack a solution to a problem even though your submitted solution to that very problem didn't pass the pretests? Thanks!
Yes.
Я люблю эти раунды.
F is really nice! Thanks!
I understand the ideas, but I don't know how to implement them in a beautiful way.
Looking forward to magical implementations.XD
Indeed. I didn't know it was possible to calculate this sum effectively... Until I solved this problem today.
f(n) = 1^k + 2^k + ... + n^k is a polynomial of degree (k + 1). So, using Lagrange's interpolation formula, it's possible to compute f(n) in O(klog(k)).
Why is the sum a polynomial of degree (k + 1)?
See the editorial. It's easy to prove by induction.
Thank you, now it's clear the induction step. I can make this more formally, for those interested. Denote . We want to prove that degree of Pk(n) is k + 1.
Base case of induction after k:
By the induction we know that deg(Pk - 1(n)) = k. Taking the derivative of P(1)k(n) = k·Pk - 1(n). This implies that deg(P(1)k(n)) = k
Therefore deg(Pk(n)) is exactly k + 1.
Oh, no... Math.. (((
Oh, yes! Math!
E is really nice!
Thanks for nice words. I tried to contribute cool tasks. At least I hope problems D and E were interesting for solving :) Both tasks are easy for implementation and I will try to invent something similar in future !
I want to sincerely thank the problemsetters. Especially the one who set D . I don't remember the last time I saw such a beautiful problem. How brilliant someone has to be to come up with such an elegant problem that can be written in problem statement in such a simple manner !! I am simply awed . Kudos!! :)
Только после того, как я с бегу накодил дерево отрезков в С, я понял, какая же простая это задача и как ее решать.
Как?
Моя идея (только что прошли претесты): для каждой позиции считаем положение двух различных ближайших левых чисел
лол, а я тут вообще sqrt-декомпозицию запрогал и получал TLE17:D
Ну корневая пишется, имхо, проще, но (азаза) дерево добралось до 22 теста
Скорость работы дерева пропорциональна прямоте рук кодера :)
Ну, за чужое дерево не поручусь, но у меня действительно было очень кривое решение за O(Msqrt(N)log(N)), ибо я еще сеты запихивал в идею:D
А вы знаете толк в извращениях!
Видимо, у меня руки зигзагообразные. Как оно у Вас работает в 4 раза быстрее моего? И ~ во столько же раз быстрее моего решения за линию...
Советую попробовать заменить cin/cout на scanf/printf. Мое дерево отрезков это ускорило с TLE20 до AC 280ms.
Спасибо! Всегда думал, что ios::sync_with_stdio(0); решает подобные проблемы, но в этой задаче именно из-за этого TL. То же самое дерево с stdiо получило АС 218ms. Мое решение за линию, кстати, с минимальным отрывом — 187ms. UPD: решение за линию с ios вообще не прошло полный набор тестов
В целом эмпирическое правило примерно следующее: если нужно ввести/вывести больше 500 000 отдельных сущностей — лучше на всякий случай использовать scanf/printf. При этом речь именно об отдельных сущностях — если там одна строка длиной миллион символов, то считается быстро.
Проблема в том, что операторы >> и << виртуальные, что начинает сказываться при большом количестве вызовов.
Idea for D : You want to make d1 = n - 1, d2 = n - 2, ..., dn - 1 = 1 so that the sum is 0. The rest is just experimenting to find the solution.
I knew this idea and yet I couldn't solve :(
One of the key ideas is that d_{n} multiplied by zero, so you can make of it anything you want.
The pattern for solution is:
Separate all in three groups: where d_i must be some even constant, where d_i must be some odd constant, and where i == n (you don't care about d_n at all).
Solution the task for first group it is something like (a b c c b a), you can see that it has exact d_i's as you need (1, 3, 5...).
To solve for second + third group put n in between of this sequence and append n after (e.g. a b c N c b a N), is has also exact d_i's as you need. (2, 4, 6...)
(Example ans for n == 4) 1 3 3 1 2 4 2 4
Как решать E?
не знаю правильное мое решение или нет, но претесты вроде прошли.
Я делал так, запускаем дфс из каждого ребенка корня и нахожу для каждого листа этого поддерева кратчайшее расстояние. После этого сортирую вершины по их дистанции и после этого делаю так что все расстояния были различными. Ответ будет максимальное из этих расстояний из каждого поддерева. Почему нам нужно именно кратчайшее расстояние не до корня, потому что в корень мы можем прийти одновременно из все его сыновей.
Почему это может работать,жадно вначале поднимаем всех тех,кто ближе. И если есть свободное окно поднимаем еще кого-то.
ссылка на код Your text to link here...
Educational Rounds are very helpful in learning new concepts and revising old concepts.
Thanks for Educational Rounds. Keep it unrated.
How to hack other people? Can i lock the submission now, if I didn't do it earlier?
How to solve C?
one way is to split array in sqrt(n) blocks. for each block, you keep an set and do binary search on it
You can do some pre-processing.
For each position, store the position of the next number that is not equal to it.
Just traverse the array from right to left
if array[i + 1] != ar[i]
, thennextUnequal[i] = i + 1
else nextUnequal[i] = nextUnequal[i + 1]
Now when you have a query(L,R,X) check A[L] if it's not equal to X, return L otherwise look at nextUnequal[L] if that's <= R, return that else return -1
It takes intelligence to see the simplicity in something complex. I was so sure this is segment tree problem, and later thought of sqrt-decomposition solution lol.
For each index of the array keep the index of the next element which is not equal to current.
Then the answer for query can be obtained like this:
1. if (a[l] != x) print l
2. else if (nxt[l] > r) print -1
3. else print nxt[l]
For each position in array remember the last position of a number different that what you have at that position(denote it d[i]), then for each query check if tab[r] != x — r is the answer, if tab[r] == x and d[r] >= l — answer is d[r], else -1
What i did was to find maximum number in the interval.
Then i also found minimum number in interval.
If both are the same and they are equal to the number we dont want it to be equal to , we output -1.
Else we look which of min and max are different from it and output one of them.
But there are better solutions.
I did it a long way by having 2 segment tree, one which reports the minimum and other which reports maximum in the range [L, R]. If both of them are equal and equal to x then print -1 else find the position of one not equal to x. Since the numbers range is [1,10**6], store indexes of each number in a vector and then binary search on them to find position. Complexity: O((n+m)logn)
kind of the same
can be solved using DP in O(N+M) time. The idea is to calculate the maximum length of subarray for each position such that the subarray contains the same number as the one in that position. You can do this in O(N) time
Then for each query go to array[l] . If this is not equal to x, tada! else jump to the position denoted by array[l] and the length of the precalculated subarray for position l. If this is within range, return the position, else -1
How to solve E?
Consider all children of 1, let them be v. We can calculate answers for each v separately, taking the maximum answer.
Now, for each v, find all leaves that belong to v, and record their distance. Sort them in decreasing order, and the answer is max(d[i]+i) for 0-based distance array. The reason is that we can think in reverse way: the ants move from root to leaves, and we always want the furthest ant to move first.
Btw, this question has appeared (exact problem) some year ago in a chinese contest.
I am not doing chinese contests, but It looks as right decision to put this task on educationl round :)
How to solve F?
See http://mirror.codeforces.com/blog/entry/23358?#comment-277833
Simple interpolation: https://en.wikipedia.org/wiki/Lagrange_polynomial.
Hi- distance cantst got hold down.
What ?
How to determine the index of min element in algorithm segment tree? Is it right? My code for problem C
check 15945814 tree1 stores index of maximum element in a range and tree2 stores index of minimum.
Thanks.
even shorter
I solved C with partial sums. Say we have to answer a query (X, Y, C): if sum of numbers in tha range [X, Y] is divisible by (Y-X+1) and sum in range [X, Y] divided by (Y-X+1) equals C then we have no element in range [X, Y] which is different from C. If we have a different element, we can binary search for the position of that different element.
Here is my solution
LE: Nevermind, I missed a case
Hacked :P
Look at this sample :
5 1
3 2 4 5 5
1 3 3
your answer is -1, that isnt correct ;)
Yeah, while I was taking a shower I realised that my solution fails that test and that I shoould hack myself, but it seems like you already hacked my solution. :p
I solved it just like you did and I hacked myself too :p
Are there at all any test cases for which an answer might fail (after passing the pretests) for the problems A and B? It's been almost 5 hours now and I have tried everything but in the end it seems that the pretests cover up almost everything for both the problems!
PS: Don't confuse this with me asking for helps to hack other's solutions. All I merely am asking is a yes or no to the question. Thanks! :)
There are many hacked solutions for A and B task, so possible some tricky testcases exist ;)
Wow, I use to teach how to calculate interpolating polynomials, but in a straight-forward way...
Couldn't believe they could be used in competitive programming until now!
Problem C have really tight time limits. I wrote O(N) solution in Java and it exceeded the time limit on test 20. It only passed when I moved the solution to C++ with scanf/printf.
I used BufferedReader and StringTokenizer in my java solution, so it's not a problem with slow Scanner class.
There was no time limits problem in your solution. Actually you have used System class to print the output which is quite slow. Also you have used println which is slower especially when it is used directly by System class(writing on console sending bytes, flushing the screen etc). To make it faster create an instance of PrintStream class and use that instance to write to the console. print("\n") uses '\n' as linefeed character and println() terminate the string with new line character depending on the platform. Best to use is '%n' with printf() in java.
15949731 15949638 15949630
Can someones guess, what hack test could be in B? halyavin have already successfully done 116 hacks:D
May be .bat with tests.cpp.
I completely overkilled C and got TLE as a return gift.
My approach-
Build a segment tree in nlogn where each node has a vector of elements of its subtree in sorted order. 2 adjacent segments will have sorted elements and so merging can be done in O(n) leading to a total build complexity of nlogn. Queries will find the range in a segment which has 'x' and then return an index outside this range. Complexity of each search is therefore log^2(n).
I realized after contest that all we need is minimum and maximum of a range to find any position which does not have x . Stupid me :/
Have the solution been rejudged already? With the full test cases and the successful hacks?
EDIT: Spoke too soon
This is the first round that I can solve problem D, although I was not in the field.