Edvard's blog

By Edvard, history, 8 years ago, translation, In English

710A - King Moves

Easy to see that there are only three cases in this problem. If the king is in the corner of the board the answer is 3. If the king is on the border of the board but not in a corner then the answer is 5. Otherwise the answer is 8.

С++ solution

Complexity: O(1).

710B - Optimal Point on a Line

The function of the total distance is monotonic between any pair of adjacent points from the input, so the answer is always in some of the given points. We can use that observation to solve the problem by calculating the total distance for each point from the input and finding the optimal point.

The other solution uses the observation that the answer is always is the middle point (by index) in the sorted list of the given points. The last fact is also can be easily proven.

C++ solution

Complexity: O(nlogn).

710C - Magic Odd Square

The problem was suggested by Resul Hangeldiyev Resul.

The solution can be got from the second sample testcase. Easy to see that if we place all odd numbers in the center in form of rhombus we will get a magic square.

C++ solution

Complexity: O(n2).

710D - Two Arithmetic Progressions

I wanted to give this problem a lot of time ago. I thought it is very standard problem, but I underestimated its difficulty.

Let's write down the equation describing the problem: a1k + b1 = a2l + b2 → a1k - a2l = b2 - b1. So we have linear Diofant equation with two variables: Ax + By = C, A = a1, B =  - a2, C = b2 - b1. The solution has the form: , where the last equation can be solved by extended Euclid algorithm and p is any integral number. The variable p should satisfy two conditions: and . The values A and B are fixed, so we can get the segment of possible values for the values p. The length of the segment is the answer for the problem.

C++ solution

Complexity: O(log(max(a1, a2))).

710E - Generate a String

The problem was suggested by Zi Song Yeoh zscoder.

This problem has a simple solution described by participants in the comments.

My solution is a little harder. Let's solve it using dynamic programming. Let zn be the smallest amount of time needed to get n letters 'a'. Let's consider transitions: the transition for adding one letter 'a' can be simply done. Let's process transitions for multiplying by two and subtraction by one simultaneously: let's decrease the number i i times by one right after getting it. Easy to see that such updates never include each other, so we can store them in queue by adding the new update at the tail of the queue and taking the best update from the head.

The solution is hard to describe, but it is very simple in the code, so please check it to understand the idea :-)

C++ solution

Complexity: O(n).

710F - String Set Queries

The problem was suggested by Alexandr Kulkov adamant.

Let's get rid of the queries for deleting a string. There are no strings that will be added two times, so we can calculate the answer for the added (but not deleted strings) and for the deleted separately and subtract the second from the first to get the answer. So we can consider that there are no queries of deletion.

Now let's use Aho-Corasik algorithm. The only difficulty is that the strings are adding in online mode, but Aho-Corasik algorithm works only after adding all the strings. Note that the answer for the given set of strings equal to the answer for any part of the set plus the answer for the remaining part. Let's use the trick with converting the static data structure (Aho-Corasik in this case) to the dynamic one.

For the set of n strings let's maintain a set of no more than logn sets of the strings with sizes of different powers of two. After adding new string we should move the sets from the lowest powers of two to the largest until we got an invariant set of sets.

Easy to see that each string will be moved no more than logm times, so we can process each query in O(logn) time.

C++ solution

Complexity: O((slen + m)logm), where slen is the total length of the string from the input.

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

By Edvard, 8 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 16 will take place on 22 August 2016 at 17:00 MSK for the first and the second divisions.

It will be the last educational round prepared by me. As I earlier said I started to work at the great team of AIM Tech and now have less time to prepare a rounds. To leave the rounds interesting and qualitative another guy will continue to prepare them.

The problemset was partially suggested by Codeforces users. The problem C was suggested by user Resul Hangeldiyev Resul. The problem E is the next problem suggested by Zi Song Yeoh zscoder. The problem F was suggested Alexandr Kulkov adamant. Other problems was suggested by me (they are standard, but it is important to be able to solve them).

All the problems was prepared by me (Edvard Davtyan). Thanks to Tatiana Semyonova Tatiana_S for checking the English statements. Thanks a lot to Ivan Popovich NVAL for testing the problems A-E and Alexandr Kulkov adamant for testing the problem F.

I hope you will enjoy the problems! I think the problemset is little bit more difficult than usual, but I'm sure that it will not stop you :-)

Good luck and have fun!

UPD 1: The testing on hacks is completed. Thank you for participation!

UPD 2: The editorial is ready.

Full text and comments »

  • Vote: I like it
  • +249
  • Vote: I do not like it

By Edvard, history, 8 years ago, translation, In English

691A - Fashion in Berland

The problem was suggested and prepared by Arthur Jaworski KingArthur.

In this problem you should simply check the conditions from the problem statement.

С++ solution

Complexity: O(n).

691B - s-palindrome

The problem was suggested by Nikita Melnikov nickmeller.

In this problem you should simply find the symmetric letters by picture and also observe that the pairs (b, d) and (p, q) is the symmteric reflections.

C++ solution

Complexity: O(n).

691C - Exponential notation

The problem was suggsted by user blowUpTheStonySilence.

This is an implementation problem. You should do exactly what is written in the problem statement. On my mind the simplest way is to find the position of the first not zero digit and the position of the dot. The difference between that positions is the value of b (if the value is positive you should also decrease it by one).

C++ solution

Complexity: O(n).

691D - Swaps in Permutation

The problem was suggested by Zi Song Yeoh zscoder.

Consider a graph with n vertices whose edges is the pairs from the input. It's possible to swap any two values with the positions in some connected component in that graph. So we can sort the values from any component in decreasing order. Easy to see that after sorting the values of each component we will get the lexicographically maximal permutation.

C++ solution

Complexity: O(n + m).

691E - Xor-sequences

The problem was suggested by Zi Song Yeoh zscoder.

Let zij be the number of xor-sequences of length i with the last element equal to aj. Let gij be equal to one if contains the number of ones in binary presentation that is multiple of three. Otherwise let gij be equal to zero. Consider a vectors zi = {zij}, zi - 1 = {zi - 1, j} and a matrix G = {gij}. Easy to see that zi = G × zi - 1. So zn = Gnz0. Let's use the associative property of matrix multiplication: at first let's calculate Gn with binary matrix exponentiation and then multiply it to the vector z0.

C++ solution

Complexity: O(n3logk).

691F - Couple Cover

The problem was suggested by Michael Kirsche mkirsche.

Let's count the number of pairs with multiple less than p. To get the number of not less pairs we should sumply subtract from n·(n - 1) the number of less pairs. Let cnti be the number of values in a equal to i and zj be the number of pairs from a with the multiple equal to j. To calculate the values from z we can use something like Eratosthenes sieve: let's iterate over the first multiplier a and the multiple of it b = ka and increment zb by the value cnta·cntk. After calculating the array z we should calculate the array of its partial sums and find the number of less pairs in O(1) time.

C++ solution

Complexity: O(n + XlogX), where X is the maximal value in p.

Full text and comments »

  • Vote: I like it
  • +47
  • Vote: I do not like it

By Edvard, history, 8 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 14 will take place on 13 July 2016 at 19:00 MSK for the first and the second divisions.

<I already have a long list of problems, so don't be upset if your problems wasn't used yet>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks (of course the difficult tasks are also needed). Please send only the problems for which you know the solution with clear statement (the story is not required). And also please add one or two samples to make the problem statement more clear.

Thanks a lot to them and all others who are sending the problems! The number of unused problems are increasing. If I didn't miss anything I already replied to all who sent me the problems at least 5-6 days ago. Please be patient if your problem was not used a long while.

</I already have a long list of problems, so don't be upset if your problems wasn't used yet>

The problemset was suggested by Codeforces users. The problem А was suggested and prepared by user Arthur Jaworski KingArthur. The problem B was suggested by Nikita Melnikov nickmeller. The problem C was suggested by user blowUpTheStonySilence. The problem D and E was suggested by Zi Song Yeoh zscoder (he is on IMO now, so good luck to him). The problem F was suggested Michael Kirsche mkirsche.

As I said the problem A is prepared by Arthur Jaworski KingArthur. All other problems was prepared by me (Edvard Davtyan). Thanks to Tatiana Semyonova Tatiana_S for checking the English statements. The problems was tested by users suggested them, respectively: Arthur Jaworski KingArthur, Nikita Melnikov nickmeller, user blowUpTheStonySilence and Michael Kirsche mkirsche. Thanks a lot to all of them!

I hope you will enjoy the problems! I think the problemset is balanced and not difficult.

Good luck and have fun!

UPD 1: All the hacks for the problem D will be rejudged.

UPD 2: Hack phase will be extended until tomorrow.

