Hi everyone!

Codeforces Round #448 (Div.2) takes place on 26th of November at 19:05 MSK. As usual, Div.1 participants can join out of competition.

This is my second round on Codeforces! I advise you to read all of the 5 problems. Hope everyone will find something interesting.

I'd like to thank vintage_Vlad_Makeev for coordination, igdor99 for helping me in developing problems. And, surely, thanks to Tommyr7, Arpa, 300iq for testing this round.

Of course, many thanks to MikeMirzayanov for great Codeforces and Polygon platforms.

Scoring: **500-1000-1750-2000-2250**

High ratings to everybody!

**UPD:** Contest is finished. Editorial will be posted soon.

**UPD:** Editorial

Congratulations to the winners!!!

**Div1**

**Div2**

Why this post is not on the main codeforces page? UDP: now it appears :P

I think NBAH posted it on his blog by mistake. It should be fixed soon.

I think Contest setters post it on their blogs, just that Mike/Coordinators pin it up on homepage..

Yes, it's true

I think you should update "other testers" soon to show your respect and thank to them.

You were finally heard.

Too late for chinese! It will take place at 00:05(UTC+8). So I can't take part in this contest. But I also hope everyone high rating!

short sad story

glhf

You also like this sound of dislikes

Good luck!

Good luck!

It helped to my friend bktl1love on his last comment ... )

High ratings to everybody! _______What a sad story..T_T

I hope no large queue like the last educational round , I should't be wating 15 min+ to know whether my solution passes pretests .

yes that sucks. 1-3 minutes is ok but 15-20 is too much

Wish Everyone will get high scores! NBAH's previous

contestCodeforces Round 367 (Div. 2) was wonderfull and gave high ratings at the end. I hope this one will be more than wonderfull for everyone. Good Luck and High Ratings.Good luck!!!

is this contest rated ?

let's hope so.

Wish you can get high rating!

Thanks for scoring ! This round is now enough special to remember it a long time :)

I have noticed that Arpa is mentioned/thanked in every blog post. Great job man.

1750 points for problem C... Seemed like a challenging contest. Still wish for the best for everyone ;)

GL & HF

Wish you can get more and more score.

Wish you can get high rating!

good luck and have fun every one :D

The best thing about the blog is — not using this line`As usual, the scoring will be announced shortly before the start of the contest.`

Best of luck to all!!

Is it rated?

It's asked You had better ask

"Is it DATED?"Did you see NBAH's wish

"_High ratings to everybody!_"in the last line of theannouncement.**???**if(yes){

Why couldn't you realize that this contest is rated.

}

else{

Read again!

}

WTH , NOt able to hack

lol

No hacking, problems are too hard. Great contest...

As predicted, problem C is much more difficult than usually.

B as well.

Go no rating...

Good problem set.

Happy_minus_Rating

Is it Div-1 contest ?

typical Div 1.5

The first A-B-C problems should be B-C-D.

"High ratings to everybody!"

Problems are way harder than usual.

