
Привет, Codeforces!
Благодаря поддержке Neapolis University Pafos, продолжается серия образовательных раундов.
В Apr/03/2025 17:35 (Moscow time) состоится Educational Codeforces Round 177 (Rated for Div. 2).
Этот раунд будет рейтинговым для участников с рейтингом менее 2100. Соревнование будет проводиться по немного расширенным правилам ICPC. Штраф за каждую неверную посылку до посылки, являющейся полным решением, равен 10 минутам. После окончания раунда будет период времени длительностью в 12 часов, в течение которого вы можете попробовать взломать абсолютно любое решение (в том числе свое). Причем исходный код будет предоставлен не только для чтения, но и для копирования.
Вам будет предложено 6 задач на 2 часа. Мы надеемся, что вам они покажутся интересными.
Раунд основан на задачах Открытого Чемпионата и Первенства Карелии по спортивному программированию. Если вы участвовали в этих соревнованиях, то воздержитесь от участия в раунде.
Задачи для раунда вместе со мной придумывали и готовили Галина Galina_Basalova Басалова, Валентин Valentin_E Ермишин и Лев robotolev Провоторин.
Хочу поблагодарить авторов задач чемпионата, чьи задачи не вошли в финальный набор для раунда: Руслан r314 Алькин, Юрий basalov_yurij Басалов, Алексей ashmelev Шмелев и Николай Nicola95 Ермолин.
Также хочу сказать большое спасибо координаторам раунда: Ивану BledDest Андросову и Михаилу awoo Пикляеву за улучшение качества задач и помощь с их подготовкой.
Спасибо нашим тестерам: Brovko, deni1000, KIRIJIJI, shnirelman, Alenochka, slash0t, LightSky, infinite_meltdown, Knh_era, M1chail, Antithesis, Kolychestiy, neohacker за ценные советы и предложения!
И конечно, огромное спасибо Михаилу MikeMirzayanov Мирзаянову за системы Polygon и Codeforces.
Удачи в раунде! Успешных решений!
Наши друзья из Neapolis University Pafos также хотят передать вам сообщение:
Открыт прием на бакалавриат по программе "Компьютерные науки и искусственный интеллект" в Университете Неаполиса в Пафосе!
JetBrains Foundation поддерживает эту программу, предоставив 20 полностью финансируемых стипендий для талантливых студентов первого курса. Изначально было объявлено о 15 стипендиях, но теперь их количество увеличено до 20, чтобы дать большему числу студентов возможность присоединиться к программе.
Каждая стипендия покрывает весь срок обучения, включая: оплату обучения, проживание, медицинскую страховку, визовые сборы и карманные деньги (300 евро в месяц).
Также теперь доступны 2 полностью финансируемые стипендии для студентов, переходящих на второй год обучения.
Первая волна набора:
- Срок подачи заявок – до 23 апреля 2025 года
- Вступительный тест – 27 апреля 2025 года
UPD: Разбор опубликован









