Блог пользователя Um_nik

Автор Um_nik, 7 лет назад, По-английски

I wanted to write super-harsh blog but then I decided to split it into educational part and whining part. This is whining part. To read some cool stuff go here. This one will also be educational on a slightly different topic. And there will be A LOT of harsh stuff.

I'm not saying that I'm perfect. That round had some really bad problemsetting issues. Problem E was googleable, problem D had very weak tests against very stupid solution (so stupid that none of the authors and testers come up with it, moreover, it is so counter-intuitive that I don't know how so many people independently did it). In two constructive problems participants could look at jury's output, the feature of which I didn't know. And I'm sorry for these issues. BUT. This comment has very negative rating despite being so true. And no one are here to back me up. So I want to speak my truth as I always do.

Let me accompany you to the world of supposedly BAD STATEMENTS. aka statements written by Um_nik.

Problem C from 2nd division of CF Round #518 gets a lot of praise for having very bad statement. Let us look at clarification requests we get on this problem. My answers here are not answers to clarifications from real contest, they are my emotions.

I think that you should be ashamed for your clarifications so I will include handles. This is probably not ethical as a problemsetter to do it. But I don't care anymore. Maybe I will be banned from setting rounds on CF. That looks like a good thing for all of us. You don't want to solve my problems, I don't want to do anything good for you.

"Is it also necessary that if 2 colors harmonize each other they should be connected?" and similar
by sam29, arif.ozturk, aman28rwt, -rs-, Vshining, tgritsaev, L0rdV0ldemort000006, Huvok, seo, shinbay, Apptica, yurics, Distructed_Cat, Adoki, dalbaeb69, chrome, ASUS, cjc, its_ulure, GhostDrag, GhostDrag
Answer: Yes. That's what "if and only if" means. Literally. That is the meaning of these words.

"Excuse me, what is number k in prob C?"
by tgritsaev, fooish, dalbaeb69
Answer: That's a good question, number k is not important for the problem, but I decided to introduce it to ensure that you'll understand that you should place only colored rooks on a chessboard.

"A,B harmonize; B,C harmonize; do A,C Harmonize?"
by harshit601, Fighter.human, Gudleyd, atrophy98, tshr
Answer: No. I have no idea where did you get it from. There is nothing resembling in the statement. Probably it's an attempt to explain some samples, but it is wrong on first sample.

"are there many solutions for sample tests or it's one solution only?"
by Bakry, _QWOiNYUIVMPFSBKLiGSMAP_, bhowmik, mahdi.hasnat
Answer: Another good question, we made global clarification about this later. This was obvious from the samples, I think, but it was a mistake not to write it. I'm sorry.

"In the first sample, we can't go from the blue rook to every green rook!!" and similar
by cfalas, OmarBazaraa, MonsterInMe, DesiChamp, cjc, aman_shahi2, DesiChamp, MonsterInMe, S.Jindal
Answer: Samples are correct. Statement is correct.

"Reply fast please"
by ck98
"The statement looks like it was done with google translate, i don't understand anything"
by AlexArdelean
Answer: That's important information.

"if there is a harmonized pair (a,b). do the ans must contain a set of union of a and b? or i can arrange without any union set."
by Distructed_Cat
"if there is a harmonized pair (a,b). is it a must to make the both set of color a and b connected?" by Distructed_Cat
"And any rook of one color is connected with any other rook of another color that means all rook of 1st color is connected with all other rook of 2nd color if both color harmonise with each other?"
by Fighter.human
"Is it necessary for two rooks of different colors to be in one set?" by bktl1love
"What is harmonize of color??"
by _Muhammad
"can i connect colors other than the described in the input"
by KyRillos_BoshRa
"Specail Judge?"
by C20192413
Answer: Do you fucking read your questions? I like that "I can't solve the problem with operations in statement, can you provide better operations for me?"

Many questions just asking to clarify what the hell is happening in this hellish statement. There are a lot more stupid questions, I just tired.

CF has a large number of participants in each round. If 5% of participants think that his/her time is more important than ours then we will have to answer 5-10 questions every minute. In this round we had 30-40 unanswered questions during an hour, waiting time to get answer to your question is 5-10 minutes. And if we can't understand your question, we spend several minutes on answering. Please. Please. PLEASE. Spend 2-3 minutes trying to answer your question yourself. Use samples. Reread the statement. This is a skill, you have to improve it. Read my blog.

Don't ask "please explain the problem, I don't understand it". We already did explain the problem. The thing called "statement". Read it. Carefully. Why do you think that we will come up with better explanation right now? We prepared this statement several days, we asked testers to read it and say if something is unclear.

Don't say that statement is bad because you can't understand it. The statement can be hard to understand because it requires some knowledge, not because it is badly written. And some statements require to know mathematical notation like "if and only if" in this particular case. I can't come up with better explanation of why there are so many people asking the same question. basically "what if and only if means".

Please assume that authors spend some time on your contest. Much more time than yours 2 hours. Because it is true.

You can remember that once I made round unrated because I found the mistake in authors solution. I didn't wrote a clarification "I think your problem suck" without explanation. I continued my attempts to solve the problem and waited for the end of the contest, then asked what is authors answer for my test. Because I expected that authors did their job well and too busy answering stupid questions during the round.

One more time I spend ~15 minutes trying to prove that my answer for sample is incorrect. When I did it, I send this clarification: "Are you sure that answer for third sample is 34? For me it seems that there are 3 valid trees, in each of them there are 6 possible ways to choose pair of vertices, and for each path there are two possible winning moves for Ember, so the answer should be 36." Compare this to what you do.

I also think that CF should abandon the practice of answering every clarification if possible. It will decrease the number of clarifications and decrease the time to answer one clarification. If I can answer "Read the problem statement", that should be the answer. If I can answer "No comments", that should be the answer.

I think I'm finished with whining about my statements. Now about this doomed community of supposedly smart people.

The thing you did called bullying. There are people who downvote everything I write independent of content. Next there are people who disliked the consequences of my words, even my comment is correct. And there are also people who don't like that I'm saying my thoughts and don't respect their idols.

I liked first comment about "should stop creating problems", and first comment about this after the round. All others don't have own thoughts and have to repeat one thing over and over again. Now it is not a joke, it is being animals.

The same goes for "mind is weak". Yeah, guys, you are so original, it was not me who said it first.

To adequate people in this community: I'm tired of speaking truth. This not your truth? Explain me why am I not right, change my point of view. You think that I'm right in some cases? Speak it up. These animals can attack lone people, but if they will see that I'm not alone, they could think for once. You think that I have no right to insult people, but the idea is correct? Downvote me, say that wording is bad, but express that you agree with meaning.

MikeMirzayanov, I understand that for you quantity is more important than quality. I'm happy that you have your army of stupid fanatics who will write "You forget to hail Mike" under each post. This army has defeated me. Congrats.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +157
  • Проголосовать: не нравится

Автор Um_nik, 7 лет назад, По-английски

But Um_nik, we all know how to read, we have our whooping 2 month of experience! Oh, my sweet summer child, my experiments show that many people with kinda cool achievements like medals on ROI don't know how to read statements. But don't worry, I'll teach you. Well, probably you won't understand anything, because you didn't try to understand anything in your life, you expect all hard work to be done for you by someone else. Let's start!

Basic rules

  • The result of reading the statement is usually pure math model. If story helps to build correct understanding, you can keep it, but still try to discard as many unnecessary details as possible.
  • Imagine you want to tell the problem to someone else. What parts you want to tell? (According to my PM, this rule won't help you).
  • Shorter = better.
  • Simpler = better.
  • Limitations are part of problem statement. Especially small limitations, because for small data you can try all the possibilities.
  • Samples are part of problem statement. After building math model, check that you model working correct on samples, at least on small samples where you can check everything fast.
  • Notes are part of problem statement.
  • Try to find familiar patterns, maybe objects you already know something about. If you are given some connected graph with exactly one simple path between each pair of vertices, it's called tree. 4 letters instead of 12 words, see?
  • Try even harder to spot something strange, something you not expecting. That probably will be the cornerstone of the problem.
  • If there is some part of the statement you don't like, try to change that to something you like. Start with understanding the object, then simplify it. There are some problems which can be completely solved by this technique.
  • If the model you get is very big, try to split it into some pieces. It would be great if pieces are independent, like 'solve problem1, then use its answer as input to problem2 and so on'.
  • On first stages it can be useful to write your new statement. On paper. By hand.
  • Problemsetters do not write random things in statements. But why would you believe me, since I'm a bad problemsetter? I don't know, maybe you shouldn't.

Some examples

I'll use Timus for almost all examples. If you see statement in Russian and you don't want to, there is a language switch in upper-left corner.
Assumed workflow: read the statement on Timus, try to understand and simplify it using the rules above. You don't have to read "solution" parts, but I warn you that my concept of reading statements works. I mean, "statement" parts will often contain huge hints to solution.
In most cases I won't write step-by-step explanations how I get the final version. You can say that that's not how teaching works. I can say that you don't want to study. I'll win, because that's my blog.

Networking the "Iset"

Statement
Solution

Magic Programmer

Statement
Solution

Scheduled Checking

Statement
Solution

Work for Robots

Statement

Coffee and Buns

Statement

Harder examples

Now I'll try to explain something.

GOV-internship 2

Statement
Solution

Martian Plates

Statement

Winnie the Pooh

Statement

Titan Ruins: Serial Control

Statement
Solution

Coolest trick of reading statements

Zamkadye

Statement

Different math models will lead you to different solutions

Well, only if you have some patterns of how you should solve problems. And you should have them, patterns are good, they're the fastest way to solve problems.

Empire Strikes Back

Statement and Solution
Statement and Solution 2

Eliminating things you don't like can solve the problem

Last example in this blog will be not from Timus, it is 2016 Yandex.Algorithm Round 3, Problem F, shout-out to Endagorion for creating such pearl.

Problems visible only to participants, so I'll give already simplified problem statement here:

Given a tree, all vertices are initially white. Two players, Red and Blue, take turns coloring white vertices (surprise) red and blue. The game ends when there are no white vertices left. The score of the game is CR - CB, where CR is a number of connected components on red vertices, and CB is a number of connected components on blue vertices. Red wants to maximize the score, Blue wants to minimize it. Find the score if both play optimally. n ≤ 2·105.

Solution

Полный текст и комментарии »

  • Проголосовать: нравится
  • +381
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-русски

Всем привет.

Мы посовещались и я решил, что нет смысла скрывать очевидное. Я и KAN будем участвовать в сезоне ICPC 2019-2020 от Нижегородского ГУ. Однако нас пока двое, а должно быть три. Вы понимаете, что это значит. Если вы молоды и энергичны...

Мы предлагаем:
- Возможность выступать в сильной команде, что, в свою очередь, влечёт:
* Больше удовольствия от контестов;
* Возможность перенимать наш опыт;
* Неплохие шансы на высокие места на соревнованиях.
- Оплата участия в сборах в Птз и МФТИ (или хотя бы большей части).

Обязательно:
- Иметь желание, как бы глупо это не звучало;
- Быть ICPC eligible в сезоне 19-20 (год рождения не раньше 1996, не более 4 региональных контестов, не более 1 финала);
- Иметь возможность в учебном году 19-20 проучиться хотя бы осенний семестр в ННГУ, а также в течении года жить в Нижнем Новгороде, при этом желательно не иметь возможности загреметь в армию;
- Не иметь личной непереносимости Um_nik (частое заболевание) и KAN (очень редкое заболевание);
- На всякий случай: владеть русским языком.

Желательно:
- Хотя бы стабильно div.1, лучше больше
- Иметь "уникальные таланты", вроде сильного математического бэкграунда или глубоких знаний в конкретной области.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +294
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-английски

CODEFESTIVAL site is updated with info about this year edition but only in Japanese.

Using Google Translate I read that this time only people living in Japan are allowed to participate (at least in the final round).

rng_58, can you confirm this?

Main reason for asking now is that the Finals date is 17.11 which is very close to TCO onsite dates (13.11-16.11).

Полный текст и комментарии »

  • Проголосовать: нравится
  • +83
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-русски

I want to apologize once more for queue problems. It has also aggravated some tight ML/TL issues which probably would be not so big otherwise. I hope you enjoyed the problems nevertheless.

Tutorial is loading...

38799778

Tutorial is loading...

38799800 — logs
38799811 — case analisys

Tutorial is loading...

38799824

Tutorial is loading...

38799831

Tutorial is loading...

38799840

I hope that Petr is not mad at me for my joke.

Tutorial is loading...

38799850
38799853 — completely different solution with complexity O(6n / 2)

Tutorial is loading...

38799873

Tutorial is loading...

38799881

I hope that PrinceOfPersia is not mad at me for my joke.

Tutorial is loading...

38799887

Полный текст и комментарии »

Разбор задач Codeforces Round 485 (Div. 1)
Разбор задач Codeforces Round 485 (Div. 2)
  • Проголосовать: нравится
  • +161
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-английски

Hello!

I'm glad to invite you all to Round 485 which will take place on Tuesday, May 29 at 18:35 UTC+3.

There will be 6 problems in each division, 3 of them are shared between divisions. 2 of div.2 problems created by KAN, 7 others created by me. The contest duration is 2 hours. My problems were originally used in HSE Championship.

I would like to thank Merkurev and GlebsHP with whom I discussed the problems, I_love_Tanya_Romanova for testing, KAN for round coordination and Codeforces and Polygon team for these beautiful platforms. I would also like to thank HSE for organizing the event. Oh, and kb. for writing great legend for one of the problems (he will be surprised).

For those who for some reason like to know score distribution in advance:
div.2: 500 — 1000 — 1250 — 1750 — 2250 — 3000
div.1: 500 — 1000 — 1750 — 2500 — 2750 — 3000
But I didn't properly discuss it with KAN so this is subject to change :)
UPD: Discussed with KAN, scores for C and D in div.2 increased by 250.

Good fun, have problems, read all the luck. As usual.

Oh, and if there will be no bad things, round will be rated. I hope.


I'm very sorry for issues with queue. I understand that it could ruin the contest for many of you. But please be understanding. Bad things happen. It could be some network problems or some electricity problems. MikeMirzayanov, KAN and other people behind Codeforces trying their best to provide good service. But sometimes it's very hard for some reasons. I hope that you enjoyed the problems despite all the bad things.

We decided that round will be rated.

Editorial will be posted tomorrow.

div.1 winners:
1. tourist
2. EvenImage
3. Radewoosh
4. webmaster
5. LHiC

div.2 winners:
1. sminem
2. Fortza_Gabi_Tulba
3. cheburazshka
4. Lomk
5. 2ez4me

Editorial is up.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +656
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-русски

Всем привет.

27 мая пройдёт личное первенство ВШЭ по спортивному программированию. К участию приглашаются (очевидно) студенты ВШЭ, а также школьники Москвы и Московской области, показавшие высокие результаты на региональном туре ВсОШ по информатике (500+ баллов, если у вас немного меньше, тоже можете подать заявку, если мы сможем вас разместить — разместим). Более подробную информацию можно прочитать здесь. Регистрация.

Задачки делаю я, другие плюшки — ФКН ВШЭ.

Ещё раз подчеркну — это не открытое первенство. Пожалуйста, не надо регистрироваться, если вы студент другого вуза :)

Дисклеймер и попытка ограничить количество участников: если ваш рейтинг ниже 1400, скорее всего вам будет весьма грустно на контесте.

На этих же задачах будет проведён Codeforces раунд 29 мая. Разумеется, о раунде будет ещё отдельное объявление :)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +102
  • Проголосовать: не нравится

