Hello! Codeforces Round 797 (Div. 3) will start at Jun/07/2022 17:35 (Moscow time). You will be offered 6-8 problems with expected difficulties to compose an interesting competition for participants with ratings up to 1600. However, all of you who wish to take part and have a rating of 1600 or higher, can register for the round unofficially.

The round will be hosted by rules of educational rounds (extended ACM-ICPC). Thus, solutions will be judged on preliminary tests during the round, and after the round, it will be a 12-hour phase of open hacks.

You will be given 6-8 problems and 2 hours and 15 minutes to solve them.

Note that the penalty for the wrong submission in this round (and the following Div. 3 rounds) is 10 minutes.

Remember that only the trusted participants of the third division will be included in the official standings table. As it is written by link, this is a compulsory measure for combating unsporting behavior. To qualify as a trusted participant of the third division, you must:

take part in at least five rated rounds (and solve at least one problem in each of them), do not have a point of 1900 or higher in the rating. Regardless of whether you are a trusted participant of the third division or not, if your rating is less than 1600, then the round will be rated for you.

Thanks to MikeMirzayanov for the platform, help with ideas for problems and for coordination of our work. Problems have been created and written by ITMO University teams: MikeMirzayanov, MisterGu, myav, Gol_D, Aris, senjougaharin, me Vladosiya.

Also many thanks to Kirill22 , daubi , Fortin , Artem_Sukharev , vsinitsynav , yorky , oversolver , majorro , ilya_totl , Undying , olya.masaeva , Kniaz , Golovanov399 , farmerboy , Absyarka , Kavaliro , neeraj_joshi for testing the contest and valuable feedback.

Good luck!

**UPD:**Editorial

as a tester, I want to say that I've waited for invite so long... and finally got it!

also, expect interesting problems :)

As a non-tester, I'm still waiting for invite

How can we be invited as a tester? I mean what are the conditions?

ScreenCast

All the best everyone hope everyone gets a positive delta

Still everyone can try

I can't have doesn't matter how hard I try

hope a good delta positive this time.

As a contestant, I want to say good luck to all contestants

Finally Dream come true!! . Now i can finally give div3 as an unrated participant !!. It took 1 year for this moment.

Same here :)

Me too :)

Me too moment :)

hello blue guys

No Offence, and congrats you are an expert!!...

Specialists in div4 be like:

Congratulations bro

agree

div 3 and div 4 are good contests for newbie participants

Exactly!!

All is good don't limit yourself

## 六国は、軍が破壊されていない賄賂秦賄賂秦と破壊の方法の電力損失で良い戦いの欠点はまた、六国は、賄賂秦のはい、強い支持の損失を買収するために互いの速度を失ったと言った賄賂秦の欠点も攻撃して外に取ることは秦が得ると勝利と得るより邑大実際に百倍の死と敗北と死実際にまた百倍の偉大な悩みの領主は最初の祖父 嵐 霜露カット考えるには戦争ではありません初代の祖父は小さな土地を持つために茨を切り、その子孫はそれを草の浪費と見て、今日は5都市、明日は10都市を切り、秦軍が来る間、安心して寝て四領を眺めることができたのです燕・趙の王は、秦に賄賂を贈らず、自分の国を守る遠大な戦略を持っていたので、燕は小国ではあったが、後に滅亡した三国志が秦に付かず、刺客もいないのであれば、勝敗の数、生存の理由も秦に比べれば簡単には測れないかもしれません世界から六国崩しの話を取り上げると、また六国の下になる

What I think of when I see Chinese spam

It's Japanese

Chinese, please calm down!!!!

Changing Chinese to Japanese makes no sense.

All the best everyone . Hope all of you get a positive delta

why so downvotes "."?

Dont know . Maybe they didn't like my well wish. Anyways my bad.

All those downvotes are because of you're wishing for positive delta (Covid variant) :)

Ooh . Should I've written plus rating then it would have been the upvotes. Correct?

First unrated div 3. Yay:)

disadvantages of being expert.That's the reason i am still specialist.

Div3 round yayy !! Is the round really meant for Div3 when we can see no tester who is <1600 ...

Also what is the point in including so many high rated testers and not a single <1600 tester ?

Obviously to make an unbalanced round :D (no offence)