UPD 3: Sorry for the problems in the problem D. The solutions that got WA3 were rejudged. The problem is OK now.

UPD 4: The contest is finished. All the solutions were judged on the full testsets. The editorial will be published soon.

UPD 5: The editorial is published.

Full text and comments »

  • Vote: I like it
  • +224
  • Vote: I do not like it

By Edvard, history, 8 years ago, translation, In English

678A - Johny Likes Numbers

The problem was suggested by Abdrakhman Ismail bash.

We should find minimal x, so x·k > n. Easy to see that . To learn more about floor/ceil functions I reccomend the book of authors Graham, Knuth, Patashnik "Concrete Mathematics". There is a chapter there about that functions and their properties.

С++ solution

Complexity: O(1).

678B - The Same Calendar

The problem was suggested by Arthur Jaworski KingArthur.

Two calendars are same if and only if they have the same number of days and starts with the same day of a week. So we should simply iterate over years and maintain the day of a week of January, 1st (for example). Easy to see that the day of a week increases by one each year except of the leap years, when it increases by two.

C++ solution

Complexity: O(1) — easy to see that we will not iterate more than some small fixed constant times.

678C - Joty and Chocolate

The problem was suggested by Sheikh Monir skmonir.

Easy to see that we can paint with both colours only tiles with the numbers multiple of lcm(a, b). Obviously that tiles should be painted with more expensive colour. So the answer equals to .

C++ solution

Complexity: O(log(max(a, b))).

678D - Iterated Linear Function

The problem was suggested by Zi Song Yeoh zscoder.

The problem can be solved using closed formula: it's need to calculate the sum of geometric progression. The formula can be calculated using binary exponentiation.

I'll describe more complicated solution, but it's more general. If we have a set of variables and at each step all variables are recalculating from each other using linear function, we can use binary matrix exponentiation. There is only one variable x in our problem. The new variable x' is calculating using formula A·x + B. Consider the matrix z = [[A, B], [0, 1]] and the vector v = [0, 1]. Let's multiply z and v. Easy to see that we will get the vector v' = [x', 1]. So to make n iterations we should multiply z and v n times. We can do that using binary matrix exponentiation, because matrix multiplication is associative.

As an exercise try to write down the matrix for the Fibonacci numbers and calculate the n-th Fibonacci number in O(logn) time. The matrix and the vector is under the spoiler.

The matrix and the vector for the Fibonacci numbers
C++ solution

Complexity: O(logn).

678E - Another Sith Tournament

The problem was suggested and prepared by Alexey Dergunov dalex.

Let's solve the problem using dynamic programming. zmask, i — the maximal probability of Ivans victory if the siths from the mask already fought and the i-th sith left alive. To calculate that DP we should iterate over the next sith (he will fight against the i-th sith): .

C++ solution

Time complexity: O(2nn2).

Memory complexity: O(2nn).

678F - Lena and Queries

The problem was suggested by AmirMohammad Dehghan PrinceOfPersia.

Let's interpret the problem geometrically: the pairs from the set are the lines and the problem to find to topmost intersection of the vertical line with the lines from the set.

Let's split the queries to blocks. Consider the lines added before the current block and that will not deleted in the current block. Let's build the lower envelope by that lines. Now to calculate the answer to the query we should get maximum over the lines from the envelope and the lines from the block before the current query that is not deleted yet. There are no more than lines from the block, so we can iterate over them. Let's find the answers from the envelope for all queries of the third type from the block at once: we should sort them and iterate over envelope using two pointers technique.

C++ solution

Complexity: .

Full text and comments »

  • Vote: I like it
  • +32
  • Vote: I do not like it