Автор Um_nik, история, 8 лет назад, По-русски

Когда-то давно я хотел сделать канал с какими-то мыслями по поводу задач с регулярных контестов
Сегодня я даже что-то сделал
Получилось стремно, на мой взгляд
Но я надеюсь, что
1. кто-то кроме меня тоже захочет что-то писать
2. формат постепенно трансформируется во что-то прикольное

В общем, приглашаются желающие рассказывать как они решают задачи, и желающие читать, как кто-то другой решает задачи.

К сожалению, RUS only. Я не готов писать так много на английском.

Ну и раз уж зашла речь: У меня есть более персональный канал, но там тоже почти все про ACM. Настолько почти все, что канал даже был признан блогом года по версии snarknews :)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +38
  • Проголосовать: не нравится

Автор Um_nik, история, 9 лет назад, По-русски

I think that most of us know about situation with problem 843B - Interactive LowerBound. The intended solution (and it looks like all possible solutions) was randomized and it generates huge amount of hacks based on fixed randseeds.

I want to mention that I'm not against good randomized problems and I even set one myself.

But for me it seems that hacks can ruin such type of problems. The only thing author's solution is better than contestant's is that it is invisible during the competition. I can even imagine that some tester's solutions (maybe not the solution which is used to generate judge answers) was broken by some hacks.