Can anyone say me the difference between educational rounds and normal rounds?
Edu rounds:
Including minuki's points biggest difference is that there is a 12 hour open hacking phase.
During this time, you/someone else can attempt to create new, valid test cases that adhere to the problem's logic and constraints, but they can only target and test the code of one other specific participant at a time.
If a submitted solution fails on one of these newly created test cases (resulting in Time Limit Exceeded or incorrect output), the creator of the successful hack earns points (i think its +100 or something). (UPD: INCORRECT DOESNT HAPPEN)
After the 12 hour hacking phase, these newly generated test cases are incorporated into the final system testing to identify any other solutions that fail under these conditions.
Edu round doesn't seem to have points of hacks…
My bad
why rating updation is delayed?
The system test is about to start, and the rating will be updated after it is completed.
For most people: classic questions and tricks For me: never seen them before and have no idea about them
new writers of Educational Codeforces Round!
I hope it goes well.
New Era in Edu rounds??
non-BledDest edu round?? surprised
As a tester, FelixArg [orz] * INF
awoo BledDest :((((
Galina_Basalova why you are newbie
I must go to bed before 11:35 pm(UTF+8), should I participate this round?
UPD: I just found that I can participate this round in UNR mode :)
When the contest is 45 minutes long:
It seems very wonderful. Cheaters everywhere.
I'm assuming they are all cheaters, since they probably don't have to ability to solve C in 3 minutes or solve E in 9 minutes (unless your like a LGM, but they aren't, so...)
The person in spot #1 literally registered right before the contest... unbelievable
I have been on Codeforces few weeks ago. Every time I looked at the scoreboard, I felt like I was intellectually disabled...
I mean the problems don't feel that hard to me. I'm currently upsolving and was able to do solve A-D in ~25 minutes (then get stuck on E). I don't mean it in the way that there's no cheaters, but the first 4 questions aren't that hard to decide.
guys i have a problem i can think and solve in my brain problems till 1700 but when it comes to implementing i suffer from lots of bugs i code c++ can somoene help me with this i need to pass newbie phase
Maybe you can turn on Warning All mode.And I write down the bugs I have made and classify them,including bugs on problems understanding and on details.Maybe this will work
How to solve E?
Digit DP,maximum value of k can be 91.
damn im dumb
Yeah but how to do it?
Like how do u know the actual value of k while constructing your number in digit dp?
There will be 30 numbers less than 1e18 which are zebra-like,with a[i]=4*a[i-1]+1. To calculate zebra-value of a number n,iterate from highest to lowest ZL number and if current ZL is higher than number add n/ZL to answer and update n to n%ZL(this is simple greedy).
Since a[i]=4*a[i-1]+1 for ZL,we can add at max 4 for each ZL,but if we add 4 for a ZL[i] then n becomes 0(n must be less than next ZL[i+1] which is 4*ZL[i]+1 ),so we can add 4 only once,hence max k is 3*30 + 1.
So,to find count of numbers less than equal to a integer n with zebra value k,calculate contribution of each ZL in zebra value of n ,now iterate backwards from highest ZL to lowest ZL and this is it.
Is there a proof for the greedy?
dp digit, although I couldn't do it on time. We can iterate from lower to higher bit, and for each bit in the even position, we try to iterate the number of 1 which will be add in that position. Notice that the number of 1 won't be increase, so we need to store the upper bound of this number each time we iterate.
Solved a Digit DP problem for the first time in a live contest, the only issue with the round is difference between (D-E) and (E-F) is too much.
which is Digit DP ? D? if so whats the intution
E is digit dp,D is knapsack.
oh
Get sum of all ci's. now get k which is ceil(sum/2), form subseqeunces of array(remove all the zeros for better understanding) which give the sum as k. for this collections of characters the number of permutation would be=(number of elements in the subseqeunce)!*(number of non zero ci's — number of elements in the subseqeunce)!/(product of factorial of all ci's). do the same for each subseqeunce you get and add them up and mod whatever value they gave/
thats what I was doing I had implementation problem due to using mint template
I thought about doing it this way. In the case of all 1s, won't it go through all possible splits of the 26 characters effectively 226 masks since every split is valid for odd/even?
b was kind of easy but I wasted time taking x as int and debugging ;(
In Problem $$$E$$$, to minimize $$$p$$$ we must write $$$x$$$ in base $$$z$$$ right?
Was C that easy or am I dumb?
its observation and i'm sure most of them used gpt as it's very classical one for GPT.
Permutation cycle and its length is already very old idea. I'll point out just 1 problem for example that use the same idea and have almost the same people solved. (This was Div. 3 from 5 months ago)
I learned various ideas associated to permutations thanks to a great blog written by nor, although they deleted all of their blogs on codeforces a couple of months ago. Luckily, I've found their original blogs hosted on this website:
one of the best introductions to permutations
So, in essence: yes, problem C was relatively straightforward if you knew the theory + saw an observation or two, although those observations would be easier to find if you knew the theory beforehand...
How to NOT TLE in D? I use memorization + recursive (calculate f(odd_remain, even_remain, current_index))
it is 2.5e5*2.5e5*26 sir, how can't u TLE?
I thought that too, I'm just wondering how to solve this
Note that for each knapsack pattern, the answer is $$$\displaystyle\frac{\lfloor\frac{n}{2}\rfloor!\lceil\frac{n}{2}\rceil!}{\prod c_i!}$$$
Therefore, you only need to calculate how many knapsack pattern there are.
Sorry can I ask how can we make sure the numerator doesnt overflow long long? Since n can be upwards of 10^5. If we take mod in between, that will alter the value right?
You can actually take mod in between, which preserves the mod value for the numerator. For the denominator, the same idea holds except now you have a fraction as an answer. If you take the mod inverse of the denominator, you can restore a whole value answer.
oh!!
omg, i did something completely different!
This will probably FST but https://mirror.codeforces.com/contest/2086/submission/313817555
What's FST?
fail system tests
Somewhat similar idea, slightly faster implementation: 313845121
you don't need odd_remain, you can get it using suffix sum...
odd_remain = sum(index, 25) — even_remain
I had right mindset in D but i dont why answer was some random no always I hate this MOD kind of questions
bro got the right mindset is already a bless, after contest I do see people instantly solve D by dp since it's classical... except me because I'm still suck at dp badly.
misread B,and wasted 1 hour,btw all questions that I read(A-D) were nice.Thanks for the contest
me too,thought they asked to find no of pairs of [L,R] or else i would have got some time for D.
Me too. Otherwise I'll have time to implement E :(
me too :(
People who solved F please explain the key logic, coz I'm missing something and its itching my brain.
Can someone tell what's wrong in my approach for problem B?
what are u even trying to do here? and why are you taking MOD ?
you were 99% correct except the floor part should have taken ceil and use this formula
it will basically tell no of subarray of size how_many in an array of size k.
but why is bro using MOD in B
Just to be safe with large numbers,bcz i thought that may be the reason of my WA
never use MOD when not specified , large number can also be answer to this problem use long long for that
Just for clarification: in some cases you may use modular arithmetics even if it wasn't specified in a problem, but only if you know that the answer will not change. For example, I have solved one problem, where I calculated answer combinatorially using mod 1e9+7 using an observation that the real answer will always be in range [-2;2].
editorial when?
How to solve D?
Decide , which characters you want to place at even positions (or odd positions) , then the sum of $$$c[x]$$$ corresponding to them must be equal to number of even positions. So just find those ways using knapsack.
Through knapsack I coudn't think of a way to do in less than n^2..., I was keeping three states -> index,evenSum,oddSum
no need of oddsum as oddsum+evensum=const
Every letter must be all placed in either odd or even place.Then we can DP,the state is the count of letters placed in odd and even places.Let n be the total count of letters,this is O(n^2)
But if we know the count of odd places,the count of even places can also be known.So the time can be O(26n)
The transfer is to place all same letters in either odd or even places,this can be calculated by Combination Number in O(1) if we have preprocessed.
My code
someone explain B please
guys just wait until editorial comes out
Hint for D please.
Get sum of all ci's. now get k which is ceil(sum/2), form subseqeunces of array(remove all the zeros for better understanding) which give the sum as k. for this collections of characters the number of permutation would be=(number of elements in the subseqeunce)!*(number of non zero ci's — number of elements in the subseqeunce)!/(product of factorial of all ci's). do the same for each subseqeunce you get and add them up and mod whatever value they gave. you would need to use dp to get these subseqeunces
although I haven't read your comment but I just wanted to tell that Hint != solution in any dictionary
For the same letters, they must appear either all in odd positions or all in even positions.
Once the positions (even or odd) for each type of letter are determined, the answer for a certain situation can be calculated using combinatorics.
The answer is fixed for all situations. Use DP to compute the final answer.
Every letter must be all placed in either odd or even place.Then we can DP,the state is the count of letters placed in odd and even places.Let n be the total count of letters,this is O(n^2)
But if we know the count of odd places,the count of even places can also be known.So the time can be O(26n)
The transfer is to place all same letters in either odd or even places,this can be calculated by Combination Number in O(1) if we have preprocessed.
My code
How to solve d ?? can anyone give the hint
You need to calculate how many permutaions you can to do when you fixed %2 for ever character. And then you can calculate how may combinations of %2 for ever character have (DP). Check my code, if you don`t understand me.
For any valid distrbution of char (ex: 'a' in odd postion, 'b' in even position, ...), the number of sequence are the same.
Parity Constraint:
Total Positions:
n = sum(c[i])be the total string length. assume 0 indexed string.E = ceil(n/2)(even positions) andO = floor(n/2)(odd positions).Subset Sum Condition:
E(remaining letters go toO).Once an assignment is fixed:
Since this value is independent of specific assignment:
X(number of valid ways to distribute letters).⠀
nicely explained
Every letter must be all placed in either odd or even place.Then we can DP,the state is the count of letters placed in odd and even places.Let n be the total count of letters,this is O(n^2)
But if we know the count of odd places,the count of even places can also be known.So the time can be O(26n)
The transfer is to place all same letters in either odd or even places,this can be calculated by Combination Number in O(1) if we have preprocessed.
My code
I think it is good problems. But i think, task D is very easy for his place. And I can`t understand, why so many people OK C on very low time?
For me, solution for C was obvious right after reading test cases.
Hahah, i need to find pen for solve this task)
So many cheaters again. So sad this is the closest shot I got at becoming master and I am probably going to lose it because of cheating :(
Why you are think that many cheaters now?
That a look at the top 20 in the leaderboard
What is the problem on top 5-20? Peoples OK ABCD very fast and try to solve E on 30-50 minutes.
This tasks are conructivities and dp, so you can OK ABCD on 30 minutes if you are lucky.
Well,I thought my rank was 172 on the board but I got rank 82.Does this mean some cheaters were discovered
no, you were probably looking at div. 1+2 scoreboard
For problem D, I was going with an approach where I needed to apply subset sum algorithm. Looking at the constraints it seemed fine.
This is using recursive memoization approach https://mirror.codeforces.com/contest/2086/submission/313827623
On the other hand this is using iterative dp https://mirror.codeforces.com/contest/2086/submission/313827274
The recursive approach gave a TLE at testcase-2 whereas iterative got accepted. Never seen such a case and I am more comfortable with recursive dp so always prefer it. Any idea why it failed?
For problem D, I was going with an approach which needed me to apply subset sum algorithm.
I went with recursive memoization approach and this is its code https://mirror.codeforces.com/contest/2086/submission/313827623
The below is the iterative dp approach for it https://mirror.codeforces.com/contest/2086/submission/313827274
The problem is that recursive method gave a TLE at testcase-2 whereas iterative approach passed all the cases. I always prefer writing dp in recursive method since I find it comfortable and have never faced this issue in any other contest.
Anyone has any idea on whats going on?
313805985 My AC recursive D
Oh nice. Will look through it once.
Recursion tends to be a bit slower compared to iterative methods.
But yeah, the time limit in this problem is a bit strict. My initial solution did not precompute the inverse factorial, so it had an extra log n complexity every time nCr was calculated, which caused a TLE. It passed after I precomputed the inverse factorial.
Oh.. I guess i need to try getting more familiar with iterative dp. Thanks btw.
Number 1 in Div.2 (jack_l_b_b) is using AI right? Compilation error in A, then submit a code like this for A:
I mean, to print 2 * n like this, and solve it in 6 minutes, I bearly think that his rating would be >1500. After that, this user spends only 5-9 minutes on B to E, with over 100 lines of code for submissions for D and E. Also, the format looks like GPT-written with comments washed out only, and the variables are too long for a human to use.
P/s: I just posted this in a post, but it is removed. The problem of today's round is great, especially F amazing task which I'm so looking forward to reading the editorial. It's just that it is really possible to use AI and get 1st place...
He's not using AI, There was a blog about a telegram group with around 800 members.
I was checking the group messages, and his codes are very similar to the codes that were sent in that group.
Imagine naming variables with less than 8 characters like you actually worked for that code...
This was my first contest, I was able to do A and B and like almost C. Overall I think I did pretty well, but then how are 7k people solving the third one? do people cheat in the contest here? also when will I get my first rating?
Today's c was comparatively easy.it's around 1300 rated problem.it may take 15-16 hours to get your first rating
Well, rating depends on number of people who solved that problem, so you can't use it to prove there wasn't mass cheating. But C was not harder than usual.
There's even a Youtube channel that live solved the problems during the contest !!
Link : https://www.youtube.com/live/4_z0spfV_pM?si=LuEVWNSrDAozlBk9
How shameful!!
niggawhat
Renaming the variables to
wahandweeisn't enough.C submission #313783798, C submission #313793850
D submission #313816983, D submission #313759625
I think we need some more strict rules and algorithms to detect AI cheaters. They are just ruining the integrity of the contests leaving you jo place for growth and measuring your actual level. A lot of starters get upset and give up on problem solving because they feel dump when they open the dash boars and find 2000+ solved D !! We need to take this more seriously.
damn it! I finally got fucked up by memset, I mean D.
For D, if I use ll dp[sum+1][27], it gives me SIGSEGV in my vs code(seg fault) but when I use vector<vector > dp(sum + 1, vector(27, 0)), it passes, any proper reasoning to it, as the max value of sum is given to be <= 5e5, unable to get the reasoning behind it. Please help.
Arrays inside functions run using stack memory, careful not to use too much
is the above reason valid for this case well ? solution-1 vs solution-2
You're calling memset T times, which takes O(26N) for each calls, the total number of calls can be up to O(26N^2)
ohk, what would be time complexity in the case of solution when using vector<vector> dp(27,vector(sum+1,-1)); isn't both will cost the same
no, since sum is guaranteed to be at most 5e5 over all test cases, the total time completexity will be at most 26*5e5
Isn't problem A ridiculously easy even for a Div 2 A problem?
Average strategy to make more participants rated:)
I noticed that some of the cheaters got live removed, however, there are still a lot of suspicious accounts which should be investigated further, e.g. in the top 5: chenzheyuan, hprwhgsafwan12, not.found
Cool man found! I think StarSink cheated.
StarSink's code in B C D E has tons of annotation. WOW! Even more than the codes?
And you can see the solving time is random and funny:
01:30 01:51 01:26 01:25 01:49.D used 1:25? That doesn't matter, maybe he forgot the contest?
Why C only 1 minute?
Then Finally A?
A used 5 minutes?
Then, E??? Why not B?
B in 2 minuets???
How is D implemented? I think i have the idea.
For problem D, an ungraceful solution is just dp without using combination of multisets, set f[i][j][0/1] as the number of ways to fill, now is the i character, has filled j chars in odd positions, now char filled to odd/even position, we can use prefix_sum to calculate numder of filled even position as every char must be filled, then use C(remain position, c[i]) to multipy previous number of ways. https://mirror.codeforces.com/contest/2086/submission/313862304
Problem D was educational, sure, and that's the reason it was easily solved by AI.
It's sad to know that cheaters might have gotten through this problem like this anyway.
Does this round become unrated? (my screenshot)
no they just haven't updated ratings yet...
Thank for pointing that out! Can you tell me when to expect the rating changed ? Because to be honest this round has completed it's hacking phase in like 4 hours prior to my previous comment.
When Editorial?
2086E - Zebra-like Numbers depends on the observation that
the optimal way to construct a zebra sum is by greedily taking the largest possible zebra numbers repeatedly.
Is there a simple proof of this property?
link
Consider the optimal decomposition of a number, i.e., decomposing it into minimal zebra numbers.
Let the $$$i$$$-th zebra number be $$$z_i$$$ (e.g., $$$z_1=1$$$, $$$z_4=85$$$), and let the count of the $$$i$$$-th zebra number in that decomposition be $$$c_i$$$.
Suppose that in the optimal decomposition of a number, a zebra number $$$z_i$$$ (where $$$i \gt 1$$$) appears at least 5 times. We observe that $$$5z_i = z_{i+1} + 4z_{i-1}$$$, which does not degrade the solution.
If the number $$$1$$$ (i.e., $$$z_1$$$) appears at least 5 times, replacing it with $$$z_2=5$$$ would yield a better decomposition.
Thus, we have Claim 1: Every number has an optimal decomposition such that $$$\forall i, c_i \le 4$$$.
If $$$c_i=4$$$ and there exists $$$j \lt i$$$ with $$$c_j \gt 0$$$, we have the relations:
Neither case worsens the solution. Hence, we obtain Claim 2: Every number has an optimal decomposition where $$$c_i$$$ consists of a prefix of zeros (possibly empty), a single $$$4$$$ (optional), followed by counts of $$$0$$$ to $$$3$$$. In regex notation:
0*4?[0-3]*.It can be easily shown that the conclusion above is equivalent to choosing numbers greedily as $$$\forall i,\sum_{j \lt i}c_jz_j \lt z_i$$$ holds.
Thanks! I think that works, though not quite as simple as I'd hoped. Pretty tough problem for an educational round!
For problem D, my solution was as follows:
First, since the indices need to be a distance apart that is equivalent to 0 mod 2. We can split the indices into red and black squares, like a chessboard.
For each valid partition, there will be a black group and a red group, and the sum of the black group will need to be ceil(n/2) and the sum of the red group will need to be floor(n/2) where n represents the total length of the string
Each valid partition can then make up multiple valid orders. The amount of valid orders of each valid partition is the product of the multinomial coefficients of both groups.
To find the valid partitions you can use iterative dp or recursion with backtracking. I used the recursive method since it was more intuitive.
Разработчики раунда лучшие!
The developers of the round are the best!
Why is the round still unrated for some people?
Yeah.I solved 5 problems in this contest and get purple now ^_^
i received a warning, for my solution coinciding with solutions with A LOT of users, i do not know why others have similar solution as me, it said to comment on this post to appeal i guess? the only proof i wouldve had were my failed attempts on vs code, but this was weeks ago so i cant access that-
but like if i am to explain my approach and code,
i basically tracked the group elements which resulted in loop/cycle and separated them
cyclecount was basically index of the loop, so tell that this element was in this loop, and i kept track of the loop length, and then basically add lengths of all separate groups.
if theres anything else i need to clarify lmk