I would agree. The problems were way too difficult, especially B and C. Goodbye rating :(

How to solve D? I thought of fixing first position where a[i] < c[i] < b[i] but c[i] can be equal to b[i] and become less later(for example ab bc answer is 1(ba)).

DP[position in permutation][is current permutation already grater than

aflag (0 or 1)][is current permutation already less thanbflag (0 or 1)].How to calculate dp[position in permutation][1 (current permutation is already greater then a )][1(current permutation already less then b)] ???? If we somehow know the remaining count of each letter then this equal number of permutations of remaining letters, but we don't know the remaining count of each other, So how to calculate this??

Thanks in advance!

Consider a function

f(stringx, 26 -numbers) which returns number of stringssconstructed with characters which is given in the input, thats<xf(x, 26numbers) can be solved using the first position that you said and the answer isf(b, (a-characters)) -f(a, (a-characters)) - 1the contest was very bad it was like div 1 please dont ever write a contest and please make it unrated because it was bullshit

I'm agree with you

Pretest 9 for C?

Why my code for E is so slow? http://codeforces.com/contest/895/submission/32688252

I think it is because you are always propagating and you only have to do it when it is necessary(i.e. lazy[nodo] != 0)

Thank You, I will check this.

what is the 8th pretest for b ? What is wrong in this ? https://ideone.com/dIQKbm

You need to think about the case k = 0

I was also stuck on the 8th pretest. It has k == 0, which may lead to WA for some programs if you don't take care of the case.

Even I got wrong answer on 8th pretest. I just handled the special case for k = 0 and the pretests passed

You need to choose subarray not subsequence.

Because segments have to be continuous

It said "continuous" pieces......I didn't catch that "continuous" first and was hacked at 1:30 ..........

Why 2^N? I think N^2.

yuShaf sets

Is solution of E based on sqrt decomposition?

In E, notice how the update affects any particular value. Assume we store the expected value at each index at current time. Now we have to deal with an update.

Consider any value in the left subarray. Let size of left and right subarrays be S1 and S2 respectively.

final_value= (S1-1)/S1 *previous_value+ (sum of values in right subarray)/(S1*S2)Similar argument can be used for all values in the right subarray as well.

Simulate these operations using a segment tree and lazy propagation.

Code

what about non independence of values?

What do you mean by non-independence? I am using linearity of expectation which does not require any such condition.

I am fool, i forgot about independence of E...

I thought E(x+y)!=E(x)+E(y) if x and y dependent of each other.

It's expected value not variance.

How did people solve C? Unable to access other submissions as of now.

The number is perfect square iff all prime degrees are even. So you can do dp with bitmask since there is only 19 primes until 70.

Didn't know this fact, thanks)

I figured as much. Could you give a more detailed description of your dp (states and transition)?

edit:wait nm this is too complicated lol

If some number is prime and >35, then it's only prime is itself.

Otherwise, it can be decomposed into the first 11 primes (up to 31). Build a bitmask for each number where mask[i] = the parity of number of times the i'th prime divides the number.

Now do dp(first i numbers, xor value of j) dp (it's like knapsack). Use the sliding window thing to save memory. This takes care of first 11 primes. Take ans = dp(n,0)

For the rest of the primes, they need to occur an even number of times in a subset. So if there are count(p) occurrences of prime p, p>=37, then you can do this 2^(count(p)-1) ways (it's p choose 0 + p choose 2 + ...). So just multiply this together for each prime p, 37<=p<70, and multiply by res and subtract 1 for the empty case.

I did the exact same fuckin thing, still couldn't pass the 14th test case :(

I handled squares and non-squares differently. I even know where my bug is :( but too slow.

this contest was awful! so sad!

Nope! Great problems. I've never failed at B so hard tbh... but C was a lot of fun, only if I could finish my dp in time. Great problems.

What is an idea behind your DP approach?

What were your dp states might I ask?

i'll give you my incomplete code https://ideone.com/BP05Of

The idea is bitmask dp and knowing that choosing odd and even number of items from a collection of size n is just 2^n-1

Please look for "solve", which is the entry point. I know my template is big :|

Explanation from AdiZer0 : The number is perfect square if all prime degrees are even. So you can do dp with bitmask since there is only 19 primes until 70.

Correct. We want dp[n][mask=0]

Hack for the first problem: 5 72 72 73 74 69 Ans: 66

Sad! I forgot that "sectors should be continuous" and submitted something useless :(

Somebody please explain div2 A ,as it had the worst explanation ever :/

Select a continuous subsegment such that the difference between the sum of the selected slices and the sum of the unselected slices is as small as possible.

He Could've wrote subsegment instead of sectors, too misleading

The problem gives you N pieces of pizza, with sizes in array 'a'. The sum of all these sizes add up to 360. Now, the problem is asking for the minimum difference between 2 section if we split the pizza into 2 contiguous sections. We can start from position 1 and iterate through, keep track of the sum before called 'SUM'. Since we know the total sum is 360, we can find the sum of the other piece by doing 360 — SUM. We then take ans = min(ans, abs(SUM — (360 — SUM)). The pizza is circular, so we can start from all possible starting positions (1...n) and do the same thing. The answer is then the minimum over all starting positions.

There is no any case for this-> if one of sector is not selected ?

If one of the sectors is not selected, then we know the sum of one sector is 0 (because not selected), and the other one must be 360. So, the highest answer possible would be 360. We can set our answer to 360 initially to cover this case.

Problems were harder than usual ( specially A and B )

How to solve div 2 problem A and B?

In problem A you can use dp, or just calculate the minimum sum, by(pseudo) cyclic shift. More in my code: Click

Very interesting tasks, I enjoy a lot of solving this problems !

How to solve C?

Note that there are atmost 19 primes less or equal to 70. And do something like

dp[current_number][mask of primes you have to get rid of].the time complexity is 2^19 * 100000 = 5e10. Can it fit the time limit? UPDATED: we can actually do in 2^19 * 70.

No. But you can notice that there are atmost 70 distinct numbers and reduce the complexity to 2

^{19}·70.If you have a number repeated k times in input, then parity is 0 for it's prime factors if the number is chosen even number of times, and parity is odd otherwise.

Please explain a it more about the dp formulation.

Imagine you grouped all numbers by their values (all except 1, we shall consider it separately).

Let

mask[i] be a mask where ones denote primes that occur odd number of times in the factorization ofi.The main idea is that a number is a perfect square if all the degrees of its primes are even. So now denote

dp[group][mask] as the number of ways to obtain such a mask of odd primes if we use numbers from groups 2 togroup.To make a transition note that if we take an even number of elements from

group+ 1, the mask doesn’t change. Otherwise the last taken element will change the parity of some primes. Hence out current mask gets xorred withmask[group+ 1].The only observation left is that the number of ways to take either an odd or an even amount of numbers if there are

nof them is equal to 2^{n - 1}.For each integer in interval [1,70] you can save mask of prime divisiors ( 19 prime divisiors until 70). After it you can iterate over numbers from 1 to 70 and calculate next DP state : DP [ i ] [ mask ] = amount of subsets with numbers ( 1...i) and current mask of of prime divisiors.

Can you elaborate it a bit more?

Let

f_{i}= how many numbersithere are in array. Note that there are 19 primes up to 70. Also, note that in square number number of occurences of every prime must be even. Considering all of that dodp_{i, parityMask}= how many subsets there are containing only numbers 1 ≤x≤isuch that parity of number of occurences ofi-th prime is denoted byi-th bit inparityMask. Obviously,dp_{0, 00...00}= 1. Figure out the remaining part of solution yourself. Answer to the problem will bedp_{70, 00...00}.Can you give some hints for the rest of the solution?

Do you think my solution for B will pass time limit, I used map<int,int> instead of index compression?

i also used map.. but i used map<long long,long long>. i'm not sure it will pass or not :(

Well, it works in logN. So I think you both do not need to worry about TL

My mistake, I also used long long.

got ac bro :D

me too :D

Gah problem B apparently had so many edge cases, I kept getting stuck at the later tests

What's the hack for B?

Handle k = 0 and duplicates in the array.

I believe both of them were already there in the sample cases!

I meant duplicates when k = 0, for example the case

8 3 0

1 1 1 3 3 3 3 3

What's the answer?

Ans = 9 as you can create 9 pairs using the three 1s.

I suppose case like

is better.

is the answer 7?

Yes, it's 7 with indexes pairs: 1-1, 1-2, 1-3, 2-1, 2-2, 2-3, 3-3.

6

70 20 50 50 80 90

not A. I am talking about B.

Oh sorry.

PEOPLE ON CODEFORCES ARE GOOD AT SARCASM

Very hard contest but problems were very interesting.

What's the answer of B:- 5 3 1 1 2 3 4 5

9

Cam i ask how the answer is 9?

Good pairs are: (1,3),(1,4),(1,5),(2,3),(2,4),(2,5), (3,3), (3,4), (3,5)

any idea about this code bug(bug'S)???-problem B-

5 3 1\n 1 2 3 4 5 ans is 9.your code prints 31.

excellent problem set!

div1.7-1.8

Can anyone help explain why my solution to B times out on case 14? Thanks in advance!

32692235

You have a double for loop from 1 to n, so the code runs in O(N^2) time. Since n = 10^5, you need O(NlogN) or similar. (In general, less than 10^8 or 10^9 operations is safe)

May I ask where I have a double for loop? I thought my time complexity was O(NlogN) due to multiset. I may have put a double for loop by accident somewhere though.

Oh, sorry I read your code wrong. Idk

It's no problem, thanks for the help!

Afaik distance works in o(n) with std::set.

std::distance works in O (N) . So your code works in O (N^2).

P.S. std::distance is same as using 'it++' several times.

oh I didn't realize that. That's unfortunate for me. Thanks for the help!

Yep, std::distance is too costly for a multiset. If you use a vector, sort the values, and use lower_bound and upper_bound, getting the indices of iterators is

O(1), rather thanO(n) for the multiset!what is pretest 8 in prob A. solved nothing today. I calculated two segments with the min difference between them like partition problem but that is apparently not the case.

I got WA in pretest 8 because I was taking a subsequence (not consecutive values).

How does this contest fit into the pizza of life?

In problem B statement, did you guys notice that previously it was written

find the number of differentwhich killed me. After the contest, it shows`UNordered`

pairs of indexes (i, j)`ordered`

. In the beginning, I realised that the solution would be with lower/upper bounds, but that very statement confused me and pushed me to thinking in terms of self-balancing trees & adding elements from end towards start, which I spent a lot of time and coded. After that in the test case 3, realised that it's not like that :(Why don't announce this change? NBAH

That's a huge error, they have to address it.

Spent the whole contest in this problem ...

It should've been announced.Even I solved the earlier version until i reread it in the last few minutes.

Solving for the number of unordered pairs is no different from ordered pairs since if (i,j) fulfills the condition Ai <= Aj then (j,i) doesn't, unless of course i is equal to j

No! For unordered pair, (i, j) = (j, i), however, for ordered pairs, (i, j) != (j, i). (of course for distinct i, j's).

Problem B:Is thisSpoiler3nlogn

complexity optimal?

Yes, That should pass.

hmm

What is the idea of problem C?

If we use naive bitmask dp for each prime, it is O (N)*2^19 (because there are 19 primes between 1 and 70) which results time exceed. The idea is if the number is a prime which exceed 35, it must be grouped with a same number. So it can be pre-processed. Since there are 11 primes between 1 and 35, this solution is O (N)*2^11 which gives AC. P.S.Be careful of using % while implmenting it -it gives TLE

GGOSinon How to do bitmask transitions using iterative DP ??? I know only for the Recursive One and thus could not solve it in time.I thought the same :(

Let d [i][j] as a number of way to make state j by using number a[1]~a[i].Let b [i] as a bitmask form of a[i]. We can divide the case : use the b [i] or not. So the recursive formula is d[i+1][j]=d [i][j^b [i]]+d[i][j] ('^' is xor operator) You can implement it by just iterating i and j using 2 'for's to 0~n-1, 0~(2^19)-1. (Initial value is d [0][0]=1, Answer is d [n][0])

You can also correct this issue by noting that there are at most 70 distinct values in the array you are given, so you just use a frequency array for each of the numbers between 1 and 70 and noting that the number of ways to choose an odd number of numbers out of a set of K numbers is always 2

^{K - 1}forK> 0.vpfwfp 70 distinct value of what ???

Many people will get rating rise just for solving A :v

And that's another reason why this contest was awful.

Well, since I'll probably get a rating rise, I'm not gonna say this is awful :)

I only solved A and my rating will go up but that was an awful contest.

I only solved A and my rating went down so this was an awful contest! :)

I think they wanted to justify their statement "High ratings to everybody!" :P

A contest where the one can be proud of solving A & B

Good Questions , i really enjoyed it..hope others too ;-)

Bitmasks + some knowledge of Combinatorics is Div.2 C now? What's the world coming to?

For Problem A in

Test case 50:

7

41 38 41 31 22 41 146 Output: 14

Is it correct? and how Explain please

Thanks :)

take the first 41 with the last 146, their sum is 187, the remaining is 360-187 = 173, therefore the difference between the 2 shares is 187-173 = 14

But if i take

series 1: 41 41 41 38 22

series 2:146 31

than the difference between series1 and series2 is 6

you must take some numbers which are adjacent to each other, note that in this problem first and last numbers are adjacent too

Thanks :)

can someone please explain for the

pizza separationques why the ans for the below sample test is 120 !!what should be the ans for this ?? ans can be zero when the 1 continuous sector contains 60 +30 +30+ 60 = 180 (starting from the 2 last 30 to the first 30 in anticlockwise order) and the 2 continuous sector contains only 180 so 180-180=0 (minimal possible difference) But my code fails for this system test case ,it is showing the ans 120 but i think minimal diff 0 can be achieved .. plzz anyone tell me i cant find where i am wrong in logic or thinking ("ANY HELP WILL BE APPRECIATED")

Your code gives 120 . The expected answer is 0 .

Your submission 32688201 checks:

A) Situations "FFFFSSSSSSS" for any numbers of Fs and Ss.

B) Situations "FSSSSSSFFFF" for any numbers of Ss and Fs only at the tail.

Your code can't correctly process something like "FFFSSSSFF".

Good contest, Very good contest, the problems where good and where fun to solve, thank you NBAH for this good contest. But please keep in mind that the problems where too hard for a div2 contest

Can anyone explain why my solution to B gets WA on case 21? 32682296 Thanks.

Input:

5 3 0

2 4 5 7 9

Your answer: 4

Correct answer: 5. (1, 1), (2, 2), (3, 3), (4, 4), (2, 3)

why here UndefinedBehavior http://codeforces.com/contest/895/submission/32691004 ? but here everything is normal http://codeforces.com/contest/895/submission/32693522 . changed only this

he in int started to count all?

Note that

`y`

could be equal to`a.end()`

.std::vector::end()is a special kind of iterator.I think it is not specified what happens if you add an integer to it (as you do in

`ans+y`

part of 32691004).Regardless, I would use parentheses to avoid unnecessary integer-iterator addition (as well as the subsequent subtraction):

`ans=ans+(y-x);`

Albeit I didn't manage to solve D in time, the contest was really cool. The only thing to bother me was the unclear statement of B. Keep it up :D

I was thinking I was the only one who have read B many times until really understand what to do in this problem

Wow !! This was one of the best contests I have ever participated in <3. All the problems were very , very nice ! I really enjoyed the round as well as the problems.

Take my heartiest love NBAH <3 <3 Hope we will get such awesome problems from you in the future. Keep up the good work man :)

And many many thanks for such nice round and all your efforts in it :)

