В воскресенье, 3-го мая, в 19:00 начнётся Раунд 3 чемпионата по программированию VK Cup 2015! Не забудьте зарегистрировать вашу команду на раунд, регистрация закроется за пять минут до его старта.
В этом раунде могут принять участие все те команды, которые отобрались в Раунде 2 или в Уайлд-кард раунде 2. Напомним, что из второго раунда допущены все те команды, что набрали не менее 928 баллов. В уайлд-кард раунде 2 было достаточно набрать 1827 баллов. Таким образом, принять участие в Раунде 2 могут 100 + 20 = 120 команд!
Участников ждет соревнование по правилам классических раундов Codeforces. Раунд 3 пройдёт в таком же формате, как и Раунд 2 — с онлайн-трансляцией, рейтинговой и доступной только для див-1 участников. Будет использована плавная динамическая система оценки задач, но сами задачи будут расположены в случайном порядке. Участникам будет предложено 6 задач.
Раунд подготовлен силами команды Codeforces, команды VK и пользователя yeputons. Как всегда, неоценимую помощь в тестировании задач оказали winger и AlexFetisov.
Напомним, что в Финал VK Cup пройдут все те команды, которые наберут положительный балл, не меньший, чем у команды на 20-м месте. Также обращаем ваше внимание, что участники всех команд, прошедших в Раунд 3 (независимо от их участия или неучастия в Раунде 3 или в его трансляции), получат фирменную футболку Чемпионата. Помимо этого, фирменной футболкой будут награждены топ-50 участников интернет-трансляции Раунда 3.
Желаем удачи и интересной борьбы!
UPD1 Раунд 3 завершён! Поздравляем топ-20 команд, которые отправятся в июле на Финал VK Cup 2015! Следите за объявлениями на сайте, точная информация о финальном раунде появится позднее.
UPD2 Тем временем появился разбор.
It's look like everyone who is participate will get a t-shirt.
What do you mean exactly? Top-50 will get t-shirts in the mirror contest. So be ready for fight!
До начала раунда менее часа. Вот вам небольшой спойлер к одной из задач:
Даже не знаю что сказать...
Парсоч?)
Все скопипастят парсоч, а там будет задача про Анатолия Ивановича
Задачи про Анатолия Ивановича там всё-таки нет.
а вот это точно спойлер!(
Блин, ну теперь точно придется своим умом контест тащить
Not rated for div2? (Why negative upvotes?)
u can't compete. VK Cup 2015 Round 3 (unofficial online mirror, Div. 1 only)
I think the opposite of "upvotes" is "downvotes" instead of "negative upvotes"...
.
Теперь должно быть "Зарегистрирован(а/ы)" :)
Команда зарегистрирована :)
Запасные аккаунты зарегистрированы. :D
Некоторые участники совсем лишены чести и, не имея права участвовать в VK Cup из-за возрастных ограничений, все равно зарегистрировались и добрались до раунда 3. Очень некрасиво.
Вероятно, у AK_47_NAGIBATOR было бы больше шансов пройти в финал, если бы не несовершеннолетние участники
Видимо большую силу имеют не
несовершеннолетние участники
,а более взрослые.Вы не загадками говорите, а напишите мне личное сообщение.
No you are wrong if you have the knowledge that participate in a competition which you want) How do you know 3 Raud passed only 100 strong teams — it's all cool if younger people were held in 3 round and fight for the finals Good luck to all participants VK Cup 2015 — Round 3 and VK Cup 2015 — Round 3 (unofficial. Webcast only Div. 1).
This contest is so
hard
with me.I think I don't have enough knowledge to be
Div1-contestants
.I hope I will become
Expert
to improve myself.Hard contest!
Даёшь уайлд-кард 3!
I got too late to participate.. but Was problem C a binary search , bcz for all x >= k , idempotent condition is true ?
I think it wasn't. I've tried binary search.
You can't use binary search — for any cycle in given graph, answer should be divisible by length of this cycle.
3 2 3 1
k=3 works k=4 does not
I failed to solve this problem, but I'm pretty sure your condition x ≥ k does not hold.
Consider a cycle 1 -> 2 -> 3 -> 1; for this example, k = 3. Setting k = 4:
f4(1) = 2, f4(2) = 3, f4(3) = 1.
f8(1) = 3, f8(2) = 1, f8(3) = 2.
What needs to be solved turns out to be a system of congruences, I think.
It's not binary search. Because if F_i(x) is not idempotent this doesn't mean that F_t(x) is not idempotent for all t less than i. For example in the third sample F_4 is not idempotent while F_3 is.
Мне показалось, или F оказалась легче, чем C?
Над С думал очень долго, писал три разных решения, в итоге 100 минут истратил.
F прочитал и понял за 7 минут, 10 минут придумывал решение, 6 минут писал его, 3 минуты искал баги, в итоге истратил 26 минут.
Хотя, возможно, я глупец и у меня всё упадёт.
UPD: С еще и упала, лол. Ну точно F — легче.
How to solve
Problem C
?In this problem, I try the value of
k
from1
to100000
(I think it can run in1s
),but it is
Wrong Anser on test 9
.Can you give me effective hint?
Hint: k can be larger than 100000, or 10^9 (I think).
Hint: Maximum possible answer is around 10^14
I wonder how did you find the maximum possible answer. May I ask you?
In the graph with edges (i->f(i)) if we have a cycle of length K, then answer should be divisible by K (such that when we apply f^K(x), we get x, and f^K(f^K(x)) = x). Therefore, an obvious lower bound for the answer would be a set of cycles of different lengths. Answer would be their LCM. To maximize LCM, let's take prime numbers. We get something like 2 + 3 + 5 + ... + 37 or something, such that sum is less than 200 and product is maximized. This is around 10^14.
And the true maximum possible answer is a division of 200 into a groups such that LCM of the sizes of these groups is maximized. This division includes not only primes but maybe some powers of primes. According to the editorial, there is a sequence which describes such maximum LCM and it is about 2 * 10^14 for 200, therefore my lower bound was pretty close.
The maximum test is actually a permutation consisting of 10 cycles of lengths (16, 9, 25, 7, 11, 13, 19, 23, 29, 31).
I tried 1 to 2500000! and got runtime error 8 times
I think answer of test 9 is bigger than 2500000.
The gist of the problem is to tranform it into one about graphs. We construct a graph with edges (i, f(i)), we see that f(x) is just the neighbor of node x, and fk(x) is the kth neighbor of node x. Now because every node has an outdegree of exactly one this graph can be decomposed into cycles or paths that lead to cycles. Now the condition fk(fk(x)) = fk(x) can be interpreted as the 2*kth neighbor of node x should equal it's kth neighbor. For nodes that are part of a cycle the answer is the a multiple of the length of the cycle(because k must satisfy the modular equation k ≡ 2 * k(mod length) which is equivalent to k ≡ 0(mod length)). So if there would be only cycles the answer would be the LCM of all the lengths of these cycles. Now what about paths? We notice that we need to pick a k such that it reaches a cycle, then for any K ≥ k we will just be walking through our cycle, so just take the length of the longest path to a cycle then pick a constant c such that c * lcm_of_cycles ≥ longest_path.
Perfect!!! The best explanation. This is better than editorial.
UPD: why me comment have more "likes" than comment above? =)
Will there be editorial?
The contest
Round 1
andRound 2
had theeditorial
, so I can pridict : will have the editorial.I also hope it will become the trust, because I can't solve anything in 6 problems
yes... and there was the system test
А на чем все С ломали?
Все? Звучит так, как будто по ней было больше 100 взломов. Меня, например, можно было взломать на ТЛ, но для этого нужно было сгенерировать тест с большим ответом.
на переполнении инта
With 5 minutes to go I asked myself, what was I thinking? Faced with my strength, a graph problem, I instead tried to solve a maths question?? (I suck at maths questions :P)
Oh well, I thought, as long as A passes I'll get a shirt.
So you could imagine my disappointment when it failed TT
So you could imagine my shock at seeing my final rank: 50 !!!!!
Solved 2 problems in 33mins, it's currently 4:30am and I could have slept 2 hours ago. But who cares I get a VK shirt :D :D
54 место! Ну как так?! Совсем чуть-чуть не хватило :(
Looks like I'm using fast input from now on...
http://codeforces.net/contest/542/submission/10988472
http://codeforces.net/contest/542/submission/10989738
Looks more like a random fluctuation in run time.
I'd also use less copy-paste if I were you :P
It's like a joke. Unfortunately for you.
Had the same issue... Trusted cin/cout too much; should've used fast input method written on my template :'(
http://codeforces.net/contest/542/submission/10989470
http://codeforces.net/contest/542/submission/10989944
For C, how to prove that the answer will fit in long long ?
I just wrote up a quick python script to see what max answer could be. Basically, you're looking for a bunch of numbers that sum to <= 200, and have maximal LCM. So just take the first primes with sum <= 200 and find their product.
Edit: This clearly isn't actually correct, see Zlobober's comment below.
thanks, at first I didn't realize that maximizing the LCM is by taking the first primes , but anyway I used this nice prove during the contest: the answer to all previous problems on codeforces fit in long long so most probably this will fit too :D
It's not enough: for small primes it's better to take p^k rather than p.
Yeah, of course you're right.
TBH I was more just giving myself a little piece of mind and then just trusting that there wouldn't be a question that'd overflow long longs :P
Maximum orders of permutations of n elements.
Nice one ,thanks.
Как решать D?
Мне кажется что A = (p1k1 + 1) * (p2k2 + 1) * ... * (pnkn + 1), где p1, p2, ..., p3 — простые числа. Но у меня wa 25.
Так и решать, только различные простые.
Ну это понятно, а дальше как?
dp[id_divisor][id_prime] — сколько способов представить divisor[id_divisor] в виде (pi1αj1 + 1)·... где максимальное p имеет индекс ≤ id_prime (среди всех возможных p).
Многие состояния недостижимы, поэтому лучше писать ленивую динамику, заходит за 150 мс.
Да, нужно было найти количество решений уравнений (p1k1 + 1) * .. * (pss1 + 1) = A, где p1, p2, .., ps - различные простые числа. Я написал перебор с некоторыми отсечениями и она прошла. Вот мой код 10987822
int dp[N][T]
instead ofint dp[T][N]
=>
I simply lost the t-shirt.Ребят, задача А — издевательство.
Как её адекватно реализовывать? А то у меня совсем треш вышел. 10989883
Если кратко:
Сканлайн. Для каждого второго отрезка пробуем его пересекать с первыми. Есть 3 типа пересечений — первый отрезок полностью включен, пересекает левую границу или еще не окончен. Для первого варианта — ДО на максимум, где храним Ф(левого конца) = длина отрезка. Для второго — ДО на максимум, где храним Ф(левого конца) = правый конец отрезка. Для третьего — храним сет ныне открытых отрезков, остортированный по левому концу.
Ну у меня так же. Я про адекватную реализацию спросил...
Btw, второй и третий вариант решается без структур простым преподсчётом максимумов/минимумов на префиксах/суффиксах.
По-моему, вполне адекватно: два сета, одно ДО, никаких особых случаев, даже компаратор аккуратно писать не надо — события в одной точке не важно в каком порядке рассматривать (если при чтении выкинуть пустые отрезки).
А чем мешают пустые отрезки?
Если конец отрезка окажется в списке событий раньше начала, мы его удалим из сета раньше, чем добавим.
Если я правильно понял, для второго варианта можно тоже сет, все симметрично с третьим. Только нужно смотреть в сет, когда второй отрезок начинается, а не заканчивается.
Переберём отрезок [ai, bi].
1) Оптимальный ответ пересекает ai -- считаем максимальное r из тех, что начинаются раньше ai. Это пара циклов.
2) Пересекает bi. Симметрично.
3) Лежит внутри. Тогда сканлайн: пусть стоим в каком-то bi. Нас интересует максимальная длина отрезка, который начался после ai (то, что он уже закончился выражается в том, мы добавляем [li, ri] в точке его конца). Это дерево отрезков для максимума.
Вроде неадекватной реализации нет.
К тому же максимум надо считать на суффиксе, так что и дерева Фенвика хватает.
Я убрал все рекламные ролики, чьё окно времени полностью входит в окно какого-то другого ролика. Тогда оставшиеся ролики сортируются одновременно и по левому краю, и по правому. Дальше я прохожу по каналам и для каждого нахожу бинарным поиском последний ролик, пересекающий левую границу предоставляемого каналом окна (то есть заканчивающийся позже её) и первый ролик, пересекающий правую границу (то есть начинающийся раньше её). Можно или взять этот, или взять тот, или взять самый длинный ролик на отрезке между ними (range minimum query, который можно реализовать тысячей способов).
How to solve problem F? Is it some sort of 0-1 knapsack?
I reduced it to knapsack with all weights as powers of 2 which can be solved greedily.
Yeah I did the same reduction but couldn't figure out how to make the knapsack run in time.. Can you elaborate on "greedily"?
If you want to take something with weight 1, you always want to take a second if it exists. So I took the two most valuable and merged them into an item with weight 2, and continued doing this for all weights until everything had a weight equal to 2^T
Could you explain the proof to your solution
Think like this. At any stage, let minimum time for a node be x. Now two cases —
1) There is only one node with time x If this node is combined with another, the net time will be > x+1. (Since x is min time) Hence we just increase the time of this node by 1 and proceed.
2) There are >=2 nodes with time x. Combine the 2 most valuable nodes with time x.
See my solution for implementation.
Another approach: dp[height][free]: maximum total interest value of the tasks in tree when we use tasks with T - t[i] ≤ height and we have at least free free leaves.
10989745
I had the same approach. How did you keep track of the number of tasks used at the same height? I had to keep my state as dp[pos][free] : where pos was the index of the task i was currently processing. I had the tasks initially sorted by (T-t[i]);
I grouped tasks with respect of T - t[i] and in each group, kept the tasks sorted by their interest values. And i had to store partial sum for each group in order to update states.
I used a simple approach. We will split tasks by time. Every minute form a level. Start from the lowest level that contains at least one task. Combine two tasks in this level with the maximum interest. Add the result as a task in next level. If there is only one add it to the next level. If the level is empty precede to the next level. If you reached the highest level (T) the answer is the maximum interest in this level.
Here is my implementation => 10989241
As far as I understand, you combine current level tasks into pairs not only once but as long as there are enough tasks to form at least one pair. Is that right?
Hard contest + Small number of participants => low rating change.
Me with 1 solved problem have a close rank with someone who didn't solve any.
I suggest count someone participated in contest if he/she see a problem not if he/she tried to solve any.
Better is to always give a simple problem, so that at least every one has a submission.
Still, one person can choose not to solve the easiest problem when he doesn't know how to solve the other ones, in order to avoid decreasing his rating.
Yeah he can. But most people won't as is evident by Div 1 contests where many persons end up solving just 1 problem.
Was anyone able to solve problem B in O(n2) at least?
I think so. Let's sort ducks by their tails positions. For each duck, let's calculate the answer ignoring ducks with tails behind this duck's tail. Assume that this duck ends at t. I claim that we will ignore this duck, or shoot at non empty prefix of sequence: t, t - r, t - 2r, ... We can check all meaningful prefixes by iterating over previous ducks.
So, are you doing some kind of DP? What about big coordinates? This sequence can be pretty long.
I check two possibilities: 1. There will be no other shots (iterate over all ducks to check this) 2. I will shoot at some previous duck's tail, so I shoot as many as I can, while still being able to shoot that duck's tail. (iterate over all ducks in reverse order).
Edit: Now I think I should also consider the sequence in the other direction t, t + r, t + 2r, ...
Is there a nice way to solve problem D?
My solution (which I debugged 2 minutes after contest) goes as follows: We have to count number of representations of the form A = (1 + p1a1)... (1 + pkak)
We call a prime p < sqrt(A) bad if there is a k such that 1 + pk|A.
We use dp[divisorsOfA][badPrimes].
dp[d][k] is number of representations of d as product of 1 + piai where pi is one of the first k bad primes.
One can easily write formula for dp[d][k].
Answer is dp[A][nrBadPrimes].
Number of divisors of A is O(sqrt(A)). But what is the number of Bad Primes in worst case? ( I think your dp array size is O(A) ) :)
well in fact max number of divisors is less than 7000 and number of bad primes for "very composite" numbers was less than 1000.
Thank you very much XD. I have this idea but I think that dp size is O(A) :(
I think I'm Loser of the match :(
Hey, can someone who solved D take a look at this submission — http://codeforces.net/contest/542/submission/10991347
I seem to be doing the same DP as in reference solution, but it's working around 3 seconds on the worst test case, and I don't know how to bring it down. During the contest I had the same solution with a map for storing dp states, but switching to unordered_map didn't help.
Specifically, can you take a look at the go() function. I left the comments on top of it to explain stuff. When the first call is made, I still have around 1.3 seconds to figure out the answer, but DP with 14M ops is working much slower. Let me know if you figure out the problem.
Thanks!
The tons of operations on maps are causing you to lose insane amounts of time in memory allocation. Just get rid of them and use static arrays instead: 10992963
And you can even reorder the dp dimensions for extra cache-friendly brownie points: 10992968
Ah, that's unfortunate ...
Thanks man!
I attempted A first because I'm familiar with data structure problems. So I solved other problems very late. One step of my algorithm in A is to iterate the ads in decreasing order of their ending time. So I wrote:
Looks alright. Huh? But the bad thing was that I iterated the ads from n — 1 to 0 instead of from 0 to n — 1. This is why I lost my T-shirt. And luckily now I have the same rating as dreamoon_love_AA.
In problem E, is there a better solution than n times BFS?
I mean solution like this:
1) check bipartity (our graph have to be bipartite)
2) In every connected component find longest path
3) The answer is sum of longest paths in every component
Still waiting for editorial...
This is editorial, but it is not translated.
The translated version of editorial appeared. Sorry for the delay!
Thanks a lot.
My first time to become an IGM. Yay
Has anyone received the T-shirt yet?
Будет ли интернет-трансляция финала?