*Mabuhay!*

I am honored to announce Codeforces Round #419. It will take place tomorrow, on June 17, 17:35 MSK.

The problems in this round are written by me, robinyu. I believe it is the first Codeforces round with a Philippine writer. I would like to extend my heartfelt gratitude to kevinsogo, AlexFetisov and winger for their invaluable help in testing the problems, KAN for his endless patience and support in preparing the contest, and of course MikeMirzayanov for the absolutely amazing Codeforces and Polygon platforms.

In this round, you will be helping Karen in her day-to-day routine.

There will be pretty pictures, drawn by the lovely Kazenokaze. Do not miss the round!

Both divisions will be given five problems and will have two hours to solve them. Keeping with authentic Codeforces tradition, scoring will be announced right before the round.

As a matter of course, you are highly recommended to *read all the problems*; though problems are arranged by expected difficulty, you may find some problems easier than others.

I hope you will enjoy the problems as much as I did writing them!

The scoring for this round is:

Div. 1: 500 — **1250** — 1500 — **2250** — **2250**

Div. 2: 500 — 1000 — 1500 — 2000 — **2750**

Good luck, and I wish you all high ratings and bug-free code!

**Update:** Congratulations to all winners!

Div. 1 | Div. 2 |
---|---|

1. Radewoosh | 1. TarasSavitskyi |

2. yutaka1999 | 2. ChillingDream |

3. W4yneb0t | 3. WA_TLE |

4. Um_nik | 4. TLEwpdus |

5. eddy1021 | 5. Tian.Xie |

Special congratulations to Radewoosh for his second consecutive Div. 1 round victory, and to both him and yutaka1999 for solving all tasks!

Thanks for your patience. The editorial has been posted. Hope it was worth the wait!

VoHiYo anime round VoHiYo

finally, a rated round after such a long wait...

is it rated?

What website you used to make such great pictures like this? And is the girl customizable? :')

Моя попытка во время контеста: http://codeforces.com/contest/816/submission/27854137

(WA 126)Моя попытка после контеста(тот же код): http://codeforces.com/contest/816/submission/27876220

(ACCEPTED)ПочемуАБСОЛЮТНО ОДИНАКОВЫЕКОДЫ получают WA и AC??????Лог чекера Can't find file C:\Contesters\Work\invoker-prod\work\codeforces2\5fce135e23ca31c3af3931016c4ef202\check-2b11d4eec984eb8ac636a09dfb665d94\run\output.fd0138e687.txt.

UPD:все исправлено!I think you should send this to MikeMirzayanov

Done

This error might be somehow connected with your nickname :)

To be seriously, it's strange bug. I hope you will get your honest rating scores back.

P.S. And why minuses? People are so agressive to others problems?

My rating was getting around

+120, but in the end got only-1Now I know I was right not to let Araragi Karen appear in round #418... in case of possible conflicts.

karen i can be your onii-chan

How about being my brother in god and working for egypt?

Hope for short statements.