Hope good practice and new colors for all rated participants

!Unrated for me too :D

i am always ready for the div3 with my cup of tea

I didn't participate in 5 rated rounds and my rating is below 1600 can I participate??

I wish that every Chinese student can get good grades in Gaokao!

how to do E?

Try to think about case : how does answer change if we pick such $$$(i,j)$$$ that $$$(A_i$$$ $$$mod$$$ $$$k)$$$ $$$+$$$ $$$(A_j$$$ $$$mod$$$ $$$k)$$$ $$$>=k$$$ .

For example : $$$k=3$$$

$$$A:{1,2,4,5}$$$

matching $$$(1,5),(2,4)$$$ gives answer $$$4$$$ and matching $$$(1,4),(2,5)$$$ gives $$$3$$$

for each value a[i], a[i]/k will always be there in the total answer. So, we can add a[i]/k for all i. Then, in another array we store a[i]%k. Now, the maximum sum of two of the remainders of a[i] and k is 2k-2. And (2k-2)/k is 1. So we have to find the number of pairs that we can form (from the remainders) such that their sum is

`greater than or equal to k`

. We can do this using greedy + two pointers. My solution — https://codeforces.com/contest/1690/submission/159852372I think the authors are very much interested in permutation graph this is 4th instance in last one month I find same kind of question F

https://atcoder.jp/contests/abc247/tasks/abc247_f

https://codeforces.com/contest/1678/problem/E

https://codeforces.com/contest/1670/problem/C

If you have some more basic questions of this concept please do share. I didn't knew about this earlier, that such a topic exists. Thanks.

How do you solve F and G?

How to solve the edge case for F while solving for LCM of each cycle?

What edge case?

Yeah, I got all the cycles and tried to get all the number of moves for each cycle such that all the letters get matched to the correct locations. But I had no idea how to go on from there without brute force.

I think brute force works? Constraints are low enough that for each cycle you can check how many rotations are needed to return this cycle to it's original position (and you can take the LCM of all this)

what happens if there are multiple possible rotations needed to return the cycle to its original position?

we take the first time the cycle returns to its original position as there is no needs to go further

All future rotations are multiples of the first.

Could you please clarify? Edit: Nevermind, I've understood. Thanks

let's say you have string "abab".The first time this string comes to it's original state after rotations is after 2 rotations.

So from here you can figure out that this string repeats itself after every 2 rotation. Now to get the answer you simply need to find this minimum rotation required for each cycle.

let's say you have got cycle of "aba", "bba", "abab", "aaa" and each of them repeats itself after 3, 3, 2, 1 rotations respectively. So, the answer for this case would be lcm(3, 3, 2, 1) = 6

you can checkout my implementation

^ Ashish mostly covered it. Essentially if it takes k operations to return the string to it's original position, then it will take another k operations to do the same thing again.

Therefore the string is in its original orientation at time k, 2k, 3k, etc. You only care about k, because all other rotations are just multiples of k.

You then need to find some number that is a multiple of all other original orientations, and therefore we arrive at our lcm idea

For individual cycle you need to find number of operations after which string will repeat with brute force and then take LCM.

try to check for pattern, like if cycle string is abab you take the lcm of answer with 2(not 4)

Speedforces

Until the last 2 problems lol

ones who solved C are more than ones who solved B !!

I took more time in A , than (B+C+D) combined xD

Yes! Sometimes $$$B$$$ is more indirect and confusing than $$$C$$$. I too spent slightly more time on problem B than C:

I spent 6 minutes on A, vs 4 minutes on B and 3 minutes on C..

`The pedestal consists of 3 platforms for 2-nd, 1-st and 3-rd places respectively.`

it's the first time in cp history to see the above misleading description ,why it can't be 1-st ,2-nd and 3-rd!

Because that's traditionally how podiums work.

Because

For problem A, can the problem statement use $$$h_1, h_2, h_3$$$ instead of $$$h_2, h_1, h_3$$$ ? Putting some formal definition helps too like

Took me a while to understand the problem statement itself

Ya, That's true );

help me solve E,

if it is greddy then write proff of correctness

or give me some tips on how to think on this kind of question