By Edvard, history, 8 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 13 will take place on 13 June 2016 at 19:00 MSK for the first and the second divisions. Almost two months passed from the previous round. That is due the next reasons: 1) I coordinated regular CF-round at the end of April; 2) about whole CP community were busy with preparing and competing in ACM ICPC WF in May; 3) at the beginning of this month I start to work at AimTech (I hope that I'll have enough time to continue prepare ERs).

<It's need to read at least once maybe you'll find something interesting>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks (of course the difficult tasks are also needed). Please send only the problems for which you know the solution with clear statement (the story is not required). And also please add one or two samples to make the problem statement more clear.

</It's need to read at least once maybe you'll find something interesting>

The problemset was suggested by Codeforces users. The problem А was suggested by user Abdrakhman Ismail bash. The problem B was suggested by Arthur Jaworski KingArthur. The problem C was suggested by Sheikh Monir skmonir. The problem D was suggested by Zi Song Yeoh zscoder (there are a lot of unused his problems). The problem E was suggested and prepared by Alexey Dergunov dalex. The simpler version of the problem F was suggested by AmirMohammad Dehghan PrinceOfPersia.

Thanks a lot to them and all others who are sending the problems! The number of unused problems are increasing. If I didn't miss anything I already replied to all who sent me the problems at least 5-6 days ago. Please be patient if your problem was not used a long while.

As I said the problem E is prepared by Alexey Dergunov dalex. All other problems was prepared by me (Edvard Davtyan). Thanks to Tatiana Semyonova Tatiana_S for checking the English statements. The problems was tested by users suggested them, respectively: Abdrakhman Ismail bash, Arthur Jaworski KingArthur, Sheikh Monir skmonir, Zi Song Yeoh zscoder, Alexey Dergunov dalex and AmirMohammad Dehghan PrinceOfPersia. Thanks a lot to all of them!

I hope you will enjoy the problems! Previous time the problems were too hard. I've tried to fix that. The problems should be simpler than usual.

Good luck and have fun!

UPD: The round is finished. The editorial is published.

It's the first summer round :-)

Full text and comments »

  • Vote: I like it
  • +185
  • Vote: I do not like it

By Edvard, history, 8 years ago, In English

Hey, Codeforces!

I've just submitted a solution for a SPOJ problem and get strange verdict. I'm using SPOJ for the first time and can't find any FAQ section there. What does it mean? And why my submission is black?

Full text and comments »

  • Vote: I like it
  • +15
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

665A - Buses Between Cities

The problem was suggested by Sergey Erlikh unprost.

Consider the time interval when Simion will be on the road strictly between cities (x1, y1) (x1 = 60h + m, y1 = x1 + ta). Let's iterate over the oncoming buses. Let (x2, y2) be the time interval when the oncoming bus will be strictly between two cities. If the intersection of that intervals (x = max(x1, x2), y = min(y1, y2)) is not empty than Simion will count that bus.

С++ solution

Complexity: O(1).

665B - Shopping

The problem was suggested by Ayush Anand JeanValjean01.

In this problem you should simply do what was written in the problem statement. There are no tricks.

C++ solution

Complexity: O(nmk).

665C - Simple Strings

The problem was suggested by Zi Song Yeoh zscoder.

There are two ways to solve this problem: greedy approach and dynamic programming.

The first apprroach: Considerr some segment of consecutive equal characters. Let k be the length of that segment. Easy to see that we should change at least characters in the segment to remove all the pairs of equal consecutive letters. On the other hand we can simply change the second, the fourth etc. symbols to letter that is not equal to the letters before and after the segment.

Greedy approach on C++

The second approach: Let zka be the minimal number of changes so that the prefix of length k has no equal consecutive letters and the symbol s'k equals to a. Let's iterate over the letter on the position k + 1 and if it is not equal to a make transition. The cost of the transition is equal to 0 if we put the same letter as in the original string s on the position k + 1. Otherwise the cost is equal to 1.

DP solution on C++

Complexity: O(n).

665D - Simple Subset

The problem was suggested by Zi Song Yeoh zscoder.

Consider the subset A that is the answer to the problem. Let a, b, c be the arbitrary three elements from A and let no more than one of them is equal to 1. By the pigeonhole principle two of three elements from a, b, c have the same parity. So we have two integers with even sum and only one of them is equal to 1, so their sum is also greater than 2. So the subset A is not simple. In this way A consists of only two numbers greater than one (with a prime sum) or consists of some number of ones and also maybe other value x, so that x + 1 is a prime.

We can simply process the first case in O(n2) time. The second case can be processed in linear time. Also we should choose the best answer from that two.

To check the value of order 2·106 for primality in O(1) time we can use the simple or the linear Eratosthenes sieve.

C++ solution

Complexity: O(n2 + X), where X is the maximal value in a.

665E - Beautiful Subarrays

The problem was suggested by Zi Song Yeoh zscoder.

The sign is used for the binary operation for bitwise exclusive or.

Let si be the xor of the first i elements on the prefix of a. Then the interval (i, j] is beautiful if . Let's iterate over j from 1 to n and consider the values sj as the binary strings. On each iteration we should increase the answer by the value zj — the number of numbers si (i < j) so . To do that we can use the trie data structure. Let's store in the trie all the values si for i < j. Besides the structure of the trie we should also store in each vertex the number of leaves in the subtree of that vertex (it can be easily done during adding of each binary string). To calculate the value zj let's go down by the trie from the root. Let's accumulate the value cur equals to the xor of the prefix of the value sj with the already passed in the trie path. Let the current bit in sj be equal to b and i be the depth of the current vertex in the trie. If the number cur + 2i ≥ k then we can increase zj by the number of leaves in vertex , because all the leaves in the subtree of tha vertex correspond to the values si that for sure gives . After that we should go down in the subtree b. Otherwise if cur + 2i < k then we should simply go down to the subtree and recalculate the value cur = cur + 2i.

C++ solution

Comlpexity by the time and the memory: O(nlogX), where X is the maximal xor on the prefixes.

665F - Four Divisors

The editorial for this problem is a little modification of the materials from the lecture of Mikhail Tikhomirov Endagorion of the autumn of 2015 in Moscow Institute of Physics and Technology. Thanks a lot to Endagorion for that materials.

Easy to see that only the numbers of the form p·q and p3 (for different prime p, q) have exactly four positive divisors.

We can easily count the numbers of the form p3 in , where n is the number from the problem statement.

Now let p < q and π(k) be the number of primes from 1 to k. Let's iterate over all the values p. Easy to see that . So for fixed p we should increase the answer by the value .

So the task is ot to find — the number of primes not exceeding , for all p.

Denote pj the j-th prime number. Denote dpn, j the number of k such that 1 ≤ k ≤ n, and all prime divisors of k are at least pj (note that 1 is counted in all dpn, j, since the set of its prime divisors is empty). dpn, j satisfy a simple recurrence:

  1. dpn, 1 = n (since p1 = 2)

  2. dpn, j = dpn, j + 1 + dpn / pj⌋, j, hence dpn, j + 1 = dpn, j - dpn / pj⌋, j

Let pk be the smallest prime greater than . Then π(n) = dpn, k + k - 1 (by definition, the first summand accounts for all the primes not less than k).

If we evaluate the recurrence dpn, k straightforwardly, all the reachable states will be of the form dpn / i⌋, j. We can also note that if pj and pk are both greater than , then dpn, j + j = dpn, k + k. Thus, for each n / i it makes sense to keep only values of dpn / i⌋, j.

Instead of evaluating all DP states straightforwardly, we perform a two-step process:

  1. Choose K.

  2. Run recursive evaluation of dpn, k. If we want to compute a state with n < K, memorize the query ``count the numbers not exceeding n with all prime divisors at least k''.

  3. Answer all the queries off-line: compute the sieve for numbers up to K, then sort all numbers by the smallest prime divisor. Now all queries can be answered using RSQ structure. Store all the answers globally.

  4. Run recurisive evaluation of dpn, k yet again. If we want to compute a state with n < K, then we must have preprocessed a query for this state, so take it from the global set of answers.

The performance of this approach relies heavily on Q — the number of queries we have to preprocess.

Statement. .

Proof:

Each state we have to preprocess is obtained by following a dpn / pj⌋, j transition from some greater state. It follows that Q doesn't exceed the total number of states for n > K.

The preprocessing of Q queries can be done in , and it is the heaviest part of the computation. Choosing optimal , we obtain the complexity .

C++ solution

Complexity: .

Full text and comments »

  • Vote: I like it
  • +70
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Note! The day of the contest here was wrong. Now it's fixed.

Educational Codeforces Round 12 will take place on 20 april 2016 at 18:00 MSK for the first and the second divisions.

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks (of course the difficult tasks are also needed). Please send only the problems for which you know the solution with clear statement (the story is not required). And also please add one or two samples to make the problem statement more clear.

The problemset was suggested by Codeforces users (it's time to lift this sentence inside the tegs). The problem А was suggested by user unprost. The problem B was suggested by Ayush Anand JeanValjean01. The problems C, D and E was suggested by Zi Song Yeoh zscoder. Sheikh Monir skmonir a long ago sent me a problem with difficulty C or D. I improved it by significant increase of the constraints (thanks to Mikhail Tikhomirov Endagorion who told how to solve such things). So the problem F was born.

Thanks a lot to them and all others who are sending the problems! The number of unused problems are increasing. If I didn't miss anything I already replied to all who sent me the problems at least 5-6 days ago. Please be patient if your problem was not used a long while.

The problems was prepared by me (Edvard Davtyan). Thanks to Maria Belova Delinur for checking the English statements. The problems was tested by users suggested them, respectively: unprost, Ayush Anand JeanValjean01, Zi Song Yeoh zscoder and Sheikh Monir skmonir. Thanks a lot to all of them!

I hope you will enjoy the problems! On my mind all the problems except of F is easier than usual, but F is harder.

Good luck and have fun!

Only 30 days left to the ACM ICPC World Finals!

It will be difficult to focus on the problems in such a beautiful place :-)

UPD1: The first part of the contest is finished. The open hacks will be opened in a few minutes.

UPD2: The editorial is ready for the problem F.

UPD3: The editorial is ready.

Full text and comments »

  • Vote: I like it
  • +255
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

660A - Co-prime Array

The problem was suggested by Ali Ibrahim C137.

Note that we should insert some number between any adjacent not co-prime elements. On other hand we always can insert the number 1.

С++ solution

Complexity: O(nlogn).

660B - Seating On Bus

The problem was suggested by Srikanth Bhat bharsi.

In this problem you should simply do what was written in the problem statement. There are no tricks.

C++ solution

Complexity: O(n).

660C - Hard Process

The problem was suggested by Mohammad Amin Raeisi Smaug.

Let's call the segment [l, r] good if it contains no more than k zeroes. Note if segment [l, r] is good than the segment [l + 1, r] is also good. So we can use the method of two pointers: the first pointer is l and the second is r. Let's iterate over l from the left to the right and move r while we can (to do that we should simply maintain the number of zeroes in the current segment).

C++ solution

Complexity: O(n).

660D - Number of Parallelograms

The problem was suggested by Sadegh Mahdavi smahdavi4.

It's known that the diagonals of a parallelogram split each other in the middle. Let's iterate over the pairs of points a, b and consider the middle of the segment : . Let's calculate the value cntc for each middle. cntc is the number of segments a, b with the middle c. Easy to see that the answer is .

C++ solution

Complexity: O(n2logn).

660E - Different Subsets For All Tuples

The problem was suggested by Lewin Gan Lewin.

Let's consider some subsequence with the length k > 0 (the empty subsequences we will count separately by adding the valye mn at the end) and count the number of sequences that contains it. We should do that accurately to not count the same sequence multiple times. Let x1, x2, ..., xk be the fixed subsequence. In the original sequence before the element x1 can be some other elements, but none of them can be equal to x1 (because we want to count the subsequence exactly one time). So we have m - 1 variants for each of the elements before x1. Similarly between elements x1 and x2 can be other elements and we have m - 1 choices for each of them. And so on. After the element xk can be some elements (suppose there are j such elements) with no additional constraints (so we have m choices for each of them). We fixed the number of elements at the end j, so we should distribute n - k - j numbers between numbers before x1, between x1 and x2, \ldots, between xk - 1 and xk. Easy to see that we have choices to do that (it's simply binomial coefficient with allowed repititions). The number of sequences x1, x2, ..., xk equals to mk. So the answer is . Easy to transform the last sum to the sum . Note the last inner sum can be calculating using the formula for parallel summing: . So the answer equals to . Also we can get the closed formula for the last sum to get logarithmic solution, but it is not required in the problem.

C++ solution

Complexity: O((n + m)log MOD), где MOD = 109 + 7.

660F - Bear and Bowling 4

The problem was prepared by Kamil Debowski Errichto. The problem analysis is also prepared by him.

The key is to use divide and conquer. We need a recursive function f(left, right) that runs f(left, mid) and f(mid+1, right) (where mid = (left + right) / 2) and also considers all intervals going through mid. We will eventually need a convex hull of lines (linear functions) and let's see how to achieve it.

For variables L, R (, ) we will try to write the score of interval [L, R] as a linear function. It would be good to get something close to aL·xR + bL where aL and bL depend on L, and xR depends on R only.

For each L we should find a linear function fL(x) = aL·x + bL where aL, bL should fit the equation ( * ):

Now we have a set of linear functions representing all possible left endpoints L. For each right endpoint R we should find xR and constR to fit equation ( * ) again. With value of xR we can iterate over functions fL to find the one maximizing value of bL + aL·xR. And (still for fixed R) we should add constR to get the maximum possible score of interval ending in R.

Brute Force with functions