I think that it breaks the problem as art piece and breaks the contest format too. You solved the problem just like authors wanted and now... it depends on is there a hacker in your room. It also breaks the idea of hacking. There is no bug in my solution, why should I be hacked? And why should the guy get 100 points for hacking me? He didn't crack my solution, he abused CF 'Run' tab.

And for me it looks like authors didn't think about that bug/feature and now they try to protect themselves in comments. For me it could be a good enough reason not to use this problem on CF round. This problem would be a good problem in ACM contest and I know that these guys do ACM contests. But maybe there were a way to prevent such abuse of hack system?

What about forbidding hacking this particular problem? It has two obvious flaws (maybe more).
1. After this post it can give a hint that you should use randomized solution — Yes, this is a problem.
2, All problems should be equal! You are taking away our sacred right to hack!!!1! — Are they? There are a lot of problems with no hacks on CF. There can be many reasons: the problem was too easy, or too hard, or it has no corner cases, or it can be solved only in one way, or, or... You can say that I propose unnatural way to prohibit hacking and in those cases it was prohibited by the problem itself. But (in my opinion) such randomized problem also naturally prohibits hacks because hacks can ruin the problem.

And it is also not true that all problems were 'equal' in this sense before. There were some problems with multitests which allow to hack with only one test in multitest. There can be a bug in handling multitesting but we cannot hack this bug.