Instead of maximizing values, we want to "minimize" loss. Notice that if we group 2 items into the same package, their sum might not be divisible by $$$k$$$. So we can see here some "profit" are lost (which is the remainder of $$$(a_i + a_j)$$$ $$$\text{mod}$$$ $$$k$$$. Therefore we want to pair items in such a way so our profit loss are minimized.

yep. It was all about minimizing waste.

For each good it is sure that u can get a[i]/k.Then you still have to deal with n a[i]%k. Use f[j] to record the number of a[i]%k that == j. If u can find two things that add up over k，ans++. Even the biggest two goods，still 2k-2，and after /k，it is 1. 159835536

it dead.hacked.(╥﹏╥)

Not able to pass E's Test case 3. Anybody has a hint??

Int overflow. Use

`ll ans = 0;`

instead of`int ans = 0;`

.My god why do you do this to me?? :) :(

My solution is firstly for each $$$i$$$, add $$$a[i]/k$$$ to the answer, then reduce $$$a[i]$$$ to its remainder divided by $$$k$$$.

Then for example with $$$k = 6$$$ : we want to pair an $$$a[i] = 4$$$ with something $$$\geq 2$$$ (so not $$$1$$$) to get more cost, this can be done with 2 pointers

Edit : nevermind, got hacked :d

I did it with binary search on maps

why is this giving WA?? what's test 2 :( code

Update: Take a look at Ticket 11121 from

CF Stressfor a counter example.isn't N always even?

How to solve E ?

we need to maximize floor((a[i] + a[j]) / k)

floor((a[i] + a[j]) / k) = a[i] / k + a[j] / k + (a[i] % k + a[j] % k) / k -> (1)

=> we need to maximize (1)

a[i] / k and a[j] / k are constants, so we cannot maximize them. Therefore, they directly contribute to the answer.

=> we only need to maximize (a[i] % k + a[j] % k) / k

The above expression can be maximized when the numerator is maximum since the denominator is constant.

=> now we need to maximize (a[i] % k + a[j] % k). This can be done by an approach similar to two-sum where we try to pair the smallest remaining element with the largest remaining element such that their sum is >= k (because only then the sum can contribute towards the answer)

Hey guys, could anyone of you help me out real quick? Speaking of problem F...

This is my submission: 159858692. I count the lengths of all cycles and see whether this cycle really changes anything in the string, if so — I include it while LCMing all valid cycles.

What did I miss here? I am thinking of some cycles of substrings like "baba". Is that the case or anything else?

"baba" will become equal to orginal string after 2 rotations and not 4

Yeah thats what I was thinking about, thanks. Any way how I could implement it in my code?

The time constraints allow you to rotate the string untill it becomes equal to original.Otherwise ,for a linear time solution you can implement it using LPS(longest prefix suffix) array.

Alright, thanks again, I'll look into it!

Or you can just use: int period = (str + str).substr(1,2*str.size()-2).find(str) +1;

Above code works in O(n) time.

How would that work? I guess I apply it incorrectly: 159869936.

Sry my mistake there should be 2*str.size()

It still seems to be failing if I use correct string for that. Check out my code in the previous comment, please.

but it s not written that sum of n over all test cases will not exceed 200.Does that mean that in a single input set, there could be 1000 inputs where n=200?

Yes. The periodic can be something like

`abcabc`

for this case, you need to take the length 3 instead of 6 into accountI see, thanks. Any way how I can insert this check in my code?

You can brute force the length of the periodic substring. For a fixed periodic with a length $$$len$$$, we can check for every substring with a length $$$len$$$ are the same substring. So we can just brute force the $$$len$$$ value (make sure that $$$len$$$ is a divisor of the cycle length as well)

This will runs in $$$O(n^2)$$$. Since $$$n$$$ is small enough, we will be able to do so

Got it, thank you for your time!

This will run in $$$O(n \cdot cnt(n)) \approx O(n \sqrt[3]{n})$$$ where $$$cnt(n)$$$ — number of divisors of $$$n$$$.

...

you can just brute force on all the factors of the length of the cycle to check the periodicity of each factor and consider the smallest one

Yep, thanks!

Ye that's about it. If you have a -> b -> a -> b cycle then it's rotational value is 2 not 4.

Why the cycle is 4, not 2?

abab [Initial String] baba abab [Returned to initial string after 2 rotation]

That is exactly what barun511 says :)