Now let's make it faster. After finding a set of linear functions fL we should build a convex hull of them (note that they're already sorted by slope). To achieve it we need something to compare 3 functions and decide whether one of them is unnecessary because it's always below one of other two functions. Note that in standard convex hull of points you also need something similar (but for 3 points). Below you can find an almost-fast-enough solution with a useful function bool is_middle_needed(f1, f2, f3). You may check that numbers calculated there do fit in long long.

Almost fast enough

Finally, one last thing is needed to make it faster than O(n2). We should use the fact that we have built a convex hull of functions (lines). For each R you should binary search optimal function. Alternatively, you can sort pairs (xR, constR) and then use the two pointers method — check the implementation in my solution below. It gives complexity because we sort by xR inside of a recursive function. I think it's possible to get rid of this by sorting prefixes in advance because it's equivalent to sorting by xR. And we should use the already known order when we run a recursive function for smaller intervals. So, I think is possible this way — anybody implemented it?

Intended solution with two pointers

Complexity: O(nlog2n).

Full text and comments »

  • Vote: I like it
  • +32
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 11 will take place on 8 april 2016 at 18:00 MSK for the first and the second divisions.

<The changes in the last paragraph>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks (of course the difficult tasks are also needed). Please send only the problems for which you know the solution with clear statement (the story is not required). And also please add one or two samples to make the problem statement more clear.

</The changes in the last paragraph>

The problemset was suggested by Codeforces users. The problem А was suggested by Ali Ibrahim C137. The problem B was suggested by Srikanth Bhat bharsi. Mohammad Amin Raeisi Smaug sent the problem C. The problem D was suggested by Sadegh Mahdavi smahdavi4 a long ago. The problem E is the last (the fourth) problem suggested by Lewin Gan Lewin. The problem F is the last (if I'm not wrong the third) problem suggested by Kamil Debowski Errichto.

Thanks a lot to them and all others who are sending the problems! At this point I've checked all the problems sent to me (except maybe for the problems sent in last week). I hope that I've replied to all of you. I have a list with all problems sent to me, so be sure I don't forget about your problem.

The problems F was prepared by Kamil Debowski Errichto. Other problems was prepared by me (Edvard Davtyan). Thanks to Maria Belova Delinur for checking the English statements. The problems was tested by users suggested them, respectively: Ali Ibrahim C137, Srikanth Bhat bharsi, Mohammad Amin Raeisi Smaug, Sadegh Mahdavi smahdavi4, Lewin Gan Lewin and Kamil Debowski Errichto. Thanks a lot to all of them!

I hope you will enjoy the problems! I'm considering the possibility to copy the problem E with larger constraints as problem G. What do you think about that?

Good luck and have fun!

P.S.: The bus from the problem B.

UPD: The contest is finished. Congrats to tribute_to_Ukraine_2022 and uwi with the win and halyavin with 93 hacks! The editorial is ready.

Full text and comments »

  • Vote: I like it
  • +160
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

652A - Gabriel and Caterpillar

The problem was suggested by unprost.

Let's consider three cases.

  1. h1 + 8a ≥ h2 — in this case the caterpillar will get the apple on the same day, so the answer is 0.

  2. The first condition is false and a ≤ b — in this case the caterpillar will never get the apple, because it can't do that on the first day and after each night it will be lower than one day before.

  3. If the first two conditions are false easy to see that the answer equals to .

C++ solution

Also this problem can be solved by simple modelling, because the heights and speeds are small.

Complexity: O(1).

652B - z-sort

The problem was suggested by Smaug.

Easy to see that we can z-sort any array a. Let be the number of even positions in a. We can assign to those positions k maximal elements and distribute other n - k elements to odd positions. Obviously the resulting array is z-sorted.

C++ solution

Complexity: O(nlogn).

652C - Foe Pairs

This is one of the problems suggested by Bayram Berdiyev bayram, Allanur Shiriyev Allanur, Bekmyrat Atayev Bekmyrat.A.

Let's precompute for each value x its position in permutation posx. It's easy to do in linear time. Consider some foe pair (a, b) (we may assume posa < posb). Let's store for each value a the leftmost position posb such that (a, b) is a foe pair. Denote that value as za. Now let's iterate over the array a from right to left and maintain the position rg of the maximal correct interval with the left end in the current position lf. To maintain the value rg we should simply take the minimum with the value z[lf]: rg = min(rg, z[lf]). And finally we should increment the answer by the value rg - lf + 1.

C++ solution

Complexity: O(n + m).

652D - Nested Segments

The problem was suggested by Alexey Dergunov dalex.

This problem is a standard two-dimensional problem that can be solved with one-dimensional data structure. In the same way a lot of other problems can be solved (for example the of finding the maximal weighted chain of points so that both coordinates of each point are greater than the coordinates of the predecessing point). Rewrite the problem formally: for each i we should count the number of indices j so that the following conditions are hold: ai < aj and bj < aj. Let's sort all segments by the left ends from right to left and maintain some data structure (Fenwick tree will be the best choice) with the right ends of the processed segments. To calculate the answer for the current segment we should simple take the prefix sum for the right end of the current segment.

So the condition ai < aj is hold by sorting and iterating over the segments from the right to the left (the first dimension of the problem). The condition bj < aj is hold by taking the prefix sum in data structure (the second dimension).

C++ solution

Complexity: O(nlogn).

652E - Pursuit For Artifacts

The problem was suggested by Alexey Dergunov dalex.

Edge biconnected component in an undirected graph is a maximal by inclusion set of vertices so that there are two edge disjoint paths between any pair of vertices. Consider the graph with biconnected components as vertices. Easy to see that it's a tree (if it contains some cycle then the whole cycle is a biconnected component). All edges are destroying when we passing over them so we can't returnto the same vertex (in the tree) after leaving it by some edge.

Consider the biconncted components that contains the vertices a and b. Let's denote them A and B. Statement: the answer is YES if and only if on the path in the tree from the vertex A to the vertex B there are an edge with an artifact or there are a biconnected component that contains some edge with an artifact. Easy to see that the statement is true: if there are such edge then we can pass over it in the tree on the path from A to B or we can pass over it in biconnected component. The converse also easy to check.

Here is one of the ways to find edge biconnected components:

  1. Let's orient all edges to direction that depth first search passed it for the first time.

  2. Let's find in new directed graph strongly connected components.

Statement: the strongly connected components in the new graph coincide with the biconnected components in old undirected graph.

Also you can notice that the edges in tree is the bridges of the graph (bridges in terms of graph theory). So you can simply find the edges in the graph.

Not too short C++ solution

Complexity: O(n + m).

652F - Ants on a Circle

The problem was suggested by Lewin Gan Lewin.

The first observation: if all the ants are indistinguishable we can consider that there are no collisions and all the ants are passing one through another. So we can easily determine the final positions of all the ants, but we can't say which ant will be in which position.

The second observation: the relative order of the ants will be the same all the time.

So to solve the problem we should only find the position of one ant after t seconds.

Let's solve that problem in the following way:

  1. Consider the positions of all the ants after m time units. Easy to see that by the first observation all the positions of the ants will left the same, but the order will be different (we will have some cyclic shift of the ants). If we find that cyclic shift sh we can apply it times.

  2. After that we will have only t ± od m time units.

So the problem now is to model the process for the one ant with m and r ± od m time units. Note that in that time interval the fixed ant will have no more than two collisions with each other ant. So if we model the process with ignoring all collisions except the ones that include the fixed ant, we will have no more than 2n collisions.

Let's model that process with two queues for the ants going to the left and to the right. Each time we should take the first ant in the queue with opposite direction, process the collision and add that ant to the end of the other queue.

Hint: you will have a problem when the fixed ant can be in two different positions at the end, but it's easy to fix with doing the same with the next ant.

C++ solution

Complexity: O(nlogn).

Full text and comments »

  • Vote: I like it
  • +43
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

[Note the unusual (for the educational round) start time!]

Educational Codeforces Round 10 will take place after a long delay on 25 march 2016 at 16:00 MSK for the first and the second divisions. The long delay is caused by the high frequency of contests and championships on Codeforces. You can read about educational rounds here and here.

<The same as before>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks.

</The same as before>

From now traditionally the problemset was totally suggested by Codeforces users. The problem А for the third time was suggested by user unprost (no hope for the short problem statement :-)). The problem B was suggested by user Smaug. The problem C is another problem from the set sent by Bayram Berdiyev bayram, Allanur Shiriyev Allanur and Bekmyrat Atayev Bekmyrat.A. Alexey Dergunov dalex suggested the problems D and E. The problem F was suggested by Lewin Gan Lewin.

Thanks a lot to them and all others who are sending the problems or just ideas of the problems!

