contest_id
stringlengths
1
4
index
stringclasses
43 values
title
stringlengths
2
63
statement
stringlengths
51
4.24k
tutorial
stringlengths
19
20.4k
tags
listlengths
0
11
rating
int64
800
3.5k
code
stringlengths
46
29.6k
356
A
Knight Tournament
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows: - There are $n$ knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to $n$. - The tournament consisted of $m$ fights, in the $i$-th fight the knights that were still in the game with numbers at least $l_{i}$ and at most $r_{i}$ have fought for the right to continue taking part in the tournament. - After the $i$-th fight among all participants of the fight only one knight won — the knight number $x_{i}$, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the $m$-th) fight (the knight number $x_{m}$) became the winner of the tournament. You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number $b$ was conquered by the knight number $a$, if there was a fight with both of these knights present and the winner was the knight number $a$. Write the code that calculates for each knight, the name of the knight that beat him.
Let's the current fight $(l, r, x)$ consists of $K$ knights fighting. Then all we have to do is to find all these knights in time $O(K)$ or $O(KlogN)$. There are several ways to do that, let's consider some of them. The first way is to store the numbers of all alive knights in std::set (C++) or TreeSet (Java). Then in C++ we can use lower_bound method to find the first knight in the fight that is alive, and to iterate over this set, each time moving to the next alive knight. In Java we should use subSet method. The second way is to define array next with the following meaning: To find the first alive knight starting from the knight $v$ we need to follow this links until we find the first knight $w$ with $next[w] = w$. In order not to pass the same links too many times, we will use the trick known as path compression (it is used in Disjoint Set Union). Note that you should handle the case when the current knight is the last knight and is out of tournament.
[ "data structures", "dsu" ]
1,500
null
356
B
Xenia and Hamming
Xenia is an amateur programmer. Today on the IT lesson she learned about the Hamming distance. The Hamming distance between two strings $s = s_{1}s_{2}... s_{n}$ and $t = t_{1}t_{2}... t_{n}$ of equal length $n$ is value $\sum_{i=1}^{n}[s_{i}\neq t_{i}]$. Record $[s_{i} ≠ t_{i}]$ is the Iverson notation and represents the following: if $s_{i} ≠ t_{i}$, it is one, otherwise — zero. Now Xenia wants to calculate the Hamming distance between two long strings $a$ and $b$. The first string $a$ is the concatenation of $n$ copies of string $x$, that is, $a=x+x+\cdot\cdot+x=\sum_{i=1}^{n}x$. The second string $b$ is the concatenation of $m$ copies of string $y$. Help Xenia, calculate the required Hamming distance, given $n, x, m, y$.
Let's denote the length of the first string as $lenX$, the length of the second string as $lenY$. Let $L = LCM(lenX, lenY)$. It's obvious that $L$ is a period of the long strings $a$ and $b$, so we can find the distance of its' prefixes of length $L$ and multiply the answer by $\frac{t e n(a)}{L}$. Let's fix the position $i$ in the string $x$ and think about all characters from the second string it will be compared with. It it easy to conclude that it will be compared with such $y_{j}$ that $i \equiv j (mod g)$, where $g = GCD(lenX, lenY)$. For each possible remainder of division by $g$ and for each character $c$ we can calculate $count(r, c)$ - the number of characters $c$ that appear in $y$ in such positions $j$ that $j mod g = r$. When calculating the Hamming distance, the character $x_{i}$ will be compared with exactly $count(i mod g, x_{i})$ characters from $y$ that are equal to it, all other comparisons will add one to the distance.
[ "implementation", "math" ]
1,900
null
356
C
Compartments
A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of $n$ compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip. The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student. However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students.
In the problem you should come up with some right greedy algorithm. One of correct approaches acts as follows: Firstly, it joins all "twos" and "ones" (to get "threes"). Several "ones" should be moved. Then you should consider two cases depend on amounts of "ones" and "twos". If initially you have more "ones", you should try to join remaining after the first point "ones" into groups of three. If initially you have more "twos", you should try to join remaining after the first point "twos" into groups of three. You can get two "threes" from three "twos". After the first point and the second point some "ones" or "twos" can remain. You shouldn't come up with common solution. Else you should just to consider all possible cases. To solve the problem you should follow your common sense (is it greedy?). Writing naive solution (bfs search) for stress purposes is not so bad for proving correctness of your solution.
[ "combinatorics", "constructive algorithms", "greedy", "implementation" ]
2,100
null
356
D
Bags and Coins
When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite simple. The third bag contains a coin and two other bags. This problem is a generalization of the childhood puzzle. You have $n$ bags. You know that the first bag contains $a_{1}$ coins, the second bag contains $a_{2}$ coins, ..., the $n$-th bag contains $a_{n}$ coins. In total, there are $s$ coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do.
It's easy to see that bags and their relations "lies directly in" should form directed forest. Each vertex should be given value $c_{i}$ - the number of coins in the corresponding bag. Let's denote the sum of values $c_{j}$ in the subtree of vertex $i$ as $f_{i}$. The following conditions should be met: $f_i = a_i$ then sum of $f_i$ of roots equals $s$. It's clear that one of the bags with largest $a_{i}$ must be the root of some tree. It's quite easy to see that the solution exists if and only if there exists a subset $a_{i1}, a_{i2}, ..., a_{ik}$ such that $a_{i1} + a_{i2} + ... + a_{ik} = s$ and this subset contains at least one bag with the largest $a_{i}$. It's obvious that it is necessary condition, the sufficiency is also easy to see: let's suppose we have such subset. Then all bags from the subset, except one of the largest, will be roots of the signle-vertex trees (i.e. $c_{i} = a_{i}$ for them). All bags that are not in the subset we will consequentially put into the largest bag, forming the "russian doll" (this tree will be directed chain). So, we reduced the task to the well-known subset-sum problem: from the items $a_{1}, a_{2}, ... a_{n}$ find the subset with the given sum $s$. This problem is NP-Complete, and with these constraints is solved in a following way: let $T(i, j) = 1$ if it is possible to obtain sum $j$ using some of the first $i$ items, and $T(i, j) = 0$ otherwise. Then $T(i,j)=T(i-1,j)\,\lor T(i-1,j-a_{i})$. The $i$-th row of this table depends only on the previous row, so we don't have to store the whole table in memory. Also we should use the fact that the values of the table are zeroes and ones, and we can use bit compression and store each row in an array of int's of size $\textstyle\left[{\frac{s}{32}}\right]$. To get the $i$-th row, we should calculate the bitwise OR of the previous row and the previous row shifted to the left by $a_{i}$ positions. That is, we can find out whether it possible to obtain the sum $s$ in approximately $\overset{n s}{\ldots}$ operations. To find the actual way to obtain $s$, we need to use the following trick: for every possible sum $j$ we will remember the value $first(j)$ - the number of such item that after considering this item it became possible to obtain $j$. This allows us to restore the solution.
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
2,700
null
356
E
Xenia and String Problem
Xenia the coder went to The Olympiad of Informatics and got a string problem. Unfortunately, Xenia isn't fabulous in string algorithms. Help her solve the problem. String $s$ is a sequence of characters $s_{1}s_{2}... s_{|s|}$, where record $|s|$ shows the length of the string. Substring $s[i... j]$ of string $s$ is string $s_{i}s_{i + 1}... s_{j}$. String $s$ is a Gray string, if it meets the conditions: - the length of string $|s|$ is odd; - character $\textstyle{\binom{k}{\frac{k}{2}}}$ occurs exactly once in the string; - either $|s| = 1$, or substrings $s[1\cdot\cdot\cdot{\frac{|s|+1}{2}}-1]$ and $s[\frac{s|+1}{2}+1\cdot\cdot\cdot|s|]$ are the same and are Gray strings. For example, strings "abacaba", "xzx", "g" are Gray strings and strings "aaa", "xz", "abaxcbc" are not. The beauty of string $p$ is the sum of the squares of the lengths of all substrings of string $p$ that are Gray strings. In other words, consider all pairs of values $i, j$ $(1 ≤ i ≤ j ≤ |p|)$. If substring $p[i... j]$ is a Gray string, you should add $(j - i + 1)^{2}$ to the beauty. Xenia has got string $t$ consisting of lowercase English letters. She is allowed to replace at most one letter of the string by any other English letter. The task is to get a string of maximum beauty.
During the contest most of participants write the solutions that are very similar to the author's one. One of the author's solution uses hashes (but there exist solution without it), you can see short description of the solution below: For each position $i$ calculate with hashes the maximal value of $L_{i}$, such that substring $s[(i - L_{i} + 1)..(i + L_{i} - 1)]$ is Gray string. Also, calculate the maximal value $P_{i}$, that substring $s[(i - P_{i} + 1)..(i + P_{i} - 1)]$ differs from some Gray string in at most one position. You can see that $P_{i} \ge L_{i}$. If $P_{i} > L_{i}$, also remember position and letter in the position, that differs Gray string and the substring. You can see, that if we don't need to change letters, then the answer for the problem is $\sum_{i=1}^{\left(3\right)}f(L_{i})$, where $f(L) = 1^{2} + 3^{2} + 7^{2} + ... + L^{2}$. So, calculate an answer without changes. Next, iterate through all positions and letters in it. What is the new answer for the problem? Look at all Gray strings that occurs in our string and touches our fixed position. After we change this position the string will not be Gray string anymore (so we should subtract the squired length of the string from our answer). Look at all Gray strings that differs in exactly fixed position from some substring of the string. If we change the letter in the position to the fixed letter, all such strings will be added to the answer (and we should add their squired lengths). Summary, with $P_{i}$ and $L_{i}$ we need to calculate for each position and letter, how the answer differs if we change the letter in the position to the fixed one. For that reason we should use offline update (+=) on the segment. After the values will be calculated we can update our answer with all possible values.
[ "dp", "hashing", "implementation", "string suffix structures", "strings" ]
3,000
null
357
A
Group of Students
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to $m$ points. We know that $c_{1}$ schoolchildren got 1 point, $c_{2}$ children got 2 points, ..., $c_{m}$ children got $m$ points. Now you need to set the passing rate $k$ (integer from 1 to $m$): all schoolchildren who got less than $k$ points go to the beginner group and those who get at strictly least $k$ points go to the intermediate group. We know that if the size of a group is more than $y$, then the university won't find a room for them. We also know that if a group has less than $x$ schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from $x$ to $y$, inclusive. Help the university pick the passing rate in a way that meets these requirements.
In this problem you need to iterate over all possible values of passing rate from 1 to 100 and for each value calculate the sizes of two groups.
[ "brute force", "greedy", "implementation" ]
1,000
null
357
B
Flag Day
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: - overall, there must be $m$ dances; - exactly three people must take part in each dance; - each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has $n$ dancers, and their number can be less than $3m$. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the $m$ dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the $n$ dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
Let's process the dances in the given order and determine the colors of dancers' clothes. If there are no dancer from some previous dance, we can give the dances different colors arbitrarily. And if there is such dancer, we already know the color of his clothes. So, we arbitrarily distribute the other two colors between the remaning two dancers.
[ "constructive algorithms", "implementation" ]
1,400
null
358
A
Dima and Continuous Line
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework. The teacher gave Seryozha the coordinates of $n$ distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the $n$-th point. Two points with coordinates $(x_{1}, 0)$ and $(x_{2}, 0)$ should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any). Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.
If our line has self-intersections, that some pair of semi-circles exists, which intersect each other. Let points $x_{1}$ < $x_{2}$ are connected with a semi-circle and points $x_{3}$ < $x_{4}$ are connected with another semi-circle. Then this semis-circles intersect if one of the conditions is true: 1). $x_{1} < x_{3} < x_{2} < x_{4}$ 2). $x_{3} < x_{1} < x_{4} < x_{2}$ Let's iterate trough all pairs of semi-circles, and check if the semi-circles intersect each other. So, the solution will have complexity $O(N^{2})$ what satisfied the constrains.
[ "brute force", "implementation" ]
1,400
null
358
B
Dima and Text Messages
Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other. Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3$word_{1}$<3$word_{2}$<3 ... $word_{n}$<3. Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message. Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.
It's clear, that adding new random symbols means, that we can simply omit them, they don't change the structure of the phrase: $< 3word_{1} < 3word_{2} < 3... word_{N} < 3$. Let's determine the phrase before inserting random elements: $s = " < 3" + word1 + " < 3" + ... + " < 3" + wordN + " < 3"$. Lets $i$ -is an index in $s$, we are waiting for. At the beginning $i$ = $0$; we will iterate though the sms and when we will meet the symbol which equals to $s_{i}$ we will simply increment $i$. if at some moment $|s| \le I$ we found all needed symbols and answer is yes, otherwise - no.
[ "brute force", "strings" ]
1,500
null
358
C
Dima and Containers
Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck. Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands: - Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end. - Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation. As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!
We know all the numbers at the beginning, so, it's clear, that we want pop three maximums. We can "precalculate " maximums with finding next zero and iterating through all numbers between two zeroes. We should do pops from different containers, so let's save maximums in the top of the stack, in the beginning of the queue and on the beginning of the dek. (you can do this in some other way) We should determine, where will be stored the 1st, 2nd and 3rd maximum. For example, the first(the biggest one) - in the stack, second - in queue, and the third - in dek. "trash" - other numbers we can save into the end of the dek. Also you need to catch cases, when two or less numbers are between zeroes.
[ "constructive algorithms", "greedy", "implementation" ]
2,000
null
358
D
Dima and Hares
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her $n$ hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to $n$ from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them? Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and $n$ don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares. Help Inna maximize the total joy the hares radiate. :)
Let's look at the first hare: we chose them befoe second, or after. If it is chosen after the second, than the solution from the 2nd hare to the last doesn't depend on the first one, otherwise, we will receive the same but before the second hair will be obviously the feed hair. So, we have two dinamics: 1). $d0i$ - answer for suffix as a separate task. 2). $d1i$ - answer for suffix if the previous hair for this suffix is feed already. Movements: $d0n = an$ $d1n = bn$ $d0i = max(ai + d1i + 1, bi + d0i + 1)$ $d1i = max(bi + d1i + 1, ci + d0i + 1)$ answer is $d01$;
[ "dp", "greedy" ]
1,800
null
358
E
Dima and Kicks
Dima is a good person. In fact, he's great. But all good things come to an end... Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle $n × m$ consisting of unit squares. For the beginning, Seryozha put Dima in a center of some square. Then he started to kick Dima (it is known, that he kicks Dima at least once). Each time when Dima is kicked he flyes up and moves into one of four directions (up, left, right, down). On each move Dima passes $k$ $(k > 1)$ unit of the length in the corresponding direction. Seryozha is really kind, so he kicks Dima in such way that Dima never meets the walls (in other words, Dima never leave the room's space). Seryozha is also dynamic character so Dima never flies above the same segment, connecting a pair of adjacent squares, twice. Seryozha kicks Dima for a long time, but Dima is not vindictive — Dima writes. Dima marked all squares in which he was staying or above which he was flying. Thanks to kicks, Dima does not remember the $k$ value, so he asks you to find all possible values which matches to the Dima's records.
The first thing to understand is that the answer is the divisor of maximal-length sequence of standing one by one ones. $(1111 \dots 11)$ Let's iterate trough this number. Now we should check the table knowing the value of $K$. Let's find the most left of ones, and choose from them the most top. Let it be $(X, Y)$. then after each step Dima can appear inly in cells which look like: $(X + K * a, Y + K * b)$. Let such cells are the vertexes of the graph. And sequences of ones - the ribs. We will build the graph. We should check that there are no additional ones in table. We should also check if the graph is connected and has en Euler's path. The value of K is the next answer under the all conditions. The correct implementation will have the complexity $O(N * N * log(N))$. In reality it will be never achieved.
[ "brute force", "dsu", "graphs", "implementation" ]
2,300
null
359
A
Table
Simon has a rectangular table consisting of $n$ rows and $m$ columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the $x$-th row and the $y$-th column as a pair of numbers $(x, y)$. The table corners are cells: $(1, 1)$, $(n, 1)$, $(1, m)$, $(n, m)$. Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table $(x_{1}, y_{1})$, an arbitrary corner of the table $(x_{2}, y_{2})$ and color all cells of the table $(p, q)$, which meet both inequations: $min(x_{1}, x_{2}) ≤ p ≤ max(x_{1}, x_{2})$, $min(y_{1}, y_{2}) ≤ q ≤ max(y_{1}, y_{2})$. Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.
If there are some good cell, which is located in the first row or in the first column, the answer is two. Similarly, if If there are some good cell, which is located in the last row or in the last column, the answer is two. Otherwise, the answer is four
[ "constructive algorithms", "greedy", "implementation" ]
1,000
null
359
B
Permutation
A permutation $p$ is an ordered group of numbers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each is no more than $n$. We'll define number $n$ as the length of permutation $p_{1}, p_{2}, ..., p_{n}$. Simon has a positive integer $n$ and a non-negative integer $k$, such that $2k ≤ n$. Help him find permutation $a$ of length $2n$, such that it meets this equation: $\sum_{i=1}^{n}|a_{2i-1}-a_{2i}|-|\sum_{i=1}^{n}a_{2i-1}-a_{2i}|=2k$.
The answer is a slightly modified permutation $1, 2, ..., 2n$. Let's reverse numbers $2i - 1$ and $2i$ for each $1 \le i \le k$. It's not hard to understand, that this permutation is good.
[ "constructive algorithms", "dp", "math" ]
1,400
null
359
C
Prime Number
Simon has a prime number $x$ and an array of non-negative integers $a_{1}, a_{2}, ..., a_{n}$. Simon loves fractions very much. Today he wrote out number ${\frac{1}{x^{a}!}}+{\frac{1}{x^{a}2}}+\ddots\div\nonumber+{\frac{1}{x^{a}n}}$ on a piece of paper. After Simon led all fractions to a common denominator and summed them up, he got a fraction: $\scriptstyle{\frac{3}{t}}$, where number $t$ equals $x^{a1 + a2 + ... + an}$. Now Simon wants to reduce the resulting fraction. Help him, find the greatest common divisor of numbers $s$ and $t$. As GCD can be rather large, print it as a remainder after dividing it by number $1000000007$ ($10^{9} + 7$).
Obviously, the answer is $x^{v}$. Let $sum = a_{1} + a_{2} + ... + a_{n}$. Also let $s_{i} = sum - a_{i}$ (the array of degrees). After that let's find value $v$ by the following algorithm: Let's consider a sequence of degrees as decreasing sequence. Now we will perform the following operation until it's possible to perfom it. Take the minimum degree $v$ from the array of degrees and calculate the number of elements $cnt$, which have the same degree. If $cnt$ multiples of $x$, then replace all $cnt$ elements by $cnt / x$ elements of the form $v + 1$. Since the sequence of degrees is a decreasing sequence, we can simply assign them to the end. If $cnt$ is not a multiple of $x$, then we found the required value $v$. Also you need to check, that $v$ is not greater then $sum$. Otherwise, $v$ will be equals to $sum$.
[ "math", "number theory" ]
1,900
null
359
D
Pair of Numbers
Simon has an array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Today Simon asked you to find a pair of integers $l, r$ $(1 ≤ l ≤ r ≤ n)$, such that the following conditions hold: - there is integer $j$ ($l ≤ j ≤ r$), such that all integers $a_{l}, a_{l + 1}, ..., a_{r}$ are divisible by $a_{j}$; - value $r - l$ takes the maximum value among all pairs for which condition $1$ is true; Help Simon, find the required pair of numbers $(l, r)$. If there are multiple required pairs find all of them.
Quite simple note: if the pair $(l, r)$ satisfies the condition 1 from the statements, then $min(l, r) = GCD(l, r)$, where $min(l, r)$ is smallest number $a_{i}$ from the segment (l, r) and $GCD(l, r)$ is a GCD of all numbers from the segment (l, r). Calculate some data structure that will allow us to respond quickly to requests $GCD(l, r)$ and $min(l, r)$. For example, you can use Sparce Table. Solutuions, that uses segment tree, is too slow. So I think, you should use Sparce Table. So, now our task quite simple. Let's use binary search to find greatest value of $r - l$: $ok(mid)$ is the function, that determines, is there some segment where $min(l, r) = GCD(l, r)$ and $mid = r - l$ ($mid$ - is fixed value by binary search). If there is some good segment, you should update boundaries of binary search correctly. After that, it's very simple to restore answer.
[ "binary search", "brute force", "data structures", "math", "two pointers" ]
2,000
null
359
E
Neatness
Simon loves neatness. So before he goes to bed, Simon wants to complete all chores in the house. Simon's house looks like a rectangular table consisting of $n$ rows and $n$ columns from above. All rows of the table are numbered from $1$ to $n$ from top to bottom. All columns of the table are numbered from $1$ to $n$ from left to right. Each cell of the table is a room. Pair $(x, y)$ denotes the room, located at the intersection of the $x$-th row and the $y$-th column. For each room we know if the light is on or not there. Initially Simon is in room $(x_{0}, y_{0})$. He wants to turn off the lights in all the rooms in the house, and then return to room $(x_{0}, y_{0})$. Suppose that at the current moment Simon is in the room $(x, y)$. To reach the desired result, he can perform the following steps: - The format of the action is "1". The action is to turn on the light in room $(x, y)$. Simon cannot do it if the room already has light on. - The format of the action is "2". The action is to turn off the light in room $(x, y)$. Simon cannot do it if the room already has light off. - The format of the action is "dir" ($dir$ is a character). The action is to move to a side-adjacent room in direction $dir$. The direction can be left, right, up or down (the corresponding dir is L, R, U or D). Additionally, Simon can move only if he see a light in the direction $dir$. More formally, if we represent the room, Simon wants to go, as $(nx, ny)$, there shold be an integer $k$ $(k > 0)$, that room $(x + (nx - x)k, y + (ny - y)k)$ has a light. Of course, Simon cannot move out of his house. Help Simon, find the sequence of actions that lets him achieve the desired result.
You should write recursive function, that will turn on the light in all rooms, where it's possible. Also this function will visit all rooms, which it may visit. Let this function is called paint(x, y), where x, y is the current room. $Paint(x, y)$ will use following idea: Let's look at all neighbors. If there is a light in the current direction (rule $3$ from the statement), and the room $(nx, ny)$ (current neighbor) has not yet visited, we will call our recursive function from $(nx, ny)$. Also, we will turn on the light in all rooms, were we were. If some room is not visited by $paint(x, y)$ and lights is on in this room, the answer is "NO". Otherwise, the answer is "YES". After that let's calculate value $dist(x, y)$ by using bfs. $dist(x, y)$ - is a minimal possible distance from the start to the current position $(x, y)$. It's possible to use in our bfs only rooms, where lights is on. After that we will write the same function $repaint(x, y)$. $Repaint(x, y)$ will use following idea: Let's look at all neighbors. If there is a light in the current neighbor $(nx, ny)$ and $dist(nx, ny) > dist(x, y)$ ($(x, y)$ - current room), let's call our recursive function from $(nx, ny)$.After that we will come back to room $(x, y)$. If there is no such neigbor $(nx, ny)$, turn off the light in the room $(x, y)$. Also you should look at my solution for more details.
[ "constructive algorithms", "dfs and similar" ]
2,400
null
360
A
Levko and Array Recovery
Levko loves array $a_{1}, a_{2}, ... , a_{n}$, consisting of integers, very much. That is why Levko is playing with array $a$, performing all sorts of operations with it. Each operation Levko performs is of one of two types: - Increase all elements from $l_{i}$ to $r_{i}$ by $d_{i}$. In other words, perform assignments $a_{j} = a_{j} + d_{i}$ for all $j$ that meet the inequation $l_{i} ≤ j ≤ r_{i}$. - Find the maximum of elements from $l_{i}$ to $r_{i}$. That is, calculate the value $m_{i}=\operatorname*{max}_{j=l_{i}}a_{j}$. Sadly, Levko has recently lost his array. Fortunately, Levko has records of all operations he has performed on array $a$. Help Levko, given the operation records, find at least one suitable array. The results of all operations for the given array must coincide with the record results. Levko clearly remembers that all numbers in his array didn't exceed $10^{9}$ in their absolute value, so he asks you to find such an array.
Let's find such value $b[i]$ that $a[i] \le b[i]$ for all indeces $i$. Let's simulate all operations and $diff[i]$ will be the difference between current value of $i$-th element and its initial value. If we have operation of first type, we change values of $diff[i]$. If we have operation of second type, we know that $a[i] + diff[i] \le m[i]$, so $a[i] \le m[i] - diff[i]$. We will get array $b$ when we union all this inequalities. Let's prove that either $b$ satisfied all conditions or there is no such array. It can be two cases, why $b$ does not suit: $\operatorname*{m}_{j\simeq L_{i}}^{\mathrm{fax}}b_{j}>m_{i}$ - it's impossible due to construction of array $b$. $\operatorname*{max}_{j=L_{i}}b_{j}<m_{i}$ - $b[i]$ is a maximal possible value of $a[i]$, so $\operatorname*{m}_{j\to L_{i}}^{\mathrm{fix}}a_{j}$ can't be bigger.
[ "greedy", "implementation" ]
1,700
null
360
B
Levko and Array
Levko has an array that consists of integers: $a_{1}, a_{2}, ... , a_{n}$. But he doesn’t like this array at all. Levko thinks that the beauty of the array $a$ directly depends on value $c(a)$, which can be calculated by the formula: \[ c(a)=\operatorname*{max}_{1<i<n-1}|a_{i+1}-a_{i}|,n>1;c(a)=0,0\leq n\leq1. \] The less value $c(a)$ is, the more beautiful the array is.It’s time to change the world and Levko is going to change his array for the better. To be exact, Levko wants to change the values of at most $k$ array elements (it is allowed to replace the values by any integers). Of course, the changes should make the array as beautiful as possible. Help Levko and calculate what minimum number $c(a)$ he can reach.
Let's solve this problem using binary search. We need to check whether we can achieve an array, when $c(a)$ will be at most $x$. Lets make dp. $dp[i]$ means minimal number of elements with indeces less than $i$, which we need to change, but we don't change $i$-th element. Let's iterate next element $j$, which we don't change. Then we know that we can change all elements between $i$ and $j$. It is equivalent to such condition $|a_{j} - a_{i}| \le (j - i) \cdot x$ Difference between neighboring elements can be at most $x$. The maximal possible difference increases by $x$ exactly $j - i$ times between elements $i$ and $j$, so this inequality is correct.
[ "binary search", "dp" ]
2,000
null
360
C
Levko and Strings
Levko loves strings of length $n$, consisting of lowercase English letters, very much. He has one such string $s$. For each string $t$ of length $n$, Levko defines its beauty relative to $s$ as the number of pairs of indexes $i$, $j$ $(1 ≤ i ≤ j ≤ n)$, such that substring \textbf{$t[i..j]$ is lexicographically larger than substring $s[i..j]$}. The boy wondered how many strings $t$ are there, such that their beauty relative to $s$ equals exactly $k$. Help him, find the remainder after division this number by $1000000007$ $(10^{9} + 7)$. A substring $s[i..j]$ of string $s = s_{1}s_{2}... s_{n}$ is string $s_{i}s_{i + 1}... s_{j}$. String $x = x_{1}x_{2}... x_{p}$ is lexicographically larger than string $y = y_{1}y_{2}... y_{p}$, if there is such number $r$ ($r < p$), that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} > y_{r + 1}$. The string characters are compared by their ASCII codes.
Let's count amount of such substrings of $t$ that are bigger than corresponding substring of $s$ and begin at the position $i$. If $t[i] < s[i]$, this amount equals $0$. If $t[i] > s[i]$, this amount equals $n - i$. If $t[i] = s[i]$, then let's find such nearest position $j, j > i$ , that $t[j] \neq s[j]$. If $t[j] > s[j]$, needed amount of substrings will be $n - j$. If $t[j] < s[j]$, needed amount of substrings will be $0$. We can rephrase this: If $t[i] > s[i]$, it will be $(1 + pref) \cdot (n - i)$ new substrings, where $pref$ means how many last elements in $s$ and $t$ is equal. Let's make dp. $dp[i][sum]$ means that we viewed $i$ positions, have $sum$ needed substrings and $s[i] \neq t[i]$. Lets iterate their common prefix $pref$. If $t[i] < s[i]$, $dp[i][sum] + = dp[i - pref - 1][sum] \cdot (s[i] - 'a')$ - we can count this value using partial sums. If $t[i] > s[i]$, $dp[i][sum] + = dp[i - pref - 1][sum - (1 + pref) \cdot (n - i)] \cdot ('z' - s[i])$. Let's iterate $pref$. Let's note that $sum - pref \cdot (n - i) \ge 0$, so $pref \le sum / (n - i)$ and $pref \le k / (n - i)$. This means that third cycle will make at most $k / (n - i)$ iterations when we find value of $dp[i][sum]$. Let's count total number of iterations: $i t=k\cdot(\sum_{i=0}^{n-1}\frac{k}{n-i})$ $=$ $k\cdot(\sum_{i=0}^{n-1}{\frac{k}{i}})$ $<$ $k \cdot (n + k \cdot log k)$.
[ "combinatorics", "dp" ]
2,500
null
360
D
Levko and Sets
Levko loves all sorts of sets very much. Levko has two arrays of integers $a_{1}, a_{2}, ... , a_{n}$ and $b_{1}, b_{2}, ... , b_{m}$ and a prime number $p$. Today he generates $n$ sets. Let's describe the generation process for the $i$-th set: - First it has a single number $1$. - Let's take any element $c$ from this set. For all $j$ ($1 ≤ j ≤ m$) if number $(c·a_{i}^{bj}) mod p$ doesn't occur in the set, then add it to the set. - Repeat step $2$ as long as we can add at least one element to our set. Levko wonders, how many numbers belong to at least one set. That is, he wants to know what size is the union of $n$ generated sets.
$p$ is prime, so there exist primitive root $g$ modulo $p$(We don't need to find it, but we know that it exists). We can write $a_{i} = g^{ri}$. Note, that $i$-th set consists of all numbers $\frac{\vec{\mathbf{a}}}{a_{i}^{j=1}}b_{j}.c_{j}$, where $c_{j} \ge 0$, or we can write it as ${g^{t}}_{j=1}^{\infty}b_{j}.c_{j}$. By Fermat's little theorem $a^{p - 1} = 1 mod p$ we have that $a^{k} mod p = a^{k mod (p - 1)} mod p$. So $\sum_{j=1}^{m}b_{j}\cdot c_{j}$ can be equal to all values $k \cdot t$ modulo $p - 1$, where $t = gcd(b_{1}, b_{2}, ... , b_{m}, p - 1)$. Note that $t$ doesn't depend on $r_{i}$, so we can assign $g = g^{t}$. Then all elements of $i$-th set will be $g^{ri \cdot k}$, where $k \ge 0$. Now we can replace $b_{i}$ by $q_{i}$, where $q_{i} = gcd(r_{i}, p - 1)$, as we do with $b_{i}$ at the beginning. Then all elements of $i$-th set will be $g^{qi \cdot k}$, where $k \ge 0$. This means that if we write all values $g^{0}, g^{1}, ..., g^{p - 2}$ in a line, $i$-th set will contain every $q_{i}$-th element. Now we need to find union of this sets.Let's do it using inclusion-exclusion principle. All our numbers are divisors of $p - 1$. Let's $dp_{i}$ be the coefficient near $i$ in inclusion-exclusion principle($i$ is a divisor of $p - 1$) and we can find this values, adding all $q_{i}$ alternatively. Also we need to find $q_{i}$. Let's find volume of the i-th set. It is equal to $\frac{p-1}{q_{i}}$. From the other side it is equal to such minimal number $d_{i}$, that $a_{i}^{di} = 1 mod p$ ($d_{i}$ is a cycle). From $a_{i}^{p - 1} = 1 mod p$ we have that $p - 1$ is divisible by $d_{i}$. So we can find $d_{i}$ as a divisor of $p - 1$. And $q_{i}={\frac{p-1}{d_{i}}}$.
[ "number theory" ]
2,600
null
360
E
Levko and Game
Levko loves sports pathfinding competitions in his city very much. In order to boost his performance, Levko spends his spare time practicing. The practice is a game. The city consists of $n$ intersections connected by $m + k$ directed roads. Two or more roads can connect the same pair of intersections. Besides, there can be roads leading from an intersection to itself. Levko and Zenyk are playing a game. First Levko stands on intersection $s_{1}$, and Zenyk stands on intersection $s_{2}$. They both want to get to intersection $f$. The person who does it quicker wins. If they get there at the same time, the game ends with a draw. By agreement both players start simultaneously and move with the same speed. Levko wants to win very much. He knows the lengths of all the roads in the city. Also he knows that he can change the lengths of some roads (there are $k$ such roads at all) if he pays the government. So, the government can change the length of the $i$-th road to any integer value in the segment [$l_{i}$, $r_{i}$] (both borders inclusive). Levko wondered if he can reconstruct the roads so as to win the game and whether he can hope for the draw if he cannot win. You should consider that both players play optimally well. It is guaranteed that we can get from intersections $s_{1}$ and $s_{2}$ to intersection $f$.
Algorithm: Firstly we will solve problem if first player can win. Let's make all roads that we can change equal to $r[i]$ and do two Dijkstra's algorithms from vertices $s_{1}$ and $s_{2}$. Let's $d1[i]$ be the distance from $s_{1}$ to $i$, $d2[i]$ be the distance from $s_{2}$ to $i$. Consider a road, that we can change, from $a$ to $b$. If $d1[a] < d2[a]$, we will set length of such road equal to $l[i]$ and do two Dijkstra's algorithms again. We run such process until any road changes its length. If $d1[f] < d2[f]$ after all changes then first player wins. If we replace condition $d1[a] < d2[a]$ by $d1[a] \le d2[a]$, we can check if Levko can end this game with a draw. Proof: Let's call "edges" only roads which Levko can change. When we do Dijkstra's algorithm we use all roads, not only edges. Let's prove that if there exist such edges values that first player wins, there exist values of edges such that first player wins and all this values equal either $l[i]$ or $r[i]$. Consider shortest pathes of both players. If only first player goes on edge from $a$ to $b$, we can set its value $l[i]$. Proof: there must hold $d1[a] < d2[a]$ because first player goes on it and wins. This condition holds after change of value of this edge. If second player goes on this edge, he loses because $d1[f] \le d1[a] + d(a, b) + d(b, f) < d2[a] + d(a, b) + d(b, F) = d2[f]$. If second player doesn't go on this edge, he loses because shortest path of first player became smaller($d(x, y)$ - shortest path from $x$ to $y$). If only second player goes on edge from $a$ to $b$, we can set its value $r[i]$. Proof: Shortest path of the first player doesn't change and shortest path of second player can only become larger. If no player go on edge, we can set its value $r[i]$. Proof: Shortest pathes of both players doesn't change. If both players go on edge from $a$ to $b$, we can set its value $l[i]$. Proof: Shortest pathes of both players decrease by (initial value of this edge - $l[i]$). After every such operation first player wins again and all edges become either $l[i]$ or $r[i]$. Consider result of our algorithm. Let's call edge "good" if its value is equal to $l[i]$ and "bad" if its value equals $r[i]$. (a) Let's prove that after performing all operations we will have $d1[a] < d2[a]$ for all good edges $(a, b)$. If we have $d1[a1] < d2[a1]$ for edge $(a1, b1)$ and after changing value of $(a2, b2)$ this condition doesn't hold. We have $d1[a1] > = d2[a1]$, $d1[a2] < d2[a2]$. We change only one edge and shortest path from $s2$ to $f$ become shorter so edge $(a2, b2)$ lies on this path. $d2[a1] = d2[a2] + d(a2, b2) + d(b2, a1) > d1[a2] + d(a2, b2) + d(b2, a1) \ge d1[a1]$. Contradiction. (b) Let's prove that after performing all operations we will have $d1[a] \ge d2[a]$ for all bad edges. We can continue our procces otherwise. (c) Let's prove that if condition $d1[a] < d2[a]$ holds for some edge but we doesn't change it on this iteration, this continion holds after this iteration. Proof is same as in (a). (d) Let's prove that if any subset of good edges is equal to $l[i]$ and $d1[a] < d2[a]$, ift also holds when we make all good edges equal $l[i]$. Let's simulate all procces and use (c). Lets prove that for all edges values(not necessary only $l[i]$ or $r[i]$), $d1[a] \ge d2[a]$ for all bad edges $(a, b)$. Assume that we have such edge. Consider shortest path of first player to its beginning. If there exist bad edges $(a1, b1)$ on this path, there must holds inequality $d1[a1] < d2[a1]$. Consider first of this bad edges $(a, b)$. Then shortest path of first player to $a$ doesn't consist any bad edge. Consider problem,m which is equivalent to our problem but finish is in vertex $a$. good and bad edges will be same. Let's change all value of edges as we do in item 1. Note? that all bad edges will be equal to $r[i]$. So only subset of good edges can be equal to $l[i]$ and $d1[a1] < d2[a1]$. By (d) we have that we can set all good edges $l[i]$ and condition $d1[a1] < d2[a1]$ will be satisfied. So we have contradiction thst this edge is bad. This means that if first player goes on any bad edge, he loses. So we can set $r[i]$ to all this edges. So we can set $l[i]$ to some subset of good edges. By (d) we have that if we have $d1[f] < d2[f]$ for some subset of good edges, this condition will be true if we set all good edges $l[i]$. Note that proof will be same if we want to check whether Levko can end a game with a draw.
[ "graphs", "greedy", "shortest paths" ]
2,800
null
361
A
Levko and Table
Levko loves tables that consist of $n$ rows and $n$ columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals $k$. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.
Matrix,in which all diagonal elements equal $k$ and other elements equal $0$, satisfied all conditions. For example, if n = 4 and k = 7, our matrix will be 7 0 0 0 0 7 0 0 0 0 7 0 0 0 0 7
[ "constructive algorithms", "implementation" ]
800
null
361
B
Levko and Permutation
Levko loves permutations very much. A permutation of length $n$ is a sequence of distinct positive integers, each is at most $n$. Let’s assume that value $gcd(a, b)$ shows the greatest common divisor of numbers $a$ and $b$. Levko assumes that element $p_{i}$ of permutation $p_{1}, p_{2}, ... , p_{n}$ is good if $gcd(i, p_{i}) > 1$. Levko considers a permutation beautiful, if it has exactly $k$ good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.
$gcd(1, m) = 1$, so if $n = k$, there is no suitable permutation. It is well known that $gcd(m, m - 1) = 1$. Lets construct following permutation. It has exactly $k$ good elements. $n - k 1 2 3 ... n - k - 1 n - k + 1 n - k + 2 ... n$
[ "constructive algorithms", "math", "number theory" ]
1,200
null
362
A
Two Semiknights Meet
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: $2$ squares forward and $2$ squares to the right, $2$ squares forward and $2$ squares to the left, $2$ squares backward and $2$ to the right and $2$ squares backward and $2$ to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard. Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count. Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board. Please see the test case analysis.
Autors have proposed different solutions. One can notice that if semiknights did not have a meeting after first step (it is not necessary they have a meeting in "good" square), they will not meet at all. This fact appears from board size and possible semiknight's moves. As the initial semiknight's squares are considered good for the meeting the semiknights have arrived to the one square and then they move together to one of the initial squares and meeting will count.
[ "greedy", "math" ]
1,500
null
362
B
Petya and Staircases
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. Now Petya is on the first stair of the staircase, consisting of $n$ stairs. He also knows the numbers of the dirty stairs of this staircase. Help Petya find out if he can jump through the entire staircase and reach the last stair number $n$ without touching a dirty stair once. One has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, then Petya cannot choose a path with clean steps only.
One has to note that the number of dirty stairs $ \le 3000$. Petya can reach stair number $n$ if the first and the last stairs are not dirty and there are not three or more dirty stairs in a row. So let sort the array of dirty stairs and go through it, checking for three or more consecutive dirty stairs. Also one need to check if the first or the last stair is in this array.
[ "implementation", "sortings" ]
1,100
null
362
C
Insertion Sort
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array $a$ of size $n$ in the non-decreasing order. \begin{verbatim} for (int i = 1; i < n; i = i + 1) { int j = i; while (j > 0 && a[j] < a[j - 1]) { swap(a[j], a[j - 1]); // swap elements a[j] and a[j - 1] j = j - 1; } } \end{verbatim} Petya uses this algorithm only for sorting of arrays that are permutations of numbers from $0$ to $n - 1$. He has already chosen the permutation he wants to sort but he first decided to swap some two of its elements. Petya wants to choose these elements in such a way that the number of times the sorting executes function swap, was minimum. Help Petya find out the number of ways in which he can make the swap and fulfill this requirement. It is guaranteed that it's always possible to swap two elements of the input permutation in such a way that the number of swap function calls decreases.
The number of times swap is called equals the number of inversions in the input permutation. It's easy to see that it is reasonable to swap only such elements $a_{i}$, $a_{j}$ that $i < j$ and $a_{i} > a_{j}$ (otherwise the number of inversions will increase). Let $d_{i, j}$ be the number of permutation of elements with indices from $0$ to $i$ inclusive which are strictly less than $j$. Then, after swapping elements with indices $i$ and $j$, the number of inversions will be $old - 2 * (d_{i, ai} + d_{j, aj} - d_{i, aj} - d_{j, ai}) - 1$, where old is the number of inversions in the initial permutation. It is sufficient to search all pairs of elements and pick those which help to minimize the number of inversions. The reader may prove the correctness of the formula as a supplementary task.
[ "data structures", "dp", "implementation", "math" ]
1,900
null
362
D
Fools and Foolproof Roads
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of $n$ cities, some pairs of cities are connected by bidirectional roads, each road is described by its length $l_{i}$. The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly $p$ new roads in the country. Constructing a road goes like this: - We choose a pair of \textbf{distinct} cities $u$, $v$ that will be connected by a new road (at that, it is possible that there already is a road between these cities). - We define the length of the new road: if cities $u$, $v$ belong to distinct regions, then the length is calculated as $min(10^{9}, S + 1)$ ($S$ — the total length of all roads that exist in the linked regions), otherwise we assume that the length equals $1000$. - We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of $q$ regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.
If the given graph contains less than $q$ connectivity components, then there's no solution. Otherwise it's optimal at first add edges that connect different components and afterwards all remaining edges (they will be connect edges from one component). For the first phase you can use greedy algorithm: each time you select two components, current weight of which is minimal, and connect them with an edge. For example, you can store weights of all components in the current graph in some data structure (like set in C++). For the second phase it's enough to find any component that contains two or more vertices (because loops are forbidden) and add all remaining edges between some two vertices of this component. If some action cannot be successfully executed (for example, you added all the edges and number of connectivity components if greater than $q$), then there's no solution. Asymptotics - $O(n + m + plogn).$
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
2,100
null
362
E
Petya and Pipes
A little boy Petya dreams of growing up and becoming the Head Berland Plumber. He is thinking of the problems he will have to solve in the future. Unfortunately, Petya is too inexperienced, so you are about to solve one of such problems for Petya, the one he's the most interested in. The Berland capital has $n$ water tanks numbered from $1$ to $n$. These tanks are connected by unidirectional pipes in some manner. Any pair of water tanks is connected by at most one pipe in each direction. Each pipe has a strictly positive integer width. Width determines the number of liters of water per a unit of time this pipe can transport. The water goes to the city from the main water tank (its number is $1$). The water must go through some pipe path and get to the sewer tank with cleaning system (its number is $n$). Petya wants to increase the width of some subset of pipes by at most $k$ units in total so that the width of each pipe remains integer. Help him determine the maximum amount of water that can be transmitted per a unit of time from the main tank to the sewer tank after such operation is completed.
Construct the following flow network. Water tank $1$ is the source, water tank $n$ is the sink. Every pipe from water tank $u$ to water tank $v$ is presented as two arcs - the first one with capacity $c_{uv}$ and cost $0$ and the second one with infinite capacity and cost $1$. Thus, the answer is the maximum flow with cost not greater than k. It can be found by standard augmenting paths algorithm.
[ "flows", "graphs", "shortest paths" ]
2,300
null
363
A
Soroban
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about them. Let's have a look at the Soroban's construction. Soroban consists of some number of rods, each rod contains five beads. We will assume that the rods are horizontal lines. One bead on each rod (the leftmost one) is divided from the others by a bar (the reckoning bar). This single bead is called go-dama and four others are ichi-damas. Each rod is responsible for representing a single digit from 0 to 9. We can obtain the value of a digit by following simple algorithm: - Set the value of a digit equal to 0. - If the go-dama is shifted to the right, add 5. - Add the number of ichi-damas shifted to the left. Thus, the upper rod on the picture shows digit 0, the middle one shows digit 2 and the lower one shows 7. We will consider the top rod to represent the last decimal digit of a number, so the picture shows number 720. Write the program that prints the way Soroban shows the given number $n$.
Not so much to say about this problem. You need to extract the digits of the given number (read it as string or repeteadly divide by 10 and take the remainders). Then carefully do the mapping of digits to its' representation.
[ "implementation" ]
800
null
363
B
Fence
There is a fence in front of Polycarpus's home. The fence consists of $n$ planks of the same width which go one after another from left to right. The height of the $i$-th plank is $h_{i}$ meters, distinct planks can have distinct heights. \begin{center} {\small Fence for $n = 7$ and $h = [1, 2, 6, 1, 1, 7, 1]$} \end{center} Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly $k$ consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such $k$ consecutive planks that the sum of their heights is minimal possible. Write the program that finds the indexes of $k$ consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).
Another easy problem. We need to calculate the sum of every consequtive segment of $k$ planks. One way to do this is to calculate partial prefix sums: $s_{i}=\sum_{j\leq i}h_{j}$. Then the sum of heights of the planks $i, i + 1, ..., i + k - 1$ is $s_{i + k - 1} - s_{i - 1}$. The other approach is to calculate the sum of the first $k$ planks: $h_{1} + h_{2} + ... + h_{k}$. By subtracting $h_{1}$ and adding $h_{k + 1}$ we get sum of $k$ planks starting from the second plank. Then, by subtracting $h_{2}$ and adding $h_{k + 2}$ we get sum of $k$ planks starting from the third plank, and so on.
[ "brute force", "dp" ]
1,100
null
363
C
Fixing Typos
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos. In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos). Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
The general idea of the solution is the following: while there are three consequtive equal characters, remove any one of them. After that we can only have typos of the second type. So, if we have one couple of equal characters immediately after another couple of equal characters ($xxyy$), we need to decide which character to remove, $x$ or $y$? Let's find the leftmost typo of the second type in the string. It is easy to see that we can always remove the character from the second couple. All these can be done in a single pass. Go through the characters of the given string and build the resulting string $ans$. Let's denote the current character as $ch$. If $ch$ is equal to the last two characters of $ans$, skip $ch$. If $ch$ is equal to the last character of $ans$ and $ans[length(ans) - 2] = ans[length(ans) - 3]$ (assume that $ans$ is 1-indexed), skip $ch$. Otherwise, append $ch$ to $ans$.
[ "greedy", "implementation" ]
1,400
null
363
D
Renting Bikes
A group of $n$ schoolboys decided to ride bikes. As nobody of them has a bike, the boys need to rent them. The renting site offered them $m$ bikes. The renting price is different for different bikes, renting the $j$-th bike costs $p_{j}$ rubles. In total, the boys' shared budget is $a$ rubles. Besides, each of them has his own personal money, the $i$-th boy has $b_{i}$ personal rubles. The shared budget can be spent on any schoolchildren arbitrarily, but each boy's personal money can be spent on renting only this boy's bike. Each boy can rent at most one bike, one cannot give his bike to somebody else. What maximum number of schoolboys will be able to ride bikes? What minimum sum of personal money will they have to spend in total to let as many schoolchildren ride bikes as possible?
Let's do a binary search over the number of boys that can rent a bike. So let's say that we want to check whether it possible for $k$ boys to rent bikes. If some $k$ boys can rent a bike, then the $k$ "richest" boys (with the most amount of personal money) also can do that. It is easy to see that if they can rent bikes, they can rent $k$ cheapest bikes (if we first sort the bikes in increasing order of price, it will be just the first $k$ bikes). So, take $k$ richest boys and try to match them with $k$ cheapest bikes, spending as much common budget as possible. The following algorithm works (try to understand and prove it before asking questions): take the boy with least number of money (of course, among the considered $k$ richest) and try to give him the cheapest bike. If the boy has ehough personal money to rent this bike, use his money to do this. Otherwise, use all his money and take some money from the common budget. Continue this process with the second cheapest bike and the second "poorest among the richest" boys. This process can end in two ways: we will either run out of budget and fail to rent $k$ bikes, or we will successfully rent these bikes.
[ "binary search", "greedy" ]
1,800
null
364
A
Matrix
You have a string of decimal digits $s$. Let's define $b_{ij} = s_{i}·s_{j}$. Find in matrix $b$ the number of such rectangles that the sum $b_{ij}$ for all cells $(i, j)$ that are the elements of the rectangle equals $a$ in each rectangle. A rectangle in a matrix is a group of four integers $(x, y, z, t)$ \textbf{$(x ≤ y, z ≤ t)$}. The elements of the rectangle are all cells $(i, j)$ such that $x ≤ i ≤ y, z ≤ j ≤ t$.
Let's notice that sum in the rectangle $(x1, y1, x2, y2)$ is $sum(x1, x2) \cdot sum(y1, y2)$. Where $sum(l, r) = s_{l} + s_{l + 1} + ... + s_{r}$. Then, we have to calc $sum(l, r)$ for every pair $(l, r)$ and count how many segments give us sum $x$ for any possible x ($0 \le x \le 9 \cdot |s|$). In the end we should enumerate sum on segemnt $[x1, x2]$ and find $s u m(y1,y2)={\frac{a}{s u m(x1.x2)}}$. There is corner case $a = 0$.
[ "combinatorics", "data structures", "implementation" ]
1,600
null
364
B
Free Market
John Doe has recently found a "Free Market" in his city — that is the place where you can exchange some of your possessions for other things for free. John knows that his city has $n$ items in total (each item is unique). You can bring any number of items to the market and exchange them for any other one. Note that each item is one of a kind and that means that you cannot exchange set ${a, b}$ for set ${v, a}$. However, you can always exchange set $x$ for any set $y$, unless there is item $p$, such that $p$ occurs in $x$ and $p$ occurs in $y$. For each item, John knows its value $c_{i}$. John's sense of justice doesn't let him exchange a set of items $x$ for a set of items $y$, if $s(x) + d < s(y)$ ($s(x)$ is the total price of items in the set $x$). During one day John can exchange only one set of items for something else. Initially, he has no items. John wants to get a set of items with the maximum total price. Find the cost of such set and the minimum number of days John can get it in.
We may assume that John may exchange any subset of his items $x$ to any other subset $y$, such as $s(x) + d \ge s(y)$ (it does not matter if $x$ intersects $y$). We can find all possible sums in subset of elements of the given set of items using standard dp (knapsack problem). John should always exchange all his current set of items to another, because if he had exchanged some subset of $x$ (current set) $z$ to $y$, we can say that he had exchanged $x$ to $(x\backslash y)\cap z$. So, we have to find shortest sequence of sets $a$, such as $s(a_{i + 1}) - d \ge s(a_{i})$ for any possible $i$ and $a_{0} = {}$. This subtask could be solved using following greedy algorithm. $a_{i}, i > 0$ is maximal correct sum such as $a_{i} \le a_{i - 1} + d$. Consider optimal answer $c$ and our answer $a$. Let $k$ is the first position where $a_{k} \neq c_{k}$ obiviously $a_{k} > c_{k}$ (because $a_{k}$ selected as maximal as possible). Then consider $q$ such as $q_{i} = c_{i}$ for $i \neq k$ and $q_{k} = a_{k}$. $q$ is either optimal. Applying similar operations we will obtain $a$. So, $a$ is optimal.
[ "dp", "greedy" ]
2,200
null
364
C
Beautiful Set
We'll call a set of positive integers $a$ beautiful if the following condition fulfills: for any prime $p$, if $\exists x\in a,x\equiv0\;\;\mathrm{mod}\;p$, then $|\{y\in a|y\equiv0\mathrm{\boldmath~\mod~}p\}|\geq\textstyle{\frac{\vert a|}{2}}$. In other words, if one number from the set is divisible by prime $p$, then at least half of numbers from the set is divisible by $p$. Your task is to find any beautiful set, where the number of elements is equal to $k$ and each element doesn't exceed $2k^{2}$.
We expected many unproved, but tested solutions. I think that careful prove of my solution with pen and paper is very difficult. So I will use some statistic-based facts. Consider the set of divisors of number $k$. One can check that it's beautiful set. If factorisation of $k$ has the form $\textstyle{\prod_{i=0}^{*}p_{i}^{\omega_{i}}}$ where $ \alpha _{i} \ge 3$ and $p_{i}$ is distinct primes, set of divisors of $k$ which is less than $\sqrt{k}$ is also beautiful. How to prove item 2? Consider set $A$ of pairs of divisors of $k$ $(a_{i}, b_{i})$ such as $a_{i} \cdot b_{i} = k$ and $a_{i} < b_{i}$. Obiviously (if $k$ is not complete square) any divisor will be contained only in one pair. It's easy too see that $a_{i}<{\sqrt{k}}$. Consider some element of factorisation of $k$ $p^{ \alpha }$ such as $k\equiv0mod p^{\alpha}$ and it is not true that $k\equiv0{\mathrm{~mod~}}p^{\alpha+1}$. Let $f(x)$ is maximal number $s$ such as $x\equiv0{\mathrm{~mod~}}p^{s}$. $f(a_{i}) + f(b_{i}) = \alpha $. For every $q$ such as $\operatorname{\overset{k}{p}}\equiv0{\pmod{q}}$ numbers $q, q \cdot p, ..., q \cdot p^{ \alpha }$ will be divisors of $k$. That implies that $\forall z\equiv\alpha{\mathrm{~~~mod~}}2|\{(a_{i},b_{i})\in A\mid|a_{i}-b_{i}|=z\}|=d$ where $d$ is number of divisors of $\textstyle{\frac{k}{p^{\alpha}}}$. So in $|A|\cdot{\frac{\alpha-2}{\alpha}}$ pairs both numbers are divisible by $p$. So set ${a_{0}, ..., a_{}|A|}$ is beautiful. But there are some pairs with $f(a_{i}) = \alpha $. $a_{i}<{\frac{\sqrt{k}}{p^{\alpha}}}$ is equivalent approval. It's always possible to find such $k$ as number of it's divisors is bigger than $2 \cdot w$ where $w$ is number of elements in required set. You may write following dp to find it. $dp[i][j]$ is minimal $k$ which is constructed of first $i$ primes ans has $j$ divisors. $d p[i][j]=m a x\{d p[i-1][k]\cdot p[i]^{k-1}\mid j\equiv0\mathrm{\boldmath~\mod~}k\}$ About $10$ primes is enough to cover all $k$. Now we can construct beautiful sets with more than $k$ elements. Using item $4$ we will understand that constructed answer is very beautiful (about 60% of elements divisible by every possible $p$) and we can always delete extra elements. Last items is not strict, but one can check it with his computer.
[ "brute force", "number theory" ]
2,300
null
364
D
Ghd
John Doe offered his sister Jane Doe find the gcd of some set of numbers $a$. Gcd is a positive integer $g$, such that all number from the set are evenly divisible by $g$ and there isn't such $g'$ $(g' > g)$, that all numbers of the set are evenly divisible by $g'$. Unfortunately Jane couldn't cope with the task and John offered her to find the ghd of the same subset of numbers. Ghd is a positive integer $g$, such that at least half of numbers from the set are evenly divisible by $g$ and there isn't such $g'$ $(g' > g)$ that at least half of the numbers from the set are evenly divisible by $g'$. Jane coped with the task for two hours. Please try it, too.
Consider random element $a_{r}$ of $a$. With probabillity $\textstyle{\frac{1}{2}}$ $a\equiv0\mod g$ where $g$ is ghd of $a$. Let $x_{i} = gcd(a_{i}, a_{r})$. There are no more than $d$ distinct $x_{i}$ where $d$ is number of divisors of $a_{r}$. We can find number of $a_{i}$ such as $a_{i}\equiv0\mathrm{\boldmath~\mod~}D_{k}.$ for every $k$ in $O(d^{2})$. ($D$ is set of divisors of $a_{r}$) Repeat item $1$ $x$ times we will get correct solution with probabillity $1 - 2^{ - x}$. There is the way to solve this problem $O(n \cdot plog + d \cdot 2^{plog})$ for iteration where $plog$ is the maximal number of distinct primes in factorisation of $a_{r}$.
[ "brute force", "math", "probabilities" ]
2,900
null
364
E
Empty Rectangles
You've got an $n × m$ table ($n$ rows and $m$ columns), each cell of the table contains a "0" or a "1". Your task is to calculate the number of rectangles with the sides that are parallel to the sides of the table and go along the cell borders, such that the number one occurs exactly $k$ times in the rectangle.
Let's find number of rectangles whick consist $k$ ones and intersect $y={\frac{m}{2}}$ in cartesian coordinate system. It's possible to do it in $n^{2} \cdot k$. We need to find closest $k$ ones on the top and on the bottom of the $y={\frac{m}{2}}$ and enumareate all segments $[l, r]$ such as $1 \le l \le r \le n$ and find closest $k$ ones on the top and on the bottom of the segments merging results for rows. If we have $k$ closest ones on the top and on the bottom of the segment we will find number of rectangles consists $k$ ones and cross $y={\frac{m}{2}}$ on $[l, r]$ in $O(k)$. Then we should find number of rectangles, which don't cross $y={\frac{m}{2}}$. Let's rotate table by 90 degrees, solve similar problem for two halfs of the table and so on. $T(n)=n^{2}\cdot k+4\cdot T(n/2)=n^{2}\log n\cdot k$ for square-shaped tables. At the picture 1 two closest ones on the top (black cells) lying on the 4'th and 2'nd horizontals. Closest ones on the bottom lying on the 5'th and 7'th. Then if $k = 2$ there are zero correct rectangles with two "ones" on the tom. There are four rectangles which consist one "one" on the top and one "one" on the bottom. You can see how segment grows up at the pictures 2, 3 and 4. Every time you should merge closest $k$ ones of the added row with closest $k$ ones of the current segment.
[ "divide and conquer", "two pointers" ]
3,000
null
365
A
Good Number
Let's call a number $k$-good if it contains all digits not exceeding $k$ ($0, ..., k$). You've got a number $k$ and an array $a$ containing $n$ numbers. Find out how many $k$-good numbers are in $a$ (count each number every time it occurs in array $a$).
Task was to find the least digit, that is not contained in the given number and compare with given $k$.
[ "implementation" ]
1,100
null
365
B
The Fibonacci Segment
You have array $a_{1}, a_{2}, ..., a_{n}$. Segment $[l, r]$ ($1 ≤ l ≤ r ≤ n$) is good if $a_{i} = a_{i - 1} + a_{i - 2}$, for all $i$ $(l + 2 ≤ i ≤ r)$. Let's define $len([l, r]) = r - l + 1$, $len([l, r])$ is the length of the segment $[l, r]$. Segment $[l_{1}, r_{1}]$, is longer than segment $[l_{2}, r_{2}]$, if $len([l_{1}, r_{1}]) > len([l_{2}, r_{2}])$. Your task is to find a good segment of the maximum length in array $a$. Note that a segment of length $1$ or $2$ is always good.
Good sequence may contain only zeroes or contain some positive number. In the second case such a sequence is not longer than sequence ${0, 1, 1, 2, 3, 5, 8, ..., x, y}$ where $y > 10^{9}$ and $x \le 10^{9}$. That's possible to find it using dummy algorithm. In the first case you may use binary search of two pointers.
[ "implementation" ]
1,100
null
366
A
Dima and Guards
Nothing has changed since the last round. Dima and Inna still love each other and want to be together. They've made a deal with Seryozha and now they need to make a deal with the dorm guards... There are four guardposts in Dima's dorm. Each post contains two guards (in Russia they are usually elderly women). You can bribe a guard by a chocolate bar or a box of juice. For each guard you know the minimum price of the chocolate bar she can accept as a gift and the minimum price of the box of juice she can accept as a gift. If a chocolate bar for some guard costs less than the minimum chocolate bar price for this guard is, or if a box of juice for some guard costs less than the minimum box of juice price for this guard is, then the guard doesn't accept such a gift. In order to pass through a guardpost, one needs to bribe both guards. The shop has an unlimited amount of juice and chocolate of any price starting with $1$. Dima wants to choose some guardpost, buy one gift for each guard from the guardpost and spend \textbf{exactly} $n$ rubles on it. Help him choose a post through which he can safely sneak Inna or otherwise say that this is impossible. Mind you, Inna would be very sorry to hear that!
The solution doesn't exist only if the mimimal way to bribe is grater than $n$. Otherwise we can increase the gift price to make $price1$ + $price2$ = $n$. Let's find the miminal way to bribe. We should buy that gift for old lady which costs less. It means, if we have 2 guards with params $a$ $b$ $c$ $d$, then minimum bribe price will be $min(a, b) + min(c, d)$. Let's choose the guard with the minimal bribe price. If the minimal bribe price is greater than $n$, answer -$1$. Otherwise, the possible answer is, for example: Guard number, $min(a, b)$, $n-min(a, b)$.
[ "implementation" ]
1,100
null
366
B
Dima and To-do List
You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong. Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete $k - 1$ tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks. Overall, Dima has $n$ tasks to do, each task has a unique number from $1$ to $n$. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has $6$ tasks to do in total, then, if he starts from the $5$-th task, the order is like that: first Dima does the $5$-th task, then the $6$-th one, then the $1$-st one, then the $2$-nd one, then the $3$-rd one, then the $4$-th one. Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.
Dima can make $k-1$ tasks, so Inna always tells him off for each $k$-th taks, beginning from the chosen place. So for the numbers with same modulo by k the answer will be the same. We should find the answer with minimal first task number so it is eniugh to calculate the sums of "tellings of" for tasks $0, 1... k-1$. We can do it in such way: Determine the array int $sum[k]$. And put the number into appropriate bucket while reading: $sum[$I mod k$] + = a[i]$. Now we should simply find first $i$ with minimal $sum[i]$. Complexity: $O(N)$.
[ "brute force", "implementation" ]
1,200
null
366
C
Dima and Salad
Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have $n$ fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal $k$. In other words, ${\frac{{\frac{a}{m}}a_{j}}{b-{b}_{j}}}=k$ , where $a_{j}$ is the taste of the $j$-th chosen fruit and $b_{j}$ is its calories. Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands! Inna loves Dima very much so she wants to make the salad from at least one fruit.
Let's calculate dinamic: $d[num][balance]$ where $num$ - last looked fruit, balance - difference between sum of colories and sum of tastes. Let's multiply each $b$ by $k$. The answer will be $d[n][0]$. $d[num][balance]$ = maximal possible sum of tastes under conditions. Step: from $d[num][balance]$ we can relax answers: $d[num + 1][balance] = max(d[num + 1][balance], d[num][balance])$ - if we don't choose a fruit $d[num + 1][balance + a[i] - b[i] \cdot k] = max(d[num + 1][balance + a[i] - b[i] \cdot k], d[num][balance] + a[i])$ - if we choose a fruit. Balance can be negative, so in programming languages which don't support negative indexation, indexes should be shifted by the biggest negative number for balance. If we determine the balance as $sum(b \cdot k) - sum(a)$ it will be the sum of all tastes.
[ "dp" ]
1,900
null
366
D
Dima and Trap Graph
Dima and Inna love spending time together. The problem is, Seryozha isn't too enthusiastic to leave his room for some reason. But Dima and Inna love each other so much that they decided to get criminal... Dima constructed a trap graph. He shouted: "Hey Seryozha, have a look at my cool graph!" to get his roommate interested and kicked him into the first node. A trap graph is an undirected graph consisting of $n$ nodes and $m$ edges. For edge number $k$, Dima denoted a range of integers from $l_{k}$ to $r_{k}$ $(l_{k} ≤ r_{k})$. In order to get out of the trap graph, Seryozha initially (before starting his movements) should pick some integer (let's call it $x$), then Seryozha must go some way from the starting node with number $1$ to the final node with number $n$. At that, Seryozha can go along edge $k$ only if $l_{k} ≤ x ≤ r_{k}$. Seryozha is a mathematician. He defined the loyalty of some path from the $1$-st node to the $n$-th one as the number of integers $x$, such that if he initially chooses one of them, he passes the whole path. Help Seryozha find the path of maximum loyalty and return to his room as quickly as possible!
The answer for some path is a range under which we can go all the way, and this range is the intersection of all the ranges on the path. We can conclude it because the number is valid for path if it is valid for all ranges in the path. We will iterate all ribs. Let the left board of range on a rib is the left board of our intersection. It means we can't use ribs whith left board greater than ours. Lets iterate all right boards, determining the answer as the range from fixed left board to the chosen right. This answer exists if we have any path from the first node to the last. Let's check if the graph is connected if we leave only ribs with left board not greater than our and right board not less than our. If the graph is connected - let's update the answer. Right board can be found by binary search so the complexity is $O(M^{2} \cdot logM)$.
[ "binary search", "data structures", "dfs and similar", "dsu", "shortest paths", "two pointers" ]
2,000
null
366
E
Dima and Magic Guitar
Dima loves Inna very much. He decided to write a song for her. Dima has a magic guitar with $n$ strings and $m$ frets. Dima makes the guitar produce sounds like that: to play a note, he needs to hold one of the strings on one of the frets and then pull the string. When Dima pulls the $i$-th string holding it on the $j$-th fret the guitar produces a note, let's denote it as $a_{ij}$. We know that Dima's guitar can produce $k$ distinct notes. It is possible that some notes can be produced in multiple ways. In other words, it is possible that $a_{ij} = a_{pq}$ at $(i, j) ≠ (p, q)$. Dima has already written a song — a sequence of $s$ notes. In order to play the song, you need to consecutively produce the notes from the song on the guitar. You can produce each note in any available way. Dima understood that there are many ways to play a song and he wants to play it so as to make the song look as complicated as possible (try to act like Cobein). We'll represent a way to play a song as a sequence of pairs $(x_{i}, y_{i})$ $(1 ≤ i ≤ s)$, such that the $x_{i}$-th string on the $y_{i}$-th fret produces the $i$-th note from the song. The complexity of moving between pairs $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals $|x_{1}-x_{2}|$ + $|y_{1}-y_{2}|$. The complexity of a way to play a song is the maximum of complexities of moving between adjacent pairs. Help Dima determine the maximum complexity of the way to play his song! The guy's gotta look cool!
There are many solutions for this task. I will describe my, you can deal with other by looking participants code. To find the answer we should calculate $maxDis[k][k]$, where $maxDis[i][j]$ - maximal complexity from note $i$ to note $j$. Now we should only iterate the song updating answer for each pair of adjacent notes. Let's think how we can calculate the matrix. For each place $(x_{1}, y_{1})$ on the guitar let's iterate pairs $(x_{2}, y_{2})$ with $y_{2} \le y_{1}$. If $(x_{2} \le x_{1})$ distance will be $x_{1}-x_{2} + y_{1}-y_{2}$. So we should find minimal $x_{2} + y_{2}$ in submatrix from $(0, 0)$ to $(x, y)$. If $(x_{2} \ge x_{1})$ distance will be $x_{2}-x_{1} + y_{1}-y_{2}$. So we should find maximal $x_{2}-y_{2}$ in submatrix from $(n-1, 0)$ to $(x, y)$. We will calculate this values for each note. We need too much memory so we should memorize only one previous row for each note. For each place we will update dinamics for both variants according to already calculated and for our own note (which is in this cell) we will also compare $(i + j)$ or $(i-j)$ with current value in the cell. Complexity $O(N \cdot M \cdot K)$
[ "brute force", "implementation", "math" ]
2,200
null
367
A
Sereja and Algorithm
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as $q = q_{1}q_{2}... q_{k}$. The algorithm consists of two steps: - Find any continuous subsequence (substring) of three characters of string $q$, which doesn't equal to either string "zyx", "xzy", "yxz". If $q$ doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. - Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string $q$ if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string $s = s_{1}s_{2}... s_{n}$, consisting of $n$ characters. The boy conducts a series of $m$ tests. As the $i$-th test, he sends substring $s_{li}s_{li + 1}... s_{ri}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$ to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test $(l_{i}, r_{i})$ determine if the algorithm works correctly on this test or not.
If you look at what is written in the statment, it becomes clear that the algorithm finishes its work, if we can get a string like: $xx$, $yy$, $zz$, $zyxzyxzyx...$ and all its cyclic shuffles. To check you just need to know the number of letters $x$, $y$ and $z$ separately. Quantities can be counted using partial sums.
[ "data structures", "implementation" ]
1,500
null
367
B
Sereja ans Anagrams
Sereja has two sequences $a$ and $b$ and number $p$. Sequence $a$ consists of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Similarly, sequence $b$ consists of $m$ integers $b_{1}, b_{2}, ..., b_{m}$. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions $q$ $(q + (m - 1)·p ≤ n; q ≥ 1)$, such that sequence $b$ can be obtained from sequence $a_{q}, a_{q + p}, a_{q + 2p}, ..., a_{q + (m - 1)p}$ by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of $q$.
We will divide the sequence on $min(n, p)$ sequences. $1$-st, $(1 + p)$-th, $(1 + 2 \cdot p)$-th, ... element will go to the first sequence, $2$-nd, $(2 + p)$-th, $(2 + 2 \cdot p)$-th... will go to the second sequence and so on. Now you need to find an answer for each of them, considering that $p = 1$. This can be solved by a simple method. You can go along the sequence from left to right and count the number of occurrences of each number. If the number of occurrences of each number will match the number of occurrences of the same number in the second sequence, then everything is OK.
[ "binary search", "data structures" ]
1,900
null
367
C
Sereja and the Arrangement of Numbers
Let's call an array consisting of $n$ integer numbers $a_{1}$, $a_{2}$, $...$, $a_{n}$, beautiful if it has the following property: - consider all pairs of numbers $x, y$ $(x ≠ y)$, such that number $x$ occurs in the array $a$ and number $y$ occurs in the array $a$; - for each pair $x, y$ must exist some position $j$ $(1 ≤ j < n)$, such that at least one of the two conditions are met, either $a_{j} = x, a_{j + 1} = y$, or $a_{j} = y, a_{j + 1} = x$. Sereja wants to build a beautiful array $a$, consisting of $n$ integers. But not everything is so easy, Sereja's friend Dima has $m$ coupons, each contains two integers $q_{i}, w_{i}$. Coupon $i$ costs $w_{i}$ and allows you to use as many numbers $q_{i}$ as you want when constructing the array $a$. Values $q_{i}$ are distinct. Sereja has no coupons, so Dima and Sereja have made the following deal. Dima builds some beautiful array $a$ of $n$ elements. After that he takes $w_{i}$ rubles from Sereja for each $q_{i}$, which occurs in the array $a$. Sereja believed his friend and agreed to the contract, and now he is wondering, what is the maximum amount of money he can pay. Help Sereja, find the maximum amount of money he can pay to Dima.
Clear that we need to collect as many of the most expensive properties that would have been possible to build the array. Note that having $n$ numbers, we have $m$ = $n \cdot (n - 1) / 2$ binding ties. See that this is a graph in which to do Euler path, adding as little as possible edges. For $n%2 = 1$ - everything is clear, and for $n%2 = 0$, you need to add an additional $n / 2 - 1$ rib. Why? This is your homework :)
[ "graphs", "greedy", "sortings" ]
2,000
null
367
D
Sereja and Sets
Sereja has $m$ non-empty sets of integers $A_{1}, A_{2}, ..., A_{m}$. What a lucky coincidence! The given sets are a partition of the set of all integers from 1 to $n$. In other words, for any integer $v$ $(1 ≤ v ≤ n)$ there is exactly one set $A_{t}$ such that $v\in A_{t}$. Also Sereja has integer $d$. Sereja decided to choose some sets from the sets he has. Let's suppose that $i_{1}, i_{2}, ..., i_{k}$ $(1 ≤ i_{1} < i_{2} < ... < i_{k} ≤ m)$ are indexes of the chosen sets. Then let's define an array of integers $b$, sorted in ascending order, as a union of the chosen sets, that is, $A_{i_{1}}\cup A_{i_{2}}\cup\cdot\cdot\cdot\cup A_{i_{l}}$. We'll represent the element with number $j$ in this array (in ascending order) as $b_{j}$. Sereja considers his choice of sets correct, if the following conditions are met: \[ b_{1} ≤ d; b_{i + 1} - b_{i} ≤ d (1 ≤ i < |b|); n - d + 1 ≤ b_{|b|}. \] Sereja wants to know what is the minimum number of sets $(k)$ that he can choose so that his choice will be correct. Help him with that.
Replace out sets by array, where the element - the number set to which its index belongs. Now take all the consequitive sub-arrays with lengths of $d$ and find a set of elements that were not found in that sub array. Clearly, if we as a response to select a subset of such set, it does not fit us. Remember all those "bad set." As we know all of them, we can find all the "bad" subsets. Now we choose the set with maximum count of elements which is not a bad set. It is better to work here with bit masks.
[ "bitmasks", "dfs and similar" ]
2,400
null
367
E
Sereja and Intervals
Sereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers $[l, r]$ $(1 ≤ l ≤ r ≤ m)$. Interval $[l_{1}, r_{1}]$ belongs to interval $[l_{2}, r_{2}]$ if the following condition is met: $l_{2} ≤ l_{1} ≤ r_{1} ≤ r_{2}$. Sereja wants to write out a sequence of $n$ intervals $[l_{1}, r_{1}]$, $[l_{2}, r_{2}]$, $...$, $[l_{n}, r_{n}]$ on a piece of paper. At that, no interval in the sequence can belong to some other interval of the sequence. Also, Sereja loves number $x$ very much and he wants some (at least one) interval in the sequence to have $l_{i} = x$. Sereja wonders, how many distinct ways to write such intervals are there? Help Sereja and find the required number of ways modulo $1000000007$ $(10^{9} + 7)$. Two ways are considered distinct if there is such $j$ $(1 ≤ j ≤ n)$, that the $j$-th intervals in two corresponding sequences are not equal.
We assume that the intervals are sorted, and in the end we will multiply the answer by $n!$, We can do so, as all segments are different. Consider two cases $n > m$ and $n \le m$. It would seem that you need to write different dynamics for them, but not difficult to show that in the first case the answer is always $0$ . The second case is the following dynamics : $dp_{i, l, r}$, $i$ - how many numbers we have considered , $l, r$ - only in this interval will be present number $i$. Also, we will need an additional dynamic $s_{i, l}$, $i$ - how many numbers are considered , $l$ - how many segments are already closed , and $i$ does not belong to any segment . There will be $4$ transfers, since every number we can not begin and end with more than one segment. Now we should add $x$ to our solution, it is quite simple: just add another parameter $0 / 1$ in our dynamics, if we had such a element in the beginning of some interval or not. With out dynamics, it is not difficult.
[ "combinatorics", "dp" ]
2,700
null
368
A
Sereja and Coat Rack
Sereja owns a restaurant for $n$ people. The restaurant hall has a coat rack with $n$ hooks. Each restaurant visitor can use a hook to hang his clothes on it. Using the $i$-th hook costs $a_{i}$ rubles. Only one person can hang clothes on one hook. Tonight Sereja expects $m$ guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price (if there are multiple such hooks, he chooses any of them). However if the moment a guest arrives the rack has no available hooks, Sereja must pay a $d$ ruble fine to the guest. Help Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, all hooks on the rack are available, all guests come at different time, nobody besides the $m$ guests is visiting Sereja's restaurant tonight.
Each time we will go through the array and look for the minimal element which is not yet marked. If we find an item, we add it to the answer and mark it, otherwise we will subtract the penlty from answer.
[ "implementation" ]
1,000
null
368
B
Sereja and Suffixes
Sereja has an array $a$, consisting of $n$ integers $a_{1}$, $a_{2}$, $...$, $a_{n}$. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out $m$ integers $l_{1}, l_{2}, ..., l_{m}$ $(1 ≤ l_{i} ≤ n)$. For each number $l_{i}$ he wants to know how many distinct numbers are staying on the positions $l_{i}$, $l_{i} + 1$, ..., $n$. Formally, he want to find the number of distinct numbers among $a_{li}, a_{li + 1}, ..., a_{n}$.? Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each $l_{i}$.
We will count value $ans_{i}$ - number of different elements on the suffix from $i$. For calculation will walk from the end of the array, and we count $ans_{i} = ans_{i + 1} + new_{ai}$, $new_{ai}$ equals to $1$, if element $a_{i}$ has not yet met and $0$ otherwise.
[ "data structures", "dp" ]
1,100
null
369
A
Valera and Plates
Valera is a lazy student. He has $m$ clean bowls and $k$ clean plates. Valera has made an eating plan for the next $n$ days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl \textbf{before eating}. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.
We will use greedy algorithm. Let's now $i$-th day, and current dish is a dish of first type. Then if we have the bowl, let's use it. Otherwise we will increase the answer. If the current dish is a dish of the second type, we first try to get the plate, and then the bowl. If there are no plates/bowls at all, then we will increase the answer.
[ "greedy", "implementation" ]
900
#include <iostream> using namespace std; int main() { int n, m, k, type; int ans = 0; cin >> n >> m >> k; for(int i = 0; i < n; i++) { cin >> type; if (type == 1) { if (m == 0) ans++; else m--; } else { if (k != 0) { k--; continue; } if (m != 0) { m--; continue; } ans++; } } cout << ans << endl; }
369
B
Valera and Contest
Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of $n$ students (including Valera). This contest was an individual competition, so each student in the team solved problems individually. After the contest was over, Valera was interested in results. He found out that: - each student in the team scored at least $l$ points and at most $r$ points; - in total, all members of the team scored exactly $s_{all}$ points; - the total score of the $k$ members of the team who scored the most points is equal to exactly $s_{k}$; more formally, if $a_{1}, a_{2}, ..., a_{n}$ is the sequence of points earned by the team of students in the non-increasing order $(a_{1} ≥ a_{2} ≥ ... ≥ a_{n})$, then $s_{k} = a_{1} + a_{2} + ... + a_{k}$. However, Valera did not find out exactly how many points each of $n$ students scored. Valera asked you to recover any distribution of scores between the students of the team, such that all the conditions above are met.
In this task you are to determine such array $a_{1}, a_{2}, ..., a_{n}$, that following conditions are met: $r \ge a_1 \ge a_2 \ge \dots \ge a_n \ge l$; $s_k = \sum_{i = 1}^k a_i$; $s_{all} = \sum_{i = 1}^n a_i$; It's clear to understand, that value $s_{k}$ should be distributed evenly between the first $k$ elements. For example, you can use following algorithm: If $k \neq n$, you should use same algorithm with other elements, but there are to distribute value $s_{all} - s_{k}$. Some participants forgot about test, where $k = n$. They received RE11.
[ "constructive algorithms", "implementation", "math" ]
1,400
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, k, l, r, s, sk; cin >> n >> k >> l >> r >> s >> sk; int tsk = s - sk; vector < int > ans(n); for(int i = 0; i < k; i++) { ans[i] = sk / k; if (sk % k != 0) ans[i]++, sk--; } if (k != n) { for(int i = k; i < n; i++) { ans[i] = tsk / (n - k); if (tsk % (n - k) != 0) ans[i]++, tsk--; } } bool ok = true; for(int i = 0; i < k; i++) { if (ans[i] < l || ans[i] > r) ok = false; for(int j = k; j < n; j++) { if (ans[j] > ans[i]) ok = false; if (ans[j] < l || ans[j] > r) ok = false; } } random_shuffle(ans.begin(), ans.end()); for(int i = 0; i < n; i++) cout << ans[i] << ' '; }
369
C
Valera and Elections
The city Valera lives in is going to hold elections to the city Parliament. The city has $n$ districts and $n - 1$ bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from $1$ to $n$, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired. There are $n$ candidates running the elections. Let's enumerate all candidates in some way by integers from $1$ to $n$, inclusive. If the candidate number $i$ will be elected in the city Parliament, he will perform exactly one promise — to repair all problem roads on the way from the $i$-th district to the district $1$, where the city Parliament is located. Help Valera and determine the subset of candidates such that if all candidates from the subset will be elected to the city Parliament, all problem roads in the city will be repaired. If there are several such subsets, you should choose the subset consisting of the minimum number of candidates.
Consider all the roads that we need to repair. Mark the ends of $u, v$ white. After that, we will consider a simple dynamic programming $d[v]$ ($v$ is the vertex) on the tree that for each vertex in the tree determines the number of white vertexes in the subtree. It is easy to calculate this by using a recursive function $calc(v, prev)$ ($v$ is the current node, and $prev$ its immediate ancestor): After that we will add to answer all white vertexes $v$ such that next condition is correct: $d[v] = 1$
[ "dfs and similar", "graphs", "trees" ]
1,600
#include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <map> #include <queue> #include <deque> #include <stack> #include <list> #include <bitset> #include <utility> #include <functional> #include <string> #include <algorithm> #include <cstring> #include <cstdio> #include <memory.h> #include <ctime> #include <cassert> #include <cmath> using namespace std; #define forn(i,n) for(int i = 0; i < int(n); i++) #define ford(i,n) for(int i = int(n) - 1; i >= 0; i--) #define fore(i,a,b) for(int i = int(a); i <= int(b); i++) #define foreach(it,a) for(__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) #define sz(a) int((a).size()) #define all(a) (a).begin(),(a).end() #define pb push_back #define mp make_pair #define ft first #define sc second template<typename X> inline X abs(const X& a) { return (a < 0 ? -a : a); } template<typename X> inline X sqr(const X& a) { return (a * a); } typedef long long li; typedef long double ld; typedef pair<int,int> pt; typedef pair<ld, ld> ptd; const int INF = 1000000000; const li INF64 = li(INF) * li(INF); const ld EPS = ld(1e-9); const ld PI = ld(3.1415926535897932384626433832795); int n; const int N = 300000 + 300; int white[N], d[N]; vector < int > g[N]; inline bool read() { if (scanf("%d", &n) != 1) return false; forn(i, n - 1) { int x, y, t; assert(scanf("%d %d %d", &x, &y, &t) == 3); x--, y--; g[x].pb(y); g[y].pb(x); if (t == 2) { white[x] = 1; white[y] = 1; } } return true; } void go(int v, int prev = -1) { d[v] = white[v]; forn(i, sz(g[v])) { int to = g[v][i]; if (prev == to) continue; go(to, v); d[v] += d[to]; } } inline void solve() { go(0); vector < int > ans; forn(i, n) { if (white[i] && d[i] == 1) { ans.pb(i + 1); } } printf("%d\n", sz(ans)); forn(i, sz(ans)) { if (i) printf(" "); printf("%d", ans[i]); } } int main() { #ifdef gridnevvvit freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif assert(read()); solve(); #ifdef gridnevvvit cerr << "Time == " << clock() << endl; #endif }
369
D
Valera and Fools
One fine morning, $n$ fools lined up in a row. After that, they numbered each other with numbers from $1$ to $n$, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun. Every fool has exactly $k$ bullets and a pistol. In addition, the fool number $i$ has probability of $p_{i}$ (in percent) that he kills the fool he shoots at. The fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot. Let's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number $j$ ($0 ≤ j ≤ k$) there is a nonzero probability that after $j$ rounds of the fun this situation will occur. Valera knows numbers $p_{1}, p_{2}, ..., p_{n}$ and $k$. Help Valera determine the number of distinct possible situations.
Let's $p[A]$ is the $p_{A}$ from the statement. It's clear to understand that you can discribe the state by using pair of integers ($A, B$), where $A$ is a number of the fool with smallest index, $B$ - the second fool from the left. It is clear to understand that fool with indexes $j \ge B$ will be living. After that we will use bfs on the states $(A, B)$. State ($0, 1$) is always visitable, because it is initial. We will push it in the queue. After that, there are only three transitions from current state $(A, B)$. $(B + 1, B + 2)$ - this transition is possible if and only if $p[A] > 0$ and there are some fool with index $j \ge B$, which has non-zero value $p[j] > 0$. $(A, B + 1)$ - this transition is possible if and only if $p[A] > 0$ and there are no fool with index $j \ge B$, which has $p[j] = 100$. $(B, B + 1)$ - this transition is possible if and only if $p[A] \neq 100$ and there are some fool with index $j \ge B$, which has non-zero value $p[j] > 0$. After that you are to determine number of states, which has distance from state $(0, 1)$ less or equal to $k$. Also you should be careful, that if there are only one fool, that he doesn't shot.
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
2,200
#include <iostream> #include <queue> #include <cstring> #include <cstdio> using namespace std; #define pb push_back #define mp make_pair #define ft first #define sc second typedef pair<int,int> pt; const int N = 3000 + 50; int n, k, p[N], d[N][N], sufP[N], sufO[N]; int main() { #ifdef gridnevvvit freopen("input.txt", "rt", stdin); freopen("output.txt", "wt", stdout); #endif cin >> n >> k; for(int i = 0; i < n; i++) cin >> p[i]; queue < pt > q; for(int i = n - 1; i >= 0; i--) { if (i + 1 != n) { sufP[i] = sufP[i + 1]; sufO[i] = sufO[i + 1]; } sufP[i] += (p[i] > 0); sufO[i] += (p[i] == 100); } q.push(mp(0, 1)); d[0][1] = 1; int ans = 1; while (!q.empty()) { pt cur = q.front(); q.pop(); int A = cur.ft, B = cur.sc; if (A >= n || B >= n || d[A][B] > k) continue; if (p[A] > 0 && sufP[B] > 0 && d[B + 1][B + 2] == 0) { d[B + 1][B + 2] = d[A][B] + 1; ans ++; q.push(mp(B + 1, B + 2)); } if (p[A] > 0 && sufO[B] == 0 && d[A][B + 1] == 0) { d[A][B + 1] = d[A][B] + 1; ans ++; q.push(mp(A, B + 1)); } if (p[A] != 100 && sufP[B] > 0 && d[B][B + 1] == 0) { d[B][B + 1] = d[A][B] + 1; ans ++; q.push(mp(B, B + 1)); } } cout << ans << endl; }
369
E
Valera and Queries
Valera loves segments. He has recently come up with one interesting problem. The $Ox$ axis of coordinates has $n$ segments, the $i$-th segment starts in position $l_{i}$ and ends in position $r_{i}$ (we will mark it as $[l_{i}, r_{i}]$). Your task is to process $m$ queries, each consists of number $cnt_{i}$ and a set of $cnt_{i}$ coordinates of points located on the $Ox$ axis. The answer to the query is the number of segments, such that each of them contains at least one point from the query. Segment $[l, r]$ contains point $q$, if $l ≤ q ≤ r$. Valera found the solution of this problem too difficult. So he asked you to help him. Help Valera.
Let's calculate sets $xs[y]$ - all segments, whose right borders are exactly equal to $y$. Now we reduce our task to another. For each query we will count the number of segments that doesn't belong to any one point. Let's it will be the value $v$. Then the answer to the query is $n - v$. We add to our request the point $0$ and a point $MV + 1$, where $MV = 1000000$. Let points request have the form $x_{1} < x_{2}... < x_{n}$. Consider the $x_{i}$ and $x_{i + 1}$. Let $p_{i}$ is the number of segments that lie strictly inside $x_{i}$ and $x_{i + 1}$. Then $v = p_{1} + p_{2} + ... + p_{n - 1}$. We will use following algorithm to find the values $p_{i}$. Let consider all such pairs $(x_{}, x_{i + 1})$ for all requests and to add them to a second set $xQ[y]$ - all pairs whose right boundary is equal to $r$. Then to find the values $p$ of pairs $(x_{i}, x_{i + 1})$ we will iterate ascending the right border. Additionally, we will support Fenwick's tree, which can make $+ = 1$ at the point, and can calculate sum of the prefix. Let $i$ - the current right border. Then we can find out the value $p$ for all pairs $(l, r)$, with the right border is equal to the $i$ $(l, i)$. Let $j$ left border of the pair. Then the answer for the pair is the value of $S - sum(j)$, where $S$ - all added to the Fenwick's left borders, and $sum(j)$ - sum of the prefix $j$. After that, for the current coordinate $i$ we need to consider all segments in the set $xs[i]$. Let $j$ left boundary of the segment. Then we need to make $+ = 1$ at the point $j$ in our Fenwick's tree. The total solution complexity is $O((n+m+c n t_{p o i n t s})\log(A))$.
[ "binary search", "data structures" ]
2,200
#define _CRT_SECURE_NO_DEPRECATE #define _USE_MATH_DEFINES #include <iostream> #include <fstream> #include <iomanip> #include <utility> #include <complex> #include <vector> #include <bitset> #include <string> #include <stack> #include <queue> #include <set> #include <list> #include <map> #include <algorithm> #include <deque> #include <cstdio> #include <cstdlib> #include <cassert> #include <climits> #include <ctime> #include <cstring> #include <cmath> using namespace std; #define pb push_back #define mp make_pair #define all(a) a.begin(), a.end() #define sz(a) int(a.size()) #define forn(i,n) for (int i = 0; i < int(n); i++) #define ford(i,n) for (int i = int(n) - 1; i >= 0; i--) #define x1 ___x1 #define y1 ___y1 #define x first #define ft first #define y second #define sc second template<typename X> inline X abs(const X& a) { return a < 0? -a : a; } template<typename X> inline X sqr(const X& a) { return a * a; } typedef long long li; typedef long double ld; typedef pair<int, int> pt; const int INF = int(1e9); const li INF64 = li(1e18); const ld EPS = 1e-9; const ld PI = ld(3.1415926535897932384626433832795); const int N = 1000 * 1000 + 13; int n, m; pt a[N]; vector<int> q[N]; inline bool read () { if (scanf ("%d%d", &n, &m) != 2) return false; forn (i, n) { int l, r; assert(scanf ("%d%d", &l, &r) == 2); a[i] = mp(l, r); } forn (i, m) { int cnt; assert(scanf("%d", &cnt) == 1); q[i].pb(0); forn (j, cnt) { int p; assert(scanf ("%d", &p) == 1); q[i].pb(p); } q[i].pb(1000 * 1000 + 3); //sort(all(q[i])); } return true; } int ans[N]; vector<int> xs[N]; vector<pt> qq[N]; int t[N]; inline int sum (int r) { int ans = 0; for (; r >= 0; r = (r & (r + 1)) - 1) ans += t[r]; return ans; } inline int sum (int l, int r) { return sum(r) - sum(l - 1); } inline void inc (int i, int add) { for (; i < N; i = (i | (i + 1))) t[i] += add; } inline void solve () { forn (i, n) xs[ a[i].y ].pb(a[i].x); forn (i, m) forn (j, sz(q[i]) - 1) { int l = q[i][j] + 1, r = q[i][j + 1] - 1; qq[r].pb(mp(l, i)); } forn (i, N) { forn (j, sz(xs[i])) { int y = xs[i][j]; inc(y, 1); } forn (j, sz(qq[i])) { int id = qq[i][j].sc; ans[id] += sum(qq[i][j].ft, i); } } forn (i, m) { printf ("%d\n", n - ans[i]); } } int main () { //freopen("input.txt", "rt", stdin); //freopen("output.txt", "wt", stdout); srand(time(NULL)); cout << setprecision(10) << fixed; cerr << setprecision(5) << fixed; assert(read()); solve(); return 0; }
370
A
Rook, Bishop and King
Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an $8 × 8$ table. A field is represented by a pair of integers $(r, c)$ — the number of the row and the number of the column (in a classical game the columns are traditionally indexed by letters). Each chess piece takes up exactly one field. To make a move is to move a chess piece, the pieces move by the following rules: - A rook moves any number of fields horizontally or vertically. - A bishop moves any number of fields diagonally. - A king moves one field in any direction — horizontally, vertically or diagonally. \begin{center} {\small The pieces move like that} \end{center} Petya is thinking about the following problem: what minimum number of moves is needed for each of these pieces to move from field $(r_{1}, c_{1})$ to field $(r_{2}, c_{2})$? At that, we assume that there are no more pieces besides this one on the board. Help him solve this problem.
There are two approaches to this task. The first is use BFS to find the shortest path three times. The second is to notice that: A rook can reach the destination in one or two moves. If the starting and the destination fields are in the same row or column, one move is enough. A bishop can reach only fields that are colored the same as the starting cell, and can do this in at most two moves: if the starting and the destination fields are on the same diagonal, one move is enough. To find this out, check that $r_1 - c_1 = r_2 - c_2$ OR $r_1 + c_1 = r_2 + c_2$. A king should make $\max(|r_1 - r_2|, |c_1 - c_2|)$ moves.
[ "graphs", "math", "shortest paths" ]
1,100
null
370
B
Berland Bingo
Lately, a national version of a bingo game has become very popular in Berland. There are $n$ players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the $i$-th player contains $m_{i}$ numbers. During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct. You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.
It is good idea to think about cards as set of numbers. It is easy to see that card $a$ can't be finished before $b$ if $b$ is subset of $a$. So all you need is to find such cards (sets) which do not have other card (other set) as subset. Since there are at most 1000 cards, you may iterate through all pairs and check that one card contains other in naive way like:
[ "implementation" ]
1,300
null
370
C
Mittens
A Christmas party in city S. had $n$ children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to $m$, and the children are numbered from 1 to $n$. Then the $i$-th child has both mittens of color $c_{i}$. The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children. The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.
Let's show that if the most frequent color appears not more than $\lfloor{\frac{n}{2}}\rfloor$ times, than all children can get mittens of distinct colors. One way to construct such solution is to sort all left mittens in the order of decreasing frequency of their colors: for the input 1 2 1 2 3 1 3 3 1 we get 1 1 1 1 3 3 3 2 2. To obtain the sequence of right mittens, rotate the sequence of left mittens to the left by the maximum color frequency (in the example it is 4, so we get the sequence 3 3 3 2 2 1 1 1 1). Then just match the sequences (1 - 3, 1 - 3, 1 - 3, 1 - 2, 3 - 2, 3 - 1, 3 - 1, 2 - 1, 2 - 1). It can be easily shown that all pairs consist of distinct colors. OK, but what to do if there is a dominating color that appears more than half times? Use exactly the same algorithm! It will maximize the number of pairs of distinct colors.
[ "constructive algorithms", "greedy", "sortings" ]
1,800
null
370
D
Broken Monitor
Innocentius has a problem — his computer monitor has broken. Now some of the pixels are "dead", that is, they are always black. As consequence, Innocentius can't play the usual computer games. He is recently playing the following game with his younger brother Polycarpus. Innocentius is touch-typing a program that paints a white square one-pixel wide frame on the black screen. As the monitor is broken, some pixels that should be white remain black. Polycarpus should look at what the program displayed on the screen and guess the position and size of the frame Innocentius has painted. Polycarpus doesn't like the game but Innocentius persuaded brother to play as "the game is good for the imagination and attention". Help Polycarpus, automatize his part in the gaming process. Write the code that finds such possible square frame that: - the frame's width is 1 pixel, - the frame doesn't go beyond the borders of the screen, - all white pixels of the monitor are located on the frame, - of all frames that satisfy the previous three conditions, the required frame must have the smallest size. Formally, a square frame is represented by such pixels of the solid square, that are on the square's border, that is, are not fully surrounded by the other pixels of the square. For example, if the frame's size is $d = 3$, then it consists of 8 pixels, if its size is $d = 2$, then it contains 4 pixels and if $d = 1$, then the frame is reduced to a single pixel.
There are a lot of correct approaches to solve the problem. But there are much more incorrect :) One way to solve the problem is following. It is easy to see that in possible answer there are two opposite sides each containing w. In opposite case frame can be shrinked. So the size of frame is $dx$ or $dy$, where $dx = maxx - minx + 1$ and $dy = maxy - miny + 1$ ($minx, maxx, miny, maxy$ are coordinates of left/right/top/bottom ws). Obviously, you should choose $max(dx, dy)$ as a size. Now we know the size of the required frame. How to find it's leftmost-topmost corner? The set of possible $x$s is: $minx, maxx - size + 1$ and 0. Indeed, you may move frame to the left until it will abuts to w by left size/right size of abuts to the left side of monitor. Similarly, the set of possible $y$s as y-coordinate of leftmost-topmost corner: $miny, maxy - size + 1, 0$. Now the solution looks like: All you need is to write frame_correct. You may iterate through frame and check that all cells inside monitor and calculate the number of ws on it. If all the cells are inside and calculated number equals to total number of w, then return true. This solution works in $O(nm)$.
[ "brute force", "constructive algorithms", "greedy", "implementation" ]
2,100
null
370
E
Summer Reading
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer. As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty. As Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.
For each book number that is in the sequence, find the leftmost and the rightmost position of this number. In other words, for each such book number we find a segment of positions that should consist of this number. If for some pair of numbers there segments intersect, it is impossible to construct the answer. The same thing happens if some segment has length more than 5. It is reasonable to separately handle the case when all given numbers are zeroes. In this case, fill in the numbers greedily, spending 2 days on each book (probably, except the last one). So, we have some blocks of numbers and gaps between them. Lets do the following DP: each state of DP is described by two values ($i, j$): $i$ means the number of block (lets enumerate them consecutively), $j$ means how far to the right will this block eventually extend (if there is a gap after this block, it is possible that we fill some prefix of this gap with the same book number that is in the block). It is clear that $j - i$ will not exceed 5, so we actually can describe the state by values ($i, j - i$), which may sound more convenient. So, the number of states is linear. Lets say that $D(i, j)$ is true if it it possible to correctly fill all the gaps that come before the $i$-th block, under condition that the $i$-th block extends to the position $j$, and $D(i, j)$ is false otherwise. To calculate the value of $D(i, j)$, lets try to extend the $i$-th block to the left in all (not so many) possible ways (to replace some number of consecutive zeroes that are in the gap just before the $i$-th block). Then, try to fix where the previous block can actually end (fix the state $D(i - 1, k)$, where $D(i - 1, k)$ is true, of course). To make a transition in DP, we should check whether it possible or not to fill the rest of the gap between the $(i - 1)$-th block and the $i$-th block. Lets say that $(i - 1)$-th block consists of number $x$, the $i$-th block consists of number $y$, and there are $f$ still unfilled positions in the gap. Than the gap can be correctly filled if and only if $2 \cdot (y - x - 1) \le f \le 5 \cdot (y - x - 1)$. If you understand this DP, it won't be difficult for you to find out how to construct the answer from it.
[ "dp", "greedy" ]
2,500
null
371
A
K-Periodic Array
This task will exclusively concentrate only on the arrays where all elements equal 1 and/or 2. Array $a$ is $k$-period if its length is divisible by $k$ and there is such array $b$ of length $k$, that $a$ is represented by array $b$ written exactly $\scriptstyle{\frac{n}{k}}$ times consecutively. In other words, array $a$ is $k$-periodic, if it has period of length $k$. For example, any array is $n$-periodic, where $n$ is the array length. Array $[2, 1, 2, 1, 2, 1]$ is at the same time 2-periodic and 6-periodic and array $[1, 2, 1, 1, 2, 1, 1, 2, 1]$ is at the same time 3-periodic and 9-periodic. For the given array $a$, consisting only of numbers one and two, find the minimum number of elements to change to make the array $k$-periodic. If the array already is $k$-periodic, then the required value equals $0$.
For array to be periodic, elements $1, 1 + k, 1 + 2 * k, \dots $ must be equal. Also, elements $2, 2 + k, 2 + 2 * k, \dots $ must be equal. And so on up to $k$. So each element of the array is a part of exactly one group. And there are $k$ groups total. Each such group is independent. Let's consider some group of elements, that contain $a$ ones and $b$ twos. All elements in this group must be equal. So we either change all ones to twos or all twos to ones. First option will require $a$ changing operations and second one - $b$ changing operations. For the optimal solution, you should select the operation with smaller number of changing operations required.
[ "greedy", "implementation", "math" ]
1,000
null
371
B
Fox Dividing Cheese
Two little greedy bears have found two pieces of cheese in the forest of weight $a$ and $b$ grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox, how are you going to do that?", the curious bears asked. "It's easy", said the fox. "If the mass of a certain piece is divisible by two, then I can eat exactly a half of the piece. If the mass of a certain piece is divisible by three, then I can eat exactly two-thirds, and if the mass is divisible by five, then I can eat four-fifths. I'll eat a little here and there and make the pieces equal". The little bears realize that the fox's proposal contains a catch. But at the same time they realize that they can not make the two pieces equal themselves. So they agreed to her proposal, but on one condition: the fox should make the pieces equal as quickly as possible. Find the minimum number of operations the fox needs to make pieces equal.
It is easy to see that the fox can do three type of operations: divide by 2, divide by 3 and divide by 5. Let's write both given numbers in form $a = x \cdot 2^{a2} \cdot 3^{a3} \cdot 5^{a5}$, $b = y \cdot 2^{b2} \cdot 3^{b3} \cdot 5^{b5}$, where $x$ and $y$ are not dibisible by 2, 3 and 5. If $x \neq y$ the fox can't make numbers equal and program should print -1. If $x = y$ then soluion exists. The answer equals to $|a_{2} - b_{2}| + |a_{3} - b_{3}| + |a_{5} - b_{5}|$, because $|a_{2} - b_{2}|$ is the minimal number of operations to have 2 in the same power in both numbers, $|a_{3} - b_{3}|$ is the minimal number of operations to have 3 in the same power in both numbers, and $|a_{5} - b_{5}|$ is the same for 5.
[ "math", "number theory" ]
1,300
null
371
C
Hamburgers
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (bread), 'S' (sausage) и 'C' (cheese). The ingredients in the recipe go from bottom to top, for example, recipe "ВSCBS" represents the hamburger where the ingredients go from bottom to top as bread, sausage, cheese, bread and sausage again. Polycarpus has $n_{b}$ pieces of bread, $n_{s}$ pieces of sausage and $n_{c}$ pieces of cheese in the kitchen. Besides, the shop nearby has all three ingredients, the prices are $p_{b}$ rubles for a piece of bread, $p_{s}$ for a piece of sausage and $p_{c}$ for a piece of cheese. Polycarpus has $r$ rubles and he is ready to shop on them. What maximum number of hamburgers can he cook? You can assume that Polycarpus cannot break or slice any of the pieces of bread, sausage or cheese. Besides, the shop has an unlimited number of pieces of each ingredient.
Let's use binary search approach. For given number of hamburgers (say, $x$) let's find the minimal number of money needed to cook them. Say, for one hamburger Polycarpus needs $c_{b}$ bread pieces, $c_{s}$ sausages pieces, $c_{c}$ cheese pieces. So for $x$ hamburgers he needs: $c_{b} \cdot x$, $c_{s} \cdot x$ and $c_{c} \cdot x$ pieces (by types). Since he already has $n_{b}$, $n_{s}$ and $n_{c}$ pieces, so he needs to buy: bread: $\max(0, c_b \cdot x - n_b)$, sausages: $\max(0, c_s \cdot x - n_s)$, cheese: $\max(0, c_c \cdot x - n_c)$. So the formula to calculate money to cook $x$ hamburgers is: $f(x) = max(0, c_{b} \cdot x - n_{b}) \cdot p_{b} + max(0, c_{s} \cdot x - n_{s}) \cdot p_{s} + max(0, c_{c} \cdot x - n_{c}) \cdot p_{c}$ Obviously, the function $f(x)$ is monotonic (increasing). So it is possible to use binary search approach to find largest $x$ such that $f(x) ler$.
[ "binary search", "brute force" ]
1,600
null
371
D
Vessels
There is a system of $n$ vessels arranged one above the other as shown in the figure below. Assume that the vessels are numbered from 1 to $n$, in the order from the highest to the lowest, the volume of the $i$-th vessel is $a_{i}$ liters. Initially, all the vessels are empty. In some vessels water is poured. All the water that overflows from the $i$-th vessel goes to the $(i + 1)$-th one. The liquid that overflows from the $n$-th vessel spills on the floor. Your task is to simulate pouring water into the vessels. To do this, you will need to handle two types of queries: - Add $x_{i}$ liters of water to the $p_{i}$-th vessel; - Print the number of liters of water in the $k_{i}$-th vessel. When you reply to the second request you can assume that all the water poured up to this point, has already overflown between the vessels.
The naive solution for this problem will work like this. Let us store an amount of water in each vessel in some array $v$. If we need to know how much water is in some vessel, we just take the number from the array. If we need to pour $x$ units of water into vessel number $i$, we must follow the simple procedure: 1. If $x = 0$ then all water is poured and we must end the procedure 2. If $i > n$ then all remaining water is spilled on the floor and we must end the procedure 3. If $x$ units of water can fit into the $i$-th vessel, then add $x$ to $v[i]$ and end the procedure 4. Fill $i$-th vessel completely and subtract used amount from $x$. 5. Assign $i = i + 1$. 6. Go to the first step. In the worst case scenario such procedure can iterate through all vessels each time. For example, if there are $n$ vessels and each vessels have capacity of one unit of water, each query like $11n$ will take $O(n)$ time to process. To make this solution faster we should notice, that once completely filled, vessel can be skipped during the algorithm above because it can not consume any more water. So instead of $i = i + 1$ assignment should be like $i = findNextNotFilledVessel(i)$. To implement this function we can use different structures. For example, we can use sorted set of numbers (set in C++, TreeSet in Java). Let store the set of indices of unfilled vessels. So to find next not filled vessel from $i$-th vessel, we must find smallest number, that is contained in set and is strictly greater than $i$. There are built-in methods for it (upper_bound in C++, higher in Java). Also, each time we fill the vessel, we must erase corresponding index from the set. So now we can see, that algorithm can not complete more that $O((m + n)logn)$ operations for all queries. Because on each iteration of the pouring procedure either the vessel is filled (which can only happen $n$ times during the whole runtime), or we run out of water (or vessels) and the procedure is stopped. So there will be only total of $O(m + n)$ iterations of the pouring procedure and each iteration require one lookup in the sorted set, which takes $O(logn)$ operations. So the total number of needed operations is $O((m + n)logn)$.
[ "data structures", "dsu", "implementation", "trees" ]
1,800
null
371
E
Subway Innovation
Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter! The President of Berland was forced to leave only $k$ of the currently existing $n$ subway stations. The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the $Ox$ axis, the $i$-th station is at point with coordinate $x_{i}$. In such case the distance between stations $i$ and $j$ is calculated by a simple formula $|x_{i} - x_{j}|$. Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such $k$ stations that minimize the average commute time in the subway! Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is $\textstyle{\frac{n(n-1)}{2}}$) and divided by the speed of the train. Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such $k$ stations that the average commute time in the subway is minimized.
It is easy to see that you need to minimize the sum of pairwise distances between $k$ stations. The main idea to do it is to sort them and the required stations will form a continuous segment. It is easy to prove by contradiction. Huge constraints do not allow to use straight-forward method to find required segment. Let's call $f(i, k)$ - sum of pairwise distances of $k$ stations starting from the $i$-th. To find $f(0, k)$ you need to start from $f(0, 0) = 0$ and use transformation from calculated $f(0, i)$ to $f(0, i + 1)$. You can use equation: $f(0,i+1)=f(0,i)+\sum_{0<i<i}(x_{i}-x_{j})=$ $=f(0,i)+x_{i}\cdot i-\sum_{\small o<i<i}x_{j}=$ $= f(0, i) + x_{i} \cdot i - sum(0, i - 1)$ where $sum(l, r)$ means $x_{l} + x_{l + 1} + ... + x_{r}$. We can precalculate $sum[i] = x_{0} + x_{1} + ... + x_{i}$ and use equation $sum(l, r) = sum[r] - sum[l - 1]$ to find $sum(l, r)$ in $O(1)$. Actually we need $f(0, k)$, $f(1, k)$ and so on (and find minimal value among them). To recalculate $f(i, k)$ to $f(i + 1, k)$ you need exclude $x_{i}$ and include $x_{i + k}$. Using the method like in the previous paragraph: $f(i + 1, k) = f(i, k) - (sum(i + 1, i + k - 1) - x_{i} \cdot (k - 1)) + (x_{i + k} \cdot (k - 1) - sum(i + 1, i + k - 1))$.
[ "greedy", "math", "two pointers" ]
2,000
null
372
A
Counting Kangaroos is Fun
There are $n$ kangaroos with pockets. Each kangaroo has a size (integer number). A kangaroo can go into another kangaroo's pocket if and only if the size of kangaroo who hold the kangaroo is at least twice as large as the size of kangaroo who is held. Each kangaroo can hold at most one kangaroo, and the kangaroo who is held by another kangaroo cannot hold any kangaroos. The kangaroo who is held by another kangaroo cannot be visible from outside. Please, find a plan of holding kangaroos with the minimal number of kangaroos who is visible.
Because of the number of holding-held relations is at most $\textstyle{\frac{N}{2}}$, We can assume that first half of kangaroos do not hold any kangaroos, and last half of kangaroos are not held by any kangaroos. So we can split kangaroos in two set, such that first set contains the kangaroos whose size is in smaller half and second set contains the kangaroos whose size is in larger half, and use easy greedy algorithm. The time conplexity is O(N log N) for sorting and O(N) for greedy, so the time conplexity is O(N log N).
[ "binary search", "greedy", "sortings", "two pointers" ]
1,600
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; int main() { int num; scanf("%d",&num); vector<int>vec; for(int i=0;i<num;i++) { int zan; scanf("%d",&zan); vec.push_back(zan); } sort(vec.begin(),vec.end()); int pt=num/2; int ans=num; for(int i=0;i<num/2;i++) { for(;;) { if(vec[i]*2<=vec[pt]) { ans--; pt++; break; } else { pt++; } if(pt==num) { break; } } if(pt==num) { break; } } printf("%d\n",ans); }
372
B
Counting Rectangles is Fun
There is an $n × m$ rectangular grid, each cell of the grid contains a single integer: zero or one. Let's call the cell on the $i$-th row and the $j$-th column as $(i, j)$. Let's define a "rectangle" as four integers $a, b, c, d$ $(1 ≤ a ≤ c ≤ n; 1 ≤ b ≤ d ≤ m)$. Rectangle denotes a set of cells of the grid ${(x, y) :  a ≤ x ≤ c, b ≤ y ≤ d}$. Let's define a "good rectangle" as a rectangle that includes only the cells with zeros. You should answer the following $q$ queries: calculate the number of good rectangles all of which cells are in the given rectangle.
We can precalculate all rectangles, in O(N^2M^2) with using consecutive sums for 2D. And then we use 4D consecutive sums, we can answer the queries. The time conplexity is O(N^2M^2+Q).
[ "brute force", "divide and conquer", "dp" ]
1,900
#include<stdio.h> int map[50][50]; int rui[51][51]; int dat[50][50][50][50]; int ans[51][51][51][51]; int main() { int mx,my,query; scanf("%d%d%d",&mx,&my,&query); for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { char zan; scanf(" %c",&zan); map[i][j]=zan-'0'; } } for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { rui[i+1][j+1]=rui[i+1][j]+rui[i][j+1]-rui[i][j]+map[i][j]; } } for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { for(int k=i;k<mx;k++) { for(int l=j;l<my;l++) { if(rui[k+1][l+1]-rui[i][l+1]-rui[k+1][j]+rui[i][j]==0) { dat[i][j][k][l]=1; } } } } } for(int i=0;i<mx;i++) { for(int j=0;j<my;j++) { for(int k=0;k<mx;k++) { for(int l=0;l<my;l++) { ans[i+1][j+1][k+1][l+1] =ans[i][j+1][k+1][l+1] +ans[i+1][j][k+1][l+1] +ans[i+1][j+1][k][l+1] +ans[i+1][j+1][k+1][l] -ans[i][j][k+1][l+1] -ans[i][j+1][k][l+1] -ans[i][j+1][k+1][l] -ans[i+1][j][k][l+1] -ans[i+1][j][k+1][l] -ans[i+1][j+1][k][l] +ans[i+1][j][k][l] +ans[i][j+1][k][l] +ans[i][j][k+1][l] +ans[i][j][k][l+1] -ans[i][j][k][l] +dat[i][j][k][l]; } } } } for(int p=0;p<query;p++) { int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); a--; b--; c--; d--; printf("%d\n", ans[c+1][d+1][c+1][d+1] -ans[a][d+1][c+1][d+1] -ans[c+1][b][c+1][d+1] -ans[c+1][d+1][a][d+1] -ans[c+1][d+1][c+1][b] +ans[a][b][c+1][d+1] +ans[a][d+1][a][d+1] +ans[a][d+1][c+1][b] +ans[c+1][b][a][d+1] +ans[c+1][b][c+1][b] +ans[c+1][d+1][a][b] -ans[c+1][b][a][b] -ans[a][d+1][a][b] -ans[a][b][c+1][b] -ans[a][b][a][d+1] +ans[a][b][a][b]); } }
372
C
Watching Fireworks is Fun
A festival will be held in a town's main street. There are $n$ sections in the main street. The sections are numbered $1$ through $n$ from left to right. The distance between each adjacent sections is $1$. In the festival $m$ fireworks will be launched. The $i$-th ($1 ≤ i ≤ m$) launching is on time $t_{i}$ at section $a_{i}$. If you are at section $x$ ($1 ≤ x ≤ n$) at the time of $i$-th launching, you'll gain happiness value $b_{i} - |a_{i} - x|$ (note that the happiness value might be a negative value). You can move up to $d$ length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to $1$), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness. Note that two or more fireworks can be launched at the same time.
I think most of the participants came up with simple DP algorithm : dp[i][j] := the maximum happiness value that you can gain when you're on poisition j at i th launching. Each value in table can be calculated by this formula : $dp[i][j] = max[k = - t * d..t * d](dp[i - 1][j + k] + b[i] - |a[i] - j|)$ where $t = t[i] - t[i - 1]$. If you look up for all k, since the table's size is O(mn), the overall complexity will be O(mn^2), and its too slow to solve the problem. Now, We're going to make this algorithm faster. Since the second term in the DP formula doesn't depend on k, you have to find maximum value of dp[i - 1][j + k] faster. Using segment tree or sparse table can fasten finding from O(n) to O(log n), but the overall complexity is still O(mn log n), and the solution will get time limit exceeded. Intended solution uses sliding window maximum (see this page http://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html) for some information), since the interval $[j - t * d, j + t * d]$ is independent for all the fireworks. It can be implemented by simple array or deque. This will speed up to calculate formula, and overall complexity will be O(mn). kcm1700 has submitted faster solution than our intended one during contest! It's complexity is O(m^2).
[ "data structures", "dp", "math" ]
2,100
#include <cstdio> #include <climits> #include <deque> #include <algorithm> using namespace std; typedef long long lint; int main() { int N, M, D; int a[1000], b[1000], t[1000]; lint dp[2][300001]; scanf("%d %d %d", &N, &M, &D); for (int i = 0; i < M; i++){ scanf("%d %d %d", a + i, b + i, t + i); } for (int i = 1; i <= N; i++){ dp[0][i] = 0; } int p = 1; int pT = 1; for (int i = 0; i < M; i++){ deque<int> dq; lint interval = min((lint)N, (lint)(t[i] - pT) * D); for (lint j = 1; j <= interval; j++){ while (dq.size() && dp[1 - p][dq[dq.size() - 1]] <= dp[1 - p][(int)j]) dq.pop_back(); dq.push_back((int)j); } for (lint j = 1; j <= (lint)N; j++){ lint k = j + interval; if (k <= (lint)N){ while (dq.size() && dp[1 - p][dq[dq.size() - 1]] <= dp[1 - p][(int)k]) dq.pop_back(); dq.push_back((int)k); } dp[p][j] = dp[1 - p][dq[0]] + (lint)(b[i] - abs(a[i] - j)); while (dq.size() && dq[0] <= (int)(j - interval)) dq.pop_front(); } pT = t[i]; p = 1 - p; } lint ans = LLONG_MIN; for (int i = 1; i <= N; i++) ans = max(ans, dp[1 - p][i]); printf("%I64d\n", ans); return (0); }
372
D
Choosing Subtree is Fun
There is a tree consisting of $n$ vertices. The vertices are numbered from $1$ to $n$. Let's define the length of an interval $[l, r]$ as the value $r - l + 1$. The score of a subtree of this tree is the maximum length of such an interval $[l, r]$ that, the vertices with numbers $l, l + 1, ..., r$ belong to the subtree. Considering all subtrees of the tree whose size is at most $k$, return the maximum score of the subtree. Note, that in this problem tree is not rooted, so a subtree — is an arbitrary connected subgraph of the tree.
We can use two pointers, which treat the interval of the consecutive numbers of node on tree. All we have to do is answer the query which requires the minimal number of size of subtree which contains all the vertices in the set, after the "add vertices to the set" and "delete verticesto the set" operations. We can calculate the distance between two nodes with LCA algorithm, then when we order the nodes by dfs order, we can answer the "add vertice" query that adds the vertice which is numbered $s$ in dfs order, and assume that previous numbered vertices in dfs order in the set is t, and next is u, we can get rid of the "add" query that $(current size of subtree)+distance(s,t)+distance(t,u)-distance(s,u), and "delete" so on. The time conplexity of LCA algorithm is O(log N), so we can solve this problem in O(Nlog N). There is another solution which uses heavy-light decomposition and segment tree. This solution is O(Nlog^2 N), which also pass.
[ "binary search", "data structures", "dfs and similar", "trees", "two pointers" ]
2,600
#include<stdio.h> #include<vector> #include<algorithm> using namespace std; #define SIZE 131072 vector<int>pat[100000]; vector<int>ko[100000]; int par[19][100000]; int depth[100000]; bool flag[100000]; int heavy[100000]; int toseg[100000]; int pattop[100000]; void dfs(int node,int d) { if(flag[node]) { return; } flag[node]=true; depth[node]=d; for(int i=0;i<pat[node].size();i++) { if(!flag[pat[node][i]]) { dfs(pat[node][i],d+1); ko[node].push_back(pat[node][i]); par[0][pat[node][i]]=node; } } } int num; void lcainit() { for(int i=1;i<=18;i++) { for(int j=0;j<num;j++) { par[i][j]=par[i-1][par[i-1][j]]; } } } int lca(int a,int b) { if(a==-1) { return b; } if(b==-1) { return a; } if(depth[a]>depth[b]) { swap(a,b); } for(int i=18;i>=0;i--) { if(depth[a]+(1<<i)<=depth[b]) { b=par[i][b]; } } if(a==b) { return a; } for(int i=18;i>=0;i--) { if(par[i][a]!=par[i][b]) { a=par[i][a]; b=par[i][b]; } } return par[0][a]; } int decomposit(int node) { int maxi=0,rr; if(ko[node].empty()) { heavy[node]=-1; return 1; } int siz=0; for(int i=0;i<ko[node].size();i++) { int z=decomposit(ko[node][i]); if(maxi<z) { maxi=z; rr=ko[node][i]; siz+=z; } } heavy[node]=rr; return siz+1; } class lcatree { public: int seg[SIZE*2]; void init() { for(int i=0;i<num;i++) { seg[SIZE+i]=i; } for(int i=num;i<SIZE;i++) { seg[SIZE+i]=-1; } for(int i=SIZE-1;i>=1;i--) { seg[i]=lca(seg[i*2],seg[i*2+1]); } } int getlca(int beg,int end,int node,int lb,int ub) { if(ub<beg||end<lb) { return -1; } if(beg<=lb&&ub<=end) { return seg[node]; } return lca(getlca(beg,end,node*2,lb,(lb+ub)/2),getlca(beg,end,node*2+1,(lb+ub)/2+1,ub)); } }; class segtree { public: int segmin[SIZE*2]; int segnum[SIZE*2]; int flag[SIZE*2]; void init() { for(int i=0;i<SIZE;i++) { segnum[SIZE+i]=1; } for(int i=SIZE-1;i>=1;i--) { segnum[i]=segnum[i*2]+segnum[i*2+1]; } } void update(int beg,int end,int node,int lb,int ub,int num) { if(ub<beg||end<lb) { return; } if(beg<=lb&&ub<=end) { segmin[node]+=num; flag[node]+=num; return; } if(flag[node]) { segmin[node*2]+=flag[node]; segmin[node*2+1]+=flag[node]; flag[node*2]+=flag[node]; flag[node*2+1]+=flag[node]; flag[node]=0; } update(beg,end,node*2,lb,(lb+ub)/2,num); update(beg,end,node*2+1,(lb+ub)/2+1,ub,num); segnum[node]=0; segmin[node]=min(segmin[node*2],segmin[node*2+1]); if(segmin[node*2]<=segmin[node*2+1]) { segnum[node]+=segnum[node*2]; } if(segmin[node*2]>=segmin[node*2+1]) { segnum[node]+=segnum[node*2+1]; } } int get() { if(segmin[1]!=0) { return SIZE; } return SIZE-segnum[1]; } }; lcatree ltree; segtree tree; int main() { int gen; scanf("%d%d",&num,&gen); for(int i=0;i<num-1;i++) { int za,zb; scanf("%d%d",&za,&zb); za--; zb--; pat[za].push_back(zb); pat[zb].push_back(za); } fill(flag,flag+num,false); for(int i=0;i<=18;i++) { for(int j=0;j<num;j++) { par[i][j]=-1; } } dfs(0,0); lcainit(); fill(heavy,heavy+num,-1); decomposit(0); int pt=0; for(int i=0;i<num;i++) { if(par[0][i]!=-1) { if(heavy[par[0][i]]==i) { continue; } } int now=i; for(;;) { toseg[now]=pt++; pattop[now]=i; now=heavy[now]; if(now==-1) { break; } } } pt=0; ltree.init(); tree.init(); int maxi=0; for(int i=0;i<num;i++) { int now=i; for(;;) { if(now==-1) { break; } tree.update(toseg[pattop[now]],toseg[now],1,0,SIZE-1,1); now=par[0][pattop[now]]; } for(;;) { int l=ltree.getlca(pt,i,1,0,SIZE-1); if(tree.get()-depth[l]>gen) { int n=pt; for(;;) { if(n==-1) { break; } tree.update(toseg[pattop[n]],toseg[n],1,0,SIZE-1,-1); n=par[0][pattop[n]]; } pt++; } else { maxi=max(maxi,i-pt+1); break; } if(pt>i) { break; } } } printf("%d\n",maxi); }
372
E
Drawing Circles is Fun
There are a set of points $S$ on the plane. This set doesn't contain the origin $O(0, 0)$, and for each two distinct points in the set $A$ and $B$, the triangle $OAB$ has strictly positive area. Consider a set of pairs of points $(P_{1}, P_{2}), (P_{3}, P_{4}), ..., (P_{2k - 1}, P_{2k})$. We'll call the set good if and only if: - $k ≥ 2$. - All $P_{i}$ are distinct, and each $P_{i}$ is an element of $S$. - For any two pairs $(P_{2i - 1}, P_{2i})$ and $(P_{2j - 1}, P_{2j})$, the circumcircles of triangles $OP_{2i - 1}P_{2j - 1}$ and $OP_{2i}P_{2j}$ have a single common point, and the circumcircle of triangles $OP_{2i - 1}P_{2j}$ and $OP_{2i}P_{2j - 1}$ have a single common point. Calculate the number of good sets of pairs modulo $1000000007$ $(10^{9} + 7)$.
All circles we must consider pass through O, so we can consider the operation inversion. At this operation, the point $(x, y)$ will be $\left({\frac{x}{x^{2}+y^{2}}},\,{\frac{y}{x^{2}+y^{2}}}\right)$. From now, we think the plane as the plane after inversed. "The circumcircles of triangles $OAB$ and $OCD$ have a single common point, and the circumcircle of triangles $OAD$ and $OBC$ have a single common point" can be said, after the inversion, $ABCD$ is parallelogram. And we can say it "the diagonal $AC$ and $BD$ have a common midpoint and the inclination of $AC$ and $BD$ are different". So all we have to do is make the list of the midpoints and inclination of all pairs of points and the line passes through them, and sort this array, and do some multiplication. It can be solved in O(N^2 log N).
[ "combinatorics", "geometry" ]
3,000
#include<stdio.h> #include<vector> #include<algorithm> #include<stdlib.h> #include<math.h> using namespace std; typedef long long ll; typedef pair<ll,ll>pii; typedef pair<pii,pii>pi4; typedef pair<pi4,pii>pi6; ll mod=1000000007; ll gcd(ll a,ll b) { for(;;) { if(a<b) { swap(a,b); } a%=b; if(a==0) { return b; } } } pii reduct(pii a) { if(a.second==0) { return make_pair(1LL,0LL); } if(a.first==0) { return make_pair(0LL,1LL); } ll g=gcd(abs(a.first),abs(a.second)); if(a.second<0) { a.first=-a.first; a.second=-a.second; } return make_pair(a.first/g,a.second/g); } pii pls(pii a,pii b) { return reduct(make_pair(a.first*b.second+a.second*b.first,a.second*b.second)); } pii mins(pii a,pii b) { return reduct(make_pair(a.first*b.second-a.second*b.first,a.second*b.second)); } pii tim(pii a,pii b) { return reduct(make_pair(a.first*b.first,a.second*b.second)); } pii div(pii a,pii b) { return reduct(make_pair(a.first*b.second,a.second*b.first)); } pi4 getsum(pi4 a,pi4 b) { return make_pair(pls(a.first,b.first),pls(a.second,b.second)); } pii getinc(pi4 a,pi4 b) { pii dx=mins(b.first,a.first); pii dy=mins(b.second,a.second); return div(dy,dx); } pi4 inv(ll za,ll zb,ll zc,ll zd) { pii dist=pls(tim(make_pair(za,zb),make_pair(za,zb)),tim(make_pair(zc,zd),make_pair(zc,zd))); return (make_pair(div(make_pair(za,zb),dist),div(make_pair(zc,zd),dist))); } vector<int>tov(vector<pii>vec) { pii now=make_pair(2000000000000000000LL,2000000000000000000LL); vector<int>ret; for(int i=0;i<vec.size();i++) { if(now!=vec[i]) { ret.push_back(1); now=vec[i]; } else { ret[ret.size()-1]++; } } return ret; } ll calc(vector<pii>v) { vector<int>vec=tov(v); ll ret=1; for(int i=0;i<vec.size();i++) { ret*=vec[i]+1; ret%=mod; } ret=(ret+mod-1-int(v.size()))%mod; return ret; } int main() { int num; scanf("%d",&num); vector<pi4>dat; for(int i=0;i<num;i++) { ll za,zb,zc,zd; scanf("%I64d%I64d%I64d%I64d",&za,&zb,&zc,&zd); dat.push_back(inv(za,zb,zc,zd)); } vector<pi6>vec; for(int i=0;i<num;i++) { for(int j=i+1;j<num;j++) { vec.push_back(make_pair(getsum(dat[i],dat[j]),getinc(dat[i],dat[j]))); } } sort(vec.begin(),vec.end()); pi4 nowsum=make_pair(make_pair(2000000000000000000LL,2000000000000000000LL),make_pair(2000000000000000000LL,2000000000000000000LL)); vector<pii>now; ll ret=0; for(int i=0;i<vec.size();i++) { if(nowsum!=vec[i].first) { if(!now.empty()) { ret+=calc(now); ret%=mod; } now.clear(); now.push_back(vec[i].second); nowsum=vec[i].first; } else { now.push_back(vec[i].second); } } ret+=calc(now); ret%=mod; printf("%I64d\n",ret); }
373
A
Collecting Beats is Fun
Cucumber boy is fan of Kyubeat, a famous music game. Kyubeat has $16$ panels for playing arranged in $4 × 4$ table. When a panel lights up, he has to press that panel. Each panel has a \textbf{timing} to press (the preffered time when a player should press it), and Cucumber boy is able to press at most $k$ panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his \textbf{two hands} in perfect timing, his challenge to press all the panels in perfect timing will fail. You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
First, you need to count the occurence of each number (1 through 9). If none of them are greater than 2 * k, Cucumber boy is able to press the panels in perfect timing. Complexity is O(1).
[ "implementation" ]
900
#include <cstdio> using namespace std; int main() { int k; int cnt[10] = {0}; char mp[4][5]; scanf("%d", &k); for (int i = 0; i < 4; i++){ scanf("%s", mp[i]); for (int j = 0; j < 4; j++){ if (mp[i][j] == '.') continue; else cnt[mp[i][j] - '0']++; } } for (int i = 1; i <= 9; i++) if (cnt[i] > 2 * k) return (!printf("NO\n")); return (!printf("YES\n")); }
373
B
Making Sequences is Fun
We'll define $S(n)$ for positive integer $n$ as follows: the number of the $n$'s digits in the decimal base. For example, $S(893) = 3$, $S(114514) = 6$. You want to make a consecutive integer sequence starting from number $m$ ($m, m + 1, ...$). But you need to pay $S(n)·k$ to add the number $n$ to the sequence. You can spend a cost up to $w$, and you want to make the sequence as long as possible. Write a program that tells sequence's maximum length.
Naive simulation (subtracting S(i) * k from w while w >= 0) won't finish in 2 seconds. At first, these two facts will make it easier to solve the problem : 1. k doesn't matter for solving this problem, so you can simply divide w with k at the first point. 2. S(10^x) + S(10^x + 1) + ... + S(10^(x+1) - 1) = 9 * x * 10^x . There are many ways to solve this problem, and I'll show you 2 ways. Binary Search Let's define f(n) as \sum_{k=1}^{n} S(n). This problem can be solved by finding largest x that satisfies f(x) - f(m - 1) <= w. If x satisfies the given inequation, also x - 1, x - 2, ... satisfies inequation since S(x) is always positive. So it can be solved by using binary search. By using fact2, you can quickly simulate the value of f(n). The answer can be rather large, so be careful not to cause overflow by too large upper bound. Overall complexity is O(log |upper_bound - lower_bound|). Cumulative Sums Let's think to speed up naive solutions that I've written at first. If you use fact 2, the number of simulation will reduce from O(|answer|) to O(1). Also, simulation will be much easier if you add S(1) + ... + S(m-1) to w. Please see my source code for further detail.
[ "binary search", "implementation", "math" ]
1,600
#include<stdio.h> typedef long long ll; ll get(ll a) { ll ret=0; ll now=1; ll t=1; for(;;) { if(now*10>a) { ret+=(a-now+1)*t; break; } ret+=now*9*t; now*=10; t++; } return ret; } int main() { ll gen,st,tim; scanf("%I64d%I64d%I64d",&gen,&st,&tim); gen/=tim; ll beg=st-1,end=20000000000000000LL; for(;;) { ll med=(beg+end)/2+1; if(get(med)-get(st-1)>gen) { end=med-1; } else { beg=med; } if(beg==end) { printf("%I64d\n",beg-st+1); break; } } }
374
A
Inna and Pink Pony
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an $n × m$ chessboard, a very tasty candy and two numbers $a$ and $b$. Dima put the chessboard in front of Inna and placed the candy in position $(i, j)$ on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types: - move the candy from position $(x, y)$ on the board to position $(x - a, y - b)$; - move the candy from position $(x, y)$ on the board to position $(x + a, y - b)$; - move the candy from position $(x, y)$ on the board to position $(x - a, y + b)$; - move the candy from position $(x, y)$ on the board to position $(x + a, y + b)$. Naturally, Dima doesn't allow to move the candy beyond the chessboard borders. Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position $(i, j)$ to one of the chessboard corners. Help them cope with the task!
Lets find a solution for shifting a candy from the position $(x_{1}, y_{1})$ into position $(x_{2}, y_{2})$. On each step we shift (increase or decrease) $x_{1}$ by $a$ and $y_{1}$ by $b$. It is not difficult to understand that if $|x_{2} - x_{1}|$ is not divisible by $a$ and $|y_{2} - y_{1}|$ is divisible by $b$ answer doesn't exist. We should also note that $|x_{2} - x_{1}| / a$ and $|y_{2} - y_{1}| / b$ Should be both even or odd as shifting is performed at a time for both values. We should also look up for a corner case when step dropes us out from the board. Now we can determine the way from $(x_{1}, y_{1})$ to $(x_{2}, y_{2})$ as $max(|x_{1} - x_{2}| / a, |y_{1} - y_{2}| / b)$. Lets calculate it for all corners and choose minimum or determine that the answer doesn't exist.
[ "greedy", "implementation" ]
2,000
null
374
B
Inna and Nine
Inna loves digit $9$ very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number $a$, consisting of digits from $1$ to $9$. Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals $9$ and replace them by a single digit $9$. For instance, Inna can alter number $14545181$ like this: $14545181 → 1945181 → 194519 → 19919$. Also, she can use this method to transform number $14545181$ into number $19991$. Inna will not transform it into $149591$ as she can get numbers $19919$ and $19991$ which contain more digits nine. Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.
We can divide the task into subtasks because if two adjacent digits have sum none-9 the number transformation doesn't depends on other side relatively to the position between this two digits. It means we should divide our task into subtasks of kind: $x$ or $xyxyxyx...xyxy$ where $x + y = 9$. We should multiply all such answers because we are looking for the whole number of variants. For $x$ answer is 1. What should we do for $xyxyxy$? Let its length is $s$. Then if $s$ is even we simply receive $s / 2$ nines. If $s$ is odd one digit (any of them) will stay. Thus each sequence $xyxyxyxyx...xyxyxy$ with odd length $s$ increases the answer IN $s$ times.
[ "combinatorics", "greedy" ]
1,500
null
374
C
Inna and Dima
Inna and Dima bought a table of size $n × m$ in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A". Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: - initially, Inna chooses some cell of the table where letter "D" is written; - then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; - Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
Our task is tranformed to the task of finding cycle or maximal way, but lets solve it without any graphs. Lets run dfs from each digit $D$, memorizing all already calculated tasks. If we come into the cell we have already been (in one of the previous $D$) than we should simply add the maximal way length to our current length. Way length is increased not in each cell but only when we come into $A$. If we come into the cell we have already been on current step (in our dfs running) this is the cycle and we should stop the algorithm. Don't forget to change the color of cell after droping from recursiong because you will receive "false cycle". Simply set the colour to current when come into the cell but decrease it before end of recursion for this cell.
[ "dfs and similar", "dp", "graphs", "implementation" ]
1,900
null
374
D
Inna and Sequence
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence $w$. Now they want to fill sequence $w$ with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses $m$ integers $a_{1}, a_{2}, ..., a_{m}$ $(1 ≤ a_{1} < a_{2} < ... < a_{m})$. Then Inna and Dima start playing, that is, adding numbers to sequence $w$. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the $a_{1}$-th, $a_{2}$-th, $a_{3}$-th, $...$, $a_{k}$-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets $k$ numbers less). Here $k$ is such maximum number that value $a_{k}$ doesn't exceed the current length of the sequence. If number $a_{1}$ is larger than the current length of $w$, then nothing falls out of the sequence. You are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence $w$ or Dima's hit on the table. Calculate the sequence $w$ after all these events happen.
Lets note that not more than $n$ numbers, thus it will be not more than $n$ dropings. We will run this process using data structure Segment Tree (you can use another structures). Lets calculate the number of numbers in current segment. When the number is added we should simply go down from the root to the leaf and increase value for each segment on the way by 1. Deletetion - vice versa. If there is enough numbers in the left subtree we should go into the right one, othervise - into the left one. Don't forget to shift the $a_{i}$ position by decreasing on $i$ as all numbers are droped immidiately. And don't forget to break the cycle as soon as you reach first $a_{i}$ such that there is no number to be droped out from it.
[ "binary search", "data structures", "dp", "trees" ]
2,000
null
374
E
Inna and Babies
Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing $n$ blue babies and $m$ red ones. Each baby is a segment that grows in time. At time moment $t$ the blue baby $(x, y)$ is a blue segment with ends at points $(x - t, y + t)$, $(x + t, y - t)$. Similarly, at time $t$ the red baby $(x, y)$ is a red segment with ends at points $(x + t, y + t)$, $(x - t, y - t)$ of the plane. Initially, at time $t = 0$ all babies are points on the plane. The goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints. You are given the positions of all babies — help Inna and Dima to find the required moment of time.
We will make the binary search to find the answer. For each time let's generate our segments and rotate them to transform them into horizontal and verticle. We can use transformation $(x, y)$ to $(x + y, x - y)$. Don't forget to make the union of all segments which were at the one diagonal and have an intersection. You should sort all segments of one type and iterate through them updating the size of the segment. Now we should only determine if there is at least one rectangle. For example we can iterate each verticle segment updating the set of all horizontal which begin not later than our verticle. For each verticle (the left one) we should iterate the right verticle and now calculate the set of horizontal which not only begin not later than the left verticle but also don't end earlier than the right one. Now we should only determine is ther is two or more horizontal segments from the set which satisfy also y-conditions for current vertical.
[ "binary search", "data structures", "dsu", "geometry", "implementation" ]
2,600
null
375
A
Divisible by Seven
You have number $a$, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7. Number $a$ doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
O(n): Because permutation of 1, 6, 8, 9 can form integers that mod 7 equals 0, 1, 2, 3, 4, 5, 6. So you can construct answer like this: nonzero digits + a permutation of 1, 6, 8, 9 + zeros.
[ "math", "number theory" ]
1,600
null
375
B
Maximum Submatrix 2
You are given a matrix consisting of digits zero and one, its size is $n × m$. You are allowed to rearrange its rows. What is the maximum area of the submatrix that only consists of ones and can be obtained in the given problem by the described operations? Let's assume that the rows of matrix $a$ are numbered from 1 to $n$ from top to bottom and the columns are numbered from 1 to $m$ from left to right. A matrix cell on the intersection of the $i$-th row and the $j$-th column can be represented as $(i, j)$. Formally, a submatrix of matrix $a$ is a group of four integers $d, u, l, r$ $(1 ≤ d ≤ u ≤ n; 1 ≤ l ≤ r ≤ m)$. We will assume that the submatrix contains cells $(i, j)$ $(d ≤ i ≤ u; l ≤ j ≤ r)$. The area of the submatrix is the number of cells it contains.
O(n*m): #We can get right[i][j] by O(n*m) dp. Let right[i][j] = how many continuous 1s is on cell (j, i)'s right. Let answer = 0 For all column i Sort right[i] #You can use O(n) sorting algorithm For j in [1..n] If right[i][j]*(n-j+1) > answer then answer = right[i][j]*(n-j+1)
[ "data structures", "dp", "implementation", "sortings" ]
1,600
null
375
C
Circling Round Treasures
You have a map as a rectangle table. Each cell of the table is either an obstacle, or a treasure with a certain price, or a bomb, or an empty cell. Your initial position is also given to you. You can go from one cell of the map to a side-adjacent one. At that, you are not allowed to go beyond the borders of the map, enter the cells with treasures, obstacles and bombs. To pick the treasures, you need to build a closed path (starting and ending in the starting cell). The closed path mustn't contain any cells with bombs inside. Let's assume that the sum of the treasures' values that are located inside the closed path equals $v$, and besides, you've made $k$ single moves (from one cell to another) while you were going through the path, then such path brings you the profit of $v - k$ rubles. Your task is to build a closed path that doesn't contain any bombs and brings maximum profit. Note that the path can have self-intersections. In order to determine if a cell lies inside a path or not, use the following algorithm: - Assume that the table cells are points on the plane (the table cell on the intersection of the $i$-th column and the $j$-th row is point $(i, j)$). And the given path is a closed polyline that goes through these points. - You need to find out if the point $p$ of the table that is not crossed by the polyline lies inside the polyline. - Let's draw a ray that starts from point $p$ and does not intersect other points of the table (such ray must exist). - Let's count the number of segments of the polyline that intersect the painted ray. If this number is odd, we assume that point $p$ (and consequently, the table cell) lie inside the polyline (path). Otherwise, we assume that it lies outside.
#T = number of treasures, B = number of booms O(n*m*2^(T+B)): #State(i, j, ts, bs) means: # 1. You are at cell (i, j) # 2. If the i-th bit of ts is 0 i-th treasure cross even edges of current path, otherwise odd edges. # 3. If the i-th bit of bs is 0 i-th boom cross even edges of current path, otherwise odd edges. Let dis[i][j][ts][bs] = min step to go to reach state (i, j, ts, bs). Then we can use bfs algorithm to calculate dis. About the bfs algorithm: We know dis[Si][Sj][0][0] = 0. For state(i, j, bs, ts) we can goto cell (i-1, j), (i+1, j), (i, j-1) and (i, j+1). Of course, we cannot go out of the map or go into a trap. So suppose we go from cell (i, j) to cell (ni, nj) and the new state is (ni, nj, nts, nbs). We can see if a treasure is crossing through the edge (i, j) - (ni, nj), if i-th treasure is, then the i-th bit of nts will be 1 xor i-th bit of ts, otherwise, the i-th bit of nts and ts will be same. The same for nbs. We can reach state (ni, nj, nts, nbs) from (i, j, ts, bs) in one step, so we just need to start bfs from state(Si, Sj, 0, 0) to get the min dis of all state. The answer will be max{value(ts) - dis[Si][Sj][ts][0]}
[ "bitmasks", "shortest paths" ]
2,600
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Div1C { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), m = in.nextInt(); char[][] g = new char[n][]; for (int i = 0; i < n; i++) g[i] = in.next().toCharArray(); Point start = null; int t = 0, b = 0; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (Character.isDigit(g[i][j])) { t = Math.max(t, (int) (g[i][j] - '0')); } else if (g[i][j] == 'B') { b++; } else if (g[i][j] == 'S') { start = new Point(i, j); } } Point[] treasure = new Point[t]; int[] value = new int[t]; Point[] boom = new Point[b]; for (int i = 0, bi = 0; i < n; i++) for (int j = 0; j < m; j++) { if (Character.isDigit(g[i][j])) { int ti = g[i][j] - '1'; treasure[ti] = new Point(i, j); } else if (g[i][j] == 'B') { boom[bi++] = new Point(i, j); } } for (int ti = 0; ti < t; ti++) value[ti] = in.nextInt(); int[][][][] cost = new int[n][m][1 << t][1 << b]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < (1 << t); k++) { for (int l = 0; l < (1 << b); l++) { cost[i][j][k][l] = 19930309; } } } } Queue<State> queue = new LinkedList<State>(); State state = new State(start, 0, 0); cost[state.p.x][state.p.y][state.ts][state.bs] = 0; queue.add(state); while (!queue.isEmpty()) { state = queue.remove(); final int[] dx = new int[] { 0, 0, 1, -1 }; final int[] dy = new int[] { -1, 1, 0, 0 }; for (int d = 0; d < 4; d++) { State nstate = new State(new Point(state.p.x + dx[d], state.p.y + dy[d]), state.ts, state.bs); if (nstate.p.x >= 0 && nstate.p.x < n && nstate.p.y >= 0 && nstate.p.y < m && !Character.isDigit(g[nstate.p.x][nstate.p.y]) && g[nstate.p.x][nstate.p.y] != '#' && g[nstate.p.x][nstate.p.y] != 'B') { for (int i = 0; i < t; i++) { if (cross(treasure[i], state.p, nstate.p)) { nstate.ts ^= 1 << i; } } for (int i = 0; i < b; i++) { if (cross(boom[i], state.p, nstate.p)) { nstate.bs ^= 1 << i; } } if (cost[nstate.p.x][nstate.p.y][nstate.ts][nstate.bs] > cost[state.p.x][state.p.y][state.ts][state.bs] + 1) { cost[nstate.p.x][nstate.p.y][nstate.ts][nstate.bs] = cost[state.p.x][state.p.y][state.ts][state.bs] + 1; queue.add(nstate); } } } } int answer = 0; for (int ts = 0; ts < (1 << t); ts++) { int get = 0; for (int i = 0; i < t; i++) if ((ts & (1 << i)) != 0) { get += value[i]; } get -= cost[start.x][start.y][ts][0]; answer = Math.max(answer, get); } System.out.println(answer); } private static boolean cross(Point p, Point l1, Point l2) { return (l1.y > p.y) != (l2.y > p.y) && p.x * (l2.y - l1.y) * (l2.y - l1.y) < (l2.x - l1.x) * (p.y - l1.y) * (l2.y - l1.y) + l1.x * (l2.y - l1.y) * (l2.y - l1.y); } } class Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } class State { Point p; public int ts, bs; public State(Point p, int ts, int bs) { this.p = p; this.ts = ts; this.bs = bs; } }
375
D
Tree and Queries
You have a rooted tree consisting of $n$ vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to $n$. Then we represent the color of vertex $v$ as $c_{v}$. The tree root is a vertex with number 1. In this problem you need to answer to $m$ queries. Each query is described by two integers $v_{j}, k_{j}$. The answer to query $v_{j}, k_{j}$ is the number of such colors of vertices $x$, that the subtree of vertex $v_{j}$ contains at least $k_{j}$ vertices of color $x$. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).
O(nlogn) or O(nlog^2n): Use binary search tree and merge them by rank. Use binary search tree that supports O(n) merging to get O(nlogn) solution. O(n*sqrt(n)): Dfs the tree to transform the problem to: Given a[i], query [l,r] k. To solve this problem: Build sqrt(n) bucket, put query [l,r] into (l/sqrt(n)+1)-th bucket For each bucket For thoese queries whose r is also in the bucket (l/sqrt(n) equals r/sqrt(n)), a brute-froce O(n) solution exists. For thoes queries whose r is not in the same bucket, let we sort them by l. We will get l[i[1]]<=l[i[2]]<=..<=l[i[k]]<=r[i[k]]<=r[i[k-1]]<=..<=r[i[1]](do not forget we get l[] and r[] by dfs the tree!). Solving them can be done in O(n) too. Since we only have O(sqrt(n)) buckets, the total time is O(n*sqrt(n)).
[ "data structures", "dfs and similar", "trees" ]
2,400
null
375
E
Red and Black Tree
You have a weighted tree, consisting of $n$ vertices. Each vertex is either painted black or is painted red. A red and black tree is called beautiful, if for any its vertex we can find a black vertex at distance at most $x$. The distance between two nodes is the shortest path between them. You have a red and black tree. Your task is to make it beautiful in the minimum number of color swap operations. In one color swap operation, you can choose two vertices of different colors and paint each of them the other color. In other words, if you choose a red vertex $p$ and a black vertex $q$, then in one operation you are allowed to paint $p$ black and paint $q$ red. Print the minimum number of required actions.
This problem can be solved by integer programming: min sum{c[i]*x[i]} subject to sum{A[i][j]*x[j]} >= 1 for all i sum{x[i]} = R x[i] = 0 or 1 for all i where c[i] = 1 if node i is black, 0 otherwise A[i][j] = 1 if distance between i and j is no greater than X, 0 otherwise R = number of red nodes. As it is known, integer programming is NP-hard. Thus, this cannot be the solution. But we can prove the following linear programing's solution is same as the integer programming's. min sum{c[i]*x[i]} subject to sum{A[i][j]*x[j]} >= 1 for all i sum{x[i]} <= R x[i] >= 0 for all i where c[i] = 1 if node i is black, 0 otherwise A[i][j] = 1 if distance between i and j is no greater than X, 0 otherwise R = number of red nodes. And the known fastest algorithm to solve linear programming is O(n^3.5). But in fact due to the property of this problem, using simplex algorithm to solve linear programming is even faster. I think it can be O(n^3), but I have no proof. So just use simplex to solve the linear programming problem above. The meaning of the integer programming: We use x[i] to stand whether node i is red or not. So we have: x[i] = 0 or 1 for all i There is a beautiful tree, for each node, exists an red node whose distance to this node is no more than X. So we have: sum{A[i][j]*x[j]} >= 1 for all i There are only R red node. So we have: sum{x[i]} = R And we need to minimize the swap number, and in fact the swap number equals to number of nodes that changed from black to red. So we need to minimize: sum{c[i]*x[i]} After changing it to linear programming: Firstly, it is obvious that the solution of the linear programming will not be worse than integer programming, because integer programming has stronger constraint. So we only need to show the solution of the linear programming will not be better than integer programming. To prove this, we need to show for an optimal solution, there will be an solution which is as good as it and all x[i] is either 0 or 1. 1. Because for "sum{A[i][j]*x[j]} >= 1 for all i", there is no need to make some x[i] > 1. It is obvious that if the solution has some x[i] > 1, we can increase x[i] for nodes that are red in the first place, so that there will not be any x[i] > 1 and this solution is as good as the old one. 2. We need to prove in an optimal solution, making some x[i] not being an integer will not get btter solution. It is really hard to decribe it. So just leave you a hint: use the property of trees to prove and consider leaves of the tree.
[ "dp", "implementation", "math" ]
3,000
#include <vector> #include <algorithm> #include <cstdio> using namespace std; #define lp for(;;) #define repf(i,a,b) #define ft(i,a,b) for (int i=(a);i<=(b);++i) #define rep(i,n) for (int i=0;i<(n);++i) #define rtn return #define pb push_back #define mp make_pair #define sz(x) (int((x).size())) typedef double db; typedef vector<int> vi; db inf=1e+10; db eps=1e-10; inline int sgn(const db& x){rtn (x>+eps)-(x<-eps);} const int MAXN=500; const int MAXM=501; int n,m; db A[MAXM+1][MAXN+1],X[MAXN]; int basis[MAXM+1],out[MAXN+1]; void pivot(int a,int b) { ft(i,0,m) if (i!=a&&sgn(A[i][b])) ft(j,0,n) if (j!=b) A[i][j]-=A[a][j]*A[i][b]/A[a][b]; ft(j,0,n) if (j!=b) A[a][j]/=A[a][b]; ft(i,0,m) if (i!=a) A[i][b]/=-A[a][b]; A[a][b]=1/A[a][b]; swap(basis[a],out[b]); } db simplex() { rep(j,n) A[0][j]=-A[0][j]; ft(i,0,m) basis[i]=-i; ft(j,0,n) out[j]=j; lp { int ii=1,jj=0; ft(i,1,m) if (mp(A[i][n],basis[i])<mp(A[ii][n],basis[ii])) ii=i; if (A[ii][n]>=0) break; rep(j,n) if (A[ii][j]<A[ii][jj]) jj=j; if (A[ii][jj]>=0) rtn -inf; pivot(ii,jj); } lp { int ii=1,jj=0; rep(j,n) if (mp(A[0][j],out[j])<mp(A[0][jj],out[jj])) jj=j; if (A[0][jj]>=0) break; ft(i,1,m) if (A[i][jj]>0&&(A[ii][jj]<=0||mp(A[i][n]/A[i][jj],basis[i])<mp(A[ii][n]/A[ii][jj],basis[ii]))) ii=i; if (A[ii][jj]<=0) rtn +inf; pivot(ii,jj); } rep(j,n) X[j]=0; ft(i,1,m) if (basis[i]>=0) X[basis[i]]=A[i][n]; rtn A[0][n]; } int d; vi adj[500]; vi wei[500]; void dfs(db A[],int u,int p,int d) { if (d>=0) { A[u]--; rep(i,sz(adj[u])) { int v=adj[u][i]; if (v!=p) { dfs(A,v,u,d-wei[u][i]); } } } } int main() { scanf("%d%d",&n,&d); int ttl=0; rep(i,n) { int ti; scanf("%d",&ti),A[0][i]=ti-1,ttl+=ti; } rep(i,n-1) { int u,v,w; scanf("%d%d%d",&u,&v,&w),--u,--v; adj[u].pb(v),adj[v].pb(u); wei[u].pb(w),wei[v].pb(w); } A[0][n]=0; rep(i,n) { dfs(A[i+1],i,-1,d); A[i+1][n]=-1; } rep(i,n) A[n+1][i]=1; A[n+1][n]=ttl; m=n+1; db get=simplex(); int ans; if (get==-inf) ans=-1; else ans=-get+0.5; printf("%d\n",ans); }
376
A
Lever
You have a description of a lever as string $s$. We'll represent the string length as record $|s|$, then the lever looks as a horizontal bar with weights of length $|s| - 1$ with exactly one pivot. We will assume that the bar is a segment on the $Ox$ axis between points $0$ and $|s| - 1$. The decoding of the lever description is given below. - If the $i$-th character of the string equals "^", that means that at coordinate $i$ there is the pivot under the bar. - If the $i$-th character of the string equals "=", that means that at coordinate $i$ there is nothing lying on the bar. - If the $i$-th character of the string equals digit $c$ (1-9), that means that at coordinate $i$ there is a weight of mass $c$ on the bar. Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
O(n): Let mid = position of ^ Let value(x) = x if x is a digit , 0 otherwise. Let sum = value(i-th char)*(i-mid) If sum = 0 then answer = balance Else if sum<0 then answer = left Else answer = right
[ "implementation", "math" ]
900
null
376
B
I.O.U.
Imagine that there is a group of three friends: A, B and С. A owes B 20 rubles and B owes C 20 rubles. The total sum of the debts is 40 rubles. You can see that the debts are not organized in a very optimal manner. Let's rearrange them like that: assume that A owes C 20 rubles and B doesn't owe anything to anybody. The debts still mean the same but the total sum of the debts now equals 20 rubles. This task is a generalisation of a described example. Imagine that your group of friends has $n$ people and you know the debts between the people. Optimize the given debts without changing their meaning. In other words, finally for each friend the difference between the total money he should give and the total money he should take must be the same. Print the minimum sum of all debts in the optimal rearrangement of the debts. See the notes to the test samples to better understand the problem.
O(n^4): Let f[i][j] = how many money i owes j #It can be proved we only need to loop n times. Loop n times do: For i,j,k in [1..n] If f[i][j]>0 and f[j][k]>0 then Let delta = min (f[i][j], f[j][k]) Decrease f[i][j] and f[j][k] by delta Increase f[i][k] by deltaAnswer will be sum{f[i][j]} O(m+n): Let owe[i] = 0 for all i #Suppose there is an agnecy to help people with debts. #If you owe someone, you give money to the agency. #If someone owes you, you get money from the agency. For each ai, bi, ci Increase owe[ai] by ci Decrease owe[bi] by ciAnsewr will be sum{owe[i]|owe[i]>0}
[ "implementation" ]
1,300
null
377
A
Maze
Pavel loves grid mazes. A grid maze is an $n × m$ rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side. Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly $k$ empty cells into walls so that all the remaining cells still formed a connected area. Help him.
Start BFS or DFS from any free cell. As the maze is connected, this search will visit all $s$ free cells. But we can stop the search when it visits $s - k$ free cells. It's obvious that these $s - k$ cells are connected to each other. Remaining $k$ cells can be transformed into the walls. Solutions which every move transform the cell which has the minimal number of neighbours passed pretests. However, it's wrong. Here is the counter-test: Top-left cell has no more neighbours than any other cell but we cannot transform it into the wall.
[ "dfs and similar" ]
1,600
null
377
B
Preparing for the Contest
Soon there will be held the world's largest programming contest, but the testing system still has $m$ bugs. The contest organizer, a well-known university, has no choice but to attract university students to fix all the bugs. The university has $n$ students able to perform such work. The students realize that they are the only hope of the organizers, so they don't want to work for free: the $i$-th student wants to get $c_{i}$ 'passes' in his subjects (regardless of the volume of his work). Bugs, like students, are not the same: every bug is characterized by complexity $a_{j}$, and every student has the level of his abilities $b_{i}$. Student $i$ can fix a bug $j$ only if the level of his abilities is not less than the complexity of the bug: $b_{i} ≥ a_{j}$, and he does it in one day. Otherwise, the bug will have to be fixed by another student. Of course, no student can work on a few bugs in one day. All bugs are not dependent on each other, so they can be corrected in any order, and different students can work simultaneously. The university wants to fix all the bugs as quickly as possible, but giving the students the total of not more than $s$ passes. Determine which students to use for that and come up with the schedule of work saying which student should fix which bug.
It's obvious that the time needed to fix all bugs is the monotonic function: if we can do it for some time, we can do it for greater time. So we can use binary search in these problem. We should learn how to check if some time $t$ is enough. At first sort all bugs by their complexity and all students by their skills. Let's consider the hardest bug. Who can fix it? It can be fixed by student whose skills is not less that this bug's complexity. Push all such students into the priority queue (sorted by students' price) and pop the cheapest student. As we check time $t$, this student must fix $t$ hardest bugs (he definitely can do it). Save that information and go to the next bug which has not been fixed yet. Again push all students which can fix it to the priority queue and pop the cheapest one. And so on. If at some moment priority queue is empty, time $t$ is not enough. If we spent too much 'money' - it's not enough as well. Otherwise we get the correct schedule.
[ "binary search", "data structures", "greedy", "sortings" ]
1,900
null
377
C
Captains Mode
Kostya is a progamer specializing in the discipline of Dota 2. Valve Corporation, the developer of this game, has recently released a new patch which turned the balance of the game upside down. Kostya, as the captain of the team, realizes that the greatest responsibility lies on him, so he wants to resort to the analysis of innovations patch from the mathematical point of view to choose the best heroes for his team in every game. A Dota 2 match involves two teams, each of them must choose some heroes that the players of the team are going to play for, and it is forbidden to choose the same hero several times, even in different teams. In large electronic sports competitions where Kostya's team is going to participate, the matches are held in the Captains Mode. In this mode the captains select the heroes by making one of two possible actions in a certain, predetermined order: pick or ban. - To pick a hero for the team. After the captain picks, the picked hero goes to his team (later one of a team members will play it) and can no longer be selected by any of the teams. - To ban a hero. After the ban the hero is not sent to any of the teams, but it still can no longer be selected by any of the teams. The team captain may miss a pick or a ban. If he misses a pick, a random hero is added to his team from those that were available at that moment, and if he misses a ban, no hero is banned, as if there was no ban. Kostya has already identified the strength of all the heroes based on the new patch fixes. Of course, Kostya knows the order of picks and bans. The strength of a team is the sum of the strengths of the team's heroes and both teams that participate in the match seek to maximize the difference in strengths in their favor. Help Kostya determine what team, the first one or the second one, has advantage in the match, and how large the advantage is.
There are some observations that do the problem very simple. The first one is that we always should pick the strongest hero. But we cannot say something similar about the bans - in different situations different bans are the best. But the most important observation is that we should consider only $m$ strongest heroes. Indeed, in every game where only strongest heroes are picked, no hero except $m$ strongest can be picked. That's why we don't need to ban them and therefore we don't need to consider them. So now we have only 20 heroes. It means we can solve the problem using the dynamic programming with bitmasks: $dp_{mask}$ will be the difference between the teams' strengths when only those heroes are picked or banned whose bits are set to 1 in the $mask$. At every state we try to pick or ban every available hero and go to the other state. The simpliest way to implement it is the recursion with memoization. The answer will be stored in $dp_{2^{m} - 1}$. Unfortunately, we couldn't estimate the real complexity of this problem (despite it has the simple solution, this solution is not so easy to think of - standard 1500 points for problem C would be better) and set too big TL (many solutions written in C++ whose complexity is $m^{2} \cdot 2^{m}$ passed - we should have been set TL to 1 second or even to 0.75 seconds). So if you solved it in $m^{2} \cdot 2^{m}$, you may assume that you're just lucky and your correct verdict is Time Limit Exceeded. Why it can be solved in $m \cdot 2^{m}$? There is no point of missing a ban - if we ban the weakest hero, nothing will change since the weakest hero won't be picked. Also this problem has weak pretests so you could hack solutions without bitmasks with almost any big random test.
[ "bitmasks", "dp", "games" ]
2,200
null
377
D
Developing Game
Pavel is going to make a game of his dream. However, he knows that he can't make it on his own so he founded a development company and hired $n$ workers of staff. Now he wants to pick $n$ workers from the staff who will be directly responsible for developing a game. Each worker has a certain skill level $v_{i}$. Besides, each worker doesn't want to work with the one whose skill is very different. In other words, the $i$-th worker won't work with those whose skill is less than $l_{i}$, and with those whose skill is more than $r_{i}$. Pavel understands that the game of his dream isn't too hard to develop, so the worker with any skill will be equally useful. That's why he wants to pick a team of the maximum possible size. Help him pick such team.
Let's note that every answer is characterized with two numbers $L$ and $R$ so that $max{l_{i}} \le L$, $R \le min{r_{i}}$, and $L \le v_{i} \le R$. If we know $L$ and $R$, we can check every person and choose those who satisfies the conditions above. Let's imagine a plane with the coordinate axes: one of the axes will be $L$, and the other will be $R$. If the point $(L, R)$ on this plane is the optimal answer, people included in this answer for sure satisfy the conditions $l_{i} \le L \le v_{i}$ and $v_{i} \le R \le r_{i}$. These conditions specify the rectangle on the plane. Since we should find the maximum number of people, we should find such point $(L, R)$ that it is inside the maximum number of the specified rectangles. Now it's the standard problem that can be solved using the scanline through one axis and the segment tree built on the other axis. The hardest part is to reduce the original problem to it.
[ "data structures" ]
2,400
null
377
E
Cookie Clicker
Kostya is playing the computer game Cookie Clicker. The goal of this game is to gather cookies. You can get cookies using different buildings: you can just click a special field on the screen and get the cookies for the clicks, you can buy a cookie factory, an alchemy lab, a time machine and it all will bring lots and lots of cookies. At the beginning of the game (time 0), Kostya has 0 cookies and no buildings. He has $n$ available buildings to choose from: the $i$-th building is worth $c_{i}$ cookies and when it's built it brings $v_{i}$ cookies at the end of each second. Also, to make the game more interesting to play, Kostya decided to add a limit: at each moment of time, he can use only one building. Of course, he can change the active building each second at his discretion. It's important that Kostya is playing a version of the game where he can buy new buildings and change active building only at time moments that are multiples of one second. Kostya can buy new building and use it at the same time. If Kostya starts to use a building at the time moment $t$, he can get the first profit from it only at the time moment $t + 1$. Kostya wants to earn at least $s$ cookies as quickly as possible. Determine the number of seconds he needs to do that.
First of all, throw away the buildings which cannot be used in any optimal answer: for each $v_{i}$ remain only one building that has speed equal to $v_{i}$ and minimal $c_{i}$. Also throw away all buildings whose speed is less than the speed of the fastest building which has $c_{i} = 0$. It's fairly obvious that at any time we should use the fastest building. And if some building is used in the optimal answer, it should be bought and used immediately when we have enough money (I will use the word 'money' instead of 'cookies'). Let's imagine the plane $(x, y)$ where $x$ axis stands for the time and $y$ axis stands for the money. We will maintain the graph of the function $y = f(x)$ - 'maximal number of money that can be obtained at the time $x$' and process the buildings one by one, changing the graph. This function is the union of the line segments with the slopes equal to $v_{i}$, and each of these line segments is active on a certain segment $[x_{li}, x_{ri}]$ of the axis $x$. For example, at the beginning the graph is just the line $y = v_{1}x$, where $v_{1}$ is the speed of building that can be bought for 0 units of money. Let the next building's price is $c_{2}$. Find the minimal point $x_{02}$ where value of our function is greater or equal to $y = f(x_{02}) \ge c_{2}$ and buy this building at the moment $x_{02}$. Then we should make the line $y = y_{02} + v_{2}x$ where $y_{02} = f(x_{02}) - c_{2}$ is the amount of money remaining after the purchase. Now we have two lines. Till some moment the first line is better (not till $x_{02}$, maybe later), but as $v_{2} > v_{1}$ there exists a moment of time (it's $ceil(x_{12})$ where $x_{12}$ is the $x$-coordinate of the lines' intersection) when the second line becomes better. Now we know the segments where a particular line is better than the others. Continue add all buildings to the graph this way. Line segments should be stored in stack, as in all problems with convex hull, and every step remove unnecessary line segments from the stack (these are the lines those position in the stack is after the line which has an intersection with the currently added line). After we process all buildings, we use our graph to find the minimal time when we have $S$ untis of money. If we also should say which building we must use, we can store for any line segment its 'parent' - the line segment which was active when the current one was bought. With such parent array it's not hard to restore the sequence of buildings in the answer. We removed this part from the problem to make it a bit easier.
[ "dp", "geometry" ]
2,800
null
378
A
Playing with Dice
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number $a$, the second player wrote number $b$. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
Make three counters: for wins of both players and for a draw. Iterate over all six ways how they can throw a dice. For each way determine who wins or there is a draw and increment the corresponding counter.
[ "brute force" ]
800
null
378
B
Semifinals
Two semifinals have just been in the running tournament. Each semifinal had $n$ participants. There are $n$ participants advancing to the finals, they are chosen as follows: from each semifinal, we choose $k$ people ($0 ≤ 2k ≤ n$) who showed the best result in their semifinals and all other places in the finals go to the people who haven't ranked in the top $k$ in their semifinal but got to the $n - 2k$ of the best among the others. The tournament organizers hasn't yet determined the $k$ value, so the participants want to know who else has any chance to get to the finals and who can go home.
You can think a bit and understand that you should consider only corner cases: $k = 0$ and $k={\frac{n}{2}}$. All other cases will be something between them. If $k = 0$, we should choose $n$ biggest elements from two sorted lists, one of the ways is to use two pointers method. And if $k={\frac{n}{2}}$, we just mark first $\frac{n t}{2}$ people in each list.
[ "implementation", "sortings" ]
1,300
null
379
A
New Year Candles
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles. Vasily has $a$ candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make $b$ went out candles into a new candle. As a result, this new candle can be used like any other new candle. Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
Let $cur_{a}$ amount of new candles, $cur_{b}$ - amount of burnt out. Initially $cur_{a} = a$, $cur_{b} = 0$, after burning all $cur_{a}$ new candles, amount of hours incremented by $cur_{a}$ and $cur_{b} + = cur_{a}$, lets make all burnt out candles into new $cur_{a} = cur_{b} / b$ $c u r_{b}=c u r_{b}\;\;\mathrm{mod}\;b$, repeat this algorithm until we can make at least one new candle. #### B: 379B - New Year Present If wallet contains more then one coin, then between orders to "put a coin" we can orders to move to adjacent wallet then back. Since for each orders to "put a coin" we spend at most 2 other orders, number of total orders for maximum test equals $300 * 300 * 3 = 270000$ it less then $10^{6}$.
[ "implementation" ]
1,000
null
379
C
New Year Ratings Change
One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors. There are $n$ users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user $i$ wants to get at least $a_{i}$ rating units as a present. The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible. Help site X cope with the challenging task of rating distribution. Find the optimal distribution.
We can to sort ratings in nondecrease order, then iterate by them we can keep minimal rating not used before. If $a_{i} > cur$, $i$'s user recieve $a_{i}$ of rating and $cur = a_{i} + 1$, else $a_{i} \le cur$ then $i$'s user recieve $cur$ of rating and $cur$ increased by one.
[ "greedy", "sortings" ]
1,400
null
379
D
New Year Letter
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, $s_{1}$ anf $s_{2}$, consisting of uppercase English letters. Then the boy makes string $s_{k}$, using a recurrent equation $s_{n} = s_{n - 2} + s_{n - 1}$, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string $s_{k}$ on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string $s_{k}$ has exactly $x$ occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string $s_{1}$ should have length $n$, and string $s_{2}$ should have length $m$. Vasya hasn't decided anything else. At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, $s_{1}$ and $s_{2}$ in the required manner. Help Vasya.
We can't fairly calculate $s_{k}$ because of length of this string which can be very large. But note that whole string not need, we just need number of $AC$ substrings, first and last letter. That help us to easy calculate number $AC$ substrings for any $s_{k}$ for some $s_{1}$, $s_{2}$. Let's iterate through $s_{1}$, $s_{2}$ using alphabet of $A$, $C$, and any other letter. We need just first and last letter and number of $AC$. Using some $s_{1}$, $s_{2}$ we can calculate $s_{k}$.
[ "bitmasks", "brute force", "dp" ]
2,000
null
379
E
New Year Tree Decorations
Due to atheistic Soviet past, Christmas wasn't officially celebrated in Russia for most of the twentieth century. As a result, the Russian traditions for Christmas and New Year mixed into one event celebrated on the New Year but including the tree, a Santa-like 'Grandfather Frost', presents and huge family reunions and dinner parties all over the country. Bying a Tree at the New Year and installing it in the house is a tradition. Usually the whole family decorates the tree on the New Year Eve. We hope that Codeforces is a big and loving family, so in this problem we are going to decorate a tree as well. So, our decoration consists of $n$ pieces, each piece is a piece of colored paper, its border is a closed polyline of a special shape. The pieces go one by one as is shown on the picture. The $i$-th piece is a polyline that goes through points: $(0, 0)$, $(0, y_{0})$, $(1, y_{1})$, $(2, y_{2})$, ..., $(k, y_{k})$, $(k, 0)$. The width of each piece equals $k$. \begin{center} {\scriptsize The figure to the left shows the decoration, the figure to the right shows the individual pieces it consists of.} \end{center} The piece number 1 (shown red on the figure) is the outer piece (we see it completely), piece number 2 (shown yellow) follows it (we don't see it completely as it is partially closed by the first piece) and so on. The programmers are quite curious guys, so the moment we hung a decoration on the New Year tree we started to wonder: what area of each piece can people see?
Let's keep union of first $i$ pieces, $S(i)$ denote the area of union for the first $i$ pieces. Then to know visible part of $i$'s piece we need to calculate $S(i) - S(i - 1)$, ( Unable to parse markup [type=CF_TEX]
[ "geometry", "schedules", "sortings" ]
2,500
null
379
G
New Year Cactus
Jack and Jill are tired of the New Year tree, now they've got a New Year cactus at home! A cactus is a connected undirected graph where any two simple cycles have at most one common vertex. In other words, this graph doesn't have any edges that lie on more than one simple cycle. On the 31st of December they are going to decorate the cactus by hanging toys to its vertices. At most one toy is going to hang on each vertex — it's either the toy Jack hung or the toy Jill hung. It's possible for a vertex to have no toys. Jack and Jill has been arguing, so they don't want any edge to connect two vertices where one vertex has Jack's toy and the other vertex has Jill's toy. Jack has decided to hang $a$ toys. What maximum number of toys $b$ can Jill hang if they both cooperate to maximize this value? Your task is to write a program that finds the sought $b$ for all $a$ from 0 to the number of vertices on the New Year Cactus.
This problem can be solved for tree by using of dynamic programming $d[v][c][a]$, where $v$ - vertex, $c$ - type of vertex(whose toys are hanged or nothing are hanged there), $a$ - number of toys hanged by Jack for this subtree, $d[v][c][a]$ denote of maximum number of toys which can be hanged by Jill. Value $d[v][c][a]$ can be calculated iterated through sons of $v$ vertext and type of these vertices. Let's compress our cactus into tree by compressing each cycle into vertex. Vertex of tree will be looks like sequence of vertex from cactus which have edges not from this cycle and intermediates that belongs only to this cycle. Now we can calculate all $d[v][c][a]$ for this tree but we must be carefully processing a vertices.
[ "dp" ]
3,100
null
380
A
Sereja and Prefixes
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in $m$ stages. Each time he either adds a new number to the end of the sequence or takes $l$ first elements of the current sequence and adds them $c$ times to the end. More formally, if we represent the current sequence as $a_{1}, a_{2}, ..., a_{n}$, then after we apply the described operation, the sequence transforms into $a_{1}, a_{2}, ..., a_{n}[, a_{1}, a_{2}, ..., a_{l}]$ (the block in the square brackets must be repeated $c$ times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
Generate the first number 100000. Will in turn handle the requests, if the request gets to the point of adding one number, just print it. Otherwise see what element will meet our and just print it from precalculated array.
[ "binary search", "brute force" ]
1,600
null
380
B
Sereja and Tree
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees. His new tree consists of $n$ levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level $1$, its index is $(1, 1)$. Here is a pseudo code of tree construction. \begin{verbatim} //the global data are integer arrays cnt[], left[][], right[][] cnt[1] = 1; fill arrays left[][], right[][] with values -1; for(level = 1; level < n; level = level + 1){ cnt[level + 1] = 0; for(position = 1; position <= cnt[level]; position = position + 1){ if(the value of position is a power of two){ // that is, 1, 2, 4, 8... left[level][position] = cnt[level + 1] + 1; right[level][position] = cnt[level + 1] + 2; cnt[level + 1] = cnt[level + 1] + 2; }else{ right[level][position] = cnt[level + 1] + 1; cnt[level + 1] = cnt[level + 1] + 1; } } } \end{verbatim} After the pseudo code is run, cell cnt[level] contains the number of vertices on level $level$. Cell left[level][position] contains the number of the vertex on the level $level + 1$, which is the left child of the vertex with index $(level, position)$, or it contains -1, if the vertex doesn't have a left child. Similarly, cell right[level][position] is responsible for the right child. You can see how the tree with $n = 4$ looks like in the notes. Serja loves to make things complicated, so he first made a tree and then added an empty set $A(level, position)$ for each vertex. Then Sereja executes $m$ operations. Each operation is of one of the two following types: - The format of the operation is "$1$ $t$ $l$ $r$ $x$". For all vertices $level, position$ $(level = t; l ≤ position ≤ r)$ add value $x$ to set $A(level, position)$. - The format of the operation is "$2$ $t$ $v$". For vertex $level, position$ $(level = t, position = v)$, find the union of all sets of vertices that are in the subtree of vertex $(level, position)$. Print the size of the union of these sets. Help Sereja execute the operations. In this problem a set contains only distinct values like std::set in C++.
Lets generate a tree as described in the statment. For each request to add items we just add a segment for a certain level. At the request of the number of items we just go through all the lower levels, considering the leftmost and the rightmost vertex in the subtree. To each level will take all intervals that it owns and for each check - whether it intersects with the interval that we have generated in the current stage. If so, simply add items to the set. The complexity of solving $O(n \cdot m)$.
[ "graphs", "implementation" ]
2,400
null