Привет, Codeforces!
Рад пригласить Вас на увлекательный (а мы постарались его сделать таким) Codeforces Round 734 (Div. 3) — раунд для третьего дивизиона, который состоится в 23.07.2021 17:35 (Московское время). Этот раунд — моя (MrPaul_TUser) первая "проба пера", и, разумеется, я бы не справился, делая его в одиночку — существенный вклад в создание раунда внесли MikeMirzayanov, BledDest и DK318.
Этот раунд содержит 6-7 задач. Задачи подобраны по сложности так, чтобы составить интересное соревнование для участников с рейтингами до 1600. Однако все желающие, чей рейтинг 1600 и выше, могут зарегистрироваться на раунд вне конкурса.
Раунд пройдет по правилам образовательных раундов. Таким образом, во время раунда задачи будут тестироваться на предварительных тестах, а после раунда будет 12-часовая фаза открытых взломов. Мы постарались сделать приличные тесты — так же как и вы будем расстроены, если у многих попадают решения после окончания контеста.
Вам будет предложено 6-7 задач и 2 часа на их решение.
Штраф за неверную попытку в этом раунде (и последующих Div. 3 раундах) будет равняться 10 минутам.
Напоминаем, что в таблицу официальных результатов попадут только достоверные участники третьего дивизиона. Как написано по ссылке — это вынужденная мера для борьбы с неспортивным поведением. Для квалификации в качестве достоверного участника третьего дивизиона надо:
- принять участие не менее чем в двух рейтинговых раундах (и решить в каждом из них хотя бы одну задачу),
- не иметь в рейтинге точку 1900 или выше. Независимо от того, являетесь вы достоверными участниками третьего дивизиона или нет, если ваш рейтинг менее 1600, то раунд для вас будет рейтинговым.
Огромная благодарность WolfBlue, BlueDiamond, harlequen, -is-this-fft-, le.mur, Bench0310, Reiva5, Golovanov399 и Sho за помощь в тестировании раунда и улучшении задач.
Всем удачи и хорошего настроения!
UPD
First time being unofficial :)
Reached 1600 yesterday...
Why? This round will be rated for you since your rating is less than 1900.
No, its rated up to 1600, not above.
"However, all of you who wish to take part and have a rating 1600 or higher, can register for the round unofficially."
So... then what does "only the trusted participants of the third division will be included in the official standings table .... do not have a point of 1900 or higher in the rating." mean?
That means that those people will be included in the official standing table.
In conclusion that means, not everybody in the official standing table will be rated.
Ah, okay, thanks.
If you want to be rated in Div3 you can refer to my rating graph how to do that ;)
hey! i saw your profile and i'm pretty curious as to how did you become expert in such a small timespan, if possible could you share some tips, tricks or advises? and like what all topics did you practice to reach where you are right now?
I was training kind of hard maybe :) when I was newbie I trained 1600 difficulty problems until I become pupil, after that I started to train 1k8 problems until I reach specialist and expert. Upd: I think the best way to do it is your rating point + 400. (Sorry for my bad english)
Now finally my exams are over. I can once again participate in contests.
Very glad to see another Div3 in small interval! good luck everyone!
Why is it showing registrations completed, does it mean I cant register for the contest now?
chill :) you have been registered to the contest that's why it is showing !
i wand problems like this one...
expert i'm coming
newbie, you're going
I appreciate that the testers are arranged such that their usernames' colors form a palindrome.
If you had not mentioned that I would have never noticed that. Thanks for informing.
Maybe a hint for the contest...XD
Codeforces Round #734 (Div. HOPE)
"..just like you will be upset if many solutions fail after the contest is over."
hope there will be strong pretests as last contest was ruined by weak pretests
The contest hasn't even happened yet...
Edit: as you edited, I hope so too...
he said "as last contest"
"I tried to make strong tests — just like you will be upset if many solutions fail after the contest is over."
phew, unlike last contest ;)
Congratulations for becoming an expert for the first time :)
see my profile I will never give div 3 I dont know how so many people solve so fast and ACM-ICPC rules sucks too.
The way people solve it fast is practice. I did the last div 3 contest just like you and you spent 1:30 hours on D, which isn't particularly hard if you're familiar with this type of idea. Blaming the ruleset is kind of dumb imo because on different rules the difference is that the problems would be much harder to balance out a longer submission window
You'll never be as fast if you never participate though.
yes you are right brother.
Speed is an acquired skill.
Liked the thanking section!! where he used symmetric colour combinations.. :)
I registered for the contest before today's one (Specialist -> Expert) and it still says I'm in competition. Just to confirm this contest won't be rated for me right.
I don't think it will be rated for you.
Enjoy solving problems from the end XD
it will be rated, if you registered as cyan, I've experienced it recently and lost 80 points of rating)
Looks like it says I'm out of competition now?
i haven't seen posts from mike about the fix, but maybe he already fixed it
Hope pretest will be strong, not like last contest
Hi everyone,
I would like to know whether I can start 8 hours following the competition starting time since the starting time is past midnight for me. (I am new to competitive programming).
Thanks very much. Cheers
No , if you give contest at later time than the mentioned time it wouldn't be considered for ratings . It will become a practice contest . For having yourself in official standings you must give contest at the mentioned time only then only you would be considered for standinds and rating change
You can start a Virtual participation whenever you want after the contest but if you want to make your rating update you have to follow the starting time.
I guess you cant participate later, but if you don't need rating, you always can participate virtual. It will be just like normal participation, but without rating. Cheers and good luck.
Now, finally before my exams, I am gonna compete.
And can anyone please spare a minute and tell me in which division do I belong, my rating being 814. Thanks.
You can participate in any contest except those rated solely for Div. 1. This means that you can participate in Div 3 , Div 2 and combined Div 1+2 rounds
Is there any chance of arranging these contests so they are in the evening or weekends. Anyone who has a job can't enter as they will be working.
If you prefer weekend contests, then AtCoder may be a good choice for you.
If I know it early, I'll not get to expert:)
So we penalty of 10 min on the wrong submission and not of 50 points. Right?
For every minute, 5 point decreases from the main point. Like, 500->495->490. So, penalty of 10 minutes and 50 points are same
it's not 5 points depends on how many points the problem has the higher points the problem has the more points decrease with time
Your cf graph
orzWhat does orz mean i read it all the time
Good Luck to Everyone
Well,you too!
o sweet lords of coding, help me reach 1200.
++
Last minute tip ! Open this to side : CF Notifications So that you don't need to wait to see AC's
Last minute tip ! Open this to side : CF Notifications So that you don't need to wait to see AC's
After so long time i'm missing a CF rated contest for my Covid. :'( Hope to come back soon.keep me in your prayer. :(
Oof.
A perfect div2 round.
A divison 2 contest with Divison 3 participants.
you should have said to check D2 before D1 instead of B2 before B1 I didn't get how dominoes are placed until i checked D2
hey can u tell me the logic behind b2, i got what the maximum number of single colour used would be but i could not figure out how to colour them without going against the rules.
any number that exists k or more times must be colored with all k colors and what's left of that number occurrences are zeroed so you need map with vector of positions of that number to do that and other numbers that exists less than k just gather their positions in one vector and color them any way
Maps are not required for this problem.
You can see my code for details.
Code: 123477048
Thanks for the great contest :)
lovely problems!
When can I check the testcases?
Problem C was incredibly similar to this problem, so much so that I copied over my solution almost verbatim...
Perhaps you should read the problem B2 before you start solving B1.
Was this meant to be a troll?
This round was too hard for Div. 3
Well I found that pretty tough and it wasn't even meant for me
Solved all but D2. Why is problem D so hard?(or maybe I'm being dumb)
I decided to focus on completing D2 instead and that deprived me of the time to attempt E or F. D2 was conceptually fine but the casework and construction is very fiddly.
Even prior to that, B2 was fine but not Div 3 problem B fine.
I implemented it by assigning different integers to each domino (so casework was on integers, without considering which letter should be used for which domino). Later I processed the integer table as follows:
Submission 123498750 containing the color assignment at the end of
st()
function.Changing D1 into D2 took slightly less than 20 minutes.
I did something pretty similar except it was just a row-by-row construction where I incremented a value (mod 26) while it matched any of its above or left neighbours.
Not conceptually too difficult for sure, but with the different cases (N odd, M odd) I found it a pain, and the kind of implementation that isn't great for a 2 hour contest except for the most efficient coders. But I was too committed by that stage to stop and move on. I have since seen that E in particular was a much cleaner question and had I realised what D2 entailed I would have skipped and solved E.
Makes a lot of sense, thanks for the reply ;)
I did something to make the casework easier-
We know at least one of n and m is even. So we have two cases-
1. n(rows) is even
2. n is odd => m(cols) must be even
In case 2, we can rotate the table by 90 degrees => n and m are swapped, and all horizontal dominoes become vertical and vice versa, ie. in the rotated configuration, k becomes m*n/2-k. So we only need to solve for case 1, and that's it. (Oh, and we rotate the matrix back before printing)
For filling the table, filling from left to right and from top to bottom at all times worked cleanly for me. (Had only to check the top, left, and bottom-left dominoes) submission
I was chatting with other people at the same time so I didn't focus. But seriously I wasn't ready for this. Without turning on my brain before the contest, I just wanted to quit the moment I saw B and D.
someone please hack my submission.123523305
It looks fine, in my opinion it should pass the system tests ;) I tried to hack you based on the fact that you allocate large arrays statically but it passed ;) Good job :D
i hope it will pass the tests
what is pretest 2 of B2 ? I was not able to figure out till the end
The problems were really interesting. Kudos to the authors involved! Would have been much better if this round was half an hour longer though
Exactly, would have been better if it was longer.
How to solve D1? I tried 3 cases. Got WA on Test 3.
Did I miss anything?
If rows are odd, then you need atleast m / 2 horizontal dominoes.
I submitted my solution with 22 seconds remaining. I couldnt see the verdict because the page was just loading. Now when i check in my submissions, there is no submission showing. And guess what, when i submitted it in practise it was accepted. Can i be helped??
B2 felt misplaced, for me B and D shoud have been swapped. Or C and B swapped. Or B, C, D reversed... whatever, I worked much to long on B2, and finally was not able to solve it.
How to solve B2?? I am not able to solve it
I binary searched for the number of elements for each type and then reconstructed the coloring according to it. I think I overkilled it though.
I don't see where binary search was required. I didn't think it was as difficult as the comments mention, but perhaps It was and I was just in form.
I really liked problem $$$B2$$$, tbh.
You can look up my code: 123477048
Incase something isn't clear in the code you can ask me. But, mind you, I'm terrible at explaining.
After having read the solution it is not very complecated.
Consider f[i] to be the freq of i in a[].
Then foreach f[i]>=k color the positions of the i in a[] with the k colors. Then put all other numbers in one big group and do the same in that group.
Maintain count and position of each character in hash table, for example if array is 1 1 2 1, the count[1] = 3 and position[1] = 0 1 3.
Create an array result filled with 0 of size n.
Next iterate through each unique character in the hash table, now there are two cases:
If count of any character >= k then that means you can paint each position containing that character with paints from 1..k, so iterate over position[character] from 0..k and fill each entry in result at position in incremental fashion, so result[ position[character][i] ] = i + 1
If count of character is < k then push the positions of position[character] in an new array say leftPositions
Now, at last, pop positions from leftPositions in size of k, and fill the popped positions in with paints ranging from 1..k, while popping in size of k, if at any time the size of leftPosition < k then stop and print result.
Here is code to this approach: https://mirror.codeforces.com/contest/1551/submission/123471900
I am doing something similar to this but failing on testcase 2, can u check it out if u can?123490522
In your code, two same numbers might end up with same color, your case handling for when count >= k is fine, problem lies in your handling of when count < k.
Consider this small case (it is not a valid test case just taking it to show whats wrong)
a = 10 11 12 10 .....
k = 3
Your code may produce output like this: 1 2 3 1 ..., you see both 10's have same paint 1, that's the problem.
:(
Why attend only virtual contest? I say, you should attend the on-going-contests as well, I suggest you not to care about ratings. Also, during the virtual contests you don't get that feel when you solve more problems than your level. Overall I say that its a different atmosphere when giving on-going-contests vs. virtual contests.
i got a WA on test 185 can anyone provide me with a counterexample 123529703
Maybe try :
n=6 k=3
a = 2 3 1 2 3 1
This case helped me to identify my mistake :)
Main idea is for every 2x2 block, I assign it a color pair based on which diagonal it's on. Technically I don't need two new colors for the ones on the very right but it made implementation slightly easier. Submission
Can you plz. elaborate your solution little bit more.
The main idea is we partition the grid into as many 2x2 blocks as possible, with each 2x2 block being able to hold two horizontal or two vertical dominoes. If $$$n$$$ or $$$m$$$ are odd (only at most one of them can be per problem constraints), then we will have an extra strip on the end (the purple and brown region in the diagram). That extra strip can only be populated with dominoes in the same direction as the strip (so horizontal if the strip is horizontal, and vertical otherwise). Now, since we don't have as many letters as dominoes, we will have to reuse some, and I make sure two touching dominoes don't share the same letter by encoding same letters on diagonals, as shown in the diagram.
I don't have the most rigorous proof for why this construction covers all cases, but the main idea is you have the wrong parity of $$$k$$$, then there's no way to evenly fill the grid without having a gap in the end that a domino of the opposite orientation cannot fill. On the other hand, if the parity is correct, this construction covers it.
You shouldn't make this contest so hard simply because DIV1/2 participants participate as well..
Isn't this output that my code generates for B2's sample input correct? Showing WA on test 1
No, there are two 5's with color 3 in test case 6.
case 6
why is this submission for E giving WA 123523281 on test case 5 I constructed a
whose states describe that we have arrived at i th point in the prefix with j moves done. To do that I first precalculate the
which says the number of elements in the suffix
such that the elements after the ith index (including i) have
, i.e. we have done j moves and after that j moves the number of elements which are now standing at the required index. Now we can iterate over the moves done and check if
and return the minimum j . please help if you can? The transitions are as follows
second transition is as follows you deleted at the ith index. so
calculates the new sum that should be added now that we have made j moves and only the index after i is affected as the left shifts happen from these indices. Final number of elements which are equal given that we have made j moves are in
and now we can simply iterate over j from 1 to n
I did exactly the same, except my dp[i][j] is the maximum good indices considering a prefix of length i with j elements kept.
The transitions are much easier:
$$$dp[i + 1][j + 1] = max(dp[i + 1][j + 1, dp[i][j] + (A[i] == j))$$$
and
$$$dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])$$$
(A is 0-indexed and every element is subtracted by 1 beforehand).
Also I don't think the pre thing is needed.
Hey I have exact same solution as yours. You can look at the implementation here. 123524901
happy thing: accepted (during contest)
sad thing: accepted (1 minute after the contest)
worse thing: unfortunately, your solution of problem X has been hacked
worst thing: wrong answer/time limit exceeded in test set X (main test)
Did anyone solve D with DP ? I used dp on columns for each two columns c and c + 1 I may put [0, 1, 2, .., min(n, k)]
they will be placed greedily from top to bottom on column c and c + 1 and the remaining cells on c and c + 1 will contain only vertical dominos, if c == m — 1 i can only place vertical dominos on c;
I really don't know why this works, but I have intuition that when placing the horizontal dominos they can form some kind of connected block, and hence I can try different shapes for this CC
Is it only me Or B2 was harder for it's position?
In today's contest , problems were great but time was less and problems were more.
Trollforces
Two contests ago I reached expert so this was unrated for me, yet I was only able to solve A and B1. Clearly I still don't deserve my rating
Help needed! There is something wrong with my lambda expression below, but I have no idea why it turned out this, from my point of view, both a & b is in the range of [0, n), but it can be some invalid value, more exactly in this code, when n >= 17, it would be a mess. I would appreciate it if anyone could help!
I have no idea about "invalid values" but you should never use <= or >= in custom sort comparator.
Thank you so much! I change the '<=' to '<', the annoying value disappeared! But why? Is it a property of the lambda expression?
No, it is not related to lambda.
Take a look at the parameters part of
https://en.cppreference.com/w/cpp/algorithm/sort
and the requirements of a comparatorhttps://en.cppreference.com/w/cpp/named_req/Compare
.Always keep this in mind.
I have no idea what will happen exactly if you use <=, (I assume it is a UB — undefined behaviour?) but UB always leads to disaster.
Got it, thank you for your reply! :-)
Problem D2 reminded me of this problem if anyone wants to try.
Problem E was very similar (though not identical) to task from XIV Polish Olympiad in Informatics: statement in Polish
How are the multiple answers tested?, like in today's B2
Hi ! I encountered something weird in my submission for todays 'C'.
Firstly I have made a 'vector of vectors' which store the property of each string i.e. the number of a's,b,c,d,e. Then while checking for character 'a', I am sorting this 'vector of vectors' according to the difference between count of a's and rest of characters.
But this is getting RTE in the comparator function:
bool comp1(vector &v1, vector &v2) {
}
While Debugging for Test case 2, 2nd test.. I found that the size of 2nd vector passed in the comparator is coming out of be 0 at one stage (but all the vectors in my 'vector of vectors' are of size 5), and obviously RTE is generated there ..
Can somebody tell more about this ambiguous behaviour ? and how to correct it ( while using the comparator function only )
PS: In Comparator i have passed as
vector<ll> &v1
only idk why it's showing vector&v1 here. Also my complete code is very ugly, so that's why am only putting snippets here !!You may want to check this
Oh my my !!!!
How are the multiple answers tested?, like in today's B2
Put every colored element in a set. Let's say that in correct solution the size of each color's set is n, now check for the given output if the size of set is equal to n and there are no repeated elements.
How to solve C ?? I am not able to solve it.
Let's define how interesting a given letter in a string as follows:
For example, in the string $$$bac$$$, $$$x_a$$$ would be $$$-1$$$ because $$$a$$$ occurs once and the number of non-$$$a$$$ letters is two. $$$1 - 2 = -1$$$.
Another example is $$$aaada$$$, $$$x_a$$$ would be $$$3$$$ because $$$a$$$ occurs four times and the number of non-$$$a$$$ letters is one. $$$4 - 1 = 3$$$.
We can find how interesting a given letter is for each letter $$$a, b, c, d, e$$$ and find the longest subsequence with a sum greater than $$$0$$$.
This is equivalent to finding the longest subarray with a sum greater than zero when sorted.
Why is that equivalent? Any intuition?
Well, greedily, we're trying to find the maximum subsequence sum, and when we sort it (in descending order), the largest elements in the array come first (obviously).
Can problem A be solved using binary search?
No, you have to implement fenwick tree for it and then build sparse table.
can someone kindly tell me why am I getting a TLE in this code for problem B2 ? It will be very appreciated..thx 123532079
You are getting TLE because it is taking a long time to parse such big preprocessor statements. Upd: Oh you removed your unformatted code from the comment lol. The actual reason is allocating array of size 2e5 in each test case and there can be upto 1e4 testcases. So you're taking time for allocating arrays of size 2e9. This will TLE.
then it should get tle in test case 1 but its getting in test case 2
Having irregular font size is undefined behaviour in C++
This is not the div.3 we wanted but this is what we needed.
I wanted this
Is there any way to get all test cases? My program for B2 constantly crashes on test 2 case 3901 and I have really no clue what's going wrong. 123544433
You have to use if conditions, its not pleasant but it works if the input is not too large. run your solution for test case 1, then for test case 2 print the input for T=3901 for others just take input and don't print anything.
Check my submissions for B2 where i printed the failing tc for 3901 ( using your code )
8 4
4 5 4 3 5 3 3 3
Your Ans: 1 1 2 2 3 3 4 0
Can anybody helps me with my code in E it gives WA on test 4
code: https://mirror.codeforces.com/contest/1551/submission/123549241
Any ideas for F?
If
k = 2
, you can pick any 2 nodes so answer isnC2
. Fork>2
—Let's say we can pick
k
nodes such that each node has a distanceD
with the other. Since all of these nodes are equidistant from each other, and the number of nodes is>=3
, this has to be a star formation with one "unselected" node at the centre, and all the selectedk
nodes are equidistant from this centre (distance ofD/2
to be precise, D can never be odd). Let's call the centreX
. Let's root the tree atX
.Also note that, any 2 selected nodes will have LCA equal to centre (meaning any path from one selected node to the other must go through centre, otherwise their distance will become shorter). What this means is that from the subtree of each child of
X
, only one node can be selected. If the number of childrenX
has is<K
, we can't selectK
nodes as the question states. If it has more children (C
is the number of childrenX
has) -Do dfs from each child of X and for a height h, let's say there are
n1, n2, n3 ... nC
nodes at height h in each child-subtree respectively. Since from each child-subtree, we can only select 1 node. The task becomes selecting K nodes (one from each child) given the above information. This can be done with dp.Looping over the root node X and height H and then solving the dp for each such combination yields the final result. You can look at my code, but my implementation is a bit messy with some extra code.
Finger crossed,for not to repeat last round hacking drama & to be specialist for the first time which missed yesterday due to hacking drama
It's not a drama. You had an incorrect solution for which you were rightfully penalized!
Yes, but it was massive for two problem, problem b was hacked/failed maintest about 3k and for problem D it was about 1.8-2k. Total standing was changed!
Only 4 different characters are needed in D2: 123522856
vertical: use aa and bb abab... abab... baba... baba...
then change to horizontal using cc and dd
ccab... ddab... baba... baba...
editorial?
can anyone give hint for C. thanks in advance :)
Can someone kindly tell me why am I getting TLE in this code for problem B2? 123566277. I really don't know why it get TLE T_T
in every testcase you are initializing 2e5 memory ..may be thats why..you don't need to because ai<=n
How long does it take to update the rating?
Come on, man. We can literally see that this is not your first Div.3 round. Why these useless comments?
i must say this wasn't div3 contest , problem C was tough for me.
Thanks for Round!
To not keep you waiting, the ratings are updated preliminarily. In a few hours/days, I will remove cheaters and update the ratings again!
Спасибо за раунд!
Can anybody help in memoizing this recursive code for problem E since I get TLE: Problem E
I don't think it is memoizable considering the recursive function has 6 dimensions. Try optimizing this and bring that 6 down to a 2.
please share hint for C.
please share hint for C.
Внимание!
Ваше решение 123450555 по задаче 1551A значительным образом совпадает с решениями других участников и находится в группе одинаковых решений rkarroy/123446796, oxxyumoron/123450555. Такое совпадение является явным нарушением правил. Отметим, что непреднамеренное утечка тоже является нарушением. Например, не следует пользоваться ideone.com с настройками по умолчанию (публичным доступом к вашему коду). Если вы имеете неоспоримые доказательства, что совпадение произошло по причине использования общего источника, опубликованного до соревнования, то напишите комментарий к посту о раунде со всеми деталями. Подробнее можно прочитать по ссылке http://mirror.codeforces.com/blog/entry/8790. Такое нарушение правил может являться основанием для блокировки вашего аккаунта или других штрафных санкций. В случае повторения нарушений, ваш аккаунт может быть заблокирован.
Здравствуйте! Я писала свой код на личном компьютере, в среде разработки. Возможно, решение совпало с чьим-то другим из-за своей простоты. Я ни с кем не общалась во время раунда, никому не отправляла код. Можно ли что-то сделать, чтобы такие ситуации больше не повторялись? Спасибо!