The problems D and E was prepared by Alexey Dergunov dalex. Other problems was prepared by me (Edvard Davtyan). I want to note the generator for the problem E its difficulty comparable with the solution to the problem F. Thanks to Maria Belova Delinur for checking the English statements. The problems was tested by users: unprost, Smaug, Aleksa Plavsic allllekssssa, Alexey Dergunov dalex and Lewin Gan Lewin. Thanks a lot to all of them!

I hope you will enjoy the problems!

P.S.: I really like the problem F and hope to see Accepted-s for it.

Good luck and have fun!

UPD: The contest is finished. The editorial is ready.

Full text and comments »

  • Vote: I like it
  • +192
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

632A - Grandma Laura and Apples

The problem was suggested by unprost.

Consider the process from the end. The last buyer will always buy a half of an apple and get a half for free (so the last string always is halfplus). After that each buyer increases the number of apples twice and also maybe by one. So we simply have the binary presentation of the number of apples from the end. To calculate the answer we should simply restore that value from the end and also calculate the total money grandma should have.

С++ solution by me.

С++ solution by unprost.

Complexity: O(p).

632B - Alice, Bob, Two Teams

The problem was suggested by Lewin Gan Lewin.

Let's calculate the prefix sums for all numbers (and store it in array s1) and for numbers with letter B (and store it in array s2). Now we can find the sum of all numbers in any segment in O(1) time and the sum of numbers with letter B.

Let's iterate over prefix or suffix to flip and calculate the sum in that case by formulas: sum(s1, 0, n - 1) + sum(s2, 0, i) - 2·sum(s1, 0, i) for prefixes and sum(s1, 0, n - 1) + sum(s2, i, n - 1) - 2·sum(s1, i, n - 1) for suffixes.

C++ solution by me.

Python solution by Lewin.

Complexity: O(n).

632C - The Smallest String Concatenation

The problem was suggested by Lewin Gan Lewin. The proof of the transitivity also belongs to him.

Let's sort all the strings by comparator a + b < b + a and concatenate them. Let's prove that it's the optimal answer. Let that operator be transitive (so if ). Consider an optimal answer with two strings in reverse order by that operator. Because of the transitivity of operator we can assume that pair of strings are neighbouring. But then we can swap them and get the better answer.

Let's prove the transitivity of operator. Consider the strings as the 26-base numbers. Then the relation a + b < b + a equivalent to . The last is simply the relation between real numbers. So we proved the transitivity of the relation a + b < b + a.

C++ solution by me.

Python solution by Lewin.

Complexity: O(nLlogn), where L is the maximal string length.

632D - Longest Subsequence

The problem was suggested by Denis Bezrukov pitfall.

Let cntx be the number of occurences of the number x in the given array (easy to see that we can ignore the numbers greater than m). Let's iterate over and 1 ≤ k, x·k ≤ m and increase the value in the position k·x in some array z by the value cntx. So the value zl equals the number of numbers in the given array which divide l. Let's find the minimal l with the maximum value zl (1 ≤ l ≤ m). Easy to see that the answer to the problem is the numbers which divide l.

Let's calculate the complexity of the solution. The number of the pairs (k, x) we can bound with the value .

C++ solution by me.

Java solution by pitfall.

Complexity: O(n + mlogm).

632E - Thief in a Shop

The problem was suggested by Alexey Chesnokov CleRIC.

Let k = 2, then it is the standard problem which can be solved by FFT (Fast Fourier Transform). The solution is the following: consider the polynomial which the i-th coefficient equals to one if and only if there is the number i in the given array. Let's multiply that polynomial by itself and find i for which the coefficient in square not equals to 0. Those values i will be in the answer. Easy to modificate the solution for the arbitrary k. We should simply calculate the k-th degree of the polynomial. The complexity will be WlogWlogk, where W is the maximal sum.

We can improve that solution. Instead of calculating the k-th degree of the polynomial we can calculate the k-th degree of the DFT of the polynomial. The only problem is the large values of the k-th degrees. We can't use FFT with complex numbers, because of the precision problems. But we can do that with NTT (Number-theoretic transform). But that solution also has a problem. It can happen that some coefficients became equals to zero modulo p, but actually they are not equal to zero. To get round that problem we can choose two-three random modules and get the complexity O(W(logW + logk)).

The main author solution has the complexity O(WlogWlogk) (FFT with complex numbers), the second solution has the same complexity, but uses NTT and the third solution has the improved complexity (but it was already hacked by halyavin).

С++ solution, complex FFT by me.

С++ solution, NTT by me.

С++ solution, improved NTT by me.

С++ solution by CleRIC.

P.S.: To get faster solution you should each time multiply the polynomials of the required degree, but not of the degree 220.

Complexity: O(WlogWlogk) or O(W(logW + logk)), depending the bravery of the coder :-)

UPD: It turns out that the first approach also has complexity O(W(logW + logk)). See below the comment of halyavin.

632F - Magic Matrix

The problem was suggested by Lewin Gan Lewin. The solution and proof also belongs to him.

Consider the undirected complete graph with n nodes, with an edge between nodes i, j with cost aij. Let Bij denote the minimum possible value of the max edge of a path from i to j. We know that aij ≥ Bij by definition.

If the matrix is magic, we can choose arbitrary k1, k2, ..., km such that aij ≤ max(ai, k1, ak1, k2, ..., akm, j) by repeating invocations of the inequality given. Also, you can show that if this inequality is satisfied, then the matrix is magic (by choosing an m = 1 and k1 arbitrary).

So, this shows that the matrix is magic if and only if aij ≤ Bij. Thus, combining with aij ≥ Bij, we have aij = Bij.

We need a fast way to compute Bij for all pairs i, j. This can be computed as the MST, as the path in the MST minimizes the max edge between all pairs of nodes. So, the algorithm works as follows. First, find the MST on the complete graph. Then, the matrix is magic if and only if the max edge on the path between i, j in the MST is exactly equal to ai, j. Also you shouldn't forget to check symmetry of the matrix and diagonal for zeros.

P.S.: Unfortunately we couldn't increase the value n in this problem: the tests already had the size about 67MB and they couldn't be given with generator. So most of the users who solved this problem uses bitset-s. The complexity of their solution is , where b = 32 or b = 64.

C++ solution, binary lifts by me.

Java solution by Lewin.

Complexity: O(n2logn) or O(n2).

Full text and comments »

  • Vote: I like it
  • +65
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Today is the first day of the spring and it's great!

Educational Codeforces Round 9 will take place on 01 march 2016 at 18:00 MSK for the first and the second divisions. You can read about educational rounds here and here. I should again notice the high density of contests and championships.

<This time it wasn't changed>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks.

</This time it wasn't changed>

The problemset again was totally suggested by Codeforces users. The problem А again was suggested by user unprost (be ready to see a long problem statement). The problem D suggested by Denis Bezrukov pitfall. Alexey Chesnokov CleRIC sent the problem E a long ago. The problems B, C and F was suggested by Lewin Gan Lewin.

Thanks a lot to them and all others who are sending the problems or just ideas of the problems!

The problems was prepared by me (Edvard Davtyan). Thanks to Maria Belova Delinur for checking the English statements. The problems was tested by the same users who suggested them: unprost, Alexey Chesnokov CleRIC and Lewin Gan Lewin. Thanks a lot to all of them!

I hope you will enjoy the problems!

Good luck and have fun!

UPD1: The first part of the contest is finished. You can hack solutions.

UPD2: There are some technical problems. The phase of open hacks will be opened later (several hours).

UPD3: Editorial is ready.

UPD4: The contest is finished. We will start system testing in a few minutes.

UPD5: TOP3 of hackers:

P_Nyagolov31 hacks

khadaev27 hacks

halyavin23 hacks

Full text and comments »

  • Vote: I like it
  • +193
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

628A - Tennis Tournament

The problem was suggested by unprost.

Here you can simply model the process. Or you can note that after each match some player drops out. In total n - 1 players will drop out. So the first answer is (n - 1) * (2b + 1). Obviously the second answer is np.

С++ solution 1

С++ solution 2

Complexity: O(log2n), O(logn) or O(1) depends on the realization.

628B - New Skateboard

This is one of the problems suggested by Bayram Berdiyev bayram, Allanur Shiriyev Allanur, Bekmyrat Atayev Bekmyrat.A.

The key observation is that the number is divisible by 4 if and only if its last two digits forms a number divisible by 4. So to calculate the answer at first we should count the substrings of length one. Now let's consider pairs of consecutive digits. If they forms a two digit number that is divisible by 4 we should increase the answer by the index of the right one.

C++ solution

Complexity: O(n).

628C - Bear and String Distance

The problem was suggested and prepared by Kamil Debowski Errichto. He also wrote the editorial.

