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
37
C
Old Berland Language
Berland scientists know that the Old Berland language had exactly $n$ words. Those words had lengths of $l_{1}, l_{2}, ..., l_{n}$ letters. Every word consisted of two letters, $0$ and $1$. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol. Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
One of the easiest to understand solutions of this problem is as follows: sort the words in ascending order of length, while remembering their positions in the source list. We will consistently build our set, starting with the short strings: strings of length one can only be strings "0" and "1". If the number of words of length one in a set are more than two, hence there are no answers. Add the desired number of strings of length one to answer, and remove it from the current list. Then look at the string of length two: each of the remaining strings of length one can be extended in two ways (having added to each of these symbols 0 and 1). Add the desired number of strings of length two in our answer, and then increase the length of the remaining strings by one. Continue this process, until we get all words from the input set. You can see that if at some moment the number of allowable words exceeded the number of remaining, the extra words can be ignored and solution takes O (N * the maximum length of input set) time.
[ "data structures", "greedy", "trees" ]
1,900
null
37
D
Lesson Timetable
When Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with $M$ classrooms numbered from $1$ to $M$, situated along it. All the students of Petya’s year are divided into $N$ groups. Petya has noticed recently that these groups’ timetable has the following peculiarity: the number of the classroom where the first lesson of a group takes place does not exceed the number of the classroom where the second lesson of this group takes place. Once Petya decided to count the number of ways in which one can make a lesson timetable for all these groups. The timetable is a set of $2N$ numbers: for each group the number of the rooms where the first and the second lessons take place. Unfortunately, he quickly lost the track of his calculations and decided to count only the timetables that satisfy the following conditions: 1) On the first lesson in classroom $i$ exactly $X_{i}$ groups must be present. 2) In classroom $i$ no more than $Y_{i}$ groups may be placed. Help Petya count the number of timetables satisfying all those conditionsю As there can be a lot of such timetables, output modulo $10^{9} + 7$.
This problem is solved by dynamic programming: state of dynamics will be a pair of numbers - the number of current room and number of groups which have first lesson in the room with a number not exceeding the current and for which the second room is not defined yet. For each state check all possible number of groups for which the second lesson will be held in the current classroom. When you add an answer from the new state, it must be multiplied by the corresponding binomial coefficients (the number of ways to select groups which have the first lesson in next room - $X_{i} + 1$, and the number of ways to select groups which have the second lesson in the current classroom).
[ "combinatorics", "dp", "math" ]
2,300
null
37
E
Trial for Chief
Having unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen. As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of $N$ lines and $M$ columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief. Scientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way.
First, we construct the following graph: each cell we associate a vertex of the same color as the cell itself. Between neighboring cells hold an edge of weight 0, if the cells share the same color and weight of 1, if different. Now, for each cell count the shortest distance from it to the most distant black cell (denoted by $D$). It is easy to see that we can construct a sequence of $D + 1$ repainting leads to the desired coloring: The first step of color all the cells at a distance less than or equal to $D$ in black color At the second step color all the cells at a distance less than or equal to $D - 1$ in whiteEtc. Of all the cells, choose the one for which this distance is minimal, and this distance increased by one will be the answer to the problem.
[ "graphs", "greedy", "shortest paths" ]
2,600
null
39
A
C*++ Calculations
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this ($expression$ is the main term): - $expression$ ::= $summand$ | $expression + summand$ | $expression - summand$ - $summand$ ::= $increment$ | $coefficient$*$increment$ - $increment$ ::= a++ | ++a - $coefficient$ ::= 0|1|2|...|1000 For example, "5*a++-3*++a+a++" is a valid expression in C*++. Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to $1$. The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by $1$. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by $1$, then — multiplied by the coefficient. The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
To get the maximal possible result you have just to sort summands in non-decreasing order by coefficients (counting coefficients with preceeding signs + and -). You should not pay attention to 'a++' or '++a'! The question is: why is it true? First, consider an expression with only 'a++'. Then our assertion is obvious: it is better to multiply 'a' by small coefficients when it has small value, and by large coefficients, when it becomes larger. The same also takes place in case of negative coefficients or a-value. Of course, it is not a rigorous proof. I hope you will think on it if you haven't get it yet. Second, consider the expression $k * a + + + k * + + a$, where $k$ is some coefficient equal for both summands. Let initial value of 'a' equals to $a_{0}$. Calculating the value of the expression both ways, we obtain: $k * a_{0} + k * (a_{0} + 2) = k * (a_{0} + 1) + k * (a_{0} + 1)$. So in this case the order is immaterial. Third, let us have the expression $k * a + + + l * + + a$, where $k$ and $l$ are two distinct coefficients. This expression can have two different values: $k * a_{0} + l * (a_{0} + 2)$ and $k * (a_{0} + 1) + l * (a_{0} + 1)$. The first value is greater than the second one if and only if $k < l$. We can deal with the expression k*++a+l*a++ analogously. Thus if we have two succesive summands with the same coefficient, we may swap or not to swap them. If we have two succesive summands with distinct coefficients, we must put the summand with a smaller coeficient first. Applying these considerations while it is necessary, we get a sequence of summands sorted by coefficients.
[ "expression parsing", "greedy" ]
2,000
null
39
B
Company Income Growth
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since $2001$ (the year of its founding) till now. Petya knows that in $2001$ the company income amounted to $a_{1}$ billion bourles, in $2002$ — to $a_{2}$ billion, ..., and in the current $(2000 + n)$-th year — $a_{n}$ billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to $1$ billion bourles, in the second year — $2$ billion bourles etc., each following year the income increases by $1$ billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers $a_{i}$ can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers $a_{i}$ from the sequence and leave only some subsequence that has perfect growth. Thus Petya has to choose a sequence of years $y_{1}$, $y_{2}$, ..., $y_{k}$,so that in the year $y_{1}$ the company income amounted to $1$ billion bourles, in the year $y_{2}$ — $2$ billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.
For this problem, the greedy solution is acceptable. Process given numbers consequently until $1$ is found. Then continue to process searching for $2$, then for $3$, etc.
[ "greedy" ]
1,300
null
39
C
Moon Craters
There are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes. An extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was –– sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis. Professor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters. According to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) That’s why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory.
The authors solution takes $O(n^{2})$ time and $O(n^{2})$ memory. Solutions with $O(n^{2}\log{n})$ time and $O(n)$ memory are also acceptable. Let us reformulate the problem. Given a set of segments on a line, and the task is to find the largest subset such that segments in it don't intersect ``partially''. Two segments $[a, b]$ and $[c, d]$ intersect partially, if, for instance, $a < c < b < d$. Take all the ends of the given segments, sort them, and compute the dynamics: $d_{None}$ is the largest possible size of such subset that segments in don't intersect partially and located between the $l$-th end and the $r$ end (in sorted order), inclusively. We want to compute $d_{None}$ having already computed $d_{None}$ for all $l \le i \le j \le r$, but $[i, j] \neq [l, r]$. First put $d_{None} = d_{None}$ if we don't take segments with the left end in $l$. Now process the segments with the left end in $l$. If the segment $[l, r]$ exists, we undoubtedly take it to our set. If we take another segment, say, $[l, i]$, where $i < r$, look at segments $[l, i]$ and $[i, r]$ (we have answers for them already computed) and try to update $d_{None}$. The asymptotics is $O(n^{2})$, because the total number of left ends is $O(n)$. Then you have to output the certificate, i.e. the optimal set itself. It can be done in the standard way.
[ "dp", "sortings" ]
2,100
null
39
D
Cubical Planet
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points $(0, 0, 0)$ and $(1, 1, 1)$. Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
The flies can NOT see each other iff they are in opposite vertices. You may use multiple ways to check this. For instance, you can check the Manhattan distance $|x_{1} - x_{2}| + |y_{1} - y_{2}| + |z_{1} - z_{2}| = 3$ or the Euclidian distance ${\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}+(z_{1}-z_{2})^{2}}}={\sqrt{3}}$. You can check if all three coorditanes are distinct (x1 != x2) && (y1 != y2) && (z1 != z2), or just (x1^x2)+(y1^y2)+(z1^z2) == 3!
[ "math" ]
1,100
null
39
E
What Has Dirichlet Got to Do with That?
You all know the Dirichlet principle, the point of which is that if $n$ boxes have no less than $n + 1$ items, that leads to the existence of a box in which there are at least two items. Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. There are $a$ different boxes and $b$ different items, and each turn a player can either add a new box or a new item. The player, after whose turn the number of ways of putting $b$ items into $a$ boxes becomes no less then a certain given number $n$, loses. All the boxes and items are considered to be different. Boxes may remain empty. Who loses if both players play optimally and Stas's turn is first?
The number of ways to put $b$ items into $a$ boxes is, of course, $a^{b}$. So we have an acyclic game for two players with positions $(a, b)$ for which $a^{b} < n$. Unfortunatly, there exists an infinite number of such positions: $a = 1$, $b$ is any. But in this case, if $2^{b} \ge n$, it is a draw position, because the only way for both players (not leading to lose) is to increase $b$ infinitely. Another special case is a position with $b = 1$ and rather large $a$. Namely, if $a\geq{\sqrt{n}}$, there is also only one move from this position - to increase $a$. If $a = n - 1$ the position is losing, if $a = n - 2$ it is winning, for $a = n - 3$ it is losing again and so on. Thus we have two kinds of positions to deal with them specially. The number of other positions is not very large, and you can compute the standard dynamics for acyclic games for them.
[ "dp", "games" ]
2,000
null
39
F
Pacifist frogs
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much. One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from $1$ to $n$ and the number of a hill is equal to the distance in meters between it and the island. The distance between the $n$-th hill and the shore is also $1$ meter. Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is $d$, the frog will jump from the island on the hill $d$, then — on the hill $2d$, then $3d$ and so on until they get to the shore (i.e. find itself beyond the hill $n$). However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.
The simple modelling of frog's jumps works too long, because $n$ can be $10^{9}$. The right solution is to count for each frog a number of smashed mosquitoes by checking divisibility of numbers of hills with mosquitoes by $d_{i}$.
[ "implementation" ]
1,300
null
39
G
Inverse Function
Petya wrote a programme on C++ that calculated a very interesting function $f(n)$. Petya ran the program with a certain value of $n$ and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of $n$ the program was run. Help Petya, carry out the inverse function! Mostly, the program consists of a function in C++ with the following simplified syntax: - $function$ ::= int f(int n) {$operatorSequence$} - $operatorSequence$ ::= $operator | operator operatorSequence$ - $operator$ ::= return $arithmExpr$; $|$ if ($logicalExpr$) return $arithmExpr$; - $logicalExpr$ ::= $arithmExpr > arithmExpr$ $|$ $arithmExpr < arithmExpr$ $|$ $arithmExpr$ == $arithmExpr$ - $arithmExpr$ ::= $sum$ - $sum$ ::= $product$ $|$ $sum + product$ $|$ $sum - product$ - $product$ ::= $multiplier$ $|$ $product * multiplier$ $|$ $product / multiplier$ - $multiplier$ ::= n $|$ $number$ $|$ f($arithmExpr$) - $number$ ::= $0|1|2|... |32767$ The whitespaces in a $operatorSequence$ are optional. Thus, we have a function, in which body there are two kinds of operators. There is the operator "return $arithmExpr$;" that returns the value of the expression as the value of the function, and there is the conditional operator "if ($logicalExpr$) return $arithmExpr$;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language — cycles, assignment operators, nested conditional operators etc, and other variables except the $n$ parameter are used in the function. All the constants are integers in the interval $[0..32767]$. The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations ">" (more), "<" (less) and "==" (equals) also have standard meanings. Now you've got to pay close attention! The program is compiled with the help of $15$-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo $32768$ (if the result of subtraction is negative, then $32768$ is added to it until the number belongs to the interval $[0..32767]$). Division "/" is a usual integer division where the remainder is omitted. Examples of arithmetical operations: \[ 12345+23456=3033,\quad0-1=32767,\quad1024*1024=0,\quad1000/3=333. \] Guaranteed that for all values of $n$ from $0$ to $32767$ the given function is performed correctly. That means that: 1. Division by $0$ never occures. 2. When performing a function for the value $n = N$ recursive calls of the function $f$ may occur only for the parameter value of $0, 1, ..., N - 1$. Consequently, the program never has an infinite recursion. 3. As the result of the sequence of the operators, the function always returns a value. We have to mention that due to all the limitations the value returned by the function $f$ is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of $n$ parameter. That's why the $f$ function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of $n$ from the interval $[0..32767]$ and a value of $f(n)$ from the same interval. Given the value of $f(n)$, and you should find $n$. If the suitable $n$ value is not unique, you should find the maximal one (from the interval $[0..32767]$).
What can I say about problem G? You should parse a given function and calculate its value for all values of $n$. Of course, it is impossible to do it just implementing the recursion, because this can work too long (see example with Fibonacci sequence). So you should use dynamic programming.
[ "implementation" ]
2,400
null
39
H
Multiplication Table
Petya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action — multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix $k$.
You have to calculate all products $i * j$, and output them in the system of notations with radix $k$.
[ "implementation" ]
1,300
null
39
I
Tram
In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly $c$ minutes to complete the route. The head of the engine house controlled the tram’s movement, going outside every $c$ minutes when the tram drove by the engine house, and the head left the driver without a bonus if he was even one second late. It used to be so. Afterwards the Berland Federal Budget gave money to make more tramlines in S***, and, as it sometimes happens, the means were used as it was planned. The tramlines were rebuilt and as a result they turned into a huge network. The previous loop route may have been destroyed. S*** has $n$ crossroads and now $m$ tramlines that links the pairs of crossroads. The traffic in Berland is one way so the tram can move along each tramline only in one direction. There may be several tramlines between two crossroads, which go same way or opposite ways. Every tramline links two different crossroads and for each crossroad there is at least one outgoing tramline. So, the tramlines were built but for some reason nobody gave a thought to increasing the number of trams in S***! The tram continued to ride alone but now the driver had an excellent opportunity to get rid of the unending control of the engine house head. For now due to the tramline network he could choose the route freely! Now at every crossroad the driver can arbitrarily choose the way he can go. The tram may even go to the parts of S*** from where it cannot return due to one way traffic. The driver is not afraid of the challenge: at night, when the city is asleep, he can return to the engine house safely, driving along the tramlines in the opposite direction. The city people were rejoicing for some of the had been waiting for the tram to appear on their streets for several years. However, the driver’s behavior enraged the engine house head. Now he tries to carry out an insidious plan of installing cameras to look after the rebellious tram. The plan goes as follows. The head of the engine house wants to install cameras at some crossroads, to choose a period of time $t$ and every $t$ minutes turn away from the favourite TV show to check where the tram is. Also the head of the engine house wants at all moments of time, divisible by $t$, and only at such moments the tram to appear on a crossroad under a camera. There must be a camera on the crossroad by the engine house to prevent possible terrorist attacks on the engine house head. Among all the possible plans the engine house head chooses the plan with the largest possible value of $t$ (as he hates being distracted from his favourite TV show but he has to). If such a plan is not unique, pick the plan that requires the minimal possible number of cameras. Find such a plan.
Consider only the part of the graph reachable from $1$. The task is to find the largest number $t$, such that a chosen set of vertices is reachable only at moments divisible by $t$. Suppose we have built such a set $S_{0}$. Look at sets $S_{1}$, $S_{2}$, ..., $S_{None}$ of all vertices reachable at moments having remainders $1$, $2$, ..., $t - 1$ modulo $t$, respectively. One can easily check that these sets are disjoint, and their union coinside with the set of all reacheble vertices. Clearly, that the edge from $u$ to $v$ can exist only when $u$ and $v$ belong to consequetive sets, i.e. $u\in S_{k}$, $v\in S_{k+1}$, $k + 1$ is taken modulo $t$. For each vertex $v$, find a distance $d_{v}$ from $1$ to $v$ (if there is multiple paths, choose any, for example, by dfs). If the edge exists from $u$ to $v$, it must be $d_{u}+1\equiv d_{v}(\mathrm{\boldmath~\mod~}t)$. By analyzing all the edges, we come to the conclusion that the optimal value of $t$ equals to the greatest common divisor of the numbers $|d_{u} + 1 - d_{v}|$. To find the set $S_{0}$ is not very difficult now.
[]
2,500
null
39
J
Spelling Check
Petya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?
The simplest solution is to find two numbers $l$ and $r$ - the length of the longest common prefix and the length of the longest common suffix of two strings, respectively. If $l + 1 < n - r$ then there is no solution. Here $n$ is the length of the first string. Otherwise we should output positions from $max(n - r, 1)$ to $min(l + 1, n)$.
[ "hashing", "implementation", "strings" ]
1,500
null
39
K
Testing
You take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field $n × m$ in size, divided into unit squares $1 × 1$ in size. The polygon contains $k$ objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit squares. The objects don't intersect and don't touch each other. The principle according to which the weapon works is highly secret. You only know that one can use it to strike any rectangular area whose area is not equal to zero with sides, parallel to the sides of the polygon. The area must completely cover some of the unit squares into which the polygon is divided and it must not touch the other squares. Of course the area mustn't cross the polygon border. Your task is as follows: you should hit no less than one and no more than three rectangular objects. Each object must either lay completely inside the area (in that case it is considered to be hit), or lay completely outside the area. Find the number of ways of hitting.
Problem K has a great number of different solutions, so I'm surprised that there was a lack of them during the contest. Solutions with time $O(k^{4})$ and even some $O(k^{5})$ solutions with optimization were acceptable, but KADR describes even better solution in $O(k^{3})$ (http://codeforces.com/blog/entry/793). Here are some jury ideas of this problem. First, let us compress the coordinates. Choose a labeled point in each object and compute by the standard dynamics the number of such labels in each rectangle. It takes $O(k^{4})$ to process all possible rectangles. The problem arises that a rectangle may contain a valid number of objects, but contain some objects not completely. To prevent this, we can check the borders. They are segments parallel to the coordinate axes, and their number is $O(k^{3})$. So we can precalc for them if they are valid or not comparing them with each object. Then we have to come back to uncompressed coordinates. The following solution is $O(k^{5})$, and it uses the limitation on the number of objects (3) inside the rectangle. Process all the triples of objects (the same, of course, with pairs and single objects). Fix a triple, and change it by a single big object. Then move from the resulting object up (and then down), and check if a row above (or below) can be included in a striked rectangle. For each row we find a longest segment [l, r], which contains the current big object and doesn't contain others. Using this information, one can easily calculate the total number of rectangles that contain the current triple.
[]
2,600
null
41
A
Translation
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a Berlandish word differs from a Birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, making a mistake during the "translation" is easy. Vasya translated the word $s$ from Berlandish into Birlandish as $t$. Help him: find out if he translated the word correctly.
Many languages have built-in reverse() function for strings. we can reverse one of the strings and check if it's equal to the other one , or we can check it manually. I prefer the second.
[ "implementation", "strings" ]
800
using System; namespace Iran { class Amir { public static void Main() { string a=Console.ReadLine(); string b=Console.ReadLine(); bool ok=true; if(a.Length!=b.Length) ok=false; for(int i=0;ok&&i<a.Length;++i) { if(a[i]!=b[a.Length-i-1]) { ok=false; break; } } if(ok) Console.WriteLine("YES"); else Console.WriteLine("NO"); } } }
41
B
Martian Dollar
One day Vasya got hold of information on the Martian dollar course in bourles for the next $n$ days. The buying prices and the selling prices for one dollar on day $i$ are the same and are equal to $a_{i}$. Vasya has $b$ bourles. He can buy a certain number of dollars and then sell it no more than once in $n$ days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day $n$?
Since number of days is very small ($2 \times 10^{3}$) we can just iterate over all possibilities of buy-day and sell-day. This will take $ \theta (n^{2})$ time which is OK.
[ "brute force" ]
1,400
using System; namespace Iran { class Amir { public static void Main() { string[] input=Console.ReadLine().Split(' '); int n=int.Parse(input[0]); int b=int.Parse(input[1]); int maximum=b; string[] dollars=Console.ReadLine().Split(' '); for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { int canbuy=b/int.Parse(dollars[i]); int more=b%int.Parse(dollars[i]); int sell=canbuy*int.Parse(dollars[j])+more; if(sell>maximum) maximum=sell; } } Console.WriteLine(maximum); }//end of main } }
41
C
Email address
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([email protected]). It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at.
The first letter of the input string can not be part of an "at" or a "dot" so we start from the second character. Greedily put "." wherever you reached "dot" and put "@" the first time you reached "at". This will take $ \theta (n)$ time , where $n$ is the length of input
[ "expression parsing", "implementation" ]
1,300
#include <iostream> #include <algorithm> using namespace std; int main() { string input; cin>>input; string made=input.substr(0,1); bool at=false; for(int i=1;i<input.length();) { if(input.substr(i,3)=="dot"&&i+3!=input.length()) { made=made+"."; i+=3; } else if(input.substr(i,2)=="at"&&at==false&&i+2!=input.length()) { at=true; made=made+"@"; i+=2; } else { made=made+input.substr(i,1); i++; } } cout<<made<<endl; return 0; }
41
D
Pawn
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its $k$ brothers, the number of peas must be divisible by $k + 1$. Find the maximal number of peas it will be able to collect and which moves it should make to do it. The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
For each cell of the table store $k + 1$ values. Where $i$th value is the maximum number of peas the pawn can take while he is at that cell and this number mod $k + 1$ is $i$. This makes a $O(n^{2} \times m \times k)$ dynamic programming which fits perfectly in the time.
[ "dp" ]
1,900
null
41
E
3-cycles
During a recent research Berland scientists found out that there were $n$ cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.
The road map with most edges is a complete bipartite graph with equal number of vertices on each side. (Prove it by yourself :D ). We can make such a graph by putting the first $\left\lfloor{\frac{n}{2}}\right\rfloor$ vertices on one side and the other $\textstyle\left[{\frac{n}{2}}\right]$ on the other side.For sure , number of edges is $\textstyle{\left[{\frac{n}{2}}\right]}\times\left[{\frac{n}{2}}\right]$
[ "constructive algorithms", "graphs", "greedy" ]
1,900
#include <iostream> using namespace std; int main() { int n; cin>>n; if(n%2==0) cout<<n/2*n/2<<endl; else cout<<n/2*(n+1)/2<<endl; for(int i=1;i<=n/2;i++) for(int j=n/2+1;j<=n;j++) cout<<i<<" "<<j<<endl; return 0; }
42
A
Guilty --- to the kitchen!
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills. According to the borscht recipe it consists of $n$ ingredients that have to be mixed in proportion $(a_{1}:a_{2}:\dots:a_{n})$ litres (thus, there should be $a_{1} ·x, ..., a_{n} ·x$ litres of corresponding ingredients mixed for some non-negative $x$). In the kitchen Volodya found out that he has $b_{1}, ..., b_{n}$ litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a $V$ litres volume pan (which means the amount of soup cooked can be between $0$ and $V$ litres). What is the volume of borscht Volodya will cook ultimately?
Let us reformulate the statement: we need to find the maximum possible value of x (mentioned in the statement) so that the amount of each ingredient will be enough. Clearly, such x equals min(b_i / a_i). Now it suffices to take minimum of the two values: soup volume we gained and the volume of the pan.
[ "greedy", "implementation" ]
1,400
null
42
B
Game of chess unfinished
Once Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", — Volodya said and was right for sure. And your task is to say whether whites had won or not. Pieces on the chessboard are guaranteed to represent a correct position (every piece occupies one cell, no two pieces occupy the same cell and kings cannot take each other). Thus, your task is only to decide whether whites mate blacks. We would remind you that it means that the black king can be taken by one of the opponent's pieces at the moment and also it cannot move to an unbeaten position. A rook moves vertically or horizontally by any number of free cells (assuming there are no other pieces on its path), a king — to the adjacent cells (either by corner or by side). Certainly, pieces cannot leave the board. The black king might be able to take opponent's rooks at his turn (see sample 3).
In this problem you are to check exactly what the statement says: if the king's position and all the positions reachable by him in one turn are "beaten", - that's a mate. Thus, we have to determine "beaten" positions correctly. Let us remove the black king from the chessboard, leave the positions of the rooks "unbeaten" (not to forget about possible taking of the rook by the black king), mark positions reachable by rooks "beaten" and then mark positions reachable by white king as "beaten".
[ "implementation" ]
1,700
null
42
C
Safe cracking
Right now you are to solve a very, very simple problem — to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both by one; you may choose two adjacent even numbers and divide both by two. Nothing else. Crack the safe!
The answer in this problem is always affirmative, which means it is always possible to make all the numbers equal to one. Greedy approach (here we somehow make two adjacent numbers even and then divide them by two) leads the sum of numbers to become less or equal to six in logarithmic (and certainly less than 1000) number of operations. There are several ways do deal with extremal cases: for instance, many of the participants coped with this by the analysis of all of the cases left. The greedy approach only is not sufficient: the crucial test for hacks was (1 1 1 2).
[ "brute force", "constructive algorithms" ]
2,200
null
42
D
Strange town
Volodya has recently visited a very odd town. There are $N$ tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.
Let us associate some numbers a_i with the vertices of the graph. If, for each edge, we assign it the sum of its endpoints' numbers, then the sum of prices along arbitrary hamiltonian cycle will be equal to the doubled sum of a_i. Therefore, it suffices us to devise such numbers a_i so that their pairwise sums will be distinct (as the edge prices should be distinct). As all of the edge prices are bounded above by 1000, we have to think of an efficient strategy to obtain such a_i. Let's choose them in greedy way, so that newly added a_i should not be equal to (a_p + a_q - a_k) for each triple of already chosen a_p, a_q, a_k. It is clear that a_n = O(n^3) as there are O(n^3) "blocking" triples (p, q, k). Another idea lies in that equality AB+CD=AC+BD should hold for every quadruple of distinct vertices A, B, C, D (summands stay for edge prices), because a hamiltonial cycle with edges AB and CD can be easily rearranged in the cycle with edges AC and BD and the sums of these cycles should be equal. You may think of how this idea was used by jury to check your solutions in exact and fast way.
[ "constructive algorithms", "math" ]
2,300
null
42
E
Baldman and the military
Baldman is a warp master. He possesses a unique ability — creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head. Because of such extraordinary abilities, Baldman has caught the military's attention. He has been charged with a special task. But first things first. The military base consists of several underground objects, some of which are connected with bidirectional tunnels. There necessarily exists a path through the tunnel system between each pair of objects. Additionally, exactly two objects are connected with surface. For the purposes of security, a patrol inspects the tunnel system every day: he enters one of the objects which are connected with surface, walks the base passing each tunnel \textbf{at least} once and leaves through one of the objects connected with surface. He can enter and leave either through the same object, or through different objects. The military management noticed that the patrol visits some of the tunnels multiple times and decided to optimize the process. Now they are faced with a problem: a system of wormholes needs to be made to allow of a patrolling which passes each tunnel \textbf{exactly} once. At the same time a patrol is allowed to pass each wormhole any number of times. This is where Baldman comes to operation: he is the one to plan and build the system of the wormholes. Unfortunately for him, because of strict confidentiality the military can't tell him the arrangement of tunnels. Instead, they insist that his system of portals solves the problem for any arrangement of tunnels which satisfies the given condition. Nevertheless, Baldman has some information: he knows which pairs of objects he can potentially connect and how much it would cost him (in hair). Moreover, tomorrow he will be told which objects (exactly two) are connected with surface. Of course, our hero decided not to waste any time and calculate the minimal cost of getting the job done for some pairs of objects (which he finds likely to be the ones connected with surface). Help Baldman!
First note that a valid graph of wormholes is either connected or consists of two connectivity components with one exit in each. The proof is in the end of this text. Also note that the first option is never optimal because one edge can be removed to get the second option. Let's build a minimal spanning tree of the input graph. If it contains more than two components, the answer for each query is -1. If it contains two components, the answer is -1 if both objects are in the same component, and the weight of the spanning tree otherwise. The most interesting case is one component: we need to cut the spanning tree into two trees containing one exit each and having minimal sum of weights (not actually cut but get the sum of weights of the resulting trees). It can be done by (virtually) removing the most heavy edge on the path between the exits; so the only thing we need to know is the weight of such edge. It can be done with LCA algorithm: for each node precalculate upward jumps of height 2^k, k=0..log n, but also for each jump calculate the maximum weight of an edge on the path of this jump. Then you can split the path a-b in paths a-lca(a,b) and b-lca(a,b) and calculate the maximum weight on each of them in O(log n) using the precalculated values. Now the proof: First, it's easy to see that such graph of wormholes is valid: we can enter any exit, cross all tunnels in this component, go to another component (there is always an edge between components because tunnel graph is connected), cross all tunnels there, cross all remaining tunnels between components and leave using one of the exits. Besides these components A and B let there be another component C (and maybe some other components) and the number of tunnels between A and C is odd, between B and C - even; in this case it's impossible to traverse all tunnels once and return to A or B, so this wormhole graph is invalid. If both exits are in the same component and there is another component and the number of tunnels between them is odd, it's invalid too. So the only options left are those mentioned in the beginning.
[ "dfs and similar", "graphs", "trees" ]
2,700
null
43
A
Football
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are $n$ lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
This is pretty obvious , you can store the two strings and how many times each of them occurred
[ "strings" ]
1,000
null
43
B
Letter
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading $s_{1}$ and text $s_{2}$ that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.
For each of the upper or lower case letters , take care about how many times it appeared in each of the strings. if for a character x , repetitions of x in the second string is more than the first string , we can't make it , otherwise the answer is YES.
[ "implementation", "strings" ]
1,100
null
43
C
Lucky Tickets
Vasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the $2t$ pieces he ended up with $t$ tickets, each of which was lucky. When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest. Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123. What maximum number of tickets could Vasya get after that?
We all know that the remainder of a number when divided by 3 is equal to the remainder of sum of its digits when divided by three. So we can put all of input numbers in 3 sets based on their remainder by 3. Those with remainder 1 can be matched with those with remainder 2 and those with remainder 0 can be matched with themselves. so the answer is:half of number of those divisible by three + minimum of those having a remainder of 1 and those having a remainder of 2
[ "greedy" ]
1,300
null
43
D
Journey
The territory of Berland is represented by a rectangular field $n × m$ in size. The king of Berland lives in the capital, located on the upper left square $(1, 1)$. The lower right square has coordinates $(n, m)$. One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out — one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.
Actually we're looking for an Eulerian tour. I found it like this: If at least one of m and n was even do it like this figure: else do it like this and add a teleport from last square to the first: But there were really nice hacks as I studied them. like these two: 1 10 and 1 2
[ "brute force", "constructive algorithms", "implementation" ]
2,000
null
43
E
Race
Today $s$ kilometer long auto race takes place in Berland. The track is represented by a straight line as long as $s$ kilometers. There are $n$ cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior — the system of segments on each of which the speed of the car is constant. The $j$-th segment of the $i$-th car is pair $(v_{i, j}, t_{i, j})$, where $v_{i, j}$ is the car's speed on the whole segment in kilometers per hour and $t_{i, j}$ is for how many hours the car had been driving at that speed. The segments are given in the order in which they are "being driven on" by the cars. Your task is to find out how many times during the race some car managed to have a lead over another car. A lead is considered a situation when one car appears in front of another car. It is known, that all the leads happen instantly, i. e. there are no such time segment of positive length, during which some two cars drive "together". At one moment of time on one and the same point several leads may appear. In this case all of them should be taken individually. Meetings of cars at the start and finish are not considered to be counted as leads.
Let's just take care about 2 cars and see how many times they change their position. This is easy. Then do this for all cars :D
[ "brute force", "implementation", "two pointers" ]
2,300
null
44
A
Indian Summer
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
One of possible ways of solving the problem is to compare every leave with all taken before. If it matches one of them, than do not take it. Since the order of leaves is immaterial, you can just sort all the leaves (for example, as pairs of strings) and delete unique leaves.
[ "implementation" ]
900
null
44
B
Cola
To celebrate the opening of the Winter Computer School the organizers decided to buy in $n$ liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles $0.5$, $1$ and $2$ liters in volume. At that, there are exactly $a$ bottles $0.5$ in volume, $b$ one-liter bottles and $c$ of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well). Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly $n$ liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer. All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.
The problem is to find a number of triples (x, y, z), such that 0 <= x <= a, 0 <= y <= b, 0 <= z <= c and 0.5 * x + y + 2 * z = n. Trying all triples gets TL, but you can try all possible values of x and y, satisfying 0 <= x <= a, 0 <= y <= b. When x and y are fixed, z can be determined uniquely. So we get O(a*b) solution.
[ "implementation" ]
1,500
null
44
C
Holidays
School holidays come in Berland. The holidays are going to continue for $n$ days. The students of school №$N$ are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.
The easiest solution is to process all the days from 1 to n, and check for each day, that it is covered by exactly one segment $[a_{i}, b_{i}]$. If you find a day which is covered by less or more than one segment, output this day.
[ "implementation" ]
1,300
null
44
D
Hyperdrive
In a far away galaxy there are $n$ inhabited planets, numbered with numbers from $1$ to $n$. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number $1$ a hyperdrive was invented. As soon as this significant event took place, $n - 1$ spaceships were built on the planet number $1$, and those ships were sent to other planets to inform about the revolutionary invention. Paradoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of $s$ hyperyears in $s$ years). When the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make $n - 2$ identical to it ships with a hyperdrive and send them to other $n - 2$ planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new $n - 2$ ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues. However the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy! Your task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet.
Let us call ships that were produced initially ''the ships of the first generation''. When a ship of the first generation reaches a planet, and new ships are build there, we call them ''ships of the second generation'', and so on. Let us prove that the first collision is between two ships of the second generation, moving towars each other. Indeed, ships of the first generation move in distict dirrections (no three points lie on the same line), so they cannot collide. If a ship of the first generation collides with a ship of the second generation, the lines of their moving form a triangle OAC, where O is the first planet, A is a planet where the ship of the second generation has been produced, and C is a point of the collision. But it's clear that OA + AC > OC, and ships are moving with the same speed, so such collision cannot happen. Speaking about ships of the third generation, they cannot be produced at all! Suppose that a ship from the first planet has reached the planet A, and then a ship from planet A has reached the planet B. But by virtue of the triangle inequality, a ship from the first planet has reached the planet B earlier, ships were produced at B, one of them was sent to A and collide with the ship, moving from A to B. For similar reasons two ships cannot collide, if one of them is moving from A to B, and another is moving from C to D. Ships moving from A to C and from C to A will collide earlier. Thus, the solution is to compute for each pair of planets A, B a perimeter of the triangle OAB, and find the minimal one.
[ "math" ]
1,800
null
44
E
Anfisa the Monkey
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into $k$ lines not shorter than $a$ and not longer than $b$, for the text to resemble human speech more. Help Anfisa.
There are multiple ways to split the string. One of them is to split it into parts of lengths n / k and n / k + 1, if n is not divisible by k. Here n is the length of the given string. If lengths of such parts are not less than a and not greater than b, the answer is found. Otherwise there is no solution.
[ "dp" ]
1,400
null
44
F
BerPaint
Anfisa the monkey got disappointed in word processors as they aren't good enough at reflecting all the range of her emotions, that's why she decided to switch to graphics editors. Having opened the BerPaint, she saw a white rectangle $W × H$ in size which can be painted on. First Anfisa learnt to navigate the drawing tool which is used to paint segments and quickly painted on that rectangle a certain number of black-colored segments. The resulting picture didn't seem bright enough to Anfisa, that's why she turned her attention to the "fill" tool which is used to find a point on the rectangle to paint and choose a color, after which all the area which is the same color as the point it contains, is completely painted the chosen color. Having applied the fill several times, Anfisa expressed her emotions completely and stopped painting. Your task is by the information on the painted segments and applied fills to find out for every color the total area of the areas painted this color after all the fills.
Imagine that all segments were drawn. We will refer to these segments as to initial segments. Lets divide the rectangle of drawing into the set of regions and segments such that there are no points of the initial segments strictly inside any region, and new segments separate the regions. Note that new set of segments can contain not only the parts of the initial segments, but also some dummy segments. Initially the color of all regions is white, while the color of each segment can be black of white (dummy segments are white). Please note that in such a partition the border of the region is not consider to belong to it. Lets build a graph where each vertice corresponds either to a region or to a segment, and add edges according to the following rules: 1) Edge between two non-dummy segments is in the graph if these segments have common end-point. 2) Edge between a region and a segment (dummy or not) is in the graph if they have more than one common point (i.e. the segment is a part of the border of the region). It is clear that every region that can be filled corresponds to some connected component of this graph. That gives us a solution. We will store a color for each vertice. When processing a filling operation, we search for all such vertices that the objects that correspond to these vertices contain the chosen point. For region, the point should lie strictly inside the region. For the dummy segment, the point should lie on it but should not coincide with it end-points. And for the non-dummy segment, the point should just lie on it. From each of the found vertices, we make a DFS or BFS which finds all vertices that are reachable from the statring vertice and have the same color, and paints them with new color. After all operations, we need to find sum of areas for such colors, that there are at least one vertice with this color. The main difficulty in the problem is to divide the rectangle into regions and segments. In my solution it is done using vertical decomposition. First, divide the rectangle into vertical stripes such that inner area of any stripe doesn't contain neiher end-points of the initial segments nor points of their intersections. Then each of these stripes is divided into trapezoid by initial segments, intersecting the stripe. Then add necessary dummy segments to separate the regions and build the graph. I think that there may be some easier ways to construct such graph.
[ "geometry", "graphs" ]
2,700
null
44
G
Shooting Gallery
Berland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shooting gallery. During the elaboration process it turned out that the program that imitates the process of shooting effectively, is needed. To formulate the requirements to the program, the shooting gallery was formally described. A 3D Cartesian system of coordinates was introduced, where the $X$ axis ran across the gallery floor along the line, along which the shooters are located, the $Y$ axis ran vertically along the gallery wall and the positive direction of the $Z$ axis matched the shooting direction. Let's call the $XOY$ plane a shooting plane and let's assume that all the bullets are out of the muzzles at the points of this area and fly parallel to the $Z$ axis. Every clay pigeon can be represented as a rectangle whose sides are parallel to $X$ and $Y$ axes, and it has a positive $z$-coordinate. The distance between a clay pigeon and the shooting plane is always different for every target. The bullet hits the target if it goes through the inner area or border of the rectangle corresponding to it. When the bullet hits the target, the target falls down vertically into the crawl-space of the shooting gallery and cannot be shot at any more. The targets are tough enough, that's why a bullet can not pierce a target all the way through and if a bullet hits a target it can't fly on. In input the simulator program is given the arrangement of all the targets and also of all the shots in the order of their appearance. The program should determine which target was hit by which shot. If you haven't guessed it yet, you are the one who is to write such a program.
Lets solve slightly different problem: for every target we will determine the shoot that hits it. Sort the targets in increasing order of their z-coordinate and process them in that order. Each target is processed as follows. Consider all shoots that potentially can hit it. It is obvious that all such shoots belong to the rectangle, corresponding to the target. From these shoots, the earliest shoot will hit the target. We should find this shoot and remove it from the set of shoots, and then turn to the next target. It's easy to see that the following condition will be held: before we process a target, all shoots that were going to hit it but faced other targer, were already removed from the set of shoots. Now we need to implement the algorithm efficiently. We will store the shoots in some data structure. This structure should be able to answer two types of queries: 1) Find element with minimum value in the given rectangle. 2) Remove the given element. In my solution I used two-dimensional index tree to manage these queries. I won't describe what the two-dimensional index tree is. I just want to make several remarks. First, the removing operation is not as easy to implement in a two-dimensional index tree as it mays seem. But we are lucky that we have no additions, just deletions! Time complexity of the model solution is $O((N + M)log^{2}N$.
[ "data structures", "implementation" ]
2,500
null
44
H
Phone Number
Alas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy. The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is $12345$. After that one should write her favorite digit from $0$ to $9$ under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is $9$. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to $(2 + 9) / 2 = 5.5$. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit $5$. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is $(5 + 3) / 2 = 4$. In this case the answer is unique. Thus, every $i$-th digit is determined as an arithmetic average of the $i$-th digit of Masha's number and the $i - 1$-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get: \[ 12345 \] \[ 95444 \] Unfortunately, when Masha tried dialing the number, she got disappointed: as it turned out, the number was unavailable or outside the coverage area. But Masha won't give up. Perhaps, she rounded to a wrong digit or chose the first digit badly. That's why she keeps finding more and more new numbers and calling them. Count the number of numbers Masha calls. Masha calls all the possible numbers that can be found by the described means of arithmancy, except for, perhaps, her own one.
The answer may be rather large, because it grows exponentially with growth of n, but it fits int64. Indeed, there are 10 ways to choose the first digit, than 1 or 2 ways to choose the second one, 1 or 2 ways for the third one, and so on. So the number of ways doens't exceed $10 \cdot 2^{None}$. The problem can be solved by dynamic programming. Let $d_{ij}$ be a number of ways to get first i digits of a correct number with the i-th digit equal to j. From such part of a number we can obtain a part of size i + 1 with (i+1)-th digit equal to $(j + a_{None}) / 2$ or $(j + a_{None} + 1) / 2$, where $a_{i}$ is the i-th digit of Masha's number. So if we have $d_{ij}$ for all $j$, we can obtain $d_{None}$. Do not forget to subtract 1, if Masha can obtain her own number. It will happen in case when each two successive digits in the given number differs at most by 1.
[ "dp" ]
1,700
null
44
I
Toys
Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her $n$ toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile.
In this problem we need to output all partitions of the given set into subsets in the order which is very similar to the Gray code. Lets denote each partition by a restricted growth string. For a restricted growth string $a_{1}a_{2}a_{n}$ holds that $a_{1} = 0$ and $a_{None} \le 1 + max(a_{1}, ..., a_{j})$ for $1 \le j < n$. Every partition can be encoded with such string using the following idea: $a_{i} = a_{j}$ if and only if elements $i$ and $j$ belong to the same subset in the partition. For example, string representation of the partition {1,3},{2},{4} is 0102. Now we will learn how to generate all restricted growth strings by making a change in exactly one position in the current string to get the next string. It is obvious that in terms of partitions it is what we are asked for in the problem. Rather easy way to build such list of strings was invented by Gideon Ehrlich. Imagine that we have the required list $s_{1}, s_{2}, ..., s_{k}$ for the length $n - 1$, We will obtain a list for the length $n$ from it. Lets $s_{i} = a_{1}a_{2}... a_{None}$, and $m = 1 + max(a_{1}, ..., a_{None})$. Then, if $i$ is odd, we will obtain strings of the length $n$ by appending digits $0, m, m - 1, ..., 1$ to $s_{i}$, otherwise we will append digits in order $1, ..., m - 1, m, 0$. Thus, starting from the list $0$ for $n = 1$ we will consequently get lists $00, 01$ for $n = 2$ and $000, 001, 011, 012, 010$ for $n = 3$. Ehrlich scheme is decribed in Knuth's "The art of programming", volume 4, fascicle 3, pages 83-84.
[ "brute force", "combinatorics" ]
2,300
null
44
J
Triminoes
There are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard ($8 × 8$) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes $1 × 2$, if the two cut out squares are of the same color, otherwise it is impossible. Petya grew bored with dominoes, that's why he took a chessboard (not necessarily $8 × 8$), cut some squares out of it and tries to tile it using triminoes. Triminoes are reactangles $1 × 3$ (or $3 × 1$, because triminoes can be rotated freely), also the two extreme squares of a trimino are necessarily white and the square in the middle is black. The triminoes are allowed to put on the chessboard so that their squares matched the colors of the uncut squares of the chessboard, and also the colors must match: the black squares must be matched with the black ones only and the white ones — with the white squares. The triminoes must not protrude above the chessboard or overlap each other. All the uncut squares of the board must be covered with triminoes. Help Petya find out if it is possible to tile his board using triminos in the described way and print one of the variants of tiling.
First, if the tiling is possible, it is unique. Consider the most upper-left position (x, y) that is not cut out. If it is black, the tiling is impossible. If it is white, look at the next position (x, y + 1). If it is cut out, the only possible way to put a trimino is to put it vertically. Otherwise we must put a trimino horisontally, because if we put it vertically, we wouldn't be able to cover the next black position (x, y + 1). These considerations give us an algorithm for the solution. Four symbols a, b, c, d are always enough to represent the tiling, because a trimino can have common sides with no more than 3 triminoes located to the left or above it. So even if all the 3 triminoes are marked by 3 different symbols, the next one may be marked by the 4-th one.
[ "constructive algorithms", "greedy" ]
2,000
null
46
A
Ball Game
A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from $1$ to $n$ clockwise and the child number $1$ is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number $2$. Then the child number $2$ throws the ball to the next but one child, i.e. to the child number $4$, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number $7$, then the ball is thrown to the child who stands $3$ children away from the child number $7$, then the ball is thrown to the child who stands $4$ children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if $n = 5$, then after the third throw the child number $2$ has the ball again. Overall, $n - 1$ throws are made, and the game ends. The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.
The solution of the problem based on modeling of the decribed process. It is important to perform a pass throw the beginning correctly. You can take the current number modulo n (and add 1), or you can subtract n every time the current number increases n.
[ "brute force", "implementation" ]
800
null
46
B
T-shirts from Sponsor
One day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of $K$ participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.
Enumerate sizes of t-shirts by integers from 0 to 4. For each size we store the number of t-shirts of this size left. To process each participant, we need to determine the number of his preferable size. Then we iterate over all possible sizes and choose the most suitable one (with the nearest number) among the sizes with non-zero number of t-shirts left.
[ "implementation" ]
1,100
null
46
C
Hamsters and Tigers
Today there is going to be an unusual performance at the circus — hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.
First of all, count the number of hamsters in the sequence. Let it is h. Try positions where the sequence of hamsters will start, and for each position count the number of tigers in the segment of length h starting from the fixed position. These tigers should be swapped with hamsters in a number of swaps equal to the number of tigers not in proper places. Choose minimum among all starting posotions.
[ "two pointers" ]
1,600
null
46
D
Parking Lot
Nowadays it is becoming increasingly difficult to park a car in cities successfully. Let's imagine a segment of a street as long as $L$ meters along which a parking lot is located. Drivers should park their cars strictly parallel to the pavement on the right side of the street (remember that in the country the authors of the tasks come from the driving is right side!). Every driver when parking wants to leave for themselves some extra space to move their car freely, that's why a driver is looking for a place where the distance between his car and the one behind his will be no less than $b$ meters and the distance between his car and the one in front of his will be no less than $f$ meters (if there's no car behind then the car can be parked at the parking lot segment edge; the same is true for the case when there're no cars parked in front of the car). Let's introduce an axis of coordinates along the pavement. Let the parking lot begin at point 0 and end at point $L$. The drivers drive in the direction of the coordinates' increasing and look for the earliest place (with the smallest possible coordinate) where they can park the car. In case there's no such place, the driver drives on searching for his perfect peaceful haven. Sometimes some cars leave the street and free some space for parking. Considering that there never are two moving cars on a street at a time write a program that can use the data on the drivers, entering the street hoping to park there and the drivers leaving it, to model the process and determine a parking lot space for each car.
Lets keep a set of cars which are currently parked. In this problem it is not essential how to keep this set. For each car, store its length and position. To process a request of type 2, we need to find the car which should leave the parking and remove it from the set. To do this, we should enumerate the cars and get the car number by the number of request. Now consider a request of type 1. As the drives tries to park his car as close to the beginning of the parking slot as possible, we can reduce the set of reasonable positions for parking: include into this set the beginning of the parking and all positions that are exactly $b$ meters after the front of some car. For every position in this set we should determine if it is possible to park car in it. Then we choose the closest to the beginning position among admissible ones.
[ "data structures", "implementation" ]
1,800
null
46
E
Comb
Having endured all the hardships, Lara Croft finally found herself in a room with treasures. To her surprise she didn't find golden mountains there. Lara looked around and noticed on the floor a painted table $n × m$ panels in size with integers written on the panels. There also was a huge number of stones lying by the wall. On the pillar near the table Lara found a guidance note which said that to get hold of the treasures one has to choose some non-zero number of the first panels in each row of the table and put stones on all those panels to push them down. After that she will receive a number of golden coins equal to the sum of numbers written on the chosen panels. Lara quickly made up her mind on how to arrange the stones and was about to start when she noticed an addition to the note in small font below. According to the addition, for the room ceiling not to crush and smash the adventurer, the chosen panels should form a comb. It was explained that the chosen panels form a comb when the sequence $c_{1}, c_{2}, ..., c_{n}$ made from the quantities of panels chosen in each table line satisfies the following property: $c_{1} > c_{2} < c_{3} > c_{4} < ...$, i.e. the inequation mark interchanges between the neighboring elements. Now Lara is bewildered and doesn't know what to do. Help her to determine the largest number of coins she can get and survive at the same time.
Denote the input matrix by $a$. Compute the partial sums in each row first: $s_{i,j}=\sum_{k=1}^{J}a_{i,k}$. All these sums can be easily computed in $O(nm)$. Then solve the task using dynamic programming. By $d_{None}$ denote the maximum sum of numbers that we can take from first $i$ rows, taking exactly $j$ numbers in row $i$ and not violating the "comb" condition. Starting values are obvious $d_{None} = s_{None}$. Transitions for $i > 1$ looks like this: 1) If $i$ is even, $d_{i,j}=s_{i,j}+\operatorname*{max}_{k=j+1,m}d_{i-1,k}$. 2) If $i$ is odd, $d_{i,j}=s_{i,j}+\operatorname*{max}_{k=1,j-1}d_{i-1,k}$. Straightforward computing of values $d_{None}$ by these formulas has complexity $O(nm^{2})$, which is not suitable. Use the following fact: if we compute values $d_{None}$ in order of decreasing $j$ in case of even $i$ and in order of increasing $j$ in case of odd $i$, the maximum values of $d_{None}$ from the previous row can be computed in $O(1)$, using value for previous $j$, i.e. without making a cycle for computation. This solution has complexity $O(nm)$ and passes all tests.
[ "data structures", "dp" ]
1,900
null
46
F
Hercule Poirot Problem
Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has $n$ rooms and $m$ doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could - open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side); - move freely from a room to a room if a corresponding door is open; - give keys to one another, being in one room. "Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.
First, note that all the described operations are invertible: opening/closing doors, moving from one room to another and exchanging keys. So we may perform such operations from the initial arrangement to get some arrangment A, and then perform some operations from the final arrangement to get the same arrangement A, in this case the answer is "YES". Let apply the following strategy to both arrangements: while there is a person who can go to some room and open some door, perform this action. As a result from each arrangement we obtain subsets of connected rooms (we call them connected parts of the house), corresponding subsets of people and corresponding subset of keys in each connected part of the house. If these resulting subsets coincide for the initial and the final arrangement, then the answer is "YES", otherwise the answer is "NO". Indeed, if they coincide, it is obvious that we can get from the initial arrangement to the resulting arrangement, and then - to the final arrangement. Otherwise it is impossible, because there exist some keys that cannot be applied to the corresponding doors, because they are in another connected part of the house, or there exist people, who have no way to get to rooms in another connected part of the house. Second, a few words about implementation. One of possible ways is to have two boolean matrices: 1) saying for each person if he/she could get to each room and 2) saying for each key the same, and then recursively implement operations:1) if a person can get to a room, try to get to neirbouring rooms, 2) the same for keys, but also trying to open a door to the neirbouring room,3) if the door opens, people and keys in the incident rooms are assigned to another room. So we try each pair person-room, person-door, key-door, key-room for O(1) times, and the total asymptotics is $O(nk + km + m^{2} + nm)$.
[ "dsu", "graphs" ]
2,300
null
46
G
Emperor's Problem
It happened at the times of the Great Berland Empire. Once the Emperor dreamt that the Messenger from the gods ordered to build a temple whose base would be a convex polygon with $n$ angles. Next morning the Emperor gave the command to build a temple whose base was a regular polygon with $n$ angles. The temple was built but soon the Empire was shaken with disasters and crop failures. After an earthquake destroyed the temple, the Emperor understood that he somehow caused the wrath of gods to fall on his people. He ordered to bring the wise man. When the wise man appeared, the Emperor retold the dream to him and asked "Oh the wisest among the wisest, tell me how could I have infuriated the Gods?". "My Lord," the wise man answered. "As far as I can judge, the gods are angry because you were too haste to fulfill their order and didn't listen to the end of the message". Indeed, on the following night the Messenger appeared again. He reproached the Emperor for having chosen an imperfect shape for the temple. "But what shape can be more perfect than a regular polygon!?" cried the Emperor in his dream. To that the Messenger gave a complete and thorough reply. - All the vertices of the polygon should be positioned in the lattice points. - All the lengths of its sides should be different. - From the possible range of such polygons a polygon which maximum side is minimal possible must be chosen. You are an obedient architect who is going to make the temple's plan. Note that the polygon should be simple (having a border without self-intersections and overlapping) and convex, however, it is acceptable for three consecutive vertices to lie on the same line.
Note that the lengths of the sides can be $\sqrt{1}$, ${\sqrt{2}}$, ${\sqrt{4}}$, $\sqrt{5}$, and so on, i.e. the roots of integers, that can be represented as $a^{2} + b^{2}$. Generate a proper quantity of such numbers. Denote them $\sqrt{r_{1}}$, ${\sqrt{r}}_{2}$, ... In some cases we can take first $n$ such numbers as lengths of sides, but in some cases we surely cannot. It depends on the parity. If the sum $r_{1} + r_{2} + ... + r_{n}$ is odd, it is impossible. Indeed, we canrepresent each side by vector $(x_{i}, y_{i})$, $x_{i}^{2} + y_{i}^{2} = r_{i}$ ($x_{i}$ and $y_{i}$ may be negative). If $r_{i}$ is even, then $x_{i} + y_{i}$ is even too. If $r_{i}$ is odd, then $x_{i} + y_{i}$ is odd. If we form a polygon with vectors of the sides $(x_{i}, y_{i})$, then $x_{1} + x_{2} + ... + x_{n} = 0$ and $y_{1} + y_{2} + ... + y_{n} = 0$, so the total sum $x_{1} + ... + x_{n} + y_{1} + ... + y_{n}$ must be even! But if $r_{1} + ... + r_{n}$ is odd, it is odd too, so to build a polygon is impossible. Let us take $r_{1}$, ..., $r_{n}$ if their sum is even, and otherwise take $r_{1}$, ..., $r_{None}$ and throw away one of them to make the sum even (in my solution I throw away the greatest such number). For each $r_{i}$ choose non-negative $x_{i}$ and $y_{i}$, $x_{i}^{2} + y_{i}^{2} = r_{i}$. In general case there are 8 possible orientations of a vector: $(x_{i}, y_{i})$, $( - x_{i}, y_{i})$, $(x_{i}, - y_{i})$, $( - x_{i}, - y_{i})$, $(y_{i}, x_{i})$, $( - y_{i}, x_{i})$, $(y_{i}, - x_{i})$, $( - y_{i}, - x_{i})$. The current subtask is to find such orientation for each vector that their sum is zero. It can be done by the greedy algorithm. Let's take the vectors from the longest ones. We will calculate current vector sum that is initially (0, 0), and it will be updated by each new taken vector. At each step choose such orientation that the current vector with that orientation minimizes the current sum (by its length) being added to it. Then, when the vectors are oriented, sort them by polar angle and apply them consequently to get a convex polygon. The described algorithm finds a required polygon for all possible tests.
[ "geometry" ]
2,500
null
47
A
Triangular numbers
A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The $n$-th triangular number is the number of dots in a triangle with $n$ dots on a side. $T_{n}={\frac{n(n+1)}{2}}$. You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number). Your task is to find out if a given integer is a triangular number.
Because of small constraints, just iterate $n$ from 1 to $T_{n}$ and check $T_{n}={\frac{n(n+1)}{2}}$
[ "brute force", "math" ]
800
null
47
B
Coins
One day Vasya came across three Berland coins. They didn't have any numbers that's why Vasya didn't understand how their denominations differ. He supposed that if one coin is heavier than the other one, then it should be worth more. Vasya weighed all the three pairs of coins on pan balance scales and told you the results. Find out how the deminations of the coins differ or if Vasya has a mistake in the weighting results. No two coins are equal.
Let's consider a graph, where the letters $A$, $B$, $C$ are the vertexes and if $x < y$, then the edge $y - > x$ exists. After that let's perform topological sort. If a cycle was found during this operation, put "Impossible" and exit. Otherwise put the answer. Another approach is acceptable because of small constaints (by Connector in russian comments). Just iterate over all of $3!$ permutaioins of the letters and check if they are sorted. If no such permutation, put "Impossible"
[ "implementation" ]
1,200
null
47
C
Crossword
Vasya trains to compose crossword puzzles. He can only compose crosswords of a very simplе type so far. All of them consist of exactly six words; the words can be read only from top to bottom vertically and from the left to the right horizontally. The words are arranged in the form of a rectangular "eight" or infinity sign, not necessarily symmetrical. The top-left corner of the crossword coincides with the top-left corner of the rectangle. The same thing is correct for the right-bottom corners. The crossword can't degrade, i.e. it always has exactly four blank areas, two of which are surrounded by letters. Look into the output for the samples for clarification. Help Vasya — compose a crossword of the described type using the given six words. It is allowed to use the words in any order.
Let's iterate over all of $6! = 720$ permutations. For every permutation let's try to put the first 3 words horizontally, the others - vertically: hor[0], ver[0] - left-up hor[2], ver[2] - right-down hor[1]: (len(ver[0]) - 1, 0)ver[1]: (0, len(hor[0]) - 1) Now let's define N = len(ver[1]), M = len(hor[1]). A Conditions for the solution existence len(hor[0]) + len(hor[2]) == M + 1 // edges of "eight" len(ver[0]) + len(ver[2]) == N + 1 // edges of "eight" len(hor[0]) >= 3 && len(hor[2]) >= 3 && len(ver[0]) >= 3 && len(ver[2]) >= 3 // "eight" is nondegenerateThe letters at start/end of appropriate strings are matchThe letters on the intersection of hor[1], ver[1] are match Now we have the right field of the size N x M, and update the answer Note In C++ if you use vector<vector<char> > or vector<string> as the field type, then you can simply use operator "<" for updating.
[ "implementation" ]
2,000
null
47
D
Safe
Vasya tries to break in a safe. He knows that a code consists of $n$ numbers, and every number is a 0 or a 1. Vasya has made $m$ attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unlucky that he hasn’t entered the code where would be more than 5 correct numbers. Now Vasya is completely bewildered: he thinks there’s a mistake in the system and it is self-contradictory. Help Vasya — calculate how many possible code variants are left that do not contradict the previous system responses.
Let's consider not the most efficient, but AC algorithm, with the complexity $O(mC_{n}^{5}log(C_{n}^{5}))$. Let's consider the 1 answer of the system: <number, v>. The amount of the variants of the password is $C_{n}^{v}$ - not very large number in constaints of the problem, you can simply generate this variants. Declare this set of variants as current. Now, for the every answer let's generate a set of possible passwords, and let's declare the intersection of this set and current set as current. After $m$ iterations we'll have some set. Then we'll erase elements from this set, which were in the answers of the system, and the answer of the problem will be the size of this set.
[ "brute force" ]
2,200
null
47
E
Cannon
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the $Ox$ axis is directed rightwards in the city's direction, the $Oy$ axis is directed upwards (to the sky). The cannon will make $n$ more shots. The cannon balls' initial speeds are the same in all the shots and are equal to $V$, so that every shot is characterized by only one number $alpha_{i}$ which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed $45$ angles ($π / 4$). We disregard the cannon sizes and consider the firing made from the point $(0, 0)$. The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: \[ v_{x}(t) = V·cos(alpha) \] \[ v_{y}(t) = V·sin(alpha)  –  g·t \] \[ x(t) = V·cos(alpha)·t \] \[ y(t) = V·sin(alpha)·t  –  g·t^{2} / 2 \] Think of the acceleration of gravity $g$ as equal to $9.8$. Bertown defends $m$ walls. The $i$-th wall is represented as a vertical segment $(x_{i}, 0) - (x_{i}, y_{i})$. When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground ($y = 0$) and stops. If the ball exactly hits the point $(x_{i}, y_{i})$, it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end.
Let's consider an algorightm with complexity $O((n + m)log(n + m))$. Exclude from considiration every wall can't be achieved by canon: $x > v^{2} / g$ Because of $ \alpha < = \pi / 4$: Function $X_{max}( \alpha )$ is monotonous Function $Y( \alpha , x)$, when x is fixed, is monotonousSuch observation allows to assign to each wall a section of the attack angle $[ \alpha 1, \alpha 2]$. If this canon shoots with angle within this section, it hits the wall. These angles can be obtained by solving equation (it will be biquadratic), but because of monotonous we can use binary search. Sort walls by $x$. Now the initial problem has reduced to the problem: for every shoot it is need to obtain minimal index of the wall, when shoot angle is between attack angles for this wall. This problem can be solved by Segment Tree for Minimum with possibility to update on an interval. At first, fill tree with KInf. Next, for every wall let's perform update($ \alpha 1$, $ \alpha 2$, index). Then let's iterate over requests. If getMin($ \alpha $) == KInf, then missle do not hit any wall and hit the land, otherwise it hit the wall with index getMin($ \alpha $).
[ "data structures", "geometry", "sortings" ]
2,200
null
50
A
Domino piling
You are given a rectangular board of $M × N$ squares. Also you are given an unlimited number of standard domino pieces of $2 × 1$ squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squares. 2. No two dominoes overlap. 3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board. Find the maximum number of dominoes, which can be placed under these restrictions.
Answer is floor(N*M*0.5). Since there is N*M cells on the board and each domino covers exactly two of them we cannot place more for sure. Now let's show how to place exactly this number of dominoes. If N is even, then place M rows of N/2 dominoes and cover the whole board. Else N is odd, so cover N-1 row of the board as shown above and put floor(M/2) dominoes to the last row. In the worst case (N and M are odd) one cell remains uncovered.
[ "greedy", "math" ]
800
null
50
B
Choosing Symbol Pairs
There is a given string $S$ consisting of $N$ symbols. Your task is to find the number of ordered pairs of integers $i$ and $j$ such that 1. $1 ≤ i, j ≤ N$ 2. $S[i] = S[j]$, that is the $i$-th symbol of string $S$ is equal to the $j$-th.
Of course you were expected to code solution which is not quadratic in time complexity. Iterate over the string and count how many times each char is used. Let Ki be the number of occurrences of char with ASCII-code i in the string S. Then answer is sum(Ki2). While coding the solution the following common mistakes were made: 1. Code quadratic solution (double loop over the string) 2. Forget to use int64. Whether in answer or in Ki squaring. 3. Wrong int64 output. All these problems were easily hacked by max test with 100000 equal chars. This turned the hacking process into the game "who hacks the next B solution faster" because newbies often made all these mistakes. This problem was severed by the fact that GCC-compiler turned out to be MinGW-compiler, so output like printf("%lld", ...) did not work on it. Another strange problem hackers faced was quiet test truncation by length about 30000 when copy/pasting it into the test editor. Of course the overflow in solution disappears after it.
[ "strings" ]
1,500
null
50
C
Happy Farm 5
The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them. For that a young player Vasya decided to make the shepherd run round the cows along one and the same closed path. It is very important that the cows stayed strictly inside the area limited by the path, as otherwise some cows will sooner or later be eaten. To be absolutely sure in the cows' safety, Vasya wants the path completion time to be minimum. The new game is launched for different devices, including mobile phones. That's why the developers decided to quit using the arithmetics with the floating decimal point and use only the arithmetics of integers. The cows and the shepherd in the game are represented as points on the plane with integer coordinates. The playing time is modeled by the turns. During every turn the shepherd can either stay where he stands or step in one of eight directions: horizontally, vertically, or diagonally. As the coordinates should always remain integer, then the length of a horizontal and vertical step is equal to $1$, and the length of a diagonal step is equal to ${\sqrt{2}}$. The cows do not move. You have to minimize the number of moves the shepherd needs to run round the whole herd.
You were asked to make all the cows strictly inside the interior of the route. Initially I planned to put "non-strict" there, but later I abandoned this idea because the answer for single point was really weird then=) The difference in solution is quite small. The answer for "strict" problem is always more than for "non-strict" by exactly 4. Some coders preferred to add four neighboring points for each point like a cross to switch to solving non-strict problem. The non-strict problem is solved in the following way. Notice that the required route can always be searched as an octagon, perhaps with some zero sides. Take four pairs of parallel lines and "press" it to the points. In other words, we find axis-aligned bounding box for the set of points. Then find axis-aligned bounding box of the point set on the picture which is rotated by 45 degrees. Now intersect these two boxes (as filled figures). We get an octagon in the common case, which is the required one. To implement the solution, we have to calculate minimums and maximums of X, Y, X+Y, X-Y through all the points, then use non-trivial formulas to get the answer. A lot of contestants solved the problem in other way. It is easy to see that to move by vector (X, Y) shepherd needs to make max(|X|, |Y|) turns. We can make the shepherd walk along the vertices of convex hull. We need to run a standard Graham scan and then iterate through all the points on the hull and sum max(|X'-X|, |Y'-Y|) for all pairs of neighboring vertices in it. This solution is also correct. There was an idea to make limit on coordinates equal to 109, but we decided that there was no need to ask for int64 again. Perhaps it'd have been better if there'd been int64 in this problem instead of problem B.
[ "geometry" ]
2,000
null
50
D
Bombing
The commanding officers decided to drop a nuclear bomb on the enemy's forces. You are ordered to determine the power of the warhead that needs to be used. The enemy has $N$ strategically important objects. Their positions are known due to the intelligence service. The aim of the strike is to deactivate at least $K$ important objects of the enemy. The bombing impact point is already determined and has coordinates of $[X_{0}; Y_{0}]$. The nuclear warhead is marked by the estimated impact radius $R ≥ 0$. All the buildings that are located closer than $R$ to the bombing epicentre will be destroyed. All the buildings that are located further than $R$ from the epicentre, can also be deactivated with some degree of probability. Let's assume that $D$ is the distance between a building and the epicentre. This building's deactivation probability $P(D, R)$ is calculated according to the following formula: \[ P(D,R)=\left\{_{\mathrm{exp}}\left(1-{\frac{D^{2}}{R^{2}}}\right)\begin{array}{c}{{;}}\end{array}\right.\stackrel{\ldots}{D\le R} \] We should regard $\exp(a)$ as $e^{a}$, where $e ≈ 2.7182818284590452353602874713527$If the estimated impact radius of the warhead is equal to zero, then all the buildings located in the impact point will be completely demolished and all the rest of important objects will not be damaged. The commanding officers want the probability of failing the task to be no more than $ε$. Nuclear warheads are too expensive a luxury, that's why you have to minimise the estimated impact radius of the warhead.
The problem statement looks intricate and aggressive. That's because the problem legend originates from civil defense classes in the university. Civil defense is such a discipline which for example teaches how to behave before and after nuclear attack... First of all we should notice that the bigger the warhead, the better (I mean the probability to succeed is higher). This seems quite reasonable. Function P(D, R) increases as R increases with fixed D. Obviously the probability to hit at least K objects increases in this case too. Hence we can find the answer by binary search. We have to be able to find the probability to accomplish the mission with fixed and known radius R to perform binary search. Now we have to solve the problem: there are N objects, each of them is destroyed with given probability (pi). Find the probability to destroy at least K of them. The problem is solved by dynamic programming which is similar to calculating binomial coefficients using Pascal's triangle. Let R[i, j] be the probability to hit exactly j objects among the first i of all the given ones. If we find all the R values for 0<=j<=i<=N, then the answer is calculated as sum_{j=k..N} R[N, j]. The base of DP is: R[0, 0] = 1. Induction (calculating the new values) is given by the formula R[i, j] = R[i-1, j-1] * pi + R[i-1, j] * (1-pi). Keep in mind that for j<0 or j>i all the elements of R are zeroes. It was shown experimentally that many coders (me included) try to solve the problem by taking into account only the closest K targets. I.e. they think that the probability to succeed is simply p1 * p2 *... * pK. This is wrong: for example, if two buildings with equal distance are given, then the probability to hit at least one of them is 1-(1-p)2 instead of p. But I decided to please these coders and composed the pretests only of the cases on which this solution passes=) So this particular incorrect solution was passing all the pretests intentionally.
[ "binary search", "dp", "probabilities" ]
2,100
null
50
E
Square Equation Roots
A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: \[ x^{2} + 2bx + c = 0 \] where $b$, $c$ are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root. Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers $b$ and $c$ such that $1 ≤ b ≤ n$, $1 ≤ c ≤ m$. Help Petya find that number.
Let D = b2-c be quarter of discriminant. The equation roots are -b-sqrt(D) and -b+sqrt(D). Thus there are two types of roots: irrational ones like x +- sqrt(y) and integer ones. We count the number of different roots separately for these types. Irrational roots are in form x+sqrt(y) (y is not square of integer). If two numbers in this form are equal, then their x and y values are also equal. It can be checked on the piece of paper. The main idea is to use irrationality of sqrt(y). Thus if two irrational roots are equal, then the equations are the same. Hence all the irrational roots of all the given equations are different. Let's iterate b=1..N. For each of b values we have to find the number of equations with positive discriminant which are not squares on integers. I.e. number of c=1...M with D = b2-c is not square of integer. We can calculate set of all possible values of D as a segment [L; R] (L >= 0). Then take its size (R-L+1) and subtract number of squares in it. It is exactly the the number of equations with irrational roots for a fixed b. Multiply it by 2 (two roots per equation) and add it to the answer. Now let's handle integer roots. For a fixed b we've calculated the segment [L;R] of all D values. Then sqrt(D) takes integer values in segment [l; r] = [ceil(sqrt(L)); floor(sqrt(R))]. We put this segment into the formula for equation roots and understand that all the integer roots of equations with fixed b compose segments [-b-r;-b-l] and [-b+l;-b+r]. However the integer roots may substantially be equal for different equations. That's why we have to mark in a global data structure that all the roots in these two segments are "found". After we iterate through all b=1..N, we have to find number of integers marked at least once in this data structure. This data structure is implemented on array. All the integer roots of equations lie in bounds from -10000000 to 0. Allocate an array Q which is a bit larger in size. To mark segment [s; t] we increment Q[s] by one and decrement Q[t+1] by one. At the end of the solution iterate through the whole array Q from left to right and calculate prefix sums to array S. I.e. S[i] = Q[-10000010] + Q[-10000009] + ... + Q[i-1] + Q[i]. Then S[i] represents number of times we've marked number i. Now iterate through S array and count number of nonzero elements. It is the number of different integer roots. The solution requires O(N) time since we have to iterate through all b values. It is likely that purely combinatoric (O(1)) formula for answer exists=)
[ "math" ]
2,300
null
53
A
Autocomplete
Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of $n$ last visited by the user pages and the inputted part $s$ are known. Your task is to complete $s$ to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix $s$.
In this problem you should read the statement and solve in any way. One of the most simple solutions is read string and last visited pages, sort (even bubble source - 1003 isn't a lot, 3rd power because we need 100 operations to compare two strings), and rundown pages. When we find good string, we should write it and exit. If there are no such one, write source string. 'Goodness' of string is checking with one if (to check lengths and avoid RTE) and for.
[ "implementation" ]
1,100
null
53
B
Blog Photo
One popular blog site edits the uploaded photos like this. It cuts a rectangular area out of them so that the ratio of height to width (i.e. the $height / width$ quotient) can vary from 0.8 to 1.25 inclusively. Besides, at least one side of the cut area should have a size, equal to some power of number 2 ($2^{x}$ for some integer $x$). If those rules don't indicate the size of the cut are clearly, then the way with which the cut part possesses the largest area is chosen. Of course, both sides of the cut area should be integer. If there are several answers to this problem, you should choose the answer with the maximal height.
The first thing we need to do is fix one side (which are power of two). Because there are two sides and copy-paste is great place for bugs it'll be better to make one more for from 1 to 2 and on the 2nd step swap w and h. It decreases amount of code. Now we know that h=2x. We need to find such w, that 0.8 <= h/w <= 1.25. Solve inequalities for w: h/1.25 <= w <= h/0.8. Because w is integer, it can take any value from ceil(h/1.25) to floor(h/0.8) inclusive. We need to maximize square and h is fixed, so our target is maximize w. We need to let w=floor(h/0.8) and check that it fit borders. If so - relax the answer. It's O(log2 h) solution. Possible bugs are: You calculate square in 32-bit type or like this: int w = ..., h = ...; long long s = w * h; In this case compiler calculate w * h in 32-bit type first, and then convert it to long long. Solution is long long s = (long long)w * h floor(0.9999999999)=0. The floor function does not correspond with inaccuracy of floating point types. It can be solved either with adding something eps to number before calling floor, or with additional check that difference between floor's result and source value is not greater than 1 - eps. p.s. The floor function is up to 8-9 times slower that conversion to int.
[ "binary search", "implementation" ]
1,700
null
53
C
Little Frog
Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are $n$ mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him.
IMHO it's the second difficulty problem. If you cannot see solution just after you saw the statement, you can write brute-force solution (rundown all permutation and check), run it for n=10 and see beautiful answer. Answer is 1 n 2 (n-1) 3 (n-2) 4 (n-3) ... Let's define two pointers - l and r. In the beginning, the first one will point to 1, and the second one - to n. On odd positions write down l (and increase it), on even - r (and decrease it). Do it while l <= r. Proof is rather easy: every jump is shorter than the previous one.
[ "constructive algorithms" ]
1,200
null
53
D
Physical Education
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is the height of the $i$-th student in the line and $n$ is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: $b_{1}, b_{2}, ..., b_{n}$, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: $a_{1}, a_{2}, ..., a_{n}$. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
This problem is also very easy. The first thing we should learn is moving element from position x to position y (y < x). Let's move x to position x - 1 with one oblivious swap. Then to position x -2. And so on. Now we want to make a1=b1. Find in b element, that equals a1 and move it to the first position. Similarly we can make a2=b2. So, we have n steps and at every step we do n - 1 swaps at the most. n<=300, so n(n-1)<=89700<106.
[ "sortings" ]
1,500
null
53
E
Dead Ends
Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are $n$ junctions and $m$ two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to $n - 1$ roads and it were still possible to get from each junction to any other one. Besides, the mayor is concerned with the number of dead ends which are the junctions from which only one road goes. There shouldn't be too many or too few junctions. Having discussed the problem, the mayor and his assistants decided that after the roads are closed, the road map should contain exactly $k$ dead ends. Your task is to count the number of different ways of closing the roads at which the following conditions are met: - There are exactly $n - 1$ roads left. - It is possible to get from each junction to any other one. - There are exactly $k$ dead ends on the resulting map. Two ways are considered different if there is a road that is closed in the first way, and is open in the second one.
The first thing you should notice - - n <= 10. It means, that we have exponential solution and we can rundown some subsets. Solution is dynamic programming d[m][subm] - number of ways to make connected tree from subgraph m (it's a bit mask) with dead ends subm (it's also a bit mask). Answer is sum of d[2n-1][x], where |x|=k (size of x as a subset is k). Recalculating isn't really hard. For empty subset and subset of two vertexes (either 0 or 1) answer is oblivious. Also you should know that there is no tree with exactly one dead end (it's easy to prove). Now for greater subsets: rundown i from subm - one of dead ends. Cut it off from tree along some edge to b (b shouldn't be a dead end, otherwise we got unconnected graph). Now we have tree with lower count of vertexes and either decreased 1 number of dead ends or with changed i to b (if b had exactly two neighbors). Answer for this tree we know already. In the end of summarizing we should divide answer by k - each tree has been taken as many times, as it has dead ends (k).
[ "bitmasks", "dp" ]
2,500
null
54
C
First Digit Law
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law). Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are $N$ random variables, the $i$-th of which can take any integer value from some segment $[L_{i};R_{i}]$ (all numbers from this segment are equiprobable). It means that the value of the $i$-th quantity can be equal to any integer number from a given interval $[L_{i};R_{i}]$ with probability $1 / (R_{i} - L_{i} + 1)$. The Hedgehog wants to know the probability of the event that the first digits of at least $K%$ of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD — most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least $K$ per cent of those $N$ values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.
Solution for this problem consists of two stages. First stage - counting the numbers with 1 as their first digit in the $[L;R]$ segment. Second stage - using this information (in fact, by given probabilities that $i$-th quantity will be good) solve the problem about $K$ percents. To solve the first sub-problem one can generate all segments of good numbers and look how many numbers from them lie in the $[L;R]$ segment. Segments of good numbers are of form $[1;1]$, $[10;19]$, $[100;199]$ and so on, that is, $[10^{i};2 \cdot 10^{i} - 1]$. After noticing that, calculating their intersection with $[L;R]$ segment is quite easy. So, we've learnt how to calculate the probability $p[i]$ that $i$-th quantity is correct: this probability $p[i]$ equals to a fraction of the number of good numbers and $R[i] - L[i] + 1$. Now we can go to the second stage of the solution: solving the problem with $N$ quantities and $K$ percents. Now we know the probabilities $p[i]$ that this or that quantity is good, and want to find the probability that $K$ percents of them will be good. This can be done using dynamic programming: let's $D[i][j]$ - probability that among first $i$ quantities exactly $j$ will be good. The starting state is $D[0][0] = 1$, and calculation of other states can be done as following: $D[i][j] = p[i - 1] \cdot D[i - 1][j - 1] + (1 - p[i - 1]) \cdot D[i - 1][j].$ After that answer to the problem will be a sum of $D[n][j]$ over all $j$ such, that $j / n \ge k / 100$.
[ "dp", "math", "probabilities" ]
2,000
null
54
D
Writing a Song
One of the Hedgehog and his friend's favorite entertainments is to take some sentence or a song and replace half of the words (sometimes even all of them) with each other's names. The friend's birthday is approaching and the Hedgehog decided to make a special present to his friend: a very long song, where his name will be repeated many times. But try as he might, he can't write a decent song! The problem is that the Hedgehog has already decided how long the resulting sentence should be (i.e. how many letters it should contain) and in which positions in the sentence the friend's name should occur, and it must not occur in any other position in the sentence. Besides, the Hedgehog decided to limit himself to using only the first $K$ letters of an English alphabet in this sentence (so it will be not even a sentence, but one long word). The resulting problem is indeed quite complicated, that's why the Hedgehog asks you to help him and write a program that will make the desired word by the given name $P$, the length $N$ of the required word, the given positions of the occurrences of the name $P$ in the desired word and the alphabet's size $K$. Note that the occurrences of the name can overlap with each other.
I'll describe here an author's solution for this problem. The solution is by a method of dynamic programming: the state is a pair $(pos, pref)$, where $pos$ - the position in the string built (it is between $0$ and $n$), and $pref$ - the current prefix of pattern $P$ (i.e. this is a number between $0$ and $length(P)$). The value $pref$ will help us to control all occurences of pattern $P$: if $pref = length(P)$ then it means that here is an ending of occurence of pattern $P$ (the beginning of the occurence was at $pos - length(P)$). The value $D[pos][pref]$ of the dynamic is $true$, if the state is reachable. We start from the state $(0, 0)$ and want to get to any state with $pos = n$. How to make moves in the dynamic? We iterate over all possible characters $C$ and try to add it to the current answer. That's why we get into a stage $(pos + 1, newpref)$, where $newpref$ is a new length of prefix of $P$. The problem constraints permitted to calculate this value $newpref$ easily, i.e. just by searching for substrings of form $P[length(P) - oldpref..length(P)] + C$ in the pattern $P$. For example, if $P = ab$ and $pref = 1$, then with the character $C = a$ we will get into $newpref = 1$ (because we added character $a$ to the string $a$, - we got string $aa$, but its longest suffix matching with the prefix of string $P$ equals to $a$). If we took $C = b$ then we would get into state $newpref = 2$. Any other character would move us into the state with $newprefix = 0$. But in reality, of course, an algorithm for calculating prefix-function can be guessed here. Really, in fact, we answer the following query: "we had some prefix of pattern $P$ and added character $C$ by its end - so what will be the new prefix?". These queries are answered exactly by prefix-function algorithm. Moreover, we can pre-calculate answers to all of these queries in some table and get answers for them in $O(1)$ from the table. This is called an automaton built over the prefix-function. One way or another, if we've taught how to calculate $newpref$, then everything is quite simple: we know how to make movements in dynamics from one state to another. After getting the solution we'll have just to restore the answer-string itself. The solution's asymptotics depends on the way we chose to calculate $newpref$. The fastest way is using the prefix-function automaton, and the asymptotics in this case is $O(kn^{2})$. But, I remind, the problem's constraints allowed to choose some simpler way with worse asymptotics. P.S. This problem was additionally interesting by the fact that one can invent many strange simple solutions, which are very difficult to prove (and most of them will have counter-examples, but very rare ones). Some of these tricky solutions passed all systests in the round. I have also created one relatively simple solution that looks rather unlike to be right, but we didn't manage to create counter-example even after several hours of stress :)
[ "brute force", "dp", "strings" ]
2,100
null
54
E
Vacuum Сleaner
One winter evening the Hedgehog was relaxing at home in his cozy armchair and clicking through the TV channels. Stumbled on an issue of «TopShop», the Hedgehog was about to change the channel when all of a sudden he was stopped by an advertisement of a new wondrous invention. Actually, a vacuum cleaner was advertised there. It was called Marvellous Vacuum and it doesn't even need a human to operate it while it cleans! The vacuum cleaner can move around the flat on its own: it moves in some direction and if it hits an obstacle there, it automatically chooses a new direction. Sooner or later this vacuum cleaner will travel through all the room and clean it all. Having remembered how much time the Hedgehog spends every time on cleaning (surely, no less than a half of the day), he got eager to buy this wonder. However, the Hedgehog quickly understood that the cleaner has at least one weak point: it won't clean well in the room's corners because it often won't able to reach the corner due to its shape. To estimate how serious is this drawback in practice, the Hedgehog asked you to write for him the corresponding program. You will be given the cleaner's shape in the top view. We will consider only the cases when the vacuum cleaner is represented as a convex polygon. The room is some infinitely large rectangle. We consider one corner of this room and want to find such a rotation of the vacuum cleaner so that it, being pushed into this corner, will leave the minimum possible area in the corner uncovered.
The most important step on the way to solve this problem - is to understand that it's enough to consider only such rotations of the polygon, that one of its sides lies on the side of the room. Let's try to understand this fact. Suppose that the fact is wrong, and there exists such a position of vacuum cleaner, that neither of its sides lies on the side of the room. Denote as $i$ and $j$ the numbers of vertices that lie on the room sides. It's easy to understand that the polygon form between vertices $i$ and $j$ doesn't make any sense itself: for each rotation we can see that from the area of triangle $OP[i]P[j]$ some constant area is subtracted, while the concrete value of this constant depends on the polygon form. That's why we see that the polygon form doesn't influence on anything (if we have fixed numbers $i$ and $j$), and we have just to minimize the area of right-angled triangle $OP[i]P[j]$. But, taking into account that its hypotenuse is a constant, it's easy to see that the minimum is reached in borderline cases: i.e. when one of the polygon sides lies on the room side. So, we've proved the fact. Then we have to invent fast enough solution. We have already obtained an $O(n^{2})$ solution: iterate over all sides of the polygon (i.e. iterating over all possible $i$), mentally push it to one side of the room, then find the threshold point $j$, then calculate answer for given $i$ and $j$. Let's learn how to do these both things in $O(1)$. In order to do the first thing (finding $j$) we can use a method of moving pointer: if we iterate over $i$ in the same order as in the input file, then we can just maintain the right value of $j$ (i.e. when we move from $i$ to $i + 1$ we have to increase $j$ several times, while it is getting further and further). In order to do the second thing (the area calculation) we have to do some precalculation. For example, we can find the mass center $Q$ of the vacuum cleaner, and pre-calculate all partial sums $S[i]$ - sums of all triangles $QP[j - 1]P[j]$ for all $j \le i$. After this precalculation we can get the answer for every $i$ and $j$ in $O(1)$ as a combination of difference of two values from $S[]$ and two triangles' areas: $QP[i]P[j]$ and $OP[i]P[j]$.
[ "geometry" ]
2,700
null
55
A
Flea travel
A flea is sitting at one of the $n$ hassocks, arranged in a circle, at the moment. After minute number $k$ the flea jumps through $k - 1$ hassoсks (clockwise). For example, after the first minute the flea jumps to the neighboring hassock. You should answer: will the flea visit all the hassocks or not. We assume that flea has infinitely much time for this jumping.
This problem is solved by simple emulation. After $2n$ jumps flea returns to initial position, because $1 + 2 + 3 + ... + 2n = n(2n + 1)$ is divisible by n. Moreover, after that, jumps would be the same as in the beginning, because $2n$ is divisible by $n$. So it is just enough to emulate first $2n$ jumps.In fact one may see that it is enough to emulate first $n$ jumps and moreover answer is "YES" exactly when $n$ is power of two. Last gives alternative solution. For example: printf("%s", n&(n-1) : "NO" ? "YES");
[ "implementation", "math" ]
1,200
null
55
B
Smallest number
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers $a$, $b$, $c$, $d$ on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them with their sum or their product. In the end he got one number. Unfortunately, due to the awful memory he forgot that number, but he remembers four original numbers, sequence of the operations and his surprise because of the very small result. Help Vladimir remember the forgotten number: find the smallest number that can be obtained from the original numbers by the given sequence of operations.
One just needs to calculate all possible answers and find the minimum. For example one may run on a set of numbers, for all pairs of numbers apply next operation to that pair and recursively run on a new set of numbers. When only one number remains, compare it to the already obtained minimum, and change that minimum if it's needed.
[ "brute force" ]
1,600
null
55
C
Pie or die
Volodya and Vlad play the following game. There are $k$ pies at the cells of $n × m$ board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.
Vladimir wins exactly when there is a pie with distance to the border not greater than 4. Indeed if there is such a pie, then Vladimir will move it to the border and then move it around the whole rim. Of course if there would be any chance to throw this pie from the board, Vladimir will use it. If he gets no such chance, then after mentioned moves all border is banned. But it means Vlad made at least $2n + 2m$ turns, when Vladimir only $2n + 2m - 1$ as a maximum. A contradiction. Else, if there is no such pie, then during first 4 turns Vlad would ban sides adjacent to each corner of the board. After that, if some pie comes to the rim he would ban adjacent side (there is no more than one such side) ans so Vladimir will never get the pie. So solution consists of only one distance check, but, as one may see, it is easy to make mistake.
[ "games" ]
1,900
null
55
D
Beautiful numbers
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
In this problem one should answer the query: how many beautiful numbers are there in the interval from 1 to R. Clearly, to check whether a number is divisible by all its digits, it is sufficient to know the remainder of a division by the lcm of all possible digits (call this lcm M), that is M = 8 * 9 * 5 * 7 = 2520. The standart dynamic solution is supposed to maintain such state parameters: the length of the number, "strictly less" flag, current remainder of a division by M and the mask of already taken digits. The first note: we can maitnain the lcm of the digits already taken, not the mask. This will decrease the number of different values of the last parameter (from 256 to 4 * 3 * 2 * 2 = 48, where 4 is the number of different powers of 2 etc). Then, it is a good idea to pre-count transitions to the new parameters. But we wanted and tried to set such a time limit restriction, so that this solution would not be enough to avoid TL. The idea that will decrease the running time even more lies in number theory. If we add digits from the end of a number we may see that the remainder of a number after division by 5 depends only on the last digit. Therefore, we may maintain the flag "last digit = 5 or 0" and ban transitions to the digit 5 if the flag is set to "false". Such an idea reduces the number of states by 5 * 2 / 2 = 5. This solution is fast enough to pass in any language, though there are even more powerful optimizations (the trick mentioned above can be done with digit 2 also).
[ "dp", "number theory" ]
2,500
null
55
E
Very simple problem
You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon.
Let us solve this problem for every point P independently. We will show how to do this in linear time, that is, O(N). It seems that the most easy way to do this is to count the number of triangles not containing P (call them good), and then subtract this value from the total number of triangles. Consider triples of vertices A, B, C that form a triangle, such that: P doesn't lie in ABC; AB separates P and C in the polygon; P lies in the polygon to the right from AB (clockwise). Note, that every good triangle provides us one such triple and each triple forms a good triangle. Thus, we may consider such triples instead of good triangles. Let's consider an arbitrary vertex of the polygon. We want it to become an A-vertex in some triple. Then we can obtain the set of vertices, suitable for B-vertex in a triple moving diagonals from A (clockwise) until we reach P. Then for the fixed A the number of triples is equal to the sum of the number of triples for this A and the fixed B, which is equal to the sum of some linear series (as all suitable C lie between A and B and their number is equal to the vertex-distance between A and B minus one). The only thing left to do is to find the last B (last until P is reached) for each vertex of the polygon. And this is a simple exercise on the two pointers technique.
[ "geometry", "two pointers" ]
2,500
null
57
A
Square Earth?
Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side $n$. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: $(0, 0)$, $(n, 0)$, $(0, n)$ and $(n, n)$.
Since the restrictions were not so big you can offer many different solutions. For example, you can construct a graph with N * 4 vertices and use bfs. But there was a faster solution with complexity O(1): enumerate the integer points lying on the square, for example, as is shown below: Then finding the number of a point by its coordinates isn't difficult. For example if a point has coordinate y == n -> then its position is n + x (if the numeration, is as shown, i.e. starts with zero). It turns out that we have transformed the square into a line with a small complication: cells N * 4 - 1 and 0 are adjacent, so we have not a line but a circle, where for the base points from 0 to 4 * N-1 the distance between the adjacent two points is 1. It is easy to take the difference of indices of the points and find the distance when moving clockwise and counterclockwise: (a-b +4 * n)% (4 * n) and (b - a + 4 * n)% (4 * n), the shortest distance will be the answer.
[ "dfs and similar", "greedy", "implementation" ]
1,300
null
57
B
Martian Architecture
Chris the Rabbit found the traces of an ancient Martian civilization. The brave astronomer managed to see through a small telescope an architecture masterpiece — "A Road to the Sun". The building stands on cubical stones of the same size. The foundation divides the entire "road" into cells, into which the cubical stones are fit tightly. Thus, to any cell of the foundation a coordinate can be assigned. To become the leader of the tribe, a Martian should build a Road to the Sun, that is to build from those cubical stones on a given foundation a stairway. The stairway should be described by the number of stones in the initial coordinate and the coordinates of the stairway's beginning and end. Each following cell in the coordinate's increasing order should contain one cubical stone more than the previous one. At that if the cell has already got stones, they do not count in this building process, the stairways were simply built on them. In other words, let us assume that a stairway is built with the initial coordinate of $l$, the final coordinate of $r$ and the number of stones in the initial coordinate $x$. That means that $x$ stones \textbf{will be added} in the cell $l$, $x + 1$ stones will be added in the cell $l + 1$, ..., $x + r - l$ stones will be added in the cell $r$. Chris managed to find an ancient manuscript, containing the descriptions of all the stairways. Now he wants to compare the data to be sure that he has really found "A Road to the Sun". For that he chose some road cells and counted the total number of cubical stones that has been accumulated throughout the Martian history and then asked you to count using the manuscript to what the sum should ideally total.
Under the restrictions on the number of requests, you cannot iteratively add staircase. But the problem is simplified by the fact that the number of cells in which it was necessary to know the number of stones was no more than 100. That's why you can check for each "interesting" cell all the queries and calculate how much each of them adds stones, so the complexity is: O (K * M), which fits within the given 2 seconds well. A faster solution with complexity O(N + M + K) is as follows: we will keep in mind two variables: a - how many items should be added now to the cell, v - how much should change a next step. So problem is to update the value of a and v so that a equaled to the number of stones in the cell after all the operations, and v - to how much a increases during the transition to the next cell. Then the problem will be reduced to that you need to properly update a and v, which is not very difficult to do, for example if there is a request (x, y, z) - then in the cell x you need to add x to a and add 1 to v, since with each next cell the number of stones for some staircase will increase by 1. Similarly, after the cell y is passed you need to subtract 1 from v and pick up from "a" the current number of stones subquery. If you save all such pairs of queries in a single array and it's possible to calculate everything in one cycle.
[ "implementation" ]
1,600
null
57
C
Array
Chris the Rabbit has been interested in arrays ever since he was a child. At the moment he is researching arrays with the length of $n$, containing only integers from $1$ to $n$. He is not good at math, that's why some simple things drive him crazy. For example, yesterday he grew keen on counting how many different beautiful arrays there are. Chris thinks that an array is beautiful if it meets one of the two conditions: - each elements, starting from the second one, is no more than the preceding one - each element, starting from the second one, is no less than the preceding one Having got absolutely mad at himself and at math, Chris came to Stewie and Brian to ask them for help. However, they only laughed at him and said that the answer is too simple and not interesting. Help Chris the Rabbit to find the answer at last.
First, let's count how many there are arrays in which each successive element starting from the second one is no less than the previous one. To do this quickly, let's take a piece of squared with height of one square and the length of N*2 - 1 square, then select N-1 squares and put crosses in them - let it encode some array, let the number of blank cells from the beginning of the array before the first cross be equal to the number of ones in the array, the number of blank cells from the first cross to the second - to the number of 2 in the array, and so on. It is easy to see that the number of empty cells will be equal to N * 2-1 - (N-1) = N. It turns out that each paper encodes an array which suits us, and moreover all the possible arrays can be encoded using such paper. There is exactly C (N * 2-1, N) different pieces of paper (the binomial coefficient of N * 2-1 to N). This number can be calculated by formula with factorials, the only difficulty is division. Since the module was prime - it was possible to calculate the inverse number in the field for the module and replace division by multiplication. So we get the number of non-decreasing sequences, respectively have the same number of non-increasing, we just need to take away those who were represented in both array sets, but they are just arrays with a similar number like {1,1,1,...,1} or {4,4,...,4,4} just subtract n.
[ "combinatorics", "math" ]
1,900
null
57
D
Journey
Stewie the Rabbit explores a new parallel universe. This two dimensional universe has the shape of a rectangular grid, containing $n$ lines and $m$ columns. The universe is very small: one cell of the grid can only contain one particle. Each particle in this universe is either static or dynamic. Each static particle always remains in one and the same position. Due to unintelligible gravitation laws no two static particles in the parallel universe can be present in one column or row, and they also can't be present in the diagonally \textbf{adjacent} cells. A dynamic particle appears in a random empty cell, randomly chooses the destination cell (destination cell may coincide with the start cell, see the samples) and moves there along the shortest path through the cells, unoccupied by the static particles. All empty cells have the same probability of being selected as the beginning or end of the path. Having reached the destination cell, the particle disappears. Only one dynamic particle can exist at one moment of time. This particle can move from a cell to a cell if they have an adjacent side, and this transition takes exactly one galactic second. Stewie got interested in what is the average lifespan of one particle in the given universe.
Let's see, if there is no occupied cells, then it is not difficult to calculate the answer - the answer is a sum of Manhattan distances, taking into account the fact that the Manhattan distance can be divided: first we can calculate the distance of one coordinate and then of another one and then just to sum up, so the answer is not difficult to find. What do we have when there are occupied cells? If the cell from which we seek the distance does not lie on the same horizontal or vertical with occupied cells - then it absolutely does not affect the difficulty of accessing the rest of the cells: This happens due to the fact that in each cell from the previous distance front (the distance to the set of cells with maximum distance from the start cell, the fronts form a diamond as you can see in the picture or from the Manhattan distance formula) there are two ways how to get to the cell, we take into account the rule that no two cells can be adjacent (either diagonally or vertically or horizontally), it turns out that such a cell does not interfere with us. But a close look at the picture brings to mind the obvious: it is the cell which is located on the same vertical / horizontal that has only one neighbor from the previous front, let's see what happens in such case: All the cells after occupied one starts "to lag" at 2 in distance, but more importantly, that changed the front! Now (with the upper side of the front) are 2 cells for which the transition from the previous front is unique, and as a consequence there are two cells meeting of which will produce a new segment of a late cells, and the angle of the front will change again. Since we are only interested in one side of its expansion (on the other hand there can not be occupied cells by the condition) so we can assume that it was expand from the start cell: It turns out that you can count how many cells will be "delayed", especially considering that the lag always equals to two. For each direction, you can choose each occupied cell and check in the left and right directions for adjacent cells series, and add delay for interval of free cell before occupied cell (in the current direction). It is possible to calculate such delays with complexity: square of the number of occupied cells (it is not greater than min(N, M)). The rest is details. You need to compute all Manhattan distances, taking into account the existence of occupied cells. To do this, first calculate the sum of distances for an empty field, then for each occupied cell calculate the distance to all the others - subtract it twice, as the extra distance is subtracted for the first time when we got out of this cell and for the second time when takes away from all other cells to the given one. But in this case we will take away twice the distance between two occupied cells - so we'll have to add them (the complexity is also a square). A total complexity of solution is O (K ^ 2) where K is the number of occupied cells.
[ "dp", "math" ]
2,500
null
57
E
Chess
Brian the Rabbit adores chess. Not long ago he argued with Stewie the Rabbit that a knight is better than a king. To prove his point he tries to show that the knight is very fast but Stewie doesn't accept statements without evidence. He constructed an infinite chessboard for Brian, where he deleted several squares to add some more interest to the game. Brian only needs to count how many different board squares a knight standing on a square with coordinates of $(0, 0)$ can reach in no more than $k$ moves. Naturally, it is forbidden to move to the deleted squares. Brian doesn't very much like exact sciences himself and is not acquainted with programming, that's why he will hardly be able to get ahead of Stewie who has already started solving the problem. Help Brian to solve the problem faster than Stewie.
The task turned out to be very difficult as it was planned. First remove all the deleted cells - let's see how changes the number of accessible cells with the increase of the new moves. First, the changes do not appear stable, but at some point we see a figure which won't to change the form anymore and will only expand, it is obvious that the figure is two-dimensional, therefore the growth of its "area" is a quadratic function, in fact, a simple check shows that with each new turn the number of cells increases by the number of new cells opened with previous turn + 28, so after a certain point, you can simply take the sum of an arithmetic progression. The case with the deleted cells is similar. In general, there are several possible options - either occupied cells block further penetration of the horse or not, in the first case bfs is simply enough to find solutions, in the second one the story is the same: over time, when the figure "becomes balanced", the number of new opened cells satisfies the same rule "prev +28" . Moreover, because of restrictions of the coordinates of the deleted cells (-10 <= x, y <= 10) this happens fairly quickly. So, use usual bfs to balance figures, and after this use the sum of the arithmetic progression.
[ "math", "shortest paths" ]
3,000
null
59
A
Word
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
This was an extremely simple problem. Simply count the number of upper case latin letters. If that is strictly greater than number of lower case letters convert the word to upper case other wise convert it to lower case. Complexity: O(wordlength)
[ "implementation", "strings" ]
800
null
59
B
Fortune Telling
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces alternatively "Loves" and "Doesn't love", at that Marina always starts with "Loves". There are $n$ camomiles growing in the field, possessing the numbers of petals equal to $a_{1}, a_{2}, ... a_{n}$. Marina wants to pick a bouquet with the maximal possible total number of petals so that the result would still be "Loves". Help her do that; find the maximal number of petals possible in the bouquet.
For this problem all you need to do is store the smallest odd number of petals and also the sum of all the petals. It is quite obvious that only if the number of petals is odd the result would be "Loves". So if the sum is even print sum - smallest odd, otherwise print the sum. Complexity: O(n).
[ "implementation", "number theory" ]
1,200
null
59
C
Title
Vasya has recently finished writing a book. Now he faces the problem of giving it the title. Vasya wants the title to be vague and mysterious for his book to be noticeable among others. That's why the title should be represented by a single word containing at least once each of the first $k$ Latin letters and not containing any other ones. Also, the title should be a palindrome, that is it should be read similarly from the left to the right and from the right to the left. Vasya has already composed the approximate variant of the title. You are given the title template $s$ consisting of lowercase Latin letters and question marks. Your task is to replace all the question marks by lowercase Latin letters so that the resulting word satisfies the requirements, described above. Each question mark should be replaced by exactly one letter, it is not allowed to delete characters or add new ones to the template. If there are several suitable titles, choose the first in the alphabetical order, for Vasya's book to appear as early as possible in all the catalogues.
This was a very nice problem. My approach was to first flag all the letters which have already appeared. Notice, that we have to output the lexicographically smallest palindrome. So, start from the middle of the letter and iterate one side... If you get a '?' stop and check if the corresponding position on the other side also has a '?'. If yes, then fill both with the lexicographically biggest letter which hasn't appeared yet in the word and also flag that letter. Once you have exhausted all the letters and there are still '?' left then simply fill them with 'a'. Now simply iterate over the word again and see if there are any question marks left, if yes copy the values in the corresponding block on the other side. At the same time check if at any time the two opposite values match or not. If they do throughout then it is a valid plaindrome which is also the lexicographically smallest palindrome. Complexity: O(wordlength + k)
[ "expression parsing" ]
1,600
#include <stdio.h> #include <string.h> int main() { int a[27], k, i, j, len, count = 0, first; char t[110]; scanf(" %d %s", &k, t); for(i = 0; i < k; i ++) a[i] = 0; len = strlen(t); for(i = 0; i < len; i ++) { if(t[i] == '?') count ++; else a[t[i] - 'a'] ++; } for(i = 0; i < k; i ++) if(a[i] == 0) { first = i; break; } j = k - 1; //printf("%d ", a[j]); for(i = len / 2 - (1 - len % 2); i > -1; i --) { if(t[i] == '?') { if(t[len - i - 1] == '?') { while(a[j] != 0 && j > 0) j --; //printf("%d ", j); t[i] = j + 'a'; t[len - i - 1] = j + 'a'; a[j] ++; } else t[i] = t[len - i - 1]; } } for(i = 0; i < len; i ++) { if(t[i] == '?') t[i] = t[len - i - 1]; } for(i = 0; i < len; i ++) { if(t[i] != t[len - i - 1]) { printf("IMPOSSIBLE"); return 0; } } for(i = 0; i < k; i ++) a[i] = 0; for(i = 0; i < len; i ++) a[t[i] - 'a'] ++; for(i = 0; i < k; i ++) if(a[i] == 0) { printf("IMPOSSIBLE"); return 0; } printf("%s", t); return 0; }
59
D
Team Arrangement
Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from $1$ to $3n$, and all the teams possess numbers from $1$ to $n$. The splitting of students into teams is performed in the following manner: while there are people who are not part of a team, a person with the best total score is chosen among them (the captain of a new team), this person chooses for himself two teammates from those who is left according to his list of priorities. The list of every person's priorities is represented as a permutation from \textbf{the rest of} $3n - 1$ students who attend the centre, besides himself. You are given the results of personal training sessions which are a permutation of numbers from $1$ to $3n$, where the $i$-th number is the number of student who has won the $i$-th place. No two students share a place. You are also given the arrangement of the already formed teams in the order in which they has been created. Your task is to determine the list of priorities for the student number $k$. If there are several priority lists, choose the lexicographically minimal one.
This was in my opinion was the toughest problem. However once you get the logic, its pretty obvious. However, it was a slightly challenging implementation for me as the structure of the data to be stored was sort of complex. The basic idea was simply that if we have to find the preference list of a number 'p' then two things might happen: Case 1: p is the most skilled in his team and thus he chose the team. In this case we know that all the members of the teams coming after p's team are less preferred than p's team mates. Let p's team mates be 'm' and 'n' such that m > n. To get the lexicographically smallest preference list, we will divide all the programmers into two lists. The first list will contain all members (ai) from teams which were chosen before p's team such that ai < m. It will also contain m and n. The second list will contain all the left over members. The separation can be done in O(n) time. Now all we need to do is sort the first list, print it, sort the second list, print it! Complexity: O(nlogn)... It can be reduced to O(n) also but the constant will be pretty high and will give almost the same result as O(nlogn). Case 2: p is not the leader of the team. Then you just have to output all number except 'p' from 1 to 3 * n.
[ "constructive algorithms", "greedy", "implementation" ]
2,000
null
60
A
Where Are My Flakes?
One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of $n$ boxes. The boxes stand in one row, they are numbered from $1$ to $n$ from the left to the right. The roommate left hints like "Hidden to the left of the $i$-th box" ("To the left of $i$"), "Hidden to the right of the $i$-th box" ("To the right of $i$"). Such hints mean that there are no flakes in the $i$-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.
Solution - $O(n^{2})$. We take phrase and parse it. Mark all cells, that obviously didn't match - $O(n)$. In the end we go through the array and count all unmarked cells. If 0 - we print "-1", else - amount of unmarked cells.
[ "implementation", "two pointers" ]
1,300
null
60
B
Serial Time!
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped $k × n × m$, that is, it has $k$ layers (the first layer is the upper one), each of which is a rectangle $n × m$ with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square $(x, y)$ of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment. Note: the water fills all the area within reach (see sample 4). Water flows in \textbf{each} of the 6 directions, through faces of $1 × 1 × 1$ cubes.
Solution - $O(k \times n \times m)$. We start BFS from given point. Go from cell to all 6 directions. The answer - number of visited cells.
[ "dfs and similar", "dsu" ]
1,400
null
60
C
Mushroom Strife
Pasha and Akim were making a forest map — the lawns were the graph's vertexes and the roads joining the lawns were its edges. They decided to encode the number of laughy mushrooms on every lawn in the following way: on every edge between two lawns they wrote two numbers, the greatest common divisor (GCD) and the least common multiple (LCM) of the number of mushrooms on these lawns. But one day Pasha and Akim had an argument about the laughy mushrooms and tore the map. Pasha was left with just some part of it, containing only $m$ roads. Your task is to help Pasha — use the map he has to restore the number of mushrooms on every lawn. As the result is not necessarily unique, help Pasha to restore any one or report that such arrangement of mushrooms does not exist. It is guaranteed that the numbers on the roads on the initial map were no less that $1$ and did not exceed $10^{6}$.
Solution - $O(2^{7} \times n^{2})$. We can see, that in connected component - if we know 1 number - then we know all others in component, because in each pare we know minimal and maximal power of each primes. Because number of different primes in one number "$< = 1000000$" is less, than 7, we can look over all possibilities of 1 number in connected compoment - and for each number, that we get, we check, that it suits. How to check? We can notice, that if we know $a$, $(a, b)$, $[a, b]$, then $b={\frac{(a,b]a,b)}{a}}$, start DFS and check.
[ "brute force", "dfs and similar" ]
2,100
null
60
D
Savior
Misha decided to help Pasha and Akim be friends again. He had a cunning plan — to destroy all the laughy mushrooms. He knows that the laughy mushrooms can easily burst when they laugh. Mushrooms grow on the lawns. There are $a[t]$ mushrooms on the $t$-th lawn. Misha knows that the lawns where the mushrooms grow have a unique ability. A lawn (say, $i$) can transfer laugh to other lawn (say, $j$) if there exists an integer (say, $b$) such, that some permutation of numbers $a[i], a[j]$ and $b$ is a beautiful triple ($i ≠ j$). A beautiful triple is such three pairwise coprime numbers $x, y, z$, which satisfy the following condition: $x^{2} + y^{2} = z^{2}$. Misha wants to know on which minimal number of lawns he should laugh for all the laughy mushrooms to burst.
Solution - $O($max numebr$)$. We can notice, that each beautiful triplet has form - $(x^{2} - y^{2}, 2xy, x^{2} + y^{2})$. Now we can gen all such triples. For each triple, we watch - if we have more than 1 number in given set - we union them. How to gen all the triples? $x > y$. $2x y\leq m a x;\Rightarrow y\leq{\sqrt{\frac{m a x}{2}}}$. This means, that $m a x\geq x^{2}-y^{2}\geq x^{2}-{\frac{m a x}{2}}\Rightarrow x\leq{\sqrt{\frac{3m a x}{2}}}$. Now for gen all this triples we an take - $x\leq{\sqrt{\frac{3m a x}{2}}}$ and $y\leq{\sqrt{\frac{m v\pi}{2}}}$. The number of iterations - $\frac{{\sqrt{3}}m n x}{2}$. what means - "union"? We take a data structure named DSU. If two number belong to one beautiful triple - they are connected with edge, in our situation - we can union corresponding to them unions.
[ "brute force", "dsu", "math" ]
2,500
null
60
E
Mushroom Gnomes
Once upon a time in the thicket of the mushroom forest lived mushroom gnomes. They were famous among their neighbors for their magic mushrooms. Their magic nature made it possible that between every two neighboring mushrooms every minute grew another mushroom with the weight equal to the sum of weights of two neighboring ones. The mushroom gnomes loved it when everything was in order, that's why they always planted the mushrooms in one line in the order of their weights' increasing. Well... The gnomes planted the mushrooms and went to eat. After $x$ minutes they returned and saw that new mushrooms had grown up, so that the increasing order had been violated. The gnomes replanted all the mushrooms in the correct order, that is, they sorted the mushrooms in the order of the weights' increasing. And went to eat again (those gnomes were quite big eaters). What total weights modulo $p$ will the mushrooms have in another $y$ minutes?
Solution - $O(n + log(xy))$. We can see, that after one minute the sum changes - it multiply on 3, and substract first and last elements of sequence. Because of that we can count of sum with help of power of matrix. What happens after sorting. First number stay on his place. On the last place - $F_{x}a_{n} + F_{None}a_{None}$. Where $n$ - number of elements, ans $F_{x}$ - $x$ Fibonacci number - with $F_{ - 1} = 0$ and $F_{0} = 1$. This means - that we can count the last number with matrix too. After that we use the first idea. If you have questions - ask them.
[ "math", "matrices" ]
2,600
null
61
A
Ultra-Fast Mathematician
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum $10^{18}$ numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part. In his contest he gave the contestants many different pairs of numbers. Each number is made from digits $0$ or $1$. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The $i$-th digit of the answer is $1$ if and only if the $i$-th digit of the two given numbers differ. In the other case the $i$-th digit of the answer is $0$. Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length $∞$ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length. Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
This was indeed the easiest problem. You just needed to XOR the given sequences. The only common mistake was removing initial 0s which led to "Wrong Answer" Common mistake in hacks which led to "Invalid Input" was forgetting that all lines in input ends with EOLN.
[ "implementation" ]
800
null
61
B
Hard Work
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer! Some days before the contest, the teacher took a very simple-looking exam and all his $n$ students took part in the exam. The teacher gave them $3$ strings and asked them to \underline{concatenate} them. Concatenating strings means to put them in some arbitrary order one after the other. For example from concatenating Alireza and Amir we can get to AlirezaAmir or AmirAlireza depending on the order of concatenation. Unfortunately enough, the teacher forgot to ask students to concatenate their strings in a pre-defined order so each student did it the way he/she liked. Now the teacher knows that Shapur is such a fast-calculating genius boy and asks him to correct the students' papers. Shapur is not good at doing such a time-taking task. He rather likes to finish up with it as soon as possible and take his time to solve 3-SAT in polynomial time. Moreover, the teacher has given some advice that Shapur has to follow. Here's what the teacher said: - As I expect you know, the strings I gave to my students (including you) contained only lowercase and uppercase Persian Mikhi-Script letters. These letters are too much like Latin letters, so to make your task much harder I converted all the initial strings and all of the students' answers to Latin. - As latin alphabet has much less characters than Mikhi-Script, I added three odd-looking characters to the answers, these include "-", ";" and "_". These characters are my own invention of course! And I call them \underline{Signs}. - The length of all initial strings was less than or equal to $100$ and the lengths of my students' answers are less than or equal to $600$ - My son, not all students are genius as you are. It is quite possible that they make minor mistakes changing case of some characters. For example they may write ALiReZaAmIR instead of AlirezaAmir. Don't be picky and ignore these mistakes. - Those signs which I previously talked to you about are not important. You can ignore them, since many students are in the mood for adding extra signs or forgetting about a sign. So something like Iran;;-- is the same as --;IRAN - You should indicate for any of my students if his answer was right or wrong. Do this by writing "WA" for Wrong answer or "ACC" for a correct answer. - I should remind you that none of the strings (initial strings or answers) are empty. - Finally, do these as soon as possible. You have less than $2$ hours to complete this.
In this problem signs can be ignored in both initial and answer strings, so first we remove signs from initial strings. Then we make a list of the six possible concatenations of the 3 initial strings and convert all of them to lowercase.For checking an answer string , we remove the signs , convert it to lowercase and check if it is just one of those 6 concatenations. There were two really nice hack protocols , the first one is: -------__________; _____; ;;;;---------_ 2 ab____ _______;;; Here all concatenations become empty. The second one was putting 0 as number of students :D
[ "strings" ]
1,300
null
61
C
Capture Valerian
It's now $260$ AD. Shapur, being extremely smart, became the King of Persia. He is now called Shapur, His majesty King of kings of Iran and Aniran. Recently the Romans declared war on Persia. They dreamed to occupy Armenia. In the recent war, the Romans were badly defeated. Now their senior army general, Philip is captured by Shapur and Shapur is now going to capture Valerian, the Roman emperor. Being defeated, the cowardly Valerian hid in a room at the top of one of his castles. To capture him, Shapur has to open many doors. Fortunately Valerian was too scared to make impenetrable locks for the doors. Each door has $4$ parts. The first part is an integer number $a$. The second part is either an integer number $b$ or some really odd sign which looks like R. The third one is an integer $c$ and the fourth part is empty! As if it was laid for writing something. Being extremely gifted, after opening the first few doors, Shapur found out the secret behind the locks. $c$ is an integer written in base $a$, to open the door we should write it in base $b$. The only bad news is that this R is some sort of special numbering system that is used only in Roman empire, so opening the doors is not just a piece of cake! Here's an explanation of this really weird number system that even doesn't have zero: Roman numerals are based on seven symbols: a stroke (identified with the letter I) for a unit, a chevron (identified with the letter V) for a five, a cross-stroke (identified with the letter X) for a ten, a C (identified as an abbreviation of Centum) for a hundred, etc.: - I=$1$ - V=$5$ - X=$10$ - L=$50$ - C=$100$ - D=$500$ - M=$1000$ Symbols are iterated to produce multiples of the decimal ($1$, $10$, $100$, $1, 000$) values, with V, L, D substituted for a multiple of five, and the iteration continuing: I $1$, II $2$, III $3$, V $5$, VI $6$, VII $7$, etc., and the same for other bases: X $10$, XX $20$, XXX $30$, L $50$, LXXX $80$; CC $200$, DCC $700$, etc. At the fourth and ninth iteration, a subtractive principle must be employed, with the base placed before the higher base: IV $4$, IX $9$, XL $40$, XC $90$, CD $400$, CM $900$. Also in bases greater than $10$ we use A for $10$, B for $11$, etc. Help Shapur capture Valerian and bring peace back to Persia, especially Armenia.
The code for converting decimal numbers to Roman was on Wikipedia , so I'm not going to explain it.Since we have the upper limit 1015 for all of our numbers , we can first convert them to decimal (and store the answer in a 64-bit integer) and then to the target base. For converting a number to decimal we first set the decimal variable to 0, then at each step we multiply it by the base and add the left-most digit's equivalent in base 10. We had some tricky test cases for this one which got many people : test #51: 2 10 0 many codes printed nothing for this one, this was also the most used hack for this problem test #54: 12 2 000..00A a sample of having initial zeros in input test #55: 17 17 0000000...000 There were many people who just printed the input if bases were equal there were two nice extremal hacks: 2 R 101110111000 and 10 21000000000000000
[ "math" ]
2,000
null
61
D
Eternal Victory
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal! He decided to visit all $n$ cities of Persia to find the best available mountain, but after the recent war he was too tired and didn't want to traverse a lot. So he wanted to visit each of these $n$ cities at least once with smallest possible traverse. Persian cities are connected with bidirectional roads. You can go from any city to any other one using these roads and there is a unique path between each two cities. All cities are numbered $1$ to $n$. Shapur is currently in the city $1$ and he wants to visit all other cities with minimum possible traverse. He can finish his travels in any city. Help Shapur find how much He should travel.
This one has two different linear-time solutions. Greedy and dynamic programming. Greedy solution: You should stop at the city with maximum distance from the root (city number 1). So all roads are traversed twice except for the roads between the root and this city. Dynamic Programming: For each city i we declare patrol[i] as the traverse needed for seeing i and all of it's children without having to come back to i (Children of a city are those cities adjacent to it which are farther from the root) and revpatrol[i] as the traverse needed to see all children of i and coming back to it. we can see that revpatrol[i] is sum of revpatrols of its children + sum of lengths of roads going from i to its children. patrol[i] can be found by replacing each of revpatrols with patrol and choosing their minimum.
[ "dfs and similar", "graphs", "greedy", "shortest paths", "trees" ]
1,800
null
61
E
Enemy is weak
The Romans have attacked again. This time they are much more than the Persians but Shapur is ready to defeat them. He says: "A lion is never afraid of a hundred sheep". Nevertheless Shapur has to find weaknesses in the Roman army to defeat them. So he gives the army a weakness number. In Shapur's opinion the weakness of an army is equal to the number of triplets $i, j, k$ such that $i < j < k$ and $a_{i} > a_{j} > a_{k}$ where $a_{x}$ is the power of man standing at position $x$. The Roman army has one special trait — powers of all the people in it are distinct. Help Shapur find out how weak the Romans are.
This one can be solved in O(nlgn) using a segment tree.First we convert all powers to numbers in range 0..n-1 to avoid working with segments as large as 109 in our segment tree. Then for each of the men we should find number of men who are placed before him and have more power let's call this gr[j]. When ever we reach a man with power x we add the segment [0,x-1] to our segment tree , so finding gr[j] can be done by querying power of j in our segment tree when it's updated by all j-1 preceding men. Now let's call number of men who are standing after j but are weaker than j as le[j]. These values can be found using the same method with a segment-tree or in O(n) time using direct arithmetic: le[j]=(power of j -1)-(i-1-gr[j]) note that powers are in range 0..n-1 now. Now we can count all triplets i,j,k which have j as their second index. This is le[j]*gr[j] so the final answer is $\sum_{j=0}^{n-1} le[j]\times gr[j]$
[ "data structures", "trees" ]
1,900
null
62
A
A Student's Dream
Statistics claims that students sleep no more than three hours a day. But even in the world of their dreams, while they are snoring peacefully, the sense of impending doom is still upon them. A poor student is dreaming that he is sitting the mathematical analysis exam. And he is examined by the most formidable professor of all times, a three times Soviet Union Hero, a Noble Prize laureate in student expulsion, venerable Petr Palych. The poor student couldn't answer a single question. Thus, instead of a large spacious office he is going to apply for a job to thorium mines. But wait a minute! Petr Palych decided to give the student the last chance! Yes, that is possible only in dreams. So the professor began: "Once a Venusian girl and a Marsian boy met on the Earth and decided to take a walk holding hands. But the problem is the girl has $a_{l}$ fingers on her left hand and $a_{r}$ fingers on the right one. The boy correspondingly has $b_{l}$ and $b_{r}$ fingers. They can only feel comfortable when holding hands, when no pair of the girl's fingers will touch each other. That is, they are comfortable when between any two girl's fingers there is a boy's finger. \textbf{And in addition, no three fingers of the boy should touch each other.} Determine if they can hold hands so that the both were comfortable." The boy any the girl don't care who goes to the left and who goes to the right. The difference is only that if the boy goes to the left of the girl, he will take her left hand with his right one, and if he goes to the right of the girl, then it is vice versa.
There was a lot of troubles because of incorrect statement. Now I hope statement is ok. Let's solve it. =) If boy will goes to the left he will take her left hand with his right one and boy's left hand and girl's right hand will be unused. Situation is looks like the same if we swap them vice versa. So, we need to check two situations and choose the best one. There is a simple way to check comfortableness, let's assume that boy has $B$ fingers on active hand and girl has $G$ fingers on active hand, so: If $B < G$ they will be happy only when $B = G - 1$, you may see a pattern $GBGBGBG...GBGBG$. In this pattern you can add no girl's finger for save the condition in statement If $B > G$ the worst but correct situation for them is a pattern $BBGBBGBB...BBGBB$. As you may see this way must be satisfy $2G + 2 > = B$ condition Simple situation is $B = G$, obviously answer is "yes"
[ "greedy", "math" ]
1,300
null
62
B
Tyndex.Brome
Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome! The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac after you buy Tyndex.Bottles and insert in into a USB port). It is highly popular due to the well-thought interaction with the user. Let us take, for example, the system of automatic address correction. Have you entered codehorses instead of codeforces? The gloomy Zoozle Chrome will sadly say that the address does not exist. Tyndex.Brome at the same time will automatically find the closest address and sent you there. That's brilliant! How does this splendid function work? That's simple! For each potential address a function of the $F$ error is calculated by the following rules: - for every letter $c_{i}$ from the potential address $c$ the closest position $j$ of the letter $c_{i}$ in the address ($s$) entered by the user is found. The absolute difference $|i - j|$ of these positions is added to $F$. So for every $i$ ($1 ≤ i ≤ |c|$) the position $j$ is chosen such, that $c_{i} = s_{j}$, and $|i - j|$ is minimal possible. - if no such letter $c_{i}$ exists in the address entered by the user, then the length of the potential address $|c|$ is added to $F$. After the values of the error function have been calculated for all the potential addresses the most suitable one is found. To understand the special features of the above described method better, it is recommended to realize the algorithm of calculating the $F$ function for an address given by the user and some set of potential addresses. Good luck!
Let's define $p$ as total length of all potential addresses $c$. In this problem obvious solution has O($p \cdot k$) difficulty and it is getting a TLE verdict. Let's speed up it by next way: we will save all position of letters 'a', 'b', ..., 'z' in address entered by user $s$ separately in increasing order. After this step we can find closest position of letter $c_{i}$ in $s$ for logarithmic time by binary search. This solution has O($p \cdot logk$) difficulty that gives "accepted". Look carefully for length of potential address (it can be more than $10^{5}$). Answer can be too big and asks you for using integer 64-bit type.
[ "binary search", "implementation" ]
1,800
null
62
C
Inquisition
In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission. The resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur. The very same resolution says that the cat's fur is a white square with the length of $10^{5}$. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes $(0;0)$ and the upper right one — to the point with coordinates $(10^{5};10^{5})$. The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point. We'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color.
All triangles are located strickly inside of square. It makes problem more simplify, because you don't need to check situations of touching sides. Let's save all segments of every triangle and cross them in pairs. There are many points at every segment - the results of crossing. Look at the every subsegment which do not contain any points of crossing inside. There are two situations: this subsegment completely lie on the side of some triangle or this subsegment completely lie inside of some triangle. We may check what is situation by this way: let's take a point at the middle of subsegment. If this point is strickly inside of some triangle then all subsegment is located inside and vice versa. We should calculate only subsegments located on the side of triangles and print their total length. If you are using integer numbers you should be careful for some operations like vector multiplication because it may leave 32-bit type. If you are using real numbers you should change you types for as large as possible for good precision (long long in c++, extended in pascal).
[ "geometry", "implementation", "sortings" ]
2,300
null
62
D
Wormhouse
Arnie the Worm has finished eating an apple house yet again and decided to move. He made up his mind on the plan, the way the rooms are located and how they are joined by corridors. He numbered all the rooms from $1$ to $n$. All the corridors are bidirectional. Arnie wants the new house to look just like the previous one. That is, it should have exactly $n$ rooms and, if a corridor from room $i$ to room $j$ existed in the old house, it should be built in the new one. We know that during the house constructing process Arnie starts to eat an apple starting from some room and only stops when he eats his way through all the corridors and returns to the starting room. It is also known that Arnie eats without stopping. That is, until Arnie finishes constructing the house, he is busy every moment of his time gnawing a new corridor. Arnie doesn't move along the already built corridors. However, gnawing out corridors in one and the same order any time you change a house is a very difficult activity. That's why Arnie, knowing the order in which the corridors were located in the previous house, wants to gnaw corridors in another order. It is represented as a list of rooms in the order in which they should be visited. The new list should be lexicographically smallest, but it also should be strictly lexicographically greater than the previous one. Help the worm.
In this problem you asks to find lexicographically next euler cycle or say that there is no way. Let's solve this problem backwards. We should repeat way of Arnie. Now it needs to rollback every his step and add edges for empty graph (graph without edges). Let's assume we had rollback edge from some vertix $x$ to vertix $y$. We need to check is there some vertix $z$ that is connected to $x$ by an edge and value of $z$ is more than $y$? Besides edge ($x$; $z$) shouldn't be a bridge because our component needs to be connected. No solution answer if it's impossible to find such $z$ at any step. But if edge ($x$; $z$) satisfied to conditions upper is exists let's change it to move and after this step our problem is to find lexicographically smallest euler way. It is possible to find only in unbreaked component of graph so every next step must going along non-brigde edges in vertix with as low number as possible. Of course, we must destroy unachievable vertices and do not destroy initial vertix. We can check is edge a bridge for O($E$) time by depth first search. Total difficulty of algorithm represented above is O($N \cdot E^{2}$).
[ "dfs and similar", "graphs" ]
2,300
null
62
E
World Evil
As a result of Pinky and Brain's mysterious experiments in the Large Hadron Collider some portals or black holes opened to the parallel dimension. And the World Evil has crept to the veil between their world and ours. Brain quickly evaluated the situation and he understood that the more evil tentacles creep out and become free, the higher is the possibility that Brain will rule the world. The collider's constriction is a rectangular grid rolled into a cylinder and consisting of $n$ rows and $m$ columns such as is shown in the picture below: In this example $n = 4$, $m = 5$. Dotted lines are corridores that close each column to a ring, i. e. connect the $n$-th and the $1$-th rows of the grid. In the leftmost column of the grid the portals are situated and the tentacles of the World Evil are ready to creep out from there. In the rightmost column the exit doors are located. The tentacles can only get out through those doors. The segments joining the nodes of the grid are corridors. Brain would be glad to let all the tentacles out but he faces a problem: the infinite number of tentacles can creep out of the portals, every tentacle possesses infinite length and some width and the volume of the corridors are, unfortunately, quite limited. Brain could approximately evaluate the maximal number of tentacles that will be able to crawl through every corridor. Now help the mice to determine the maximal number of tentacles of the World Evil that will crawl out of the Large Hadron Collider.
In this problem you were to find the maximal flow in network with a cyllinder structure. The dynamic solution with complexity $O(mn2^{n})$ was considered.It's well known that the maximal flow is equal to value of the minimal cut. Also all the sources must belong to one part of the cut and all the drains --- to the other part. Then we look over all the vertices from the left to the right, from the top to the bottom and append to the one or the other part of the cut, recalculating the answer during the process. The trivial solution has complexity $O(2^{mn})$ and doesn't fit the time limit. But we can notice the number add to the answer after appending a new vertice to some part of the cut depends only on what parts of the cut the vertices in the current and the previous columns belong to. So we can calculate such a value using dynamic programming: what is the minimal cut can be obtained by adding $i$ columns and the mask of belongings of vertices of the $i$th column to the parts of the cut is $mask$. Then we have $2^{n}$ conversions because there are $2^{n}$ different states of the $i - 1$th column. So we have the $O(mn2^{None})$ solution. But this solution also can be improved. We calculate the minimal cut, if $i - 1$ columns are added completely and $j$ vertices from the $i$th column are added, and mask of belongings of vertices that have no neighbours on the right is $mask$. Then we append $j$-th vertice to one of the parts, recalculate the value of the cut and do the conversion. So we have $mn2^{n}$ conditions and $O(1)$ conversions from the every condition and the solution's complexity is $O(mn2^{n})$.
[ "dp", "flows" ]
2,700
null
63
A
Sinking Ship
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All $n$ crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to $n$) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically: The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last. If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less). For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.
This problem can be easily solved with the following algorithm. First, read names ans statuses of all crew members into an array. Next, iterate over the entire array 4 times. In the first pass output names of rats. In the second pass output names of women and children. In the third pass output names of men. Finally, in the fourth pass output the name of the captain.
[ "implementation", "sortings", "strings" ]
900
null
63
B
Settlers' Training
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly $n$ soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease. Every soldier has a rank — some natural number from $1$ to $k$. $1$ stands for a private and $k$ stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank. To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the $n$ soldiers are present. At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank $k$ are present, exactly one soldier increases his rank by one. You know the ranks of all $n$ soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank $k$.
In this problem you can simulate the process of soliders training until there is at least one soldier with rank less than $k$. We iterate over the array of ranks and increase by one the ranks of every soldier who is the last in his group (if he has the rank less than $k$, of course). This operation preserves non-decreasing order of the ranks. Obviously we will need no more than $kn$ trains. So we have $O(kn^{2})$ solution. It fits the limits. You can prove that we will make no more than $n + k$ trains in the solution above. Therefore it really works in $O(n(n + k))$. In addition there is an $O(n)$ solution.
[ "implementation" ]
1,200
null
63
C
Bulls and Cows
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it. The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all it's digits should be different. The guesser tries to guess the number. He makes a series of guesses, trying experimental numbers and receives answers from the first person in the format "$x$ bulls $y$ cows". $x$ represents the number of digits in the experimental number that occupy the same positions as in the sought number. $y$ represents the number of digits of the experimental number that present in the sought number, but occupy different positions. Naturally, the experimental numbers, as well as the sought number, are represented by four-digit numbers where all digits are different and a leading zero can be present. For example, let's suppose that the thinker thought of the number 0123. Then the guessers' experimental number 1263 will receive a reply "1 bull 2 cows" (3 occupies the same positions in both numbers and 1 and 2 are present in both numbers but they occupy different positions). Also, the answer to number 8103 will be "2 bulls 1 cow" (analogically, 1 and 3 occupy the same positions and 0 occupies a different one). When the guesser is answered "4 bulls 0 cows", the game is over. Now the guesser has already made several guesses and wants to know whether his next guess can possibly be the last one.
Consider all of the numbers which the thinker may thinks of. Next we select from them ones which fit all thinker's answers. If there is exactly one such number, output it. If there are no such numbers, output "Incorrect data". Otherwise output "Need more data". The complexity of this solution is $O(10^{4} \times n)$. Most of mistakes in this problem were caused by leading zeros. Either while printing the answer or while transforming numbers into strings for checking them.
[ "brute force", "implementation" ]
1,700
null
63
D
Dividing Island
A revolution took place on the Buka Island. New government replaced the old one. The new government includes $n$ parties and each of them is entitled to some part of the island according to their contribution to the revolution. However, they can't divide the island. The island can be conventionally represented as two rectangles $a × b$ and $c × d$ unit squares in size correspondingly. The rectangles are located close to each other. At that, one of the sides with the length of $a$ and one of the sides with the length of $c$ lie on one line. You can see this in more details on the picture. The $i$-th party is entitled to a part of the island equal to $x_{i}$ unit squares. Every such part should fully cover several squares of the island (it is not allowed to cover the squares partially) and be a connected figure. A "connected figure" presupposes that from any square of this party one can move to any other square of the same party moving through edge-adjacent squares also belonging to that party. Your task is to divide the island between parties.
Main idea of the solution is walk the island around with a "snake". You can do it, for example, this way: or this way: Then we can just "cut" the snake into the pieces of appropriate length. It is clear that all the resulting figures will be connected. The complexity of this solution is $O(max(B, D) \times (A + C))$.
[ "constructive algorithms" ]
1,900
null
63
E
Sweets Game
Karlsson has visited Lillebror again. They found a box of chocolates and a big whipped cream cake at Lillebror's place. Karlsson immediately suggested to divide the sweets fairly between Lillebror and himself. Specifically, to play together a game he has just invented with the chocolates. The winner will get the cake as a reward. The box of chocolates has the form of a hexagon. It contains 19 cells for the chocolates, some of which contain a chocolate. The players move in turns. During one move it is allowed to eat one or several chocolates that lay in the neighboring cells on one line, parallel to one of the box's sides. The picture below shows the examples of allowed moves and of an unacceptable one. The player who cannot make a move loses. Karlsson makes the first move as he is Lillebror's guest and not vice versa. The players play optimally. Determine who will get the cake.
Define a state as some layout of sweets in a box. We have to detrmine for every state whether it is winning or losing. The state is winning if you can do a acceptable move to a losing state. Otherwise it is losing. For example, the state corresponding to the empty box is losing because there are no moves from this state. A state corresponding to a box containing only one candy is winning because there is a move leading to a losing state - eating the candy leaves the box empty. Thus, if the state given in the input is winning the answer is "Karlsson", otherwise answer is "Lillebror". It's useful to represent a state with a 19-bit mask where the i-th bit is 1 if there is a candy in the i-th cell. Similarly, each move can be respresented with a mask where the i-th bit is 1 if the candy in the i-th cell is to be eaten during the move. Note that a move $move$ can be done in a state $mask$ if $m o v e{\mathrm{~AND~}}m a s k==m o v_{t}$, and doing this move leads to the state $m a s k\mathrm{\bf~XOR~}m o v\epsilon$. Also note that in this case $m a s k\mathrm{\bf~XUR~}m o v e<m a s k$. These observations lead to the following solution: iterate over every state from $0$ to $2^{19} - 1$. For each state examine the list of possible moves and find ones that can be done in the current state. Assuming that we know the winningness of the states with lesser numbers, we can determine the winningness of the current state as described above. It's convenient to precompute the masks for all possible moves and store them in an array. This is apparently the most tricky part of this problem with lots of approaches ranging from the explicit enumeration to long intricate functions producing the moves list. Any approach will do, provided it is carefully implemented. The complexity of this solution is $O(2^{19}k)$, where k is the number of different moves (which turns out to be equal to $103$).
[ "bitmasks", "dfs and similar", "dp", "games", "implementation" ]
2,000
null
65
A
Harry Potter and Three Spells
A long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert $a$ grams of sand into $b$ grams of lead, the second one allows you to convert $c$ grams of lead into $d$ grams of gold and third one allows you to convert $e$ grams of gold into $f$ grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable... Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.
Fist, consider the case when all the numbers are non-zero. You can take a*c*e grams of sand, turn them into b*c*e grams of lead, and them turn into b*d*e grams of gold, and them turn into b*d*f grams of sand. If b*d*f > a*c*e, you can infinitely increase the amount of sand and consequently the amount of gold. Otherwise, if b*d*f <= a*c*e, it is impossible to get infinitely large amount of gold. The same is true when the fraction (a*c*e)/(b*d*f) has zero numerator only or zero denuminator only. Otherwise there is 0/0, and you have to check cases specially.
[ "implementation", "math" ]
1,800
null
65
B
Harry Potter and the History of Magic
The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates. So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes. Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than $2011$, or strictly before than $1000$. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.
The problem has greedy solution. Change a digit in the first date to make it as small as possible. At each of the next steps try all one-digit exchanges in the current date and choose one that makes the date not less than the previous one and as small as possible at the same time. If the last year won't exceed 2011 - the answer is found. Otherwise there is no solution. How to prove that? Consider any correct answer. Clearly, if the first date in it is different from the smallest possible number that can be obtained from the first of given years, your can put the smallest number instead of it. The second date can be exchanged by the smallest possible number not exceeding the first number, etc.Ar a result you obtain a greedy solution that is built by the algorithm described above. If the greedy solution doesn't exist, solution doesn't esist too. The problem also has a dynamic solution.
[ "brute force", "greedy", "implementation" ]
1,700
null