This brings us to less cardinal solution: make some bounds on hacks. Like n ≤ 100 or (in this particular problem) let only choose values in list, but not their order.

Anyway, I think that problemsetters and coordinator should think about these matters in the future.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +69
  • Проголосовать: не нравится

Автор Um_nik, история, 9 лет назад, По-английски

cgy4ever, when will the round be? clist.by says that it will be tomorrow in 19:00 (MSK), but three days ago it was 18:00 (MSK) and I also cannot find anything related on TopCoder itself. For example, there is no such competition in Web Arena calendar.

Полный текст и комментарии »

Теги tco
  • Проголосовать: нравится
  • +47
  • Проголосовать: не нравится

Автор Um_nik, история, 9 лет назад, По-русски

Я получил футболку с надписью "CODEFORCES THREADS 2017", но я не помню такого контеста.
С другой стороны, за Good bye 2016 обещали футболки.

Возможно, я не знаю какого-то перевода слова thread.

Так или иначе, MikeMirzayanov (или gKseni), можете рассказать, что это за футболка?)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +12
  • Проголосовать: не нравится

Автор Um_nik, история, 9 лет назад, По-английски

Suppose we want to solve a problem by doing binary search on answer. Then the answer will be checked against jury's answer by absolute or relative error (one of them should be smaller then ε). For simplicity we will assume that our answer is always greater than 1 and smaller than B. Because of that, we will always use relative error rather than absolute.