There is no solution if the given required distance is too big. Let's think what is the maximum possible distance for the given string s. Or the more useful thing — how to construct a string s' to maximize the distance? We can treat each letter separately and replace it with the most distant letter. For example, we should replace 'c' with 'z', and we should replace 'y' with 'a'. To be more precise, for first 13 letters of the alphabet the most distant letter is 'z', and for other letters it is 'a'.

Let's solve a problem now. We can iterate over letters and greedily change them. A word "greedily" means when changing a letter we don't care about the next letters. We generally want to choose distant letters, because we may not find a solution otherwise. For each letter si we change it into the most distant letter, unless the total distance would be too big. As we change letters, we should decrease the remaining required distance. So, for each letter si consider only letters not exceeding the remaining distance, and among them choose the most distant one. If you don't see how to implement it, refer to my C++ solution with comments.

Other C++ solution

Complexity: O(n).

628D - Magic Numbers

Kareem Mohamed Kareem_Mohamed suggested the simpler version of the problem.

Denote the answer to the problem f(a, b). Note that f(a, b) = f(0, b) - f(0, a - 1) or what is the same f(a, b) = f(0, b) - f(0, a) + g(a), where g(a) equals to one if a is a magic number, otherwise g(a) equals to zero. Let's solve the problem for the segment [0, n].

Here is described the standard technique for this kind of problems, sometimes it is called 'dynamic programming by digits'. It can be realized in a two ways. The first way is to iterate over the length of the common prefix with number n. Next digit should be less than corresponding digit in n and other digits can be arbitrary. Below is the description of the second approach.

Let zijk be the number of magic prefixes of length i with remainder j modulo m. If k = 0 than the prefix should be less than the corresponding prefix in n and if k = 1 than the prefix should be equal to the prefix of n (it can not be greater). Let's do 'forward dynamic programming'. Let's iterate over digit in position i. We should check that if the position is even than p should be equal to d, otherwise it cannot be equal to d. Also we should check for k = 1 p should be not greater than corresponding digit in n. Now let's see what will be the next state. Of course i' = i + 1. By Horner scheme j' = (10j + p) mod m. Easy to see that . To update the next state we should increase it: zi'j'k' +  = zijk. Of course all calculations should be done modulo 109 + 7.

C++ solution

Complexity: O(nm).

628E - Zbazi in Zeydabad

The problem was suggested by Ali Ahmadi Kuzey.

Let's precalculate the values zlij, zrij, zldij — the maximal number of letters 'z' to the left, to the right and to the left-down from the position (i, j). It's easy to do in O(nm) time. Let's fix some cell (i, j). Consider the value c = min(zlij, zldij). It's the maximum size of the square with upper right ceil in (i, j). But the number of z-patterns can be less than c. Consider some cell (x, y) diagonally down-left from (i, j) on the distance no more than c. The cells (i, j) and (x, y) forms z-pattern if y + zrxy > j.

Let's maintain some data structure for each antidiagonal (it can be described by formula x + y) that can increment in a point and take the sum on a segment (Fenwick tree will be the best choice for that). Let's iterate over columns j from the right to the left and process the events: we have some cell (x, y) for which y + zrxy - 1 = j. In that case we should increment the position y in the tree number x + y by one. Now we should iterate over the cells (x, y) in the current column and add to the answer the value of the sum on the segment from j - c + 1 to j in the tree number i + j .

С++ solution

Complexity: O(nmlogm).

628F - Bear and Fair Set

The problem was suggested and prepared by Kamil Debowski Errichto. He also wrote the editorial.

At the beginning, to make things simpler, we should add a query (hint) with upTo = b, quantity = n, and then sort queries by upTo. Sorted queries (hints) divide interval [1, b] into q disjoint intervals. For each interval we know how many elements should be there.

Let's build a graph and find a max flow there. The answer is "YES" only if the flow is n.

  • The first group A contains 5 vertices, representing possible remainders.
  • The second group B contains q vertices, representing intervals.

Each vertex from A should be connected with the source by an edge with capacity n / 5. Each vertex from B should be connected with the sink by an edge with capacity equal to the size of the interval. Between each vertex x from A and y from B should be an edge with capacity equal to the number of numbers in the interval y, giving remainder x when divided by 5.

You can also use see that it's similar to finding matching. In fact, we can use the Hall's marriage theorem. For each of 25 sets of vertices from A (sets of remainders) iterate over intervals and count how many numbers we can take from [1, b] with remainders from the fixed set of remainders.

The implementation with the Hall's theorem: C++ solution.

Complexity: O(2Cn). In our problem C = 5.

Full text and comments »

  • Vote: I like it
  • +65
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 8 will take place on 19 February 2016 at 18:00 MSK for the first and the second divisions. You can read about educational rounds here and here. I hope that the high density of contests on Codeforces will not startle you and you will participate in ER8.

<The phrase about simple problems is added in the end>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

It seems that it is harder to invent interesting simple problems (like A and B) than difficult ones. So don't be afraid to suggest interesting simple or very simple tasks.

</The phrase about simple problems is added in the end>

This time (for the first time) the problemset was totally suggested by Codeforces users. The problem А suggested by user unprost. The problem B was taken form the problems sent by Bayram Berdiyev bayram, Allanur Shiriyev Allanur, Bekmyrat Atayev Bekmyrat.A. The problem D suggested by Kareem Mohamed Kareem_Mohamed (but I made it more difficult to make it more interesting for you :-)). The problem E sent Ali Ahmadi Kuzey. The problems C and F are suggested by Kamil Debowski Errichto.

Thanks a lot to them and all others who are sending the problems or just ideas of the problems!

This time the problems wasn't prepared only by me (Edvard Davtyan). Thanks a lot to Kamil Debowski Errichto who not only suggested the problems C and F, but also prepared them. Thanks to Maria Belova Delinur for checking the English statements. Also thanks a lot to Ali Ahmadi Kuzey who helped me with testing of some problems.

A few words about the problems: A) Easy problem with the long statement; B) I hope you will not write hard solution; C) It's interesting; D) It's a little technical, but contains very useful technique; E) I like this problem; F) Very cool problem if you will not solve during the contest I recommend to solve it in practice.

Good luck and have fun!

UPD1: The first phase of the contest finished. Hacks started. The editorial is ready.

By the reason that all the problems of Errichto are about a bears, below you can see the illustration for the problem C (it seems Limak is the leftmost):

Full text and comments »

  • Vote: I like it
  • +200
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

622A - Infinite Sequence

Let's decrease n by one. Now let's determine the block with the n-th number. To do that let's at first subtract 1 from n, then subtract 2, then subtract 3 and so on until we got negative n. The number of subtractions will be the number of the block and the position in the block will be the last nonnegative number we will get.

С++ solution

Complexity: .

622B - The Time

In this problem we can simply increase a times the current time by one minute (after each increasing we should check the hours and the minutes for overflow).

Another solution is to use the next formulas as the answer: .

C++ solution 1

C++ solution 2

Complexity: O(a) or O(1).

622C - Not Equal on a Segment

This problem is a simplified version of the problem suggested by Mohammad Nematollahi Deemo.

This problem can be solved differently. For example you can use some data structures or sqrt-decomposition technique. But it is not required. We expected the following simple solution from the participants. Let's preprocess the following values pi — the position of the first element to the left from the i-th element such that ai ≠ api. Now to answer to the query we should check if ar ≠ x then we have the answer. Otherwise we should check the position pr.

C++ solution

Complexity: O(n).

622D - Optimal Number Permutation

This problem was suggested by Aleksa Plavsic allllekssssa.

Let's build the answer with the sum equal to zero. Let n be even. Let's place odd numbers in the first half of the array: the number 1 in the positions 1 and n, the number 3 in the positions 2 and n - 1 and so on. Similarly let's place even numbers in the second half: the number 2 in the position n + 1 and 2n - 1, the number 4 in the positions n + 2 and 2n - 2 and so on. We can place the number n in the leftover positions. We can build the answer for odd n in a similar way.

Easy to see that our construction will give zero sum.

C++ solution

Complexity: O(n).

622E - Ants in Leaves

This problem was suggested by Aleksa Plavsic allllekssssa.

Easy to see that the answer is equal to the answer over all sons of the root plus one. Now let's solve the problem independently for each son v of the root. Let z be the array of the depths of all leaves in the subtree of the vertex v. Let's sort z. Statement 1: it's profitable to lift the leaves in order of their appearing in z. Statement 2: denote ax — the time of appearing the x-th leaf in the vertex v, let's consider the leaves zi and zi + 1 then azi + 1 ≥ azi + 1. Statement 3: azi + 1 = max(dzi + 1, azi + 1), where dx is the depth of the x-th leaf in the subtree of the vertex v. The last statement gives us the solution for the problem: we should simply iterate over z from left to right and recalculate the array a by formula from the third statement. All statements can be easily proved and it's recommended to do by yourself to understand better the idea of the solution.