Hope for ecchi (see artist's weebsite).

I never understood why the scoring is announced right before the round if it's always the same...

Not always, actually. There might be minor changes like it was in the previous one (i.e C and D were worth 1750 points instead of common 1500 and 2000)

Why is scoring always announced just before the round, Could anyone tell what was the idea behind this tradition initially ?

Woho.. never thought of getting an Anime theme based Round.. Made my day.

So we had a Bakemonogatari round and now an anime round. Things are looking bright for CF.

What round is the Bakemonogatari round?

418

Thanks!

Very interesting topic..

"...you may find some problems easier than others."In other words, There will be a math problem at DIV 2 C or D :(

Well said .. :) Div 2 D

Oh, there was no rated round for Div.1 for 27 days!

But today, there is a contest that probably rated for Div.1 so I'm especially looking forward to this contest.

(Previous rated round for Div.1 is Codeforces Round #415.

I think all anime fans will participate on this round.

I don't think so. This is not a place where one who is into anime participate the contest just because it's anime-themed. Anyway I haven't ever expected to see a contest involving anime character, great surprise.

Many of my friend (Japanese) says, "I like the character Kujou Karen, so I'd like to participate in this round (Actually I don't know even who is Kujou Karen)

Another interesting fact in Kujou Karen in competitive programming is KujouKaren in Atcoder is very strong and got 5th in MUJIN Programming Contest.

So much anime culture in competitive programming... surprised.

Actually, the user KujouKaren in atcoder is me...

I've tried to register the username KujouKaren in CF but I found that this ID has been used KujouKaren.

You can take the handle in the next new year I guess if you wish as KujouKaren is inactive for 2years and hasn't participated in any rated contest.

just informed my friend about the round and he is a big time anime fan.

he canceled his date today :P

anime round , sound cool to me .

Karen is so cute DA☆ZE~

⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄

Why can't I register for the contest? The system tells me that I've registered but I really have't. Upd: Fixed

nice round ! now i think every one want's to help karen in her day-to-day routine ;D

It is a welfare of otuka!!Nice picture.

I registered, then cancelled the registration and now can't register again.

(the other computer says that I'm registered)

Same to me

Wow! A writer from my home country :) Congrats to kevinsogo for being top 1 in Google Code Jam 2017 Round 3 :D

It will be hard to concentrate on problems.

As we know, competitive programming is moemoeSports! I'm looking forward to the CUTE image and clear problem statement!

Well, I think I am the only one that watched the entire series of Kiniro Mosaic just because it will be featured on this contest. God bless moe anime.

I hope that problems statement very clear.

I don't think so cause of pics and story !

Short description will be helpful everybody.

Please I hope no 10 min delays.

How about the "right before the round" scoring distribution ?

UPD:FixedVery unusual Scoring for div.2 :D

i know what to comment to get upvotes!

take some downvotes too :P

Hack page not loading..?

is there something wrong with codeforces. I have been trying to submit C for 20 minutes but I couldn't submit. Its like there's no response from codeforces site.

Same happened to me but they fixed it

Please fix it soon. I am unable submit yet.

Go to your contest dashboard. Ask it to the "Ask a question" section below.

thanks man. submitted only 2 minute before contest.

edit: nvm

Same here,please reply!

First time opened last problems, because of pics.

How to solve D?

I recognized all patterns except n % 4 == 3. Could you please explain it?

If you have n % 4 == 3 and you don't know how to answer it, just apply one step and you have n % 4 == 2 and you know how to solve it.

What you mean by apply one step?

If you could find the patterns for n % 2 then you could transform n % 2 == 1 into n % 2 == 0 by bruteforcing one step.

Could you please improve the explanation? Thanks!

My solution was simple: find the relation for when n is even. If it is odd, make 1 step for it to become even. Note through the drawing below the problem that the operations are still at the same order so you can apply what you found for n % 2 == 0.

If you had the relation for n % 2 == 1 you could start from n % 2 == 0 and apply the step 3 times, now the operation is the same as starting from n % 2 == 1 (it starts adding) and you can use the relation you have. Other than that kind of stuff, you need to note that each number will influence the answer independently and then do some bruteforce solution to find some pattern from inputs like 0 0 1 0 0 0 0, at least I think almost everyone did that.

This is straight from my code, it might be helpful to you (it's in portuguese and comb is a binomial coeficient):

// par -> j par = comb(n / 2 — 1, j / 2) // par -> j impar se n / 2 % 2 == 0 é negativo, se não é positivo // par -> j impar comb(n / 2 — 1, j / 2)

// impar -> transforma no par e resolve

For odd indices the coefficients are .

Even indices are .

Maybe you can find one formula for both.

When you miss the case n=1 and you don't believe on correctness of your pattern

If you manage to recongize one pattern it is enough, since you can build the other in a brute way from the recognized pattern.

How to solve Div1B :(

I think to use binomial coefficients. (Pascal's triangle)

Is Div1 — B solvable using matrix exponentiation? would also be interested to know other methods. TIA

What will be the transition function? The transition function will change depending on the level we're at. eg: from level 10 to 5 has a different transition function than 12 -> 6.

In short, according to my understanding, we can't. To use mat-exp we need a consistent transition function, that doesn't depend on level.

I passed pretests by finding pattern of the coefficients (Huh). There were 4 cases, (parity of n, parity of (n/2))

Wow! nice. I was looking for a similar pattern but didn't think it would depend on parity of n/2.

Hack for Div 2 C ?

Hack for Div2 C?

Typically, when n > m.

Thanks My output was 5 and then all rows :/

The answer is 5 row 1 row 2 row 3 row 4 row 5 right?

No, answer is 3 because problem asks for minimal number of moves(I saw it only now).

Omg I missed it too. And most people in my room...

I forgot about the min even though I checked both row and columns :'(

I made the same mistake first but realized it just before the contest ended while testing my own solutions. Managed to resubmit just in time :D

using the minimum number of movesNo: 3 col 1 col 2 col 3

Is it the right answer?

`3`

`col 1`

`col 2`

`col 3`

Yes.

fuck :(

I can not believe this... I knew this exception but accidentally typed n instead of m...

`if(n<m) for(int i=0;i<**n**;i++) for(int p=0;p<dm;p++) printf("row %d\n",i+1);`

`else for(int j=0;j<**n**;j++) for(int p=0;p<dm;p++) printf("col %d\n",j+1);`

Sometimes you need to start from columns not from rows... Consider a table:

010 010 010 010 010 010

My solution because of this was hacked... Bye bye rating :D

Div 2 C is from an old Cook-Off

You had an opportunity to solve it in 5 minutes =)

I was making sure , that I dont mess up anything.

Its easier than that . Here one matrix is always all zeroes . In the question you mentioned in your link, the other matrix is different and you need to make both matrices equal . Div 2C is an easier version of that .

Hmm, but can't we apply the same technique on both matrices and compare the residue matrix after all operations? If the residue is same, then they are same.

That feeling when you screw up your rating because of one "if" condition in Div1 A :(

The Art of the Covfefelmao

div 2B please ?

I solved it with Segment Tree + BIT. For each given n range, update the range with segment tree. Then for each i from 1 to 200000, point query with segment tree checking whether it is >= k. If it is, then update point i in BIT with +1

Later, for each query, just do a range query with BIT.

P.S. I think it's pretty much overkill. Maybe others have much simpler idea.

No need to use BIT/segment tree when all queries are after update.

Code

Do you know partial sum?

for i [ 1, n ] arr[a]++; arr[b+1]--

then find the cum. sum in the arr[].

and then also do the cum sum in the array to find if the arr[i] is >= k.

then just ans is for query l to r cum[r]- cum[l-1]

Something like this link

Is there the case of the type :

2 1 1 1

(div 2 C)

in the pretests ?

I don't think so. This is one of the hacking test.

## HACKATHON COMING

How to solve D? Is it involved inclusion-exclusion principle?

Div2B is very similar to this problem — http://www.spoj.com/problems/UPDATEIT/

I think they are pretty different.

I used the exact strategy mentioned in the link above . I have done the above mentioned one.

Was D variation of pascal triangle or something? can anyone tell what was wrong with my code

try this testcase: 1 1

Ohh Crap! Thanks though :)

Can someone tell me what particular cases may occur in div1D? I've spent 30 minutes trying to find a bug and didn't find anything...WA on pretest 4. Has it happened to anyone else, too? If so, how did you fix it?

Solved C 3 minutes after ending...

Solved C 20 seconds after endings...

How to solve div2 B? -_-

Do you know partial sum?

for i [ 1, n ] arr[a]++; arr[b+1]--

then find the cum. sum in the arr[].

and then also do the cum sum in the array to find if the arr[i] is >= k.

then just ans is for query l to r cum[r]- cum[l-1]

Solved it with segment tree.

Overkill

but i did it http://codeforces.com/contest/816/submission/27857211

B would have been interesting if each query had its own 'k'. That would have been a good question on merge sort tree .

No need for merge sort tree if queries come after updates.

Then, i would have gone for segment tree and a node will be a sorted vector of elements lying in segment. Now for query, just binary search to find. Query would be O( log(n) **2)

How is merge sort tree approach different from that ?

Let's say we calculate 2 arrays:

l_cnt[t]— how many intervalsstartwith temperaturet?r_cnt[t]— how many intervalsendwith temperaturet?Then we can figure out in

O(1) the number of intervals covering some given temperaturetin the following way:think about sum A[1...r] then you need to add 1 to [l, r]. 1<=l<=r<=a. think about sum A[1...r-1] then you need to add 1 to [l, r]. 1<=l<=r<=a. think about sum A[1...r-2] then you need to add 1 to [l, r]. 1<=l<=r<=a. You store array D[1...n] Add 1 to D[l], subtract 1 from D[r+1]. And them D[i]=D[i-1]+D[i]. Here you have a prefix array Check if D[b]-D[a-1]>=k.

With Binary Search code

Can you explain why your code works ?

For each temprature check in how many ranges it lies within the range (with binary search explained below)

For all those tempratures whose value is >=k we use prefix array dp[i] = dp[i-1]+1(if its is more than k) else dp[i] =dp[i-1]

3.now every query can be answered in O(1) time .

Total complexity is O(nlogn)

Now to check in how many ranges a tempratue values lie within you can use upper_bound and lower_bound function from stl calculate the lower_bound from the right array as it will return no. of values in right array more than that value , after that we need to subtract those values from the above values whose left index is more than the required temprature so we use upper_bound function , and the difference between the two is our answer , now if it is >=k than we should include it else not.

obviously , we need to sort left and right arrays

My C is failing System Test today :(

Canany one give me a clue for problem B? I think solution is binary search but I can't code :(

Use prefix array

How to solve Div2 C?

Of course, a coupon cannot be used without buying the corresponding goodAnyone forgot this case like me ? :'(No, because then you can just use all the coupons :P

No i don't think so what about this case :

4 4

2 1

2 1 1

10 9 1

2 1 3

We can not use all the coupons

If you can use a coupon but not buy the good, Then you can just use all the coupons but buy only the lowest (C-D) items as long as you can. In other words, equivalent to the problem, you have an array of values (equal to C-D), find the max no of items you can buy with sum <= B.

Div 2 C was an 99% copy of this problem. MRTNSFRM

Just wrote what was in the editorial.

Edit: Did not notice bhishma's comment.

What was complexity of your solution for C? Mine was brute force that works in 0(500 * n * m)

You can do it in if you just find minimum in row/column and substract it. Since max answer is roughly

max(n,m) * 500, it is faster. However, your complexity should be totally fine.I did exactly what you mentioned . Hope i pass system tests . This is my first time that first 3 passed pretests.. Update : I got TLE in 3rd :/

Also you can use DP+priority Queue to do it in (n*m). Link to my code here

Thanks

Spent a lot of time on C, found a DP approach, proved the correctness, proved the time complexity is less than , submitted 15 minutes before end of contest and got WA on pretest 3.

Panicked.

Re-read the statement to find out that

D_{i}is the discount and not the price after discount.Phew. Hope it holds.

I am guessing it is similar to the question "Barricades" from "Looking for a challenge" book.

I'm guessing div1-E was inspired by Bathroom Stalls from this year's GCJ Qualification Round?

So that's why it looked familiar!! The new 10^18 bounds though...

Problem E is similar to Problem C from this year Qualifications Round in Google Code Jam, but this problem was more challenging.

Can anybody please tell me, if there is a segment tree + lazy propagation approach for Div2 B ??

Yes, it can be done in that way too but it can be solved easily using prefix array. Look at this code — 27855143

You can just find all temperatures that suit and answer on queries using binary search

Make an array of pairs with size 200000.

let the first element of the pair as start of some of the given ranges and the second as the end.

now iterate over all values from 1 to 200000 cumulating sum like the following:

sum += a[i].first , sum -= a[i].second. but before subtracting the end check if the sum on index i is greater than or equal to K then on another array mark i as true or just 1.

now build a segment tree (regular segment tree of sum) on the array of marks. and answer regular sum query on it.

sorry for detailed explanation :D code

What a fucking problem D (Div.2) that was garbage :/

Shit > problem D

if your king paid that billions for improving mathematical books instead of trump you wouldn't have said that :)

What is the time complexity of this solution for Div2 E/Div1 C?? Is this

O(n^{2}) orO(n^{3}). I think it is the latter, what do you think?It is actually O(n^2) because for each u, the total number of iterations is the number of pairs(x, y) such that lca(x, y) = u. That sums up to number of all pairs (x,y) in the tree.

The sad thing is that I thought O(n^2 * log(n)) was fine so I sorted each node's descendants to calculate f[u][i][0] instead of running another DP :(

Yeah that's sad indeed I thought that this solution will be slow so I didnt program that and instead I was trying to optimize it.

Shit. :(

You can learn about this trick using this problem Barricades whose solution is described here (just download the preview).

815E - Karen and Neighborhood is a simplified version of task 3 (OGLEDALA) from Croatian olympiad in informatics 2015 March 28th

=(

`+12:-2`

Div2C/Div1A — https://www.codechef.com/problems/MTRNSFRM

Div1E — https://code.google.com/codejam/contest/3264486/dashboard#s=p2 (very similar)

As I know, Div2E/Div1C also appeared in some past contest.

It loks like author is very good at copying problems)

What's wrong with div1 E being similar. Can't the author be inspired by the problem? Most people here did the GCJ but did not solve this anyway.

DIV2A- http://codeforces.com/problemset/problem/108/A

Div1C is similar to Codechef Snackdown 2017 Elimination Round problem BLACKCOM (just some weeks ago).

only because both problems are "dp on tree" then you consider them similar? in my opinion they are quite different

Problemsets are quite different. I mean the solutions of optimizing O(n^3) to O(n^2) are similar.

160+ tests in problem A X_X

398 tests in problem E O_o Maybe it's E just because of that? :D

My last 2 minutes: I somehow had unused functions (but compiled) that were dependent on my local template :|

That's the closest clutch I have ever seen! Great job at saving your rating haha

Sorry, Karen I couldn't help you in Task: C,D,E :(

My contest submission status:

The Time and the Memory value is increasing, and I can even make two trapezoids!

That's interesting! :D

Very slow system testing :p

That's because Div2 C has over 175 testcases!

Ohhkk

E peeled of easy binary searches in main and ifs for k=1,2

That's ... unexpected ;p

(this function tells "how many people will be placed on interval (l, r) if l and r are already occupied and people will not move in if distance is smaller than dis or it is equal to dis and their position is > bd)

Taking someone's problem and making it just a bit harder is definitely not the best way to create programming problems.

Well... were I more skillful, I'd have solved C easily.

Were I more tactical, I'd have skipped C quickly and would have solved D sooner and probably solved E.

I can't believe I can't solve a task that 100+ ppl can solve. If this happens in IOI, I can put my head through a wall.

That's already well known trick mentioned many times on CF that such dp runs in O(n^2) and not in O(n^3) and solving it in O(n^3) is pretty straightforward

Well...I always solve this kind of tasks using dp on dfs sequences, which somehow don't work(at least I think) on this task.

What do you mean by that? I do it in a most standard way of doing dps on trees

where dp[v][cnt][coupon] is cheapest cost of buying cnt guys from v's subtree so that I used coupon on v if coupon==1

How to prove the complexity is indeed

O(n^{2})?Search the comments here in this page...

Thanks for the help.

For each subtree you'll make Size of previous subtrees * Size of this subtree, the sum of everyone of these is the number of pairs of vertices (u, v), so it is O(n^2).

Thanks for the help.

well it works in

O(n^{2}*logn) in this task I guessAs a forever yellow, I am very happy about the difficulty of Div1B and Div1C — usually Div1B is somehow clear (save for maybe some implementation challenges), and Div1C is just too difficult. This difficulty distribution definitely felt more fun.

Your mileage may vary, for others this difficulty jump might have been to much between Div1A and Div1B ... what are your thoughts?

It's surprising week sample, week pretest and cute image :P

was there any better way to solve div1B than observe pattern in this

I don't think so. I also tried to do it like this (but did a mistake in a brute xdd) and people I talked to also did same thing. You can also magically guess what the answer will be and check it manually :D.

I would like to know closed form for n%4 == 3 and n%4 == 0 as well. Will wait for that editorial :)

For it is .

for n%4 == 0 , let x = (n-2)/2 , then the sequence is xC0 , -xC0 , xC1 , -xC1 , ... , xCi , -xCi , ... xCx , -xCx.

for n%4 == 3 , try to observe nth and the n-1th row , its either [n-1][i] + [n-1][i-1] or [n-1][i] — [n-1][i-1] depending on parity.

Since pattern for n%4 == 0 is really nice one. We can just perform the operation for n%4 times and then use the pattern for the n%4 ==0. One more observation to make is that if the last operation you performed in above step ( to reduce to n%4==0 ) is '+' then now our starting operation in the new scenario will be '-' which is different then the standard problem. Only change we need to make now is to use the same formula as mentioned by @majk but just omit the pow(-1,i) part ( all the values will be +ve if we start with a '-' operation ) my code

good pretests for div2 C

system testing is too slow! :(

Very slow system testing.

Am I the only who couldn't hack any solution because whenever I tried to open some solution it wrote that I need to install the newest version of Adobe flash player?

I spent 15 minutes and finally installed new version, but I still was recieving such messages.

I wanted to try hacking 5 minutes before the end so I just gave up after seeing that message.

I always use Chrome but for hacking I use firefox xD (because I get same error and I don't know how to fix it xD)

A screencast of my (pathetic) performance.

Maybe I should study more math before participating future contests as of late so many DIV2 C,D are using maths. So the algorithms I know are not needed here. I wish I am a math guy lol.

Just some complexity checking here. Can anyone tell me why my code runs only in 62ms ? http://codeforces.com/contest/816/submission/27862413 I use 4 nested loops with O(500*n*m*(n+m)) right here. Shouldn't 10^9 at least takes 1 second in codeforces judge?

Thanks.

ah i could hack a lot of solutions(( but i wasted time trying to solve D

How to solve Div2 D

ans = k0 * a0 + k1 * a1 + k2 * a2 + ... + k(n-1) * a(n-1)

Corner cases:

n % 4 == ???:

1: t = n / 2 — 1;

Then k = {C(t, 0), 0, C(t, 1), 0, ... }

2: t = (n — 1) / 2

Then k = {C(t, 0), C(t, 0), C(t, 1), C(t, 1), ...}

Other two cases for exercize.

How did you come this to solution, observation?

yes, just bruteforce to 20

:3 , just :3

Two first places in a row? Incredible :D

Marcin_smu did it some time ago, it can be seen that he's my "coach" on my university XD

Yea, 318 and 319. Poland strong :D

On 318 and 319, Marcin_smu both took 1st place, mnbvmar (also from Poland) both took 2nd place.

Why so many people (including me) forgot to handle the n>m case (div2 C)?.... and nobody hacked my solution :'( :'(

Mine was hacked 2 minutes before the end... :D

the best thing in this contest that the problems was clear and easy to understand thanks robinyu

It's over, I have the high ground!

Finally I am blue again !!

I hope, I can see pink in future.

Finally expert!!! <3

Div. 2 C n > m case. RIP.

Sometimes, I just wish. D:

When will the next round be?

In July =)

nope!

My screencast here (99th place :C)

I cant figure out why my code is giving negative output on test 19 for Div1 B. Link http://codeforces.com/contest/815/submission/27857089

In your code, a1 can be negative. So, say a1=-1e9, a2=1e9; Then (a1-a2+MOD) is still negative.

Okay but see this submission(i printed a1 and a2 if ans is negative) http://codeforces.com/contest/815/submission/27868207. So a1 is not negative here.

Okay, This time the bug's in the other branch, ans=(a1+a2)%MOD. Here, a1+a2 becomes negative, since a2 is negative.

just add if(ans < 0) ans += MOD

Can not get any idea about Div2 C..Help needed about realizing the solution of the problem ..

If you fix the number of times you add to the first row, all other variables get fixed automatically. Let no of times you add to row i be ri and that of column j be cj. If you fix r1, cj = arr[1][j]-r1. Now, ri = arr[i][1] — c1. After that you just check if all ri>0 and cj>0 and ri+cj == arr[i][j]. Then it is valid. If it is valid, take the minimum number of steps, which is sum of ri and cj. There are atmost 500 values possible for r1, as 0<=r1<=500 because 0<=arr[1][1]<=500.

Time complexity is O(M*n*n) where M is max value in array.

Code

In which category does problem C(Div 2) falls in?

Greedy maybe?

Had some weird errors during the contest in div2 C. Four five submissions. Please look into it so that it doesn't repeat. submission

Can anyone tell me why my C answer is wrong.?

https://pastebin.com/TzpachRc

You want to find the solution with the minimal number of moves. The solution

`50 col 1 col 2 ... col 50`

consists of less moves than your solution.Nice both pictures and problems

ARIGATO GOSAI MASSHH for the round... :D

How to prove that the order of making changes in various rows and columns in div2C is interdependent .... Someone plz help i have trouble in understanding....

I mean can't we apply the transformation in any order i.e why do we only need to do the rows first and then the column or viceversa

Each transformation can be represented by a matrix addition. And those operations are commutative.

How to solve Div 2 B without a segment tree?

Using cumulative sum.

I used binary search. First, for each temperature you check if it's admissible or not(you can do it just iterating through them and calculating balance of segments) and add it to the array if it is(array will be sorted if you start from t = 1). Then on queries you just do binary search to find the first and the last suitable temperature for current query. My code: http://codeforces.com/contest/816/submission/27853021

My screencast

Hope you find it interesting

This is my submission for problem A:27853670

It says my solution failed at pretest 10. If i run that on my mac i'm getting the right answer which is 20. Can anybody explain where it went wrong...

You are accessing the strings s1 and s2 but they are empty, which is undefined behavior. That's why it may work on your mac but not with the online judge.

My approach for Div2 C:first calculate minimum element in each row .it denotes the number of operation we can do in corresponding row.and store it inside a vector named row

Now calculate the maximum element among each element we have calculated in the previous step.let's denote it by

mnnow for each column calculate its maximum element.let denotes it by

mx.Then abs(mn-mx) will denotes the number of operaetion in a column, and store abs(mn-mx) inside a vector named colnow to check for invalid case.make a new matrix lets say ff.each cell(i,j) of the ff matrix will be row[i-1]+col[j-1].if g!=ff then print -1 else answer exit

now to calculate the answer.just calculate the sum of all element in vector row and col lets saya answer is ns1;

Now do the step-1 for column and step-3 for row and store the result inside vectores col1 and row1, and calculate the answer ns2

answer will be minimum of nsand ns2 see modeMy code

Ok, I've upsolved Div2C in greedy approach after the contest, but I don't understand why it works! Can anyone explain?

What problem B? I didn't understand :(( help me!!!

You are tasked to find the sum of lengths of segments (all their values >= k) within given intervals [l,r] (both ends inclusive).

This problem is tailor-made for segment tree/fenwick tree. My solution using segment tree: link.

Of course, a fenwick tree solution is similar but easier.

Your solution is

4 timesfaster than mine, but I can't understand how?Your solution's complexity:build: O(NlogN)

First loop: O(NlogN)

Second loop: O(NlogN)

Third loop: O(N)

Queries Loop: O(Q)

My solution's complexity:First loop: O(N)

Second loop: O(N)

Queries loop: O(Q)

So overall your solution runs in O(NlogN) and mine in O(N), but your solution passed in 486ms and mine in 1933ms.

My code link

P.S: I submitted it in practice, does it have any effect.I have seen other's solution there's too takes around 1800ms.

After adding ios_base::sync_with_stdio(0) (that makes cin/cout faster) your solution runs in 670 ms, so it's much closer to 500ms :)

I used java for solving 816A. It worked perfectly fine on my computer ( I have JAVA 8 too) but not on codeforces. It gave a runtime error. Following is the code snippet:

Thing is, if in = "05:39", for my computer rev.substring(3,5) = "50".

However for codeforces, rev.substring(3,5) = ":5".

Hence, for codeforces rev.substring(4,6) = "50", while for me it is an ArrayIndexOutOfBoundError

Can anyone tell me why is this happening?

I tried your solution on 1. "05:39" 2. "05:39 " It showed me the same error on (2), so I guess the test cases have a space character at the end and that is causing some problem.

The scanner is set to stop amd ignore ' ' and '\n'. Is there any other characters I should ignore?

you are using a readline() and your readline() breaks when (c == '\n') or (c = read() != -1), so I guess it is still reading that space symbol. EDIT: your readWord() also fails, just try this->

if (c != ':' && !(c >= '0' && c <= '9')) in your readLine() or readWord(). This is a temporary fix just meant for this problem. I guess the input has some strange whitespace char at the end which I don't know about. I tried submitting your code with this and it worked! http://codeforces.com/contest/816/submission/27884725

I guess this is the problem. Thanks a lot for your help, I was really confused!

No problem!

Hello, frag.jdk

I think i found the error but if you can share your complete code i can be sure about it.

Here is what i think : the error is the in the

rev.substring(3, 5).If you are working with integers and then trying to make a string like if hh = 12 and mm = 55 you create a string eaquals to (12:55) in other word some sort of concat... you will for sure get a run time error.Why? imagine you have mm = 59 and you want to increment it to 60 then you which will give you 0. and imagine you have hh = 0 which you will increment to 1 the string will be

"1:0"not"01:00"rev.substringhave range from 3, 5 which are out of "1:0"'s range.I hope i made it clear.

I have solved 2 problems and want to know why my answers are skipped, what is the reason???

It means you cheated

Any idea when will the editorials be uploaded ? Thanks

May be jury doesn't have their own solutions for all of the problems and they are now trying to understand the code of the guys who solved them.

Hi, so to me seems like a notorious coincidence

Waiting for editorial

blackEarth's (North Korea, obviously) submissions times:

Not to mention subtle differences in coding styles in the submissions on D/E (using LL or ll for long long, cin/cout vs scanf/printf,

`if (x)`

vs`if(x)`

, ...).Please provide the Editorial.

`Editorial will be uploaded by tomorrow`

I am pretty sure that today is tomorrow for yesterday :D

How to solve Karen and supermarket?

Notice that coupons form a tree rooted at 1.

Then calculate dp[current vertex][total number of goods purchased in the subtree of this vertex][did we apply a coupon for the good in this vertex]. After that the answer will be maximum possible i such that either dp[root][i][0] or dp[root][i][1] is not greater than b.

Check my code for details :)

27885164

Thanks! So we are trying to minimize the cost of i goods at vertex v.

Your complexity looks high, close to n^3 :| How did this pass TL?

It's not really n^3, though it looks like so.

Consider the two for loops for recalculating dp for current vertex u.

The outer one indicates how many goods you buy from the subtrees of all children of u, that go BEFORE the newly added vertex v.

The inner loop indicates how many you buy from the subtree of v.

Thus, the two loops effectively enumerate all pairs of vertices, where two vertices in a pair are FROM SUBTREES OF DIFFERENT CHILDREN OF u, that is, all pairs of vertices with LCA = u. This means, no pair is checked twice, resulting in overall complexity O(n^2)

Nicely explained :)

Nice observation!

.

If I'm not mistaken, the problem "Barricades" from here has much in common with this one. It's proved that the complexity is O(n^2).

editorial for problem B?

Look my comment below.

My solution for problem B. Complexity is

O(3nlogn+qlog^{2}(MAX)) where is MAX = 200001 or more. So lets first build Segment Tree with adding on segment(with Lazy Propogation) and then when comes eachl_{i}andr_{i}add 1 on segmentl_{i}andr_{i}. Then lets create an array of size MAX and for eachifrom 1 to MAX assignarr_{i}its value in first segment tree. Secondary we need to build new 2D segment tree that called merge sort tree on the arr(you can see realization in my code). This kind of segment tree allows us to calculate how many numbers there are in array between elementsLandRwhich are less than anyK. Finally when we have queryl_{i}andr_{i}the answer will ber_{i}-l_{i}+ 1 -Kwhere isKis the number of elements than lesskbetweenl_{i}andr_{i}. I know my solution is bad and very crazy thats why i am looking for an other solution. My code: http://codeforces.com/contest/816/submission/27852820 Also i noticed that my solution works whenkis different for all queries.You know, all of your queries are offline... Just use prefix sum array :)

Oh... of course. Thank you very much

you can use prefix sum to solve this problem .

Waiting for editorials, Can anyone provide a tutorial for Div2-Problem D?

In case you missed, refer to the following comments in order http://codeforces.com/blog/entry/52653?#comment-367266, http://codeforces.com/blog/entry/52653?#comment-367389

Waiting for problem D div2 solution

27897999 div2B. What is wrong?

You don't need to use operator * on iterators here. x — y works like pointer arithmetic, result of (x-y) will be number of elements in vector between x and y. I resubmitted your code without * and it is AC. http://codeforces.com/contest/816/submission/27900041

waiting for another contest but none near by :( !!

Definatley should have done E instead of D. A similar but harder question appeared in Code Jam 2016 Finals.

Sir, very good contest, love thee questions, thnank you