Suppose we have made n iterations of our binary search — what information do we have now? I state that we know that real answer is lying in some segment [xi, xi + 1], where 1 = x0 < x1 < ... < xi < ... < x2n = B. And what is great — we can choose all xi except for x0 and x2n.

Now, for simplicity, we will also assume that we will answer xi + 1 for segment [xi, xi + 1] and the real answer was xi — it is the worst case for us. It is obvious that we will not do that in real life, any other answer would be better, but you will get the idea.

So, what is our relative error? It is . Worst case for us is when relative error is maximal. It is logical to make them equal — exactly what we do by binary search with absolute errors. . We can assume that so . Now we have , but , so . How large should be n to get error less than ε? . Much smaller than .

How to write such binary search? We want to choose m in such a way that or simply .

Now I want to deal with some assumptions I made.

How to choose answer in the end? Again, (it is basically the same as dividing the segment in binary search).

What to do if the answer can be smaller than 1? Try 1; if answer is smaller than 1~--- use standard binary search (because absolute error smaller than relative); is answer is bigger than 1~--- use the binary search above.

P.S. I have never heard about this idea and come up with this while solving 744D - Hongcow Draws a Circle. I'm sorry if it is known for everyone except for me.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +375
  • Проголосовать: не нравится

Автор Um_nik, история, 9 лет назад, По-русски

Если вы зарегистрированы на тимусе, то вы должны были получить письмо с приглашением на этот контест. Контест состоится в субботу (19 ноября) в 11 МСК.

Вас не должно смущать, что это юниорский чемпионат, так как мы "немного" переборщили со сложностью. Насколько я помню, при отыгрывании Merkurev сдал все задачи за 15 минут до конца контеста, поэтому я думаю, что контест может быть интересен широкому кругу участников, вплоть до сильнейших команд.

Контест проводится по стандартным правилам ACM, длительность — 5 часов. К участию приглашаются как команды (до трех человек), так и одиночные участники. На этих же задачах проводился отбор на чемпионат Урала для уральских команд, поэтому, пожалуйста, не принимайте в нём участие, если вы писали этот отбор.

Контест готовили Um_nik, sivukhin, kb., Tinsane и crassirostris.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +99
  • Проголосовать: не нравится

Автор Um_nik, история, 10 лет назад, По-английски

Hello!

October Clash on HackerEarth has started and you have 23 more hours to go.

I am the author of this problemset and niyaznigmatul is a tester. I want to thank sivukhin who helped me a lot with preparation.

I hope you find the problems interesting and wish you good luck!

Полный текст и комментарии »

  • Проголосовать: нравится
  • +47
  • Проголосовать: не нравится

Автор Um_nik, история, 10 лет назад, По-английски

Q1: I'm a newbie. What should I do to become great coder?
A1: Stop doing competetive programming Solve problems.

Q2: I'm doing CP for two months and I'm still not red green. What should I do?
A2: You are lazy and impatient Solve more problems.

Q3: You became a red in less than two years, it is unbelievable!
A3: No, it isn't. You can do it too if you will solve fucking problems.

Q4: You became a red blah-blah-blah such a huge fan blah-blah. Oh, and what should I do to become as great as you?
A4: ... right. You already know the answer. Solve problems. I hate you.

Q5: I'm not good at DP [or something]. What can you suggest?
A5. Maybe you should try to stop asking stupid questions and solve some problems on DP? Or read some blogs and editorials.