I have trained for 5 days and became specialist. I am looking forward to next contest

http://codeforces.com/contest/895/submission/32679304 is judged an error, but works in my compiler?

the last line in your while loop should be if(i==n) i=0 not i==0

[update: ACCEPTED] Where is my wrong approach for problem B 32694817

delete2/32687180, coutinho/32687203, OutSpace/32688038, blindspot/32689194

LOL, this is 4 photo machines. I was canceled for using the ideone for C. And these 4 people have found, then they copy my code. My fail but I hate their, LOL

Can someone please suggest some cases(possibly small n so that I can debug) for my code (Problem C) http://codeforces.com/contest/895/submission/32711673

It is giving correct answer till n=1000 (in System cases) but I don't know why it is giving WA for n around 10e5

You missed a prime number, you only have 19, and there are 20 in total.

Edit: nevermind.

We have 19 primes before 70 https://primes.utm.edu/lists/small/100000.txt

Please tell me which one I am missing if I am wrong

My mistake, my code said 20 because it counted up to 75.

pw2 array size should be 1e5 not 70.

Thanks :)

Can anyone tell me what's wrong with this code?

Running fine on local. :(

Test: #1, time: 0 ms., memory: 1844 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER Input

4 90 90 90 90

Output -664469436

Answer 0

Checker Log wrong answer 1st numbers differ — expected: '0', found: '-664469436'

Line 16 should be k < 2*n instead of i < 2*n

Check here: http://codeforces.com/contest/895/submission/32737382

THIS IS VERY IMPORTANT !!!

I submitted my solution for problem A during the contest and it passed the pretests then I got RTE on test 49 during system test phase, after the contest I resubmitted the exact same code and I got ACCEPTED !!!!

submission during contest : http://codeforces.com/contest/895/submission/32683171 submission after the contest : http://codeforces.com/contest/895/submission/32733925

PLEASE NBAH CHECK THIS PROBLEM !

THANKS.

I belive that you accessed invalid position on the array as you used

`for (int j=i; j<N+i; j++)`

N+i-1 will be outside of bounds since the array has only N positions and, by accessing not allocated memory you get an undefined behviour, which means that anything could happen, even geting AC even though it is wrong. That is actually a very common doubt for begginers, in his last post Mike talked about that. In his words:

"Many Codeforces visitors are already tired of the questions of less experienced participants: "Why does my solution not work on some test on the Codeforces servers, if I locally launch it and it works correctly? You have the wrong compiler/servers!" In 99% of cases this is an example of undefined behavior in a program."

One of the most informative rounds ever. Thanks for your efforts!

Can anyone explain Meet in the middle solution for C?

What's the idea behind this submission 32677264 for problem C?

What is a smaller form of test case 13 for C? My program keeps outputting 1000000006 and I don't know why. A lot of other people also have the same wrong output.

Maybe you need to change int to long long?

you cannot make x = a*b%MOD using integers for a and b because they will overflow and you will take the MOD from the result of this overflow

Thanks so much! That was the error, apparently. So the -1 output was just a coincidence. :P

Nephren_Ruq_Insania WOW!

There's a small bug in the winners.The rank9 of div1 is the same as the rank1 of div2.

Why is problem A wrong? test case 8 says answer is 40 while the true answer is 0. Come on guys no one wants to correct it??? :(

Considering that there are more than 3000 people who have solved the problem, it's more likely that you're wrong. :) Did you split the pizza into two

continuoussectors?