Does the time taken to solve questions matter in div 3 & div 4 contests?

Like if 2 people solve the same number of questions, do they get the same rank or does the one who took less time to solve them get a higher rank?

The one who spent less time gets a higher rank.

If the equal cycles of a string are its periods then what is KMP made for???

I remember using this above rule in an atcoder contest, but I forgot it today due to knowing what KMP does

You don't need KMP for this. I think normal brute force would work to check all periods. I used divisors which need modular arithmetic to prove correctness

What's KMP?

https://cp-algorithms.com/string/prefix-function.html#compressing-a-string

EDIT : Got the failing test case. Thanks!

Can someone tell me why my code : https://codeforces.com/contest/1690/submission/159863108 is giving index out of bounds, also do tell the test case that is failing. Thanks!

In submission, it is written " 'out of bounds' on the line 128". Probably when rem[k-i] is empty

Assuming that

`i == k-i`

then, you might reach a case where the size of the vector only consists of 1 element and you're popping back it twice (for example where $$$i$$$ and $$$k-i$$$ is equal to 0)Nice round! and very educational.

what's wrong for this code for F? https://codeforces.com/contest/1690/submission/159857773

You have directly assumed that the number of members in the cycle is the number of iterations it will take to loop back to initial value or 1 in the case of similar characters in the loop. But suppose take the case abab in this it will take 2 iterations only. abab --> baba --> abab.

What you actually needed to do here was find if the string has a repeating pattern which you can do in two ways as pointed by many people — 1. Using Longest Prefix Suffix — O(n) time complexity 2. Or rotating the array till it is equal to its initial value — O(n^2)

get it thnx

You haven't considered if a cycle has string like

`abcabc`

, when this is the case, the length of the cycle is not 6 but 3thnx

Emmm....Why I am an official participant with rating 1601?!?

xd

probably you registered the contest before you reached expert ,that happened to me before.

seems u r right, thx!

Please tell us if your rating changes after this contest is done.

My rating has decreased by 41...

Big F, hope you recover in the next contest

For problem F I have counted length of all cycles and also the stored the text string formed for each cycle and then simply use Longest prefix suffix logic to find if there is a repeating pattern so as to find min iterations in which cycle loops back to initial value and finally I have taken lcm of all these values.

But still it is giving WA. Can anyone please help me figure out what's wrong in my approach? :(

Link to my solution

Take a look at Ticket 11101 from

CF Stressfor a counter example.Thank you!!

I don't know why I went for DSU to accumulate the strings in each loop it was looking like an overkill and it turned out to be wrong as well. Otherwise I would have passed :(

What does overkill mean?

This is my solution could you provide counter example

1 4 abab 2 3 4 1 your output:- 4 correct output:- 2

logicforces

Hi! Why does this submission 159869794 get AC, but this 159757251 — WA?

This kind of bugs is one of nightmares in java. Remember that ArrayList returns Integer, not int. You should use equals instead of ==, when you are comparing Integer with Integer. In your AC code, you compared Integer with int, so it was fine.

How to solve D??

I tried to iterat through all substrings of length K and count the 'W' cahr and every time update the ans with ans=min(ans,cnt)

It can be solved using prefix sum. You basically count up to each index how many 'B' are there and store them in an array, the loop through this prefix array and check in a subarray of length k how many 'B' are there. I'm not really good at explaining so you can check my code and ask any questions if you want

It's just like when you asked to give the sum of elements from L to R but here the number of 'B' and update answer with k — number of B?

smart solution thank you!!

Yes that's exactly the idea. Anytime bro.

B WAAAAAA

In problem F, how do I find cycle for an alphabet?

If you want to find cycles in permutation then you can use DSU.

dsu works but is kind of an overkill. I usually go for a dfs-like iteration and keep visiting the next element until I reach the beginning from where my iteration started. I also keep a bool array to not run a specific cycle twice

I'm gonna become blue now, thx

https://codeforces.com/contest/1690/submission/159865329 Can anyone give a counter example?

Take a look at Ticket 11322 from

CF Stressfor a counter example.thank you very much

please give me a counter example.

https://codeforces.com/contest/1690/submission/159917497