Q6: I can't solve a problem / understand your code. Can you help me?
(Well, it is not a bad question in general. It is a good (if you really want me to explain something not to write the solution instead of you) question. But...)
A6: Sure. Can you provide the link to the problem / code?
(I'm not joking, it is a real story).

Bonus!
Q0: Hello bro/sir.
A0: Stop doing this please.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +628
  • Проголосовать: не нравится

Автор Um_nik, история, 10 лет назад, По-английски

Access to the specified resource has been forbidden.

Codeforces said 20 minutes ago when I was trying to login. The same was about two weeks ago. In both cases I was unable to login for about 10 minutes.
And I constantly logout. Sometimes I can't read 3-4 blog posts before logout.

There were a post about logouting two or three days ago but I can't find it now because search is not working too.

Полный текст и комментарии »

Теги bug
  • Проголосовать: нравится
  • +38
  • Проголосовать: не нравится

Автор Um_nik, история, 10 лет назад, По-английски

I've noticed during the contest that we can see all the hacks in our room.

Now MikeMirzayanov says that it was a bug and will be fixed soon.

I think it really will be bad if there are tons of hacks. But it is very useful to know which problems can be hacked (I mean which problems was already hacked by someone). Can you add number of successfull and unsuccessfull hacks on each problem to the PROBLEMS page?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +130
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

Допустим, вы проводите соревнование для очень разной по силе аудитории. Например, у нас завтра отбор на ВКОШП.

В каком порядке вы бы стали рассказывать задачи на разборе?

Можно рассказывать в порядке A, B, C ... Правда, если в середине встретится сложная задача, то слабые участники могут забить и перестать слушать.

Логичное решение: давайте отсортируем задачи в порядке предполагаемой сложности (в конце концов, по количеству AC). Но тогда сильные участники не будут слушать сразу, а потом могут забыть "включиться". Или, того хуже, начнут шуметь и мешать остальным слушать.

Что бы вы сделали?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +24
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

Приглашаю принять участие в онлайн-версии уральской региональной командной олимпиады по программированию.

Это уральский отбор на ВКОШП, и я думаю, что этот контест будет хорошей тренировкой для школьных команд. Однако я также приглашаю и студенческие команды; на мой взгляд, контест будет интересен и им тоже.

Контест состоится в субботу 17.10 в 11:00 МСК одновременно с самой олимпиадой.

Авторы задач — Um_nik, sivukhin, kb., hx0, Merkurev, KuchumovIlya, droptable (спойлер: задача не имеет отношения к палиндромам!)

Продолжительность контеста — 5 часов, правила ACM ICPC. Условия будут на русском и английском языках. Ссылка на вход

Полный текст и комментарии »

  • Проголосовать: нравится
  • +117
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

Пользуетесь ли вы prewritten-кодом на раундах OpenCup?)
Разделю вопрос на два:
1) Если вы используете шаблон, пишите ли вы его каждый раз в начале контеста? (понятно, что это не влияет на результаты почти никак, просто интересно)
2) Пользуетесь ли вы заранее написанными стандартными алгоритмами (поток, венгерка, суфструктуры, что-нибудь ещё)?

Про нас (Ural FU Dandelion): Мы пишем шаблон каждый раз в начале контеста (может, за редкими исключениями), стандартные алгоритмы не копируем.

Ни в коей мере не хочу никого пристыдить или в чём-то обвинить, тем более что использование prewritten-кода разрешено правилами. Всем добра :)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +54
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

Тест:
{1}
{1}
Ответ жюри: 2
Количество перестановок с каким-то свойством больше, чем количество перестановок вообще.
UPD: Они уже заметили.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +22
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

569A - Музыка

Пусть перед очередным запуском прогружено S секунд песни, найдем, сколько будет прогружено перед следующим запуском. . Отсюда x = qS.

Тогда решение: будем умножать S на q пока S < T. Количество таких умножений — это ответ.

Сложность —

569B - Инвентаризация

Подойдём к задаче с другой стороны: а сколько максимально можно оставить номеров, чтобы получилась перестановка? Очевидно, что эти номера должны быть от 1 до n, причем среди них не должно быть повторяющихся. И понятно, что это условие необходимое и достаточное.

Такую задачу можно решать жадным алгоритмом. Если мы встретили число, которого ещё не было, при этом оно от 1 до n, то мы его оставим. Для реализации можно завести массив used, в котором отмечать уже использованные числа.

Затем нужно ещё раз пройти по массиву и распределить неиспользованные числа.

Сложность — O(n).

568A - Простые или палиндромы?

Известно, что количество простых чисел, не превосходящих n, — число порядка .

Если мы зафиксируем длину числа k, то количество палиндромных чисел такой длины будет порядка . Это .

Таким образом, количество простых чисел асимптотически больше количества палиндромных чисел, а значит для любой константы A найдётся ответ. И для такого ответа . В нашем случае n будут не больше 107.