С++ solution

Complexity: O(nlogn).

622F - The Sum of the k-th Powers

This problem was suggested by Ivan Popovich NVAL.

Statement: the function of the sum is a polynomial of degree k + 1 over variable n. This statement can be proved by induction (to make step you should take the derivative).

Denote Px the value of the sum for n = x. We can easily calculate the values of Px for x from 0 to k + 1 in O(klogk) time. If n < k + 2 then we already have the answer. Otherwise let's use Lagrange polynomial to get the value of the sum for the given value n.

The Largange polynomial have the following form: . In our case xi = i - 1 and yi = Pxi.

To calculate P(n) in a linear time we should use that xi + 1 - xi = xj + 1 - xj for all i, j < n. It's help us because with that property we can recalculate the inner product for i + 1 from the inner product for i simply by multiplying by two values and dividing by two values. So we can calculate the sum in linear time over k.

С++ solution

Complexity: O(klog MOD) (logk appeared because we should find the inverse element in the field modulo MOD = 109 + 7).

Full text and comments »

  • Vote: I like it
  • +90
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 7 will take place on 10 February 2016 at 18:00 MSK for the first and second divisions. You can read about educational rounds here and here.

<This paragraph was modified last time>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

</This paragraph was modified last time>

Thanks a lot to Aleksa Plavsic allllekssssa who suggested the problems D, E and Ivan Popovich NVAL for the problem F. Also thanks to Mohammad Nematollahi Deemo who suggested the problem that was highly simplified and will be under the letter C.

The round was prepared by me, Edvard Davtyan. Thanks a lot to MikeMirzayanov we invented the problems A, B and C together. Also thanks to Maria Belova Delinur for checking the English statements, Aleksa Plavsic allllekssssa and Ivan Popovich for testing the problems.

We tried to make the problems easy but interesting. I think that the problems is mathematized a little. I hope you will enjoy the problems!

Good luck and have fun!

P.S.: The Codeforces Educational Rounds was recognized by Snarknews as the best project in competitive programming in 2015 (the picture below is the prize).

UPD1: The first phase of the contest is ended. You can hack any other solution.

UPD2: The editorial is ready.

UPD3: The round is over, the results is final.

Full text and comments »

  • Vote: I like it
  • +313
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

620A - Professor GukiZ's Robot

Easy to see that the answer is max(|x1 - x2|, |y1 - y2|).

С++ solution

Complexity: O(1).

620B - Grandfather Dovlet’s calculator

Let's simply iterate over all the values from a to b and add to the answer the number of segments of the current value x. To count the number of segments we should iterate over all the digits of the number x and add to the answer the number of segments of the current digit d. These values can be calculated by the image from the problem statement and stored in some array in code.

C++ solution

Complexity: O((b - a)logb).

620C - Pearls in a Row

Let's solve the problem greedily. Let's make the first segment by adding elements until the segment will be good. After that let's make the second segment in the same way and so on. If we couldn't make any good segment then the answer is  - 1. Otherwise let's add all uncovered elements at the end to the last segment. Easy to prove that our construction is optimal: consider the first two segments of the optimal answer, obviously we can extend the second segment until the first segment will be equal to the first segment in our construction.

C++ solution

Complexity: O(nlogn).

620D - Professor GukiZ and Two Arrays

We can process the cases of zero or one swap in O(nm) time. Consider the case with two swaps. Note we can assume that two swaps will lead to move two elements from a to b and vice versa (in other case it is similar to the case with one swap). Let's iterate over all the pairs of the values in a and store them in some data structure (in C++ we can user map). Now let's iterate over all the pairs bi, bj and find in out data structure the value v closest to the value x = sa - sb + 2·(bi + bj) and update the answer by the value |x - v|. Required sum we can find using binary search by data structure (*map* in C++ has lower_bound function).

C++ solution

Сложность: O((n2 + m2)log(n + m)).

620E - New Year Tree

Let's run dfs on the tree and write out the vertices in order of their visisiting by dfs (that permutation is called Euler walk). Easy to see that subtree of any vertex is a subsegment of that permutation. Note that the number of different colours is 60, so we can store the set of colours just as mask of binary bits in 64-bit type (*long long* in C++, long in Java). Let's build the segment tree over the permutation which supports two operations: paint subsegment by some colour and find the mask of colours of some segment.

С++ solution

Complexity: O(nlogn).

620F - Xors on Segments

We gave bad constraints to this problem so some participants solved it in O(n2 + m) time.

Note that . The values f(0, x) can be simply precomputed. Also you can notice that the value f(0, x) is equal to x, 1, x + 1, 0 depending on the value x modulo 4.

Let's use Mo's algorithm: we should group all the queries to blocks by the left end and sort all the queries in each block by the right end. Let r be the maximal left end inside the current group then all left ends will be in distance not greater than from r and right ends will be in nondecreasing order, so we can move the right end by one (total we will made no more than n movements in each block). During moving of the right end inside some group from the value r + 1 to the value of the current right end we will maintain two tries: the first for the values f(0, x - 1) and the second for the values f(0, x), in the first we will maintain the minimal value of x, in the second — the maximal. After adding some values to the trie we should find the maximal value that can be formed by the current value x. To do that we should go down in the first trie maintaining the invariant that in the current subtree the minimal value is not greater than x. Each time we should go by the bit that is not equal to the corresponding bit in x (if we can do that, otherwise we should go by the other bit). In the second trie we should do the same thing with the difference that we should maintain the invariant that the maximal value in the current subtree is not less than the value x. After moving the right end we should iterate from the left end of the query to r and update the answer (without adding the current value to the tries). Also after that all we should iterate over all the queries and with new empty tries iterate from the left end to r, add the current values to the tries and update the answer.

С++ solution: in this code the trie number 0 corresponds to the second trie and the trie number 1 corresponds to the first trie.

Complexity: .

Full text and comments »

  • Vote: I like it
  • +60
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hello, Codeforces!

Educational Codeforces Round 6 will take place on 21 January 2016 at 18:00 MSK for the first and second divisions. You can read about educational rounds here and here.

<Your Ad Could Be Here>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

If you have ideas for some problems or maybe already prepared problems that you can't use in rounds or official competitions, you can write to me.

</Your Ad Could Be Here>

Thanks a lot to Aleksa Plavsic allllekssssa who suggested several problems, two of them you will see on the round (the problems D and F). Also thanks to Bayram Berdiyev bayram, Allanur Shiriyev Allanur, Bekmyrat Atayev Bekmyrat.A. They are together suggested five problems, two of them you will see on the round (the problems B and E).

As usual the round was prepared by me, Edvard Davtyan. Thanks a lot to MikeMirzayanov we invented the problems A and C together. Also thanks to Maria Belova Delinur who will check English statements and Aleksa Plavsic allllekssssa who help me with problem testing and have constantly been in touch.

The first problem is pretty simple, so I'm waiting fast accepteds from you. The last problem is pretty difficult, so respect to all particiants who will solve it. I hope you will enjoy the problems!

Good luck and have fun!

UPD 1: I forgot to thank all other users who already sent me the ideas for the problems. I'll try to give that problems to the next rounds.

UPD 2: The main part of the contest is finished. The phase of hacks is started.

UPD 3: The editorial is ready.

UPD 4: The round is over, the results is final.

Full text and comments »

  • Vote: I like it
  • +258
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

616A - Comparing Two Long Integers

Note that solutions in Java with BigInteger class or input() function in Python2 will fail in this problem. The reason is the next: standard objects stores numbers not in decimal system and need a lot of time to convert numbers from decimal system. Actually they are working in O(n2), where n is the legth of the number.

To solve this problem you should simply read the numbers to strings and add leading zeroes to the shorter one until the numbers will be of the same length. After that you should simply compare them alphabetically.

С++ solution

Python solution

Complexity: O(n).

616B - Dinner with Emma

Firstly you should find the minimum value in each row and after that you should find the maximum value over that minimums. It's corresponding to the strategy of Jack and Emma.

C++ solution

Complexity: O(nm).

616C - The Labyrinth

Let's enumerate all the connected components, store their sizes and for each empty cell store the number of it's component. It can be done with a single dfs. Now the answer for some impassable cell is equal to one plus the sizes of all different adjacent connected components. Adjacent means the components of cells adjacent to the current impassable cell (in general case each unpassable cell has four adjacent cells).

C++ solution

Complexity: O(nm).

616D - Longest k-Good Segment