Sure, take a look at Ticket 11505

thank you!

Is there a possibility that the answer for F exceeds $$$10^{18}$$$?

No

can anyone tell me why my code giving WA https://codeforces.com/contest/1690/submission/159887831

1 6 cabcba 6 1 5 2 3 4

correct output — 2 your output — 4

My Rating was 973 initially, still this contest is showing unrated for me. Why so ?

The results aren't out yet

How to solve G

Can someone tell me why f is wrong in the 100th of the second example?Thanks you!

that test is 9 cbbbcbccb 9 5 6 8 4 3 1 2 7 which contains a cycle of index 5-2-8-4 cbcb ,it justs need 2 steps instead of 4 so the answer is 6 not 12

Video Editorials of problems from A to F:- https://www.youtube.com/playlist?list=PLB3mqFus13RjjJxKEhaAGtIh9LKEW8mhB

What about G?

I will upload soon. Didn't get the time to solve G till now.

Great explanation (watched F).

Subscribed!

Will the editorial be released for this?

Its been around 13 hours since its completion.

After giving the contest, why am I still unrated?? This was my first contest.

Due to the hacking phase that was completed just a few moments ago. I guess you will get your ratings in a while!

wHeRE EdiToRiaLl?

why it is showing unrated till now

I think given explanation of example in E is wrong. Please correct me, if I am missing something.

Example is, n=6,k=3, weights of goods a=[3,2,7,1,4,8]

We have to pack them into n/2 packages, ie. two goods in each package, and such that total cost is minimised, where cost is [weight_of_package/k], (ROUNDED DOWN).

So, "according to me", they should be packed into these packages: [7,1] (cost=8/3 = 2), [3,2] (cost=5/3 = 1), and [4,8] (cost=12/3 = 4)

So, cost should be 2+1+4 = 7. (This is the minimum I can get)

But in example the minimum cost given is 8. How ? Or there's some caveat in my approach ?

The problem is a maximization problem, not minimization.

I had a doubt. Is this contest unrated. My rating is less than 1600 and I have given 5 rated contests before.Have the ratings been applied yet?

No

why weak pretests on E.

Why blame the pretests if you couldn't write a robust code..

First 3-digit placement, yay! :D Thank you for this contest! <3

This is my submission for E, why getting TLE, complexity seems to be O(n+k^2) to me which should be fine, https://codeforces.com/contest/1690/submission/159917329

It's $$$O(T(N+K^2))$$$ which cannot pass

But the constraint for K is 1000 , so K^2 should give 10^6 which is enough I think , considering it is given sum over all test case will not exceed 2*10^5

There's no constraint on the sum of $$$K$$$ over all the test cases.

Can someone plz tell me why is this code failing at test 2? "problem B" https://codeforces.com/contest/1690/submission/159826598

Consider the case, a=[6 5 7] and b=[0 0 2]. Here, your logic will give output as yes as it first compares for 6,5 and then for 5,7 but the correct output shall be No. Understand why this problem arises and Modify your logic to correct it.

The first mistake syntax error you are doing is that (if(su[i]==su[i-1]) continue;). this condition can give you index out of bound for i=0, and accessing su[0-1] = s[-1].

The test case where your code is when you need to compare the difference of current ith to greater previous than last one. i.e 1 4 5 1 2 5 1 0 0 0

Expected : NO OUTPUT: YES

still not updated the ratings ..... it's been more than 17 hours since it got finished.

same problem.. i dont know why but for both of us the round was unrated

JUST WAIT OMG!!!

My solution for F was accepted in Python but not in PyPy3

ಥ_ಥ

Attention!

Your solution 159836981 for the problem 1690F significantly coincides with solutions Pretest2/159836252, Ksathwik03/159836981. Such a coincidence is a clear rules violation. Note that unintentional leakage is also a violation. For example, do not use ideone.com with the default settings (public access to your code). If you have conclusive evidence that a coincidence has occurred due to the use of a common source published before the competition, write a comment to post about the round with all the details. More information can be found at http://codeforces.com/blog/entry/8790. Such violation of the rules may be the reason for blocking your account or other penalties. In case of repeated violations, your account may be blocked.