Поэтому мы можем для всех чисел до 107 проверить, являются ли они простыми (с помощью решета Эратосфена), а также являются ли они палиндромными (с помощью наивного алгоритма, или же можно динамикой считать зеркальное отображение числа). Затем мы посчитаем префиксные суммы, а потом линейным поиском найдём ответ.

При A ≤ 42 ответ не превышает 2·106.

Сложность — .

568B - Симметричное и транзитивное

Давайте сначала разберёмся, в чем же конкретно неправ Вовочка. В доказательстве хорошо всё, кроме того, что мы сразу взяли a, b такие, что . Если такие есть, то действительно . А если их нет? Если для a нет такого b, что , то, очевидно, не (иначе мы бы взяли b = a).

Отсюда понятно, что наше бинарное отношение — это какое-то отношение эквивалентности, к которому присоединили такие элементы a, что для всех них не существует таких b, что .

Тогда решение можно разбить на две части:

  1. Посчитать количество отношений эквивалентности на множествах размеров 0, 1, ..., n - 1

  2. Посчитать, сколькими способами туда можно добавить недостающие "пустые" элементы.

Отношение эквивалентности можно задать разбиением на классы эквивалентности.

Тогда первую часть задачи можно решить динамическим программированием: dp[elems][classes] — кол-во способов разбить elems первых элементов на classes классов эквивалентности. Переход — каждый элемент мы можем либо отнести в один из уже существующих классов, тогда их количество не изменится, либо же создать новый класс, тогда их количество увеличится на 1.

Вторая часть задачи. Зафиксируем m — размер множества, над которым мы посчитали количество отношений эквивалентности. Тогда нам нужно добавить к нему ещё n - m "пустых" элементов. Позиции для них можно выбрать C[n][n - m] способами, где C[n][k] — биномиальные коэффициенты. Их можно заранее посчитать треугольником Паскаля.

Тогда ответ — .

Сложность — O(n2)

568C - Новый язык

Пусть мы зафиксировали буквы на каких-то позициях, как проверить, что на остальные позиции можно расставить буквы так, чтобы получилось слово из языка? Ответ — 2-SAT. Действительно, для каждой позиции есть два взаимоисключающих варианта (гласная и согласная), а правила языка — это импликации. Таким образом, такую проверку мы можем сделать за O(n + m).

Будем уменьшать длину префикса, который мы оставляем таким же, как у слова s. Тогда следующая буква должна быть строго больше, чем в s, а весь дальнейший суффикс может быть любым. Переберём эту букву и проверим с помощью 2-SAT, есть ли решения. Как только мы обнаружили, что решения есть, мы нашли правильный префикс лексиграфически минимального ответа. Затем будем обратно наращивать префикс, какая-то из букв точно подойдёт. Мы получили решение за O(nmΣ ). Σ из решения можно убрать, заметив, что каждый раз нам нужно проверять только минимальные подходящие гласную и согласную буквы.

Также нужно не забыть случай, когда все буквы в языке одной гласности.

Сложность — O(nm)

568D - Указательные столбы

Предположим, что решение есть. Если n ≤ k, то мы можем на каждую дорогу поставить по столбу. Иначе рассмотрим любые k + 1 дорогу. По принципу Дирихле среди них найдутся две, для которых будет общий указатель. Переберём эту пару дорог, поставим столб на их пересечение, уберем дороги, которые тоже проходят через эту точку. Мы свели задачу к меньшему числу столбов. Таким рекурсивным перебором мы решим задачу (если решение существует).

Решение это работает за . Если написать аккуратно, это может зайти.

Но это решение можно ускорить. Заметим, что если у нас есть точка, через которую проходит хотя бы k + 1 дорога, то мы обязаны поставить столб в эту точку. При достаточно больших n (у меня в решении отсечка n > 30k2) такая точка точно есть (если решение существует), причём её можно искать вероятностным алгоритмом. При условии, что решение существует, вероятность, что две произвольные дороги пересекаются в такой точке не меньше , поэтому если попробовать 100 раз, то с вероятностью такая точка найдется, и мы сможем уменьшить k.

Все проверки можно делать в целых числах.

Сложность — .

568E - Наибольшая возрастающая подпоследовательность

Будем поддерживать массив c: c[len] — минимальное число, на которое может заканчиваться возрастающая подпоследовательность длины len (Одно из двух стандартных решений задачи о наибольшей возрастающей подпоследовательности). Элементы этого массива возрастают и добавление очередного элемента v к обработанной части последовательности сводится к нахождению такого i, что c[i] ≤ v и c[i + 1] ≥ v. При обработке пропуска нам нужно попробовать вставить все числа из множества b. Предварительно их отсортировав и двигаясь двумя указателями вдоль массивов b и c мы можем проделать нужные обновления за O(n + m).