This problem is given because on the Codeforces pages we often see questions like "What is the method of the two pointers?". This problem is a typical problem that can be solved using two pointers technique.

Let's find for each left end l the maximal right end r that (l, r) is a k-good segment. Note if (l, r) is a k-good segment then (l + 1, r) is also a k-good segment. So the search of the maximal right end for l + 1 we can start from the maximal right end for l. The only thing that we should do is to maintain in the array cntx for each number x the number of it's occurrences in the current segment (l, r) and the number of different numbers in (l, r). We should move the right end until the segment became bad and then move the left end. Each of the ends l, r will be moved exactly n times.

C++ solution

Complexity: O(n).

616E - Sum of Remainders

Unfortunately my solution for this problem had overflow bug. It was fixed on contest. Even so I hope you enjoyed the problem because I think it's very interesting.

Let's transform the sum . Note that the last sum can be accumulated to only value min(n, m), because for i > n all the values will be equal to 0.

Note in the last sum either or . Let's carefully accumulate both cases. The first sum can be simply calculated by iterating over all . We will accumulate the second sum independently for all different values . Firstly we should determine for which values i we will have the value . Easy to see that for the values i from the interval . Also we can note that the sum of the second factors in with fixed first factor can be calculaed in constant time — it's simply a sum of arithmetic progression . So we have solution with complexity .

С++ solution

Complexity: .

616F - Expensive Strings

This problem was prepared by Grigory Reznikow vintage_Vlad_Makeev. His solution uses suffix array.

This problem is a typical problem for some suffix data structure. Four competitors who solved this problem during the contest used suffix automaton and one competitor used suffix tree. My own solution used suffix tree so I'll describe solution with tree (I think it's simple except of the building of the tree).

Let's build the new string by concatenation of all strings from input separating them by different separators. The number of separators is O(n) so the alphabet is also O(n). So we should use map<int, int> to store the tree and the complexity is increased by O(logn). Let's build the suffix tree for the new string. Let's match all the separators to the strings from the left of the separator. Let's run dfs on the suffix tree that doesn't move over separators and returns the sum of the costs of the strings matched to the separators from the subtree of the current vertex. Easy to see that we should simply update the answer by the product of the depth of the current vertex and the sum in the subtree of the current vertex.

С++ solution

Complexity: O(nlogn).

Full text and comments »

  • Vote: I like it
  • +63
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

Hi, Codeforces!

Happy New Year! Holidays and 2015 year have passed and year 2016 is ahead. I wish you good luck in programming competitions and achieving all of your goals this year.

Educational Codeforces Round 5 will take place on 11 January 2016 at 18:00 MSK for the first and second divisions. You can read about educational rounds here and here.

<A year has passed, but paragraph remains unchanged.>

The round will be unrated for all users and it will be held with extented ACM ICPC rules. You will have two hours to solve six problems. After that you will have one day to hack any solution you want. You will have access to copy any solution and test it locally.

</A year has passed, but paragraph remains unchanged.>

Thanks a lot to Grigory Reznikow vintage_Vlad_Makeev who prepared a good problem (the problem F in ER 5). You can send to me some ideas of problems or maybe already prepared problems that you can't use in rounds or official competitions.

As usual the round was prepared by me, Edvard Davtyan. Thanks a lot to MikeMirzayanov for helping to invent the problems. Also thanks in advance to Maria Belova Delinur who will check English statements.

I think the problems is not difficult (except maybe for problem F). I hope you will enjoy the problems and solve all of them!

Good luck and have fun!

UPD 1: Coding phase is finished. You can hack other solutions for 24 hours.

UPD 2: The editorial is ready.

UPD 3: During the phase of hacks we found the following: the same solutions on Python2 and Python3 works differently on different large tests. For example, some of Python3 solutions works very slow on tests with only zeros, but Python2 works very slow on tests with nines. Some of solutions works in around one second so we decided to increase the time limit for the problem A to 2 seconds. All the solutions will be rejudged soon on the complete testset.

UPD 4: The round is over. All solutions will be rejudged soon on the complete testset (includes the hacks).

Full text and comments »

  • Vote: I like it
  • +213
  • Vote: I do not like it

By Edvard, history, 9 years ago, translation, In English

612A - The Text Splitting

Let's fix the number a of strings of length p and the number b of strings of length q. If a·p + b·q = n, we can build the answer by splitting the string s to a parts of the length p and b parts of the length q, in order from left to right. If we can't find any good pair a, b then the answer doesn't exist. Of course this problem can be solved in linear time, but the constraints are small, so you don't need linear solution.

Complexity: O(n2).

612B - HDD is Outdated Technology

You are given the permutation f. Let's build another permutation p in the following way: pfi = i. So the permutation p defines the number of sector by the number of fragment. The permutation p is called inverse permutation to f and denoted f - 1. Now the answer to problem is .

Complexity: O(n).

612C - Replace To Make Regular Bracket Sequence

If we forget about bracket kinds the string s should be RBS, otherwise the answer doesn't exist. If the answer exists each opening bracket matches to exactly one closing bracket and vice verse. Easy to see that if two matching brackets have the same kind we don't need to replace them. In other case we can change the kind of the closing bracket to the kind of the opening. So we can build some answer. Obviously the answer is minimal, because the problems for some pair of matching pairs are independent and can be solved separately.

The only technical problem is to find the matching pairs. To do that we should store the stack of opening brackets. Let's iterate from left to right in s and if the bracket is opening, we would simply add it to the stack. Now if the bracket is closing there are three cases: 1) the stack is empty; 2) at the top of the stack is the opening bracket with the same kind as the current closing; 3) the kind of the opening bracket differs from the kind of the closing bracket. In the first case answer doesn't exist, in the second case we should simply remove the opening bracket from the stack and in the third case we should remove the opening bracket from the stack and increase the answer by one.

Complexity: O(n).

612D - The Union of k-Segments

Let's create two events for each segment li is the time of the segment opening and ri is the time of the segment closing. Let's sort all events by time, if the times are equal let's sort them with priority to opening events. In C++ it can be done with sorting by standard comparator of vector<pair<int, int>> events, where each element of events is the pair with event time and event type ( - 1 for opening and  + 1 for closing).

Let's iterate over events and maintain the balance. To do that we should simply decrease the balance by the value of the event type. Now if the balance value equals to k and before updating it was k - 1 then we are in the left end of some segment from the answer. If the balance equals to k - 1 and before updating it was k then we are in the right end of the segment from the answer. Let's simply add segment [left, right] to the answer. So now we have disjoint set of segments contains all satisfied points in order from left to right. Obviously it's the answer to the problem.

Complexity: O(nlogn).

612E - Square Root of Permutation

Consider some permutation q. Let's build by it the oriented graph with edges (i, qi). Easy to see (and easy to prove) that this graph is the set of disjoint cycles. Now let's see what would be with that graph when the permutation will be multiplied by itself: all the cycles of odd length would remain so (only the order of vertices will change, they will be alternated), but the cycles of even length will be split to the two cycles of the same length. So to get the square root from the permutation we should simply alternate (in reverse order) all cycles of the odd length, and group all the cycles of the same even length to pairs and merge cycles in each pair. If it's impossible to group all even cycles to pairs then the answer doesn't exist.

Complexity: O(n).

612F - Simba on the Circle

The author solution for this problem uses dynamic programming. I think that this problem can't be solved by greedy ideas. Let's calculate two dp's: z1i is the answer to the problem if all numbers less than ai are already printed, but the others are not; and z2i is the answer to the problem if all numbers less than or equal to ai are already printed, but the others are not. Let's denote dij — the least distance between i and j on the circular array and odij is the distance from i to j in clockwise order. Easy to see that z2i = minj(zj + dij) for all j such that the value aj is the least value greater than ai. Now let's calculate the value z1i. Consider all elements equals to ai (in one of them we are). If there is only one such element then z1i = z2i. Otherwise we have two alternatives: to move in clockwise or counterclockwise direction. Let we are moving in clockwise direction, the last element from which we will write out the number would be the nearest to the i element in counterclockwise direction, let's denote it u. Otherwise at last we will write out the number from the nearest to the i element in clockwise direction, let's denote it v. Now z1i = min(z2u + odiu, z2v + odvi). Easy to see that the answer to the problem is mini(z1i + dsi), over all i such that ai is the smallest value in array and s is the start position.

Additionally you should restore the answer. To do that, on my mind, the simplest way is to write the recursive realization of dp, test it carefully and then copy it to restore answer (see my code below). Of course, it's possible to restore the answer without copy-paste. For example, you can add to your dp parameter b which means it's need to restore answer or not.

Complexity: O(n2).

Code

Full text and comments »

  • Vote: I like it
  • +23
  • Vote: I do not like it