I have referred and used the template provided by gfg (https://www.geeksforgeeks.org/minimum-rotations-required-to-get-the-same-string-set-2/) which has been published before the start of the contest ,to solve the problem of of minimum rotations to get back the original string i did not use any unfair means or copied the solution you can check our both code they are completely different except for that rotation string part. [user:https://codeforces.com/profile/MikeMirzayanov] i request you to please check and do the needful :).

I would like to mention that the account with whom i was (plagiarized)[https://codeforces.com/profile/Pretest2] , his rating got increased whereas my rating wasn't

I am amazed how many participants are discussing their "missed" rating change instead of solving unsolved problems.

$$$P.S.$$$ It's simple, if there was no announcement that round have became unrated, you should just wait a bit.

my rating is less than 1600 so if i am right this round should be rated for me but why is this contest not showing in rated graph? and my rating too remained unchanged.

The ratings have not been updated yet. You will see your rating's changes only after they have been updated.

Rating update is slow(；′⌒`)

I reloaded many times with the expectation of seeing my positive delta. But it didn't appear :(

Just use CF Predictor

Carrot is also good

Wait so I just added Carrot, and it shows a different predicted rating change, much lower than CF Predictor. Why so?

Carrot is normally much more accurate than CF predictor. So you should go with the rating that carrot predicts

wth !! It's

unratedfor everyone . You can see in your graph in the profile ,change to all contests .Don't make multiple accounts

https://codeforces.com/blog/entry/103654 A round is never unrated unless there is a specific blog stating so

May I know will there be any Editorial for the contest. It is my first contest and I only solve 4 lol~ It is a fun and beginner-friendly contest.

When will the ratings get updated?

Its unrated . Change profile graph to all

why

It's not unrated. It's just that the rating isn't calculated yet

it is here

Yeah. Congrats on becoming expert

Hey Vladosiya, MikeMirzayanov

I just recieved a message saying that my solution in the last div.3 contest coincided with Time_to_pass. I'm mistakenly accused of cheating in #797 (Div. 3).

I swear that I didn't cheat in the contest, and all the codes in this contest are 100% written by me. Both were my IDs only. I tried solving it from another ID to avoid penalty. I know it was not never a good habit. I will not be doing these silly things onwards. I apologize for my mistake. I have given around 30 contests and this is the first time I have done this. Please help me. [I can give proof if needed about the IDs ownership]

But this is what cheating is

apology accepted not.

Who else got bamboozled by F and did union find only to get a wrong answer and not knowing why Only after contest, then realised its a directed graph and uf cannot be applied here

Dear MikeMirzayanov,

Sir my rating get changed even though it should be unrated for me can you check this as it will be unfair for others.

hello admins I have just received a message saying my solution 159822431 for the problem 1690B significantly coincides with solutions 7878797/159821282.It was unintentionally because I have used ideone.com and I am totally unaware of that because till now I have given few contests on Codeforces using VScode and this was the first time I have used ideone.com because of some updation required in vscode. And I have checked 7878797 user id recently and I have found that this id is having its rating skipped in its previous contest also and one more thing is that this id have used different templates of code in every question, these two things are enough to know that user id 7878797 is a cheater and have copied my solution of 1690B which was totally written by me. So, I am totally innocent and hence this is my humble request to give me my ratings back and now onwards I will totally follow the instructions of which I was unaware previously. Thank you

Hi Admin, ( Vladosiya , MikeMirzayanov )

I received a message regarding the contest Codeforces Round 797 (Div. 3) saying that: my solution for the 1690E - Максимизация цен coincides with about 11 other people. - I'm a newbie here and I don't know many people, so cheating/copying is unethical and impossible for me. I've realized what mistake I did. I use ideone.com and other open judges (for this contest I used ideone) to test my solution on sample cases, didn't know that people could copy down answers/solutions from ideone.com. I know this is a clear rules violation as per unintentional leakage, however, I was totally unaware of it. I'm really sorry about this and I'll make sure to use only local and private testing systems in the future. I went through the solutions of the people mentioned and noticed that they had copied the code, with some modifications, which is unfair for me. Can you please look into this and return my ratings, I had a decent positive delta. It'll really boost my morale. Thanks.

you will get more positive rating changes in the future again. it was a mistake and you got the lesson (not using public online ides). It is not a big deal, just forget about it.