Авторами подразумевалось использование O(n) памяти для восстановления ответа. Этого можно добиться следующим образом: 1. Параллельно с массивом c будем хранить массив cindex[len] — индекс элемента, на который заканчивается оптимальная НВП длины len. Если она заканчивается в пропуске — будем хранить, например,  - 1. 2. Также сохраним для каждого не пропуска — длину НВП(lenLIS[pos]), заканчивающейся в этой позиции (это несложно делается в процессе вычисления массива c) и позицию(prevIndex[pos]) предыдущего элемента в этой НВП (если это пропуск, опять же  - 1).

Теперь приступим к восстановлению ответа. Пока мы не наткнулись на пропуск — можно спокойно восстанавливать НВП с конца. Сложность обнаруживается, когда несколько следующих элементов последовательности попали в пропуски. Но можно несложно определить что это за пропуски и чем их заполнить. А именно: пусть сейчас мы стоим в позиции r. Нам нужно найти такую позицию l (не пропуск), что мы сможем заполнить ровно lenLIS[r] - lenLIS[l] пропусков между l и r возрастающими числами в интервале (a[l]..a[r]). Позицию l можно итеративно перебирать от r - 1 до 0, параллельно насчитывая число пройденных пропусков. Проверку условия описанного выше можно несложно сделать с помощью пары бинпоисков.

Немного подробнее и с деталями:

  1. Как узнать, что между позициями l и r можно заполнить пропуски так, чтобы не ухудшить генерируемый ответ?
    Пусть countSkip(l, r) — количество пропусков на интервале (l..r), а countBetween(x, y) — количество различных чисел из множества b, лежaщих в интервале (x..y). Тогда позиции l и r хорошие тогда и только тогда, когда lenLIS[r] - lenLIS[l] = min(countSkip(l, r), countBetween(a[l], a[r])). countSkip можно насчитывать в процессе уменьшения границы l, countBetween(x, y) = max(0, lower_bound(b, y) - upper_bound(b, x)).

  2. Что делать, если НВП заканчивается или начинается в пропуске (тогда мы не знаем, откуда начать/где закончить)?
    Наиболее простым решением будет добавить  - ∞ и  + ∞ в начало и конец нашего массива соответственно. Это позволит избежать проблем с такими крайними случаями.

Сложность — времени, O(n + m) памяти

Полный текст и комментарии »

Разбор задач Codeforces Round 315 (Div. 1)
Разбор задач Codeforces Round 315 (Div. 2)
  • Проголосовать: нравится
  • +110
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

Всем доброго времени суток.

Скоро состоится Codeforces Round #315, авторами которого являются студенты УрФУ sivukhin и Um_nik. Это второй наш раунд, первый пришелся на черные дни Codeforces, и мы надеемся, что второй наш раунд не вызовет таких катаклизмов :)

Мы хотим поблагодарить команду Codeforces за эту замечательную платформу и Polygon. Особенно хотим отметить Zlobober за помощь в подготовке задач.

Желаем всем удачи!

UPD1:
Разбалловка.
div2 : 500-1000-1500-2250-2750
div1 : 500-1000-1500-2250-2500
Настоятельно рекомендуем прочитать условия всех задач. Мы постарались подготовить достаточно разнообразные задачи, вполне возможно, что сложные для нас задачи будут простыми для вас.

UPD2:
Разбор

UPD3:
Поздравляем победителей!

div1:
1. KAN
2. Petr
3. enot110
4. tonyjjw
5. Konijntje

div2:
1. Lost
2. loser21
3. fyiwxp221
4. hqpwca
5. LazyWolfLin

Всем спасибо за участие.

Полный текст и комментарии »

  • Проголосовать: нравится
  • +289
  • Проголосовать: не нравится

Автор Um_nik, история, 11 лет назад, По-русски

More precisely: How to generate large inputs?

Полный текст и комментарии »

Теги tc
  • Проголосовать: нравится
  • -19
  • Проголосовать: не нравится

Автор Um_nik, 11 лет назад, По-русски

А пока все радуются фантастической возможности поучаствовать в Я.Алгоритме, у меня назрел вопрос по VKCup.

В официальной группе ВК была информация о том, что онсайт будет 24-27 июля.
Может быть, я что-то пропустил, но на кф я ничего такого не видел.

"Лучшие 20 команд по результатам отборочных интернет-этапов будут приглашены в финал соревнования, который состоится в июле 2015-го года в Санкт-Петербурге. Компания ВКонтакте покроет расходы на проезд и проживание финалистов, которые будут бороться не только за звание лучших из лучших, но и призовой фонд чемпионата." (c)
С кем связаться по поводу билетов и проживания?

Полный текст и комментарии »

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится