Хотите выиграть футболу? Или узнать как придумывать задачи для соревнований по программированию? А как насчет порешать 7 задач за два с половиной часа?
Если ответ хотя бы на один вопрос из перечисленных выше -- да, тогда Codeforces Round #270 непременно для вас. Раунд был разработан мной в Калифорнии, и приготовлен в системе Polygon (оригинал: designed by me in California, assembled in polygon). Спасибо MikeMirzayanov за прекрасную систему и Gerald за помощь в организации и тестирование раунда. Раунд стартует в обычное время в воскресенье, не упустите возможность посоревноваться!
Организаторы Marathon24 решили сделать подарок лучшим участникам раунда! Лучшие 25 участников получат специальные футболки от Marathon24! Большое им спасибо!
Эта картинка всего лишь для привлечения вашего внимание. Настоящие футболки будут иметь специальный дизайн от Marathon24!
Существует несколько статей, которые призваны научить, как стать автором задач для соревнований по программированию. Например, Problemsetter's Memoir и Way of Problemsetter. Но все они детально рассматривают только лишь процесс подготовки задач. Возможно, вы не знаете как начать готовить контесты по той причине, что у вас нет идей для задач.
В последние три года я подготовил очень много задач. Например, два Codeforces раунда (#190 и #228), также я подготовил ровно 100 задач для Topcoder. Поэтому я решил написать небольшой учебник, чтобы поделиться своими знаниями по придумыванию задач с общественностью... Стоп, как насчет привести контест, в условиях задач которого будут содержаться советы по придумыванию задач. Так я пришел к идее: в каждой задаче контеста будет описываться определенный способ придумать новую задачу, затем в качестве примера в условии будет описан процесс придумывания новой задачи этим способом; эту новую задачу вам и предстоит решить!
Обратите внимание, этот раунд будет немного специфическим: все участники (и Div1, и Div2) будут соревноваться в одном и том же контесте, а контест будет состоять из 7 задач! Продолжительность контеста увеличена до двух с половиной часов.
В конце я хочу немного рассказать о себе (как это сделал marat.snowbear в предыдущем анонсе). Меня зовут Gaoyuan Chen, и родом я из Китая. Я жил в Beijing в течение 23 лет (до этого августа), а затем поступил в университет южной Калифорнии в Лос Анджелесе, чтобы научиться разработке игр. Как разработчик игр я постарался сделать раунд как можно более интересным (конечно, в раунде есть задача про известную игру). Когда я переехал в штаты, я стал использовать Facebook, так что если вы хотите узнать меня лучше или пообщаться со мной в чате, заходите на мою страницу: https://www.facebook.com/cgy4ever.
Остальная информация, например, разбалловка задач (возможно, последняя задача будет иметь стоимость 3500!) будет опубликована позднее.
Желаю всем удачи и удовольствия от решения задач!
Update1 : Разбалловка: 500 — 1000 — 1500 — 2000 — 3000 — 3000 — 3500
These T-shirts look a bit generic :D
It is just an image to attract your attention. Real tshirts will be designed specially for Marathon24!
Thanks everyone who downvoted this comment . I broke a record and became last one in contribituon list . This is a big achievement in my eyes. Start upvoting now !
Neither are your spam comments right for codeforces .
What is the current record in most downvoted comment on Codeforces? That one here looks like a pretty good candidate :P.
The author now has the second lowest contribution: http://mirror.codeforces.com/top-contributed/friends/false/page/34
Now it's definitely the lowest :>. He may be contribution version of worse :D. Btw when I was writing my previous post it got something like -160, now it has -392. This must be record :D.
Now it has -600. Wow :D
I missclicked upvote, how can i get my vote back(to downvote ofc)
You can make another account, downvote from it and repeat as long as you find it fun :D
downvoat rating: -206 (min. candidate master, -206)
The amount of downvotes for his comment is below worse's rating :P.
And his comments has more downvotes, than the post has upvotes :D
Do we want to win a T-shirt? Yes, we do. Do we want to learn how to design tasks for programming contest? Yes, we do. Do we want to solve 7 tasks in 2.5 hours? Yes, we do.
Do we care about your opinion? No, we don't. Do we care if you don't participate in the round? No, we don't.
Have a nice day.
wow, positive man!
No, that is NOT how you link an image. You're linking your profile page, which is not an image.
so, you want to break the record of highest up voted comment? good luck!
am i the only one around here who up voted the non edited version of this comment?
My pp is very cool
aaahhh! my record has been broken!
The age of long round descriptions has started
Its really nice and interesting to know about the problem setters.
So are the top-25 of both rounds getting t-shirts?
UPD: sorry I misread, both divisions are competing in one contest
Oh yes, this will be very useful for me. Maybe I will learn how to write a non-math problem (!!)
Is this a rated event?
Yes. Why not?
This is not the first rated round for both division. (e.g. Good Bye 2013 was rated for both div, but the duration is 2:00 instead of 2:30)
Just because I saw both division round for the first time. :)
You introduced your self in your blog. But, Something was question to me for a long time. Why is your username cgy4ever? What does cgy means and why forever? :-)
His name is Gaoyuan Chen; in China, the family name goes first, so Chen Gaoyuan (CGY).
So, His username is something like : "Viva me!" ? :D
you are mine one of all time favourite coder , you always write code simple and understandable :) . last couple of rounds was not good for me i hope this time my rating will increase :D . it always great to compete with both division :)
My favourite problem setter !! I have tried to mimic/ learn problem writing by looking at his problems. Your problems are really creative and provide a lot to learn. A big thank to you cgy4ever from heart :)
"then I went to University of Southern California in Los Angeles to learn Game Design and Game Development."
That sounds awesome :D
Is there any game you've designed?
That's a Yo Gi Oh Problem setted by him Link , maybe he was a part of the team who designed it ? =D
Oh, no, Yo-Gi-Oh is not designed by me. :)
That is indeed a great game, I played it (and watched the anime, at least first season) when I was in primary school.
That's impossible timewise, the franchise is from early years of this century.
Oh, so you know I just start my way to become a game designer, so don't expect some famous games designed by me at this time.
We have a game design course this semester, and we are designing non-digital games every week. (We have not only CS student but also students from School of Cinematic Arts, and most of them don't know how to program, so we design games that do not require programming)
That is a fun course, these pictures shows how other people are playing games that my team designed in first few weeks (it is called playtest: they play our game and give us some feedback, then we use these feedback to improve our design, and repeat this process again and again):
http://puu.sh/bPARt/49974bf0b6.jpg | http://puu.sh/bPASe/91b97133b2.JPG
I'm sure that if you do the same thing for gameplays as you do for contest problem ideas, you are almost guaranteed to discover a few game-changing ideas eventually. Good luck with that!
Great format: 7 broblems — more place for solving ideas and more interesting standings!
At least its my thought.
This round will be on my 17th birthday :) I hope this will be a great round for me and for all.
I do hope you provide sample implementations for the really hard problems. Its always a pleasure to read your code cgy4ever !! :D
I've a feeling like Codeforces is becoming more than a problem solving and programming site , I'm feeling lucky to be in this great community with brilliant minds
Problem setter is very interesting of facebook chat. :D
Just curious, do you have any special reason behind making this contest combined for both divisions?
There must be some reasons but I don't know that. :)
This decision was made by Gerald (or maybe MikeMirzayanov or some other people in codeforces side). I think this idea is great so I agreed to use it.
Probably because there are prizes. It's hard to compare participants if they are given different problems.
And I'm sure there'd suddenly be many incredibly amazing participants in div2
I think div1 will get all all prizes.
You mean UNRATED ones ??!!
no_name_weak_vegetable was an unrated user who won T-Shirt :P.
Another Chinese Round arriving!
Enjoy the T-shirts:)
What does "cgy" in your handle mean?
Maybe it is Chen GaoYuan.
Yesterday I was virtually participating in #254 round, and in one problem there is an answer http://mirror.codeforces.com/contest/444/problem/D :D
An exciting announcement :) Wish this round success !
Surely the best way of creating new problems — misreading other problems. I created a lot problems that way :D.
For example: http://www.artofproblemsolving.com/Forum/viewtopic.phpp=2498536&sid=add5e05df3e05f2371cd0bee14294831#p2498536 — I misunderstood phrase "rounding down to the closest integer", I somehow ignored "down" and focused on choosing the closest integer, so 5,2 should be rounded to 5, but 5,7 should be rounded to 6. It turned out it has a really cute solution and later it that problem was posed in the most popular polish mathematical periodical "Delta" :D. Can you find the solution :)?
Lame way of creating new problems: "What can be done by using centroid decomposition?" :P.
Another fun way of creating new problems is to get inspiration from real-life situations. For example when being annoyed at people getting on the plane when they block the aisle taking care of their luggage and causing 50 people to wait. It immediately comes to mind that given time of blocking aisle when finding one's place for all people, one should firstly find an optimal arrangement, so that the summed time of waiting is minimized!
Two easy ways:
(see the problems E, I, J from our last gym contest)
"change one word" -> most probably minimize to maximize or vice versa :D
regarding point 2, it seems cgy4ever agrees with u. :)
(see problem D for more context)
I once created around 4 problems (for a physics competition) by naming them by quotes from Fish Fillets and creating problems based on them. Of course, it's easier to make physics problems because you just take an IRL scenario and make a simplified model if it's unsolvable :D
sorry
There's no "yuo" on that page, so we'll still minus you.
“all contestants from Div1 and Div2 will compete in one contest”, does it mean a difficult way for the div2 members to get the T-shirt ?
Yeah, for me too.(I always jump from div1 to div2, then back) :D
I don't know how exactly the rating is calculated in codeforces contests. But from the limited number of contests I did till now, what I came to know is that my rating would increase/decrease depending on whether I got a better/worse rank than the previous contest. Since this time, Div 2 contestants will be doing the contest with Div 1 contestants, the ranking of Div 2 contestants will most probably not be better than last time. Does this mean that we (Div 2) are going to get a drop in the rating?
No. The update will be adjusted to that unusual contest (I mean, formula for updating ratings covers all cases in a relatively fair way, any special treatment is needed).
as difficult as for div.1
Жалко что с отбором Минским на ВКОШП пересекается.:(
ACM-ICPC rules?
Score distribution is mentioned, so probably not.
Why are you downvoted?
I also wonder...
some people want to watch the world burn.. (may be, some user found it's fun to down-vote)
Is this a rated contest ?
Yes
worse настал твой час получить самое большое увеличение рейтинга. Ну или можешь и дальше в минус уходить, в принципе, и то, и то — интересно.
Ты ещё не понимал, что так оно и случится :) 469 место
А может Lo_R_D — это мой основной аккаунт, и я просто решил поднять себе вклад, как вам такой вариант? ;)
Да-да, определённо я — это ты. У меня перед этим раундом возникло желание по-взламывать кого-нибудь, чтобы уйти в минус и вылететь из div1, так как последнее время, ожидая раунд для div2, я засыпал, потому что не было достаточной мотивации для участия.
А еще была идея попросить Мишу добавить кнопочку "Сбросить рейтинг на 1500" для первого дивизиона, уверен, Гена и Петя бы обрадовались такой кнопочке.
It was designed by me in California, Assembled in polygon
Are you mimicking Apple? haha
https://www.apple.com/designed-by-apple/
Yes, I fount it in the back of my iPhone, and it looks interesting.
Could be 5k registrants! Fingers Crossed
5000+ registration and all of them are official . This is great :D
delayed :(
i think its normal for 5000+ registration
Yeah, and crashing is normal for 5000+ registrations too :D
I get the feeling there site will be slow/down often...
Will this round rated??
For the n'th time, yes.
Yes, look for the answer of vishfrnds above.
The contest was delayed because this guy didn't registered at time
5419
Sorry TopCoder It's The Age Of CodeForces
Хотел зарегистрироваться => нажал кнопку => предложило сначала зайти на сайт => зашел => забыл снова нажать на регистрацию => я не участвую. Жизнь — боль.
C. Уроки дизайна задач: недетеминированность
А где же первая "Р"?..
мне интересно на сколько поднимется рейтинг worse, он сейчас на 500+ месте
worse solved the first 4 problems! I wonder if he is going to hack everyone again!
also, i just noticed that he solved B in just 32 seconds!
Ставлю, что worse дадут 1000+ рейтинга
worse solved first 4 problems!
I'm going to kill myself :D
and didn't do even one unsuccessful hack! :D
Oh my god, I forgot about unsuccessful hacks, what a shame... Now my rainting will increase, it wasn't in my plans, I hate myself :(
You should solved all 7 problems in contest,and make many many unsuccessful challenge until your score's absolute value equals to the score when you solved 7 problems.
Because you are the one in my friend list, when it came to 2 hours after starting, I was so surprised that you hadn't done any hack! And I doubted that you write the code which can pass pretest and FST. After system test, you surprised me again. In the end, I doubted you either forgot to hack (maybe you forgot it is the "worse" account) or want to make a "V" rating (decreasing and increasing). You can make another achievement that become IGM from white rating (rating below zero)~~ BTW. When I finished the problem C, I clicked the friends' rank and notice your rank is in front of mine... At that time, I felt I am worse than "worse" as well as the "worst"...
I can be your friend.
to be honest what ever you did for fun or anything make you as a celebrity :D today anyone from codeforces community at least know about two handle tourist and worse :D
Btw i believe oneday you will be a red coder :) i would like to ask you a personal question how old are you ?
It's a secret. I'll tell you when I become a red coder ;)
"i believe oneday you will be a red coder" — done! ;)
Thanks for your belief in me!
Я усвоил уроки по дизайну задач, но смог пока придумать только математическую задачу по мотивам задачи D: верно ли утверждение, что для любого дерева с нечетным количеством вершин, сумма расстояний между каждыми двумя вершинами будет равна сумме всех рёбер, помноженных на некоторые чётные числа? То есть
сумма( Sij, i = 1..n, j = 1..n ) / 2 = сумма( Ai * Ri, i = 1..n-1 )
, где Sij — расстояние между i и j вершиной, Ri — вес i ребра, Ai — некоторые чётные числа.Впервые так долго нечего делать во время раунда, смотрю чужие решения.
Первое ощущение — ОНИ ВСЕ СПИСЫВАЮТ ДРУГ У ДРУГА ))
Да, и еще остается время подумать о том, какую все-таки фигню написал сам.
UPD как решать D ?
На Д у меня идея была такая: Что то типо Дейкстры. Из первой вершины идем в самую ближнюю. Потом из 2ух вершин в самую близкую и так далее. В результате у нас получилось дерево. И сверяем расстояние от каждой вершины до другой. Не хватило минуты что бы сдать это. Так что возможно я что то не до понял.
Вы придумали алгоритм Прима для нахождения MST :)
Ой да... Это же Прима :) Что то со мной не то :) Ну хоть я это быстро придумал
Блин, была и такая идея. Но мне почему то очень уж хотелось пытаться строить дерево каким-то dfs-ным алгоритмом. А потом проверять через lca (которое не умею писать). Оказалось кто-то строил дейкстрой, в разборе — крускал. И также в разборе сказано, что проверить успешность построения можно не только lca, но и вообще за квадрат (это пока не понятно).
UPD Нет, в разборе сказано проверять, запустив N dfs или bfs, не поверил сперва.
Are there maxtests in pretests? Will all those solutions pass?
How do you "check" ? by doing all pair shortest paths specialized for a tree ?
EDIT: sorry comment was meant for your MST post for problem D !
yes, checking all shortest pathes by running n dfs's
How is problem D supposed to be solved?
I found MST and then check if its correct answer.
What algorithm did you use to find MST ?
I used Prim's algo, but I believe Kruskal's algo will do too.
Can you please tell me what do you exactly mean by "check if its correct answer." after finding the MST?
Check that all pairwise distances are correct. It could be done in plenty of ways, I used dfs from each vertex.
How did you find MST ? How did you derived edges from the distance matrix ?
There are many ways. For example, if you pick vertices i, j, then you can recover the path between them: k is on this path iff D[i][j] = D[i][k] + D[j][k]; sorting by D[i][k] gives their order on the path. This way, if you pick i as the root and try all j, k, you have all supposed edges and are left with checking their treety.
Okay, I'm probably going to hang myself, but what was the idea for B ? I just didn't get it...
I use this: try to send people to top floor first and use any spare capacity for the floors below. continue same downwards
the idea is that you have to move to the highest floor ... so it makes sense to make a greedy approach : pick the highest k people (Fi) and transport them and come back and do the same thing again ...
Okay, now I know why I didn't get it... I just didn't realize that 1st floor is really 1st, i. e. floors are not 0-based! And it was written in the statement like bazillion times and I was just wondering how they got the answers to the samples... goodbye cruel world :D
Я понимаю, что, чтоб писать такое как мое решение на задачу D, нужно быть конченым извращенцем, но почему Мин Каркас + LCA не правильно?
прост)
Омг, написал в B динамику d[человек][группа][его место в группе], заблочил задачу, посмотрел другие решения и понял, какой я идиот :(
По C написал динамику dp[pos][prev_choice]
UPD failed systest, add 2 lines of code, AC. +1 reason to think about greedy twice before writing dp (at least, it may help to write dp properly).
UPD2 я опять в ауте, опять перепутал spoken languages
UPD3 блин, все
Я, конечно, написал динаму по одному параметру, но тоже огорчился, когда стал смотреть чужие решения. Тем не менее, в одном чужом решении нашел багу — помог себе и человеку.
Что было в тех простых решениях?
Сортируем массив по невозрастанию, и каждый k-тый плюсуем. умножаем на 2
Are there any rules which forbid using inline assembler in C/C++ code? With it, problem G becomes super-easy...
I might get a lot of downvotes for this, but I don't see which assembler magic you can use to make the brute-force approach viable, (if thats what you mean by super-easy...)
Compute bit count via SSE3. (I'd like to note that even without assembler magic, __builtin_popcount results in ~7.9s for the worst case; but SSE3 bitcount results in <3s).
Good job ilyakor!
I have tested builtin_pop_count() and made sure it will fail. But it turns out many people uses cnt[x<<16] + cnt[x>>16] and passed.
I think I should learn more knowledge about low level computer science, like assembler.
More faster way is splitting 64-bit long long on 4 16-bit shorts.
It was difficult to hack in this round :(
Wonder how long System Tests are going to take with so many people and 7 problems...
worse'll increase +inf i think
My standing is after worse.Am I worst? T_T
And my ranking, too :D
Can anyone please tell how to hack a code with code generator .
If your test case is too large, for example it has over 100 inputs, you can write a code to generate your test case, then codeforces compile your code and give the output to the selected code for hack.
I tried to write max_tests with code generator, but did not success. Write 105 integers from 1 to 105 by hands would take to me more than 2,5 hours.
do u mean 105?
http://mirror.codeforces.com/blog/entry/14028 Editorial.
How to solve B?
sort and greedy
worse is going to jump pretty high, i guess :)
He got AC on A,B,C so far. Wait for D
now D also!
Today, worse goes up and tourist goes down...must be opposite day!
Opposite Day :D
LOOOOOL :D
I am more interested to see rating change of worse than mine :)
i don't think he will become higher than Newbie.
If there is a bug in rating system, he might overshoot tourist :P
Maybe when you reach negative rating and white color, you will never have it possitive?
How to solve C? I submitted a solution which passed pretests but I am afraid that it will fail systests.
Greedy. Take the minimum of 1st string according to given permutations.
set flag=0
Then go to all other permutations in given order and take minimum of them which is greater than the first string and make it as the current string If none of the names now has string greater than current string then break the loop and answer is NO so set a flag=1 else make current string as lower of the two strings of a permutation and do next iteration
if(flag) ans=NO
else answer is YES
Я в D отсортировал ребра (если считать элементы матрицы потенциальными ребрами) по весу, каждую вершину поместил в систему непересекающихся множеств.
Дальше, проходил по всем ребрам. Если текущее соединяет вершины из разных множеств, объединял множества, и добавлял ребро в список ребер дерева. Иначе ничего не делал.
Потенциальные ребра с весом 0 выкидывал на момент чтения.
Дальше, проверил, что граф связный, через n bfs-ов нашел расстояния между кратчайшими вершинами. (Между двумя вершинами дерева есть только 1 путь, поэтому кратчайшее расстояние можно искать bfs-ом)
Получил TL 10 (http://mirror.codeforces.com/contest/472/submission/8011182 ). Немного разогнал bfs, но снова TL10. (http://mirror.codeforces.com/contest/472/submission/8014663 )
На моем компьютере около 0.9 секунд занимает считывание и примерно секунду сортировка. bfs за 0.3
Кто-нибудь использовал ту же идею?
Алгоритм правильный, но очень много входных данных (20002), поэтому используйте
ios_base::sync_with_stdio(false);
Я использовал scanf.
Ваша программа выполнилась за 11 с. на моем компьютере на макс. тесте. Т.е. видимо, у меня ошибка в решении, и где-то появляется бесконечный цикл.
Похоже, что измерение астрономического времени вместо процессорного создает очень большую погрешность
Запуск был в дебаге или релизе?
В dev-cpp). Думаю, что это в релизе, т.к. если запускать с возможностью отладки, то работает 56 секунд.
Код с подсчетом времени: http://codepad.org/e5PYsTBV Генератор теста: http://codepad.org/iDGPCoK0
Проблема оказалась не в зацикливании. Просто я хранил веса ребер в
long long
вместоint
-а, и это замедляло их сортировку на пол секундыhe is lucky :P
submission: 7999344
Isn't it correct ?
when n%k equals 0, he is accessing p[-1].
p[-1] is equal to zero when p is global
Because I neglected this fact I made an unsuccessful hack today
it's UB not depending on globalness of array.
Sorry for getting the fact wrong. What does UB mean by the way ?
unexpected behavior
Undefined behavior.
That's feeling, when you know that your n^3 solution won't pass system testing, but you steel can not stop hoping :|
тем временем пошёл уже второй час систетов:)
Верный знак быстрого обновления рейтингов :)
i tried hacking 8002822 with n = 17, but the code (correctly) returned 8, 9 as output. can anybody explain how?
I don't know why...It's strange because 8>=n/2 and he have i<n/2.That's black magic :))
it's even more puzzling because i successfully hacked 7998356 with the same input n = 17.
When the round started I was a bit excited to be in the same room with you, since I've noticed you're active and known in the community and also I participated in #258.
But then i got disappointed when you hacked me ~10 minutes before the end, when my solution was locked (all because of a missing '=' sign).
Nice find though. :)
glad to know that i'm atleast a little "famous" :D
Well, he reads from not unitialized variable and it's UB(may work in any way), probably it's optimized in that way that a and i are effectively the same variable, because in any correct case(when there's no UB) a and i are equal
compile this code with clang++ and g++, got two random numbers 8015726
did you use
-O2
?no, I didn't use
with -O2 output is 0 17 with g++ and 8 9 with clang++
In case anyone's wondering, this page lists the flags used by the compilers on CF. As for "-O2" flag, this manual explains what the flag does. In short: it's a 2nd level optimization.
never use doubles with no eps.
never use doubles if int is enough.
j*j <= i
D problem was very pleasant for me. After a hour of thinking (and that's what I like) I discovered how to solve it, but sadly I wasn't able to implement a correct solution. Thanks for round!
Во время контеста придумал решение по D, которое работает за n^3 с отсечениями. Понял, что долго, и решил не писать его. После контеста написал — зашло, lol, с максимальным временем 1668 мс.
Если кому интересно, решение носит вот такую идею:
По первой строке матрицы располагаем вершины в точках на целочисленной координатной прямой. То есть, если первая строка 0 1 1 5, то первая вершина в точке 0, вторая в 1, третья в 1, четвёртая в 5.
По первой строке сортируем по возрастанию все вершины.
Идём по отсортированным вершинам и смотрим их расстояние до других вершин, где мы еще не были. Это расстояние может быть равно значениям двух видов: а) разности положения на координатной прямой, б) или же нам необходимо пройти все точки слева от этих двух (то есть точки, в которых мы уже были), и тогда расстояние между вершинами должно быть равно
(положение первой вершины на прямой) - (положение некоторой вершины слева) + (положение второй вершины на прямой) - (положение той же некоторой вершины слева)
.Если получить какое-либо расстояние между двумя точками не получается — ответ No. Так же отдельно проверяем матрицу на симметричность, равенство диагонали нулю, и неравенству элементов вне диагонали нулю. Если всё хорошо — ответ Yes.
Решение
у меня было что-то похожее, только работало за квадрат.
сортируем вершины по первой или любой другой строке.
рассматриваем i-ю вершину. Ищем максимальное j<i, для которого
d[0][j]+d[j][i]==d[0][i]
, и проводим реброi-j
.проверяем, чтобы граф был связным и все расстояния корректными (я сделал n dfs-ов)
Ну, отсечения разные бывают. Попробовал бы посчитать, сколько примерно будет работать.
Кстати, интересует решение G. Расскажите кто-нибудь, пожалуйста. Я зациклился на идее с sqrt-декомпозицией но дальше, чем время работы примерно в , которое моему скиллу писания на Java не очень понравилось, я не продвинулся. Или так и надо было?
Я не поленился и посчитал, и для n = 2000 вышло вообще 2666666000000. Может где-то ошибся в расчетах, но вообще по идеи должно быть так:
n * ( ( n — 1 ) * 1 + ( n — 2 ) * 2 + ... + 1 * ( n — 1 ) ).
Посчитай лучше в глобальной переменной количество присвоений, вводов, выводов (в т.ч. и в компараторе для sort).
Код
Для самого печального теста вышло: 2 484 943 712. Это без учета сортировки.
Может где-то переборщил, да и компилятор возможно оптимизирует некоторые места. Но решение таки заТЛилось из-за дополнительных подсчетов глобальной переменной.
Ну тогда это что-то новенькое, видел как циклы по 10^9 залетали за секунду, это удивлять уже перестало. Но тут как бы посложнее, чем пара циклов. К тому же, если и правда дело в оптимизациях — на векторах может еще быстрее заработать (их он различает по расположению в памяти, в отличие от указателей на массивы, может перестанет копировать лишний раз где-нибудь). Но это уже совсем наркомания :D
Ты уж прости, но как-то так себе отсечения, если при n = 2000 O(n3) выливается в 2666666000000 :)
Зато шестёрок много... 666
Ну.. Я умею это делать за N * 512( * 8) + Q * (512 + N / 512)
8017008
Petr won this round with a nice margin!
delete
Can anybody tell me why this solution of mine Timed out. But this got accepted. The first one used scanf to read inputs. The second used cin with sync_with_stdio(false). I assumed both of them are comparable in the time it takes.
1964 ms
is just a question of luck. Just for experiment — try to addin the second code.
Adding that Gave a TLE(http://mirror.codeforces.com/contest/472/submission/8016199)
Well, the experiment was failed) I saw that sort = TL but stable_sort = AC, so it's better to write codes that far from TL)
One of the best rounds I've ever participated. Congrats!
My rank of contest is
R = 2^A + Q
where
A is a count of my accepted solutions
Q is a quality of problems
didn't you noticed smth like this? :D
http://mirror.codeforces.com/contest/472/submission/8011195
http://mirror.codeforces.com/contest/472/submission/8015575
An identical problem to B was used a few weeks ago in a URI Online Judge contest. Link
I have access to the identical problem in Polygon, it's too easy to be unique
Even being an easy problem, it's cool to solve. It was a good choice.
I really enjoyed the problems, the mixed divisions was a great idea, as the problems were approachable for both divisions users. Thanks for the great contest.
Problem D is one of the most hard problems that I ever sent on contests (if do not take into account that I have copypasted code for DSU and Dijkstra from emaxx:)) ). Thanks for interesting problem D and interesting stories about problem creating:)
Отличный контест. Я уже готов было сдаться на третьей задаче, но всё-таки удалось решить ещё 2. Это мой первый контест, когда удалось выйти за 3 решённых верно задачи :) Сложность подобрана просто отлично!
Время по D: 1980 мс. Тебе очень повезло)))
Странное время на самом деле, учитывая, что куба там нет :)
Константа решает. Вот одно и то же решение, но в одном — multiset, а в другом — priority_queue: 8018809 8018805
P.S. Я к тому, что и n*n*logn может не зайти)
Прошерстив тут комменты, понял, что видимо надо было добавить строчку:
UPD: сейчас перепослал задачу с этой строчкой, получил Время: 389 мс :) В 5 раз быстрее.
Ага... я еще очень посмеялся над парнем, который писал, что у него ввод 0.9с занимает. Аналогичная магическая строчка есть и для вывода, можешь взять её из любого моего решения недавнего.
А на счет сложности задач я с тобой не соглашусь.
Задача С была уж слишком простой. Возможно, что её решило на 500 человек меньше, чем B, только потому, что они психологически думали, что не решат её. Уверен, если поменять местами B и С — количество решений по С изменилось бы и догнало B. Её усложняет только условие. Я так вообще не понял сначала, что дано в массиве p, и поэтому писал неправильный код, зачем-то sort() использовал. Я даже сейчас не смогу объяснить, что я думал, ибо это такой бред, скорее всего.
Задачу Е явно недооценили по сложности. Тут уже можно судить по количеству человек, которые её решили. Поменять её местами с F и давать 3500 баллов за неё — было бы неплохо. Да и вообще, если автор хотел сделать обычный раунд, только общий для 1 и 2 дивизиона, то это слишком сложная C div1, обычно её решают хотя бы 100 человек.
When ratings will be updated?
@admins Please can anyone tell the approx time it would take for rating update ? If it is >= 30 mins I will go to sleep :p
Actually, the contest was not balanced. It doesn't deserve +537, too bad that I had voted it before it started. Three easy straightforward problems that almost everyone solved, one problem that requires to think a bit, and three very complicated ones. Many people were doing nothing after they had solved D. Problem E should have been replaced.
C should have been harder too . A , B , C were very easy but the jump from C to D was large for low-skilled people like me . So most of the people were able to solve all A,B,C and the ranking was solely determined by speed .
Not only by speed!
Don't forget about hacks!
Oh, of course! Can you imagine how I enjoyed almost 2-hour searching for that
s1.compareTo(s2) <= 1
in problem C?It was pretty much a div1+div2 round, but with 2xD instead of C+D. That's why 3 easy problems — div2 A,B,C.
I would've removed G and put an easier problem after D.
Alternatively, there's a nice hack that shouldn't remove the main point from F and makes the code much less tricky: providing additional 64 registers whose values at the end don't matter.
Yes you are right. I found E is hard to implement few days ago, but I don't have another task to replace at that moment. Maybe we should swap E and F and don't allow x[i]^=x[i] in F (then it will be much easier: we can get 2 same bases).
I tried to made first 2 tasks as easy as possible. (There are 7 tasks, so if you only solve 1 you will kind of feel sad, right.)
For C and D, I think the difficulty is fine.
What about my trick of using additional 64 (or any other power of 2 that doesn't give away much from the solution) registers? You can simply copy the base to them and get rid of a troublesome chunk of code.
That is, at least my solution would be much easier :D
Yes, I was thought about add a constraints like n >= 100 (so it will give you 32 registers after Gaussian elimination) , but it will be a bit strange.
That constraint probably wouldn't do the trick I have in mind.
The point is that when you have the base copied into separate registers and in reduced form (dunno if that's the right term, the one where pivot 1s are unique on their columns), constructing a vector from them (in a separate variable) is extremely easy. So when you have the idea, there's just textbook GEM and that left.
It does look a bit strange, but it can always be wrapped in a surrealistic story :D and would most likely increase the number of successful solutions.
I don't understand your reply. Since we are dealing with vectors of length <=32, rank of that matrix was <=32 and n>=100 will imply that after reducing whole matrix you will have at least n-rank>=n-32>=68>=32>=rank free registers where you can copy base and do what you have described. In the end you get rid of that copied base. Either you didn't realize what I wrote or I don't understand why that constraint wouldn't do the trick.
Because these vectors will have to be edited eventually, and that'll mean you don't necessarily have a base in reduced form at some point. Think how easy it is to construct a vector from such a base.
You don't "get rid" of the copied base, you still need to convert its vectors to desired ones (in y).
1) Reduce Xs to base
2) Reduce Ys to base (and put those operations in the end in reversed order)
3) Copy base of X to registers with indices n-rank_x+1, ..., n
4) Erase base of X from registers with indices 1, ..., rank_x
5) Create Ys base in registers with indices 1, ..., rank_y using that copied base of X
6) Erase copied base of X
What is troublesome here? You don't need here any no longer needed vectors from base of X to newly created vectors from base of Y
Okay, with real separate registers:
You don't actually need a lot of ideas this way — no need to care about x[i]^x[i], no need to put GEM of Y in reverse order, you don't need swaps at all... I don't know if it wouldn't make the problem too easy, because there's almost no difficulty in implementation.
Hm, okay, that is a difference, but I think that this difference between what I proposed and what I proposed is 5 times smaller than between what I proposed and between actual solution xd.
It is true that my way demands doing operations on Y and to that we need idea of reversing which wasn't obvious for me that we can do this, but the most important thing is that we don't need to erase vectors from base X while deriving vectors from Y, what was really painful for me — we can use whole base of X all the time.
Undoubtedly :D
Since I expressed the vectors of Y in the base of X, moving from one base to another became just like moving from the canonical base to another. And that's quite trivial.
OK, so you got base X and want to create base Y. You create first vector from base Y — name it y1. You have to put it somewhere, e.g. in a place of first vector from base X — name it x1. But if you needed x1 to be able to derive other vector from base Y you will have to reuse y1! And that will be OK only in case when y1 included x1 — in opposite case we are already screwed! So we have to care about what we are replacing also. How are you dealing with that problem?
Imagine it in matrix form: you start with an identity matrix (base X) and want to create a different matrix (base Y expressed in base X) by standard operations "xor i-th row by j-th". The matrix is in (this is the term) reduced row echelon form, because GEM. It should be pretty obvious by now.
Also, if x[i]^x[i] is not permitted, then you still need to get to reduced row echelon form with the base of Y, by sorting rows — or state that it's impossible.
I think it would be the best choice to forbid x[i]^=x[i], make it worth 2500 pts instead of 3000 pts and swap E and F. Main ideas will still be included and we won't need anymore pretty ugly piece of code and have much more AC what won't cause such a big jump of difficulty between ABCD and EFG.
It is true that we will lose not that obvious part also demanding some thinking, but sometimes it is better to give up on significant issue, because task will become less enjoyable and won't gain interest of number of people which it deserve. I learnt that once when I proposed really nice and pretty hard problem for Polish OI, but I included a bit of geometry in it and people were afraid of that even though that geometry part was pretty easy. It ended with 0 ACs, nobody even knew how to solve it, because people were omitting this task. You can see this task here: http://main.edu.pl/en/archive/oi/21/lam (though it doesn't have english version, maybe translators can do the trick).
Depends on the implementation — for me, that "ugly piece of code" is 3 lines when expressing Y in the base of X.
When we will forbid x[i]^=x[i], reduced bases of X and Y will have to be exactly the same. That will make whole problem much easier. I somehow don't believe that it caused a 3lined difference in your code. In my code 8018580, I wouldn't longer need that last long for loop (that starting with "for (int i = 1; i <= st_y — 1; i++) {") which caused me much more trouble than everything else here.
Codes are public, so it's not really a question of believing :D
8018626, lines (originally 3):
If that operation was not permitted, I could've omitted only these 3 lines.
Sorry to say that, but ugh, your solution looks pretty complicated and completely impossible to read, because of incredibly ugly indentation. First for loop after comment "//base" looks really ridiculous, because of places where "}" are put inside it. Is that an effect of some changes in your code while uploading it? I won't believe that it can be your standard coding style.
If we will forbid x[i] ^= x[i] problem will be like:
Reduce X
Reduce Y
Check if they are exactly the same and if so then print already generated result.
Some parts of it are unnecessary, but that's unrelated to the x[i]^x[i] problem.
Yes, that's my standard writing style — do you think CF would remove selected indents on upload in my code only? I can't read the style with 1
}
on each line and not indented the same way as the loop it completes, so I understand that others can't read mine — but what do I care in a contest?То чувство, когда ждешь обновления рейтинга worse больше чем своего
То чувство, когда ты worse и тоже ждешь
Дайте нам рейтинг!
+319? ...
рекорд поднятия рейтинга))
А что, если нам не обновляют рейтинг, потому что worse сломал систему?
Опять? =(
7708612 7709278
i think worse today will cause unexpected behavior for code-forces rating system. :-D
btw he was in my room.
[http://mirror.codeforces.com/contest/472/room/131]
Why was the time limit of D so tight? Even n^2logn solutions got TLE.
Yes, it is true :(((.
n^2 log(n) passed!
this is mine
thats 1.8 seconds in C++. Think about the java users.
Похоже все как и я не ожидали, что у worse будет там мало плюсов к рейтингу за этот контест.
you are very good and smart!good boy,so cute~sorry my enlish is bad,hope you can understand.I don't want tell you I lost my sleep and very boring and don't known what I say,why me is so foolish ..TAT...hhhhhhhhhh,good luck and good night:D
it's time to sleep
I should running in morning in 1 hour..too sad:(
Talking about records... (which I mentioned here http://mirror.codeforces.com/blog/entry/13997#comment-189548). I thought that I may have just experienced the biggest drop of rating in whole Codeforces history (-132), but it turned out that tourist got such hopeless place — 21st and got -135 to rating :P. In regular Div1 contest, not joint with Div2, it is impossible to fall below -110 even if tourist would get last place :P.
Frankly saying, I prefer regular round than those joint ones.
Additional easy A and B cause that they are worth 500 and 1000 and other tasks are each worth additional 1000 and in that case having standard D (here F) accepted in second hour is worth less than standard B (here D) accepted pretty quickly. That is obviously bad feature.
worse only got +319...
me too :-(.
You got -17 not +319 :>>
Hmm, I think he means that he's disappointed, too. :D
Do you really think that I didn't know this? This was a joke :P.
I'm disapointed too.
I woudn't if this will be record, but unfortunetly no((( For example, avelino_2013 get +333, no_name_weak_vegetable(+426, just registered)
See more on Know Your Meme.
i'm even more disappointed that it was not even among the top 17 rating increases for this round!
(reference: round stats by DmitriyH)
In problem D, I don't know why the first one is wrong and second one correct.
d[u][v] = d[u][LCA] + d[LCA][v] --> WA
d[u][v] = d[u][root] + d[v][root] - 2 * d[LCA][root] --> AC
Oh lala :'(
Anybody help figure out why my submission 8015497 of Problem D is wrong at test 9? Thx.
Round Stats
Included it in the announcement.
btw, congratulations for become master again!
Thanks! :) And, certainly, thanks for the great round and interesting announcement!
Because of really good pretests, short (and quite boring) describtion of hacks can be found here.
жалко Arterm-а, он занял 26 место...
Comment Deleted
Я предлагаю все соревнования Codeforces делать так: не делить всех на 2 дивизиона, а предлагать либо 7 задач за 2,5 часа, или 5 — за 2 часа. Первый тип пусть будут сложные соревнавания, а вторые — легкие соревнования. MikeMirzayanov что вы думаете?
Зачем раз за разом tourist'у решать div2A?
Ему зачем-то нужен высокий рейтинг...
Не люблю культов личности, и рейтинг для меня это эпифеномен, а не самоцель.
Но это не займет полчаса или больше. Зато будет интереснее для людей с рейтеингом 1600-1800, половина которых в разных дивизионах?
Не подскажете почему задача D не прошла по ТЛЕ 10 тест на компиляторе MS C++, а на GNU C++ 4.7 получила АС ?
Решал: MST+DSU и DFS из каждой вершины для проверки расстояний.
Собственно вопрос даже не в том "почему", а скорее, всегда ли GNU будет быстрее MS ?
Потому что
ios::sync_with_stdio(false);
в MSVC++ ничего не делает, потоки всё равно остаются синхронизированными и медленными.Спасибо, теперь понятно.
Действительно отправил на MS с scanf\printf прошла, хотя немного медленнее.
I had a problem during the contest.My id "techboy" had been shown twice in the list which leads to same id.I solved three problems with 1 WA and 1 AC in A,1 AC in B and 1 AC in C. But it was showing that one id has got 1 WA in A and 1 AC in B while another one got 1 AC in A and 1 AC in C. So in the end i got double negative rating and also was far below in the ranklist than the position I should be in.I need help as soon as possible :(
I think cgy4ever in this competition put his name beside the names of all time big competitors... Just like in sample tests for problem C. :)
В первом предложении ошибка: Хотите выиграть футболу