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
⌀ |
|---|---|---|---|---|---|---|---|
150
|
B
|
Quantity of Strings
|
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly $n$, based on the alphabet of size $m$. Any its substring with length equal to $k$ is a palindrome. How many such strings exist? Your task is to find their quantity modulo $1000000007$ ($10^{9} + 7$). Be careful and don't miss a string or two!
Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
|
We can offer you two solitions: You can build a graph with positions in sting as a nodes and equality in any substring of length $k$ as edges. Lets denote $e$ the number of components in the graph. The answer is $m^{e}$. Analyze four cases: $k = 1$ or $k > n$, the answer is $m^{n}$. $k = n$, the answer is $m^{(n + 1) / 2}$. $k$ mod $2 = 1$, any string like abababab... is ok, so the answer is $m^{2}$. $k$ mod $2 = 0$, all symbols coincide and the answer is $m$.
|
[
"combinatorics",
"dfs and similar",
"graphs",
"math"
] | 1,600
| null |
150
|
C
|
Smart Cheater
|
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus $62$ has exactly $n$ stops (stop $1$ goes first on its way and stop $n$ goes last). The stops are positioned on a straight line and their coordinates are $0 = x_{1} < x_{2} < ... < x_{n}$.
Each day exactly $m$ people use bus $62$. For each person we know the number of the stop where he gets on the bus and the number of the stop where he gets off the bus. A ticket from stop $a$ to stop $b$ ($a < b$) costs $x_{b} - x_{a}$ rubles. However, the conductor can choose no more than one segment NOT TO SELL a ticket for. We mean that conductor should choose C and D (С <= D) and sell a ticket for the segments [$A$, $C$] and [$D$, $B$], or not sell the ticket at all. The conductor and the passenger divide the saved money between themselves equally. The conductor's "untaxed income" is sometimes interrupted by inspections that take place as the bus drives on some segment of the route located between two consecutive stops. The inspector fines the conductor by $c$ rubles for each passenger who doesn't have the ticket for this route's segment.
You know the coordinated of all stops $x_{i}$; the numbers of stops where the $i$-th passenger gets on and off, $a_{i}$ and $b_{i}$ ($a_{i} < b_{i}$); the fine $c$; and also $p_{i}$ — the probability of inspection on segment between the $i$-th and the $i + 1$-th stop. The conductor asked you to help him make a plan of selling tickets that maximizes the mathematical expectation of his profit.
|
First lets use the linearity of expected value and solve task independently for each passanger. For each path segment (route between neighboring stations) we calculate expected value of profit in case we do not sell a ticket for this segment. In case we sell it the expectation of profit is 0. Now we only need to find the subsegment of segment [a, b] of maximal sum for each passanger. That's easy to do by the segment tree, we only need to calc four values for each node: best - the maximal sum of elements on some subsegment max_left - the maximal sum on prefix max_right - the maximal sum on suffix sum - the sum of all elements
|
[
"data structures",
"math",
"probabilities"
] | 2,200
| null |
150
|
D
|
Mission Impassable
|
Market stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest ("We don't go to Nvodsk..."). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (in fact, he wanted to complete the quest himself). But all of a sudden a stranger appeared at the door of his office. "Good afternoon. My name is Chuck and I solve any problems" — he said.
And here they are sitting side by side but still they can't complete the mission. The thing is, to kill the final boss one should prove one's perfect skills in the art of managing letters. One should be a real magician to do that. And can you imagine what happens when magicians start competing...
But let's put it more formally: you are given a string and a set of integers $a_{i}$. You are allowed to choose any substring that is a palindrome and delete it. At that we receive some number of points equal to $a_{k}$, where $k$ is the length of the deleted palindrome. For some $k$, $a_{k} = $-1, which means that deleting palindrome strings of such length is \textbf{forbidden}. After a substring is deleted, the remaining part "shifts together", that is, at no moment of time the string has gaps. The process is repeated while the string has at least one palindrome substring that can be deleted. All gained points are summed up.
Determine what maximum number of points can be earned.
"Oh" — said Chuck, raising from the chair, — "I used to love deleting palindromes, just like you, but one day I took an arrow in the Knee".
|
In this problem you have to use dynamic programming. For our convenience we will calulate three type of values: $Best[l][r]$ - best result player can achieve on the segment $[l, r]$. $Full[l][r]$ - best result player can achieve on the segment from $[l, r]$ if he fully destroys it. $T[l][r][Len]$ - best result player can achieve on the segment from $[l, r]$ and remain the palindrome of length $len$ and only it. Now solution: $Full[l][r]$. Let's look which move will be the last. This will be removing the palindrome of length $len$ and $c[len] \ge 0$. What is the best result we can achieve? $c[len] + T[l][r][len]$. $Best[l][r]$. Either we will destroy all subtring from $l$ to $r$, either there exists a letter which we did not touch. That means that all our moves lies fully to the left or fully to the rigth to that position. So $Best[l][r] = Full[l][r]$ or $Best[l][r]$ = $Best[l][m] + Best[m + 1][r]$ for some $m$, $l \le m < r$. $T[l][r][len]$. $len = 0$, $len = 1$ - two special cases, which is easy to solve without any dynamic. In other case, let's take a look on the left-most position. It either will lie in the result string or not. If not, then let's find the first position which does. Denote it as $m$ ($l < m \le r$). Everything what lies to the left need to be fully deleted. So the answer is $Full[l][m - 1] + T[m][r][len]$ (for $l < m \le r$). Similarly, for the right-most letters. If it does not lies in the result string we remove everything to the right and our result is $T[l][m][len] + Full[m + 1][r]$ (for $l \le m < r$). The last option: both left-most and rigth-most letters lies in the result string. It is possible only if $s[l] = s[r]$. So our result is $T[l + 1][r - 1][len - 2]$ (only if $s[l] = = s[r]$).
|
[
"dp",
"strings"
] | 2,600
| null |
150
|
E
|
Freezing with Style
|
This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as $n$ junctions connected with $n - 1$ bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction $v$), and the place to set up the contests (junction $u$). Besides, at the one hand, they want the participants to walk about the city and see the neighbourhood (that's why the distance between $v$ and $u$ should be no less than $l$). On the other hand, they don't want the participants to freeze (so the distance between $v$ and $u$ should be no more than $r$). Besides, for every street we know its beauty — some integer from $0$ to $10^{9}$. Your task is to choose the path that fits in the length limits and has the largest average beauty. We shall define the average beauty as a median of sequence of the beauties of all roads along the path.
We can put it more formally like that: let there be a path with the length $k$. Let $a_{i}$ be a non-decreasing sequence that contains exactly $k$ elements. Each number occurs there exactly the number of times a road with such beauty occurs along on path. We will represent the path median as number $a_{⌊k / 2⌋}$, assuming that \textbf{indexation starting from zero} is used. $⌊x⌋$ — is number $х$, rounded down to the nearest integer.
For example, if $a = {0, 5, 12}$, then the median equals to $5$, and if $a = {0, 5, 7, 12}$, then the median is number $7$.
It is guaranteed that there will be at least one path with the suitable quantity of roads.
|
If there exists a path with the median $ \ge k$, for some $k$, then there exists a path with the median $ \ge q$, for each $q \le k$. That means we can use binary search to calculate the answer. So now the task is: is there any path with the median greater or equal to $Mid$ ? We will calc the edge as $+ 1$ if it's wight $ \ge Mid$, or as $- 1$ in other case. Now we only need to check if there exists a path with legal length and the sum greater than or equal to zero. Let's denote some node $V$ as a root. All paths can be divided into two types: that contains $v$, and that do not. Now we are to process all first-type paths and run the algorithm on all subtrees. That is so-called divide-and-conquer strategy. We can trivially show that it is always possible to choose such vertex $v$ that all it's subtrees will have size less than or equal to the size of the whole tree. That means that each node will be proccessed in $LogN$ trees max. So, if we solve the task for one level of recursion in $O(F(N))$, we'll solve it in time $O(F(N) * log^{2}(N))$ on the whole. First, lets get $O(N * Log(N))$. For each node we shall calc it's deepness, cost of the path to the root ans the first edge (the number of the root's subtree). It will be better now to use 2 and 0 as the edges costs, instead of -1 and 1. Now we shall process root's subtrees one by one. For each node we want to know if there exists a node $u$ in any other subtree such that the Unable to parse markup [type=CF_TEX] and $cost[v] - deep[v] + cost[u] - deep[u] \ge 0$. To do that we need to know the maximum of the function $(cost[u] - deep[u])$ with the deep values between max(0, $L - deep[v]$) and $R - deep[v]$ inclusive. To achieve $O(N * log(N))$ you need only to use segment tree. To achieve an AC contestants were to write all code optimally, or to think of one more idea. It is possible to have $O(N)$ on one level of recursion and $O(N * log^{2}(N))$ in total if you sort roots subtrees in non-decreasing order and use any structure that can answer getmax query on all segments of length $(R - L + 1)$ and all prefixes and suffixes.
|
[
"binary search",
"data structures",
"divide and conquer",
"trees"
] | 3,000
| null |
151
|
A
|
Soft Drinking
|
This winter is so cold in Nvodsk! A group of $n$ friends decided to buy $k$ bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has $l$ milliliters of the drink. Also they bought $c$ limes and cut each of them into $d$ slices. After that they found $p$ grams of salt.
To make a toast, each friend needs $nl$ milliliters of the drink, a slice of lime and $np$ grams of salt. The friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?
|
Soda will be enough for $gas$ = $(K$ * $L)$ / $(N$ * $l)$ toasts. Limes will last for $laim = (C * D) / N$ toasts. Salt is enough for $sol = P / (p * N)$ toasts. Total result: $res = min(gas, laim, sol)$.
|
[
"implementation",
"math"
] | 800
| null |
151
|
B
|
Phone Numbers
|
Winters are just damn freezing cold in Nvodsk! That's why a group of $n$ friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size $s_{i}$ (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.
You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type).
If the phone book of one person contains some number two times, you should count it \textbf{twice}. That is, each number should be taken into consideration the number of times it occurs in the phone book.
|
In this task you were to implement the described selection of the maximum elements.
|
[
"implementation",
"strings"
] | 1,200
| null |
152
|
A
|
Marks
|
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has $n$ students. They received marks for $m$ subjects. Each student got a mark from $1$ to $9$ (inclusive) for each subject.
Let's consider a student the best at some subject, if there is no student who got a higher mark for this subject. Let's consider a student successful, if there exists a subject he is the best at.
Your task is to find the number of successful students in the group.
|
In this problem you should do exactly what is written in the statement.
|
[
"implementation"
] | 900
| null |
152
|
B
|
Steps
|
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.
Vasya noticed that the yard is a rectangular $n × m$ field. The squares have coordinates $(x, y)$ ($1 ≤ x ≤ n, 1 ≤ y ≤ m$), where $x$ is the index of the row and $y$ is the index of the column.
Initially Vasya stands in the square with coordinates ($x_{c}, y_{c}$). To play, he has got a list of $k$ vectors $(dx_{i}, dy_{i})$ of non-zero length. The game goes like this. The boy considers all vectors in the order from $1$ to $k$, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).
A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square $(x, y)$, and the current vector is $(dx, dy)$, one step moves Vasya to square $(x + dx, y + dy)$. A step is considered valid, if the boy does not go out of the yard if he performs the step.
Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.
|
Let's find a formula for the position $(x, y)$ and vector $(dx, dy)$, how many steps to stop the boy can do. You should use "almost" binary search, for example, see the code written by RAD.
|
[
"binary search",
"implementation"
] | 1,300
| null |
152
|
C
|
Pocket Book
|
One day little Vasya found mom's pocket book. The book had $n$ names of her friends and unusually enough, each name was exactly $m$ letters long. Let's number the names from $1$ to $n$ in the order in which they are written.
As mom wasn't home, Vasya decided to play with names: he chose three integers $i$, $j$, $k$ ($1 ≤ i < j ≤ n$, $1 ≤ k ≤ m$), then he took names number $i$ and $j$ and swapped their prefixes of length $k$. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of $3$, the result will be names "AABAD" and "CBDRD".
You wonder how many different names Vasya can write instead of name number $1$, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers $i$, $j$, $k$ independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo $1000000007$ $(10^{9} + 7)$.
|
In this task, it was necessary to understand that in position $1$ Vasya can get any name of a special form. More exactly, it's the name of form $s$ = $s_{1}$ $s_{2}$ $s_{3}$ $s_{4}$ $...$ $s_{m}$, where $s_{1}$ - the first letter of any of the names, $s_{2}$ - the second letter of any of the names, $...$ $s_{m}$ - $m$-th letter of any of the names. Then the answer to the problem is the product of $cnt_{i}$ ($1 \le i \le m$), where $cnt_{i}$ is a number of different letters in the names placed in position $i$.
|
[
"combinatorics"
] | 1,400
| null |
152
|
D
|
Frames
|
One day Vasya got hold of a sheet of checkered paper $n × m$ squares in size. Our Vasya adores geometrical figures, so he painted two rectangles on the paper. The rectangles' sides are parallel to the coordinates' axes, also the length of each side of each rectangle is no less than 3 squares and the sides are painted by the grid lines. The sides can also be part of the sheet of paper's edge. Then Vasya hatched all squares on the rectangles' \underline{frames}.
Let's define a rectangle's frame as the set of squares \textbf{inside} the rectangle that share at least one side with its border.
A little later Vasya found a sheet of paper of exactly the same size and couldn't guess whether it is the same sheet of paper or a different one. So, he asked you to check whether the sheet of paper he had found contains two painted frames and nothing besides them.
Please note that the frames painted by Vasya can arbitrarily intersect, overlap or even completely coincide.
The coordinates on the sheet of paper are introduced in such a way that the $X$ axis goes from top to bottom, the $x$ coordinates of the squares' numbers take values from $1$ to $n$ and the $Y$ axis goes from the left to the right and the $y$ coordinates of the squares' numbers take values from $1$ to $m$.
|
It was necessary to understand if there are two borders or not. Let's distinguish those $x$ - and $y$-coordinates, in which there are at least $3$ consecutive symbols '#', becouse the length of each border is no less then $3$. It is clear that the coordinates of the corners of borders should be chosen only from those selected $x$ and $y$. In general, the various selected $x$ no more then $4$ and various selected $y$ no more then $4$. Except that case when the height or width of the first border is $3$, and length of the second side of this border is more than $3$, and one side of the second border fills a part of the inside first at least. For example: ####### ####### ####### #.....# #######The first border: ####### #.....# ####### ....... .......The second border: ....... ####### #.....# #.....# #######There are $7$ different $y$-coordinates in the example. Carefully processed these cases separately, it is quite simple. (Let's choose $4$ $y$-coordinates: minimum, maximum, second minimum and second maximum). Otherwise, if the amount selected $x$ - and $y$-coordinates no more then $4$, then let's choose opposite corners of the first and second borders and verify that the selected borders - the correct borders and there are no other characters '#'. Checking is carried out at $O(n + m)$ or $O(1)$ (using partial sums).
|
[
"brute force"
] | 2,600
| null |
152
|
E
|
Garden
|
Vasya has a very beautiful country garden that can be represented as an $n × m$ rectangular field divided into $n·m$ squares. One beautiful day Vasya remembered that he needs to pave roads between $k$ important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete.
For each garden square we know number $a_{i}_{j}$ that represents the number of flowers that grow in the square with coordinates $(i, j)$. When a square is covered with concrete, all flowers that grow in the square die.
Vasya wants to cover some squares with concrete so that the following conditions were fulfilled:
- all $k$ important squares should necessarily be covered with concrete
- from each important square there should be a way to any other important square. The way should go be paved with concrete-covered squares considering that neighboring squares are squares that have a common side
- the total number of dead plants should be minimum
As Vasya has a rather large garden, he asks you to help him.
|
The solution of this problem is based on dynamic programming. $dp[mask][v]$ - the value of the minimum correct concrete cover, if we consider as important elements only elements of the mask $mask$, and there are additionally covered the vertex $v = (i, j)$ of the field. There are two types of transfers. First of all we can, as if to cut coverage on the vertex $v$. Then you need to go through subpattern of vertex $submask$, which will go to the left coverage and make an optimizing transfer. Update $dp[mask][v]$ with the value $dp[submask][v] + dp[mask ^ submask][v] - cost(v)$. Second, perhaps in the vertex $v$ in the optimal coverage mask $mask$, which covers the vertex $v$, you can not make the cut separating the set of vertices. In this case, this vertex forms something a kind of <>. And there a vertex $u$ exists, on which we can make the cut, with the whole shortest path from a vertex $u$ to $v$ belongs to the optimal coverage. Let's precalculate the shortest paths between all pairs of cells. Now to make this transition, we should count the value of dynamics $dp[mask][v]$ for all vertices $v$ only on the basis of the first transition. Now you can make the second transition. For all $u$, $dp[mask][v]$, update the value of $dp[mask][u] + dist(v, u) - cost(u)$. Let's process separately state in which exactly one bit in the mask, and the vertex which corresponding to this bit is equal to $v$. In this case the answer is equal to $cost(v)$, of course. Thus, each solution is obtained for the $O(min(3^{k} \cdot n \cdot m, 2^{k} \cdot (n \cdot m)^{2}))$.
|
[
"bitmasks",
"dp",
"graphs",
"trees"
] | 2,500
| null |
154
|
A
|
Hometask
|
Sergey attends lessons of the $N$-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the $N$-ish language. Sentences of the $N$-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks.
Sergey totally forgot about the task until half an hour before the next lesson and hastily scribbled something down. But then he recollected that in the last lesson he learned the grammar of $N$-ish. The spelling rules state that $N$-ish contains some "forbidden" pairs of letters: such letters can never occur in a sentence next to each other. Also, the order of the letters doesn't matter (for example, if the pair of letters "ab" is forbidden, then any occurrences of substrings "ab" and "ba" are also forbidden). Also, each pair has different letters and each letter occurs in no more than one forbidden pair.
Now Sergey wants to correct his sentence so that it doesn't contain any "forbidden" pairs of letters that stand next to each other. However, he is running out of time, so he decided to simply cross out some letters from the sentence. What smallest number of letters will he have to cross out? When a letter is crossed out, it is "removed" so that the letters to its left and right (if they existed), become neighboring. For example, if we cross out the first letter from the string "aba", we get the string "ba", and if we cross out the second letter, we get "aa".
|
Constriction saying that no letter occurs in more than one forbidden pair lets us to use the greedy solution. Without the constriction the problem is quite hard. Let's look at all occurences of letters from some pair. They form several continuous substrings divided by some other letters. We can note that in optimal solution the substrings cannot merge, 'cause we can leave at least one letter in each of such parts. So, for each of these substrings problem is solved independently. To resolve conflicts within a substring, one has to remove all letters of some kind, 'cause while there are letters of both kinds there will be conflicts. Clearly, from each continuous substring of forbidden letters we remove all letters of the kind which number is less than another. The answer can be counted in O(kN) with k runs through the string.
|
[
"greedy"
] | 1,600
| null |
154
|
B
|
Colliders
|
By 2312 there were $n$ Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from $1$ to $n$. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.
In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals $1$)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.
Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).
Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the $i$-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.
To the request of "+ i" (that is, to activate the $i$-th collider), the program should print exactly one of the following responses:
- "Success" if the activation was successful.
- "Already on", if the $i$-th collider was already activated before the request.
- "Conflict with j", if there is a conflict with the $j$-th collider (that is, the $j$-th collider is on, and numbers $i$ and $j$ are not relatively prime). In this case, the $i$-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them.
The request of "- i" (that is, to deactivate the $i$-th collider), should receive one of the following responses from the program:
- "Success", if the deactivation was successful.
- "Already off", if the $i$-th collider was already deactivated before the request.
You don't need to print quotes in the output of the responses to the requests.
|
The clueless solution ''store all the enabled numbers and compare each new number with each of them'' works too slow, as we can add all the prime numbers below $n$, number of which is O(n / log n). We can note that for each number k > 1 at any time no more than one collider is turned on which number is divided by k. Let us store an array which has in k-th element the number of turned-on collider which is divided by k, on 0 if there is no such at the moment. To enable the collider with number q we can look over q's divisors and check whether all the array's elements with these numbers have 0's. If some of them has a positive integer, that's the number of collider we conflict with - we can just print it and go on. Otherwise, we have to put q into all the overlooked elements. This works in O(M sqrt(N) + N). There's faster solution as we can store all of the above only for prime divisors. Total size of the prime divisors list for number from 1 to N is O(N log log N). Thus we have a solution with complexity O(N log log N + M log N), as the number of prime divisors of k doesn't exceed log k (exact upper bound - log k / log log k * (1 + o(1)).
|
[
"math",
"number theory"
] | 1,600
| null |
154
|
C
|
Double Profiles
|
You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user.
The social network contains $n$ registered profiles, numbered from $1$ to $n$. Some pairs there are friends (the "friendship" relationship is mutual, that is, if $i$ is friends with $j$, then $j$ is also friends with $i$). Let's say that profiles $i$ and $j$ ($i ≠ j$) are doubles, if for any profile $k$ ($k ≠ i$, $k ≠ j$) one of the two statements is true: either $k$ is friends with $i$ and $j$, or $k$ isn't friends with either of them. Also, $i$ and $j$ can be friends or not be friends.
Your task is to count the number of different unordered pairs ($i, j$), such that the profiles $i$ and $j$ are doubles. Note that the pairs are unordered, that is, pairs ($a, b$) and ($b, a$) are considered identical.
|
We want to count the number of pairs of vertices in a undirected graph which neighbours' sets are equal up to these vertices. To count the pairs which sets of neighbours are equal we can hash these sets (for instance, count the polynomial hash of adjacency matrix row) and sort the hashes. Than we have to add the pairs of doubles which have an edge between them. We can note that there are no more such pairs than there are edges in the graph. So we can iterate through edges and check hashes for equivalence considering the presence of the edge (in case of polynomial hash we just add some degrees to them and then compare them). Other solution was to count another version of the previous hash, now adding a loop to each vertex, and to count the number of pairs just like in the previous case. Moreover, we could try and sort the whole lists of adjacencies (which previuosly should be sorted too). As their total size is 2M, this works fine too, but needs an accurate realization. Hash solution complexity - O(N log N + M).
|
[
"graphs",
"hashing",
"sortings"
] | 2,300
| null |
154
|
D
|
Flatland Fencing
|
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on one, the winner (or rather, the survivor) transfers to the next round.
Before the battle both participants stand at the specified points on the $Ox$ axis with integer coordinates. Then they make moves in turn. The first participant moves first, naturally. During a move, the first participant can transfer from the point $x$ to any integer point of the interval [$x + a$; $x + b$]. The second participant can transfer during a move to any integer point of the interval [$x - b$; $x - a$]. That is, the options for the players' moves are symmetric (note that the numbers $a$ and $b$ are not required to be positive, and if $a ≤ 0 ≤ b$, then staying in one place is a correct move). At any time the participants can be located arbitrarily relative to each other, that is, it is allowed to "jump" over the enemy in any direction. A participant wins if he uses his move to transfer to the point where his opponent is.
Of course, the princess has already chosen a husband and now she wants to make her sweetheart win the tournament. He has already reached the tournament finals and he is facing the last battle. The princess asks the tournament manager to arrange the tournament finalists in such a way that her sweetheart wins the tournament, considering that both players play optimally. However, the initial location of the participants has already been announced, and we can only pull some strings and determine which participant will be first and which one will be second. But how do we know which participant can secure the victory? Alas, the princess is not learned in the military affairs... Therefore, she asks you to determine how the battle will end considering that both opponents play optimally. Also, if the first player wins, your task is to determine his winning move.
|
As the moves choices are symmetrical for both players, if one player can reach another in one move from some disposition, the other player also can reach the first. So, if we are allowed to stand in one place (i.e. a <= 0 <= b), we can just stand still and wait for another player to come. If she wants to win, she will have to step within our reach before that so that we can get her. So, if the first player doesn't reach the second initially, there is a draw as no one can ensure her victory. Thus we finished the case a <= 0 <= b: either the first player wins in one move, or there is a draw. Now, let a and b have the same sign. Denote d = x2 - x1. If a <= b < 0, we can go to the situation with (d, a, b) = (-d, -b, -a), which is similar to the initial. So later on 0 < a. So we have the following game: there are integers d and 0 < a <= b. In one move each player can substract an arbitrary integer number from segment [a; b] from d. The player who gets d = 0 after her move wins. If at some point d < 0, a draw is proclaimed (as no one can win anymore). The interesting case is d > 0. Note that if d mod (a + b) = 0, the second player can use the symmetrical strategy: for every first player's move x of she can make a move a + b - x, and support the condition d mod (a + b) = 0. As d decreases, the second player eventually moves to 0 and wins. So, if d mod (a + b) = 0, the second player wins. Thus, if d mod (a + b) is in [a; b], the first player wins, as he can reduce the game to the previous case by letting the second player move in the losing situation. What about all the other situations? Turns out all the other position are draws. We prove that by induction: let d = k(a + b) + l, where l in [0; a + b). Case l = 0, as we just proved, is losing, cases l in [a; b] are winning. If l is in [1; a - 1], we cannot move to losing position (we use the induction assumption for lesser k), but after the move a, we move to the draw position (if k = 0, we move to the negative number, otherwise we get into [(k - 1)(a + b) + b + 1; k(a + b) - 1] segment, every position from which is a draw by assumption). Similarily for l = [b + 1; a + b - 1], move to a draw - b.
|
[
"games",
"math"
] | 2,400
| null |
154
|
E
|
Martian Colony
|
The first ship with the Earth settlers landed on Mars. The colonists managed to build $n$ necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It was decided to use the protective force field generating system to protect the colony against possible trouble.
The system works as follows: the surface contains a number of generators of the field (they can also be considered as points). The active range of each generator is a circle of radius $r$ centered at the location of the generator (the boundary of the circle is also included in the range). After the system is activated, it stretches the protective force field \textbf{only over the part of the surface, which is within the area of all generators' activity}. That is, the protected part is the \textbf{intersection} of the generators' active ranges.
The number of generators available to the colonists is not limited, but the system of field generation consumes a lot of energy. More precisely, the energy consumption does not depend on the number of generators, but it is directly proportional to the \textbf{area}, which is protected by the field. Also, it is necessary that all the existing buildings are located within the protected area.
Determine the smallest possible area of the protected part of the surface containing all the buildings.
|
We have to find the area of intersection of all circles containing the given set of points (it's clear that the intersection has the least area, and we have an unlimited number of circles). First, what shape does such an intersection have? Its border contains some circle arcs of radius R meeting at some points of convex hull. If we determine which points are present in the border, we can count the total area as the sum of polygon area and several circle segments. So, how to determine those points? It's clear that if there is a circle of radius R containing all the points and having some of them on its border, then this particular point is present in the border of the intersection. If we fix the circle and move it in some direction, it eventually will run into some point - so we can find at least one point. Then we can perform something similar to ''present wrapping'' - go around the convex hull and support the set of the border points while controlling the relative position of the arcs. While this solution is fast, it is very hard to write and it was not assumed that it should be written during the contest. There is much simpler solution based on quite different idea. We build the convex hull of the set so that no three points lie on the same line. Let us take the very large R so that every point of convex hull is present in the intersection border. As we gradually decrease R, some points will start to disappear from the border. How to determine which point falls out first? For point u in the convex hull denote its left and right neighbours l(u) and r(u). It's clear, that the first point to disappear will be such point u which has the largest radius of circle going through u, l(u) and r(u) (when R becomes equal to this radius, two arcs will merge into one in point u, while all the other will have joints in them; we will call this radius critical for u). Then we remove u from convex hull and do not take it into account. We repeat while the largest critical radius is larger than R. The rest points will be exactly the points forming the border. How to do this fast? Note that when we remove some point from the set the critical radii will change only for its two neighbours. Let us store a priority queue containing critical radii along with point numbers. On every iteration we extract the largest critical radius, remove the corresponding point from the set, and refresh the information about the neighbours in the queue. We repeat while the largest radius is greater than R. As we just simulate the process of R decreasing, everything works correctly. The complexity of this procedure is O(n log n), as we have no more than n iterations and on every iteration we perform the constant number of operations with the queue of size at most n. There is an unclear case, when the border contains only two points. Then on the last phase we have three points in the set and the algorithm doesn't have a clue which one to remove as they have equal critical radii. But we know that the triangle with vertices in these points is obtuse-angled, as we cannot shrink the circumcircle of an acute-angle triangle, as that would contradict with the circle existence condition. So we have to remove the point with the obtuse angle.
|
[
"geometry"
] | 3,000
| null |
155
|
A
|
I_love_\%username\%
|
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly \textbf{more} points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly \textbf{less} points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
|
You should do what is written: go through the sequence and count the elements which are greater or less than all of its predecessors. We don't even have to store the whole sequence, just the current minimum and maximum. Complexity - O(N), but squared still works fine.
|
[
"brute force"
] | 800
| null |
155
|
B
|
Combination
|
Ilya plays a card game by the following rules.
A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number $a_{i}$, and the bottom contains number $b_{i}$, then when the player is playing the card, he gets $a_{i}$ points and also gets the opportunity to play additional $b_{i}$ cards. After the playing the card is discarded.
More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number $b_{i}$, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.
Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?
|
Clearly, we can play the cards with $b_{i}$ > 0 first as each of them gives at least one extra move. After that, the number of extra moves left doesn't depend on the order of playing. The left cards all have $b_{i}$ = 0, so we play those of them which have larger $a_{i}$. Simpler version of this solution: sort all the cards by decrease of $b_{i}$, if equal - by decrease of $a_{i}$, and then go through the sorted array from beginning to end, simulate the counter and sum up the points. Remember not to fall over the edge of array if the sum of $b_{i}$'s is larger than the number of cards. Complexity - O(n log n) (or O(n^2), if using bubblesort, which is still accepted).
|
[
"greedy",
"sortings"
] | 1,100
| null |
158
|
A
|
Next Round
|
"Contestant who earns a score equal to or greater than the $k$-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules.
A total of $n$ participants took part in the contest ($n ≥ k$), and you already know their scores. Calculate how many participants will advance to the next round.
|
Just sort. Notice 0 in the array.
|
[
"*special",
"implementation"
] | 800
| null |
158
|
B
|
Taxi
|
After the lessons $n$ groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the $i$-th group consists of $s_{i}$ friends ($1 ≤ s_{i} ≤ 4$), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
|
Choose the 3 and 1 as much as possible. And let 2 combine with themselves. If there are more 1s and 2s, let two 1s combine with 2, and every four 1s take same taxi.
|
[
"*special",
"greedy",
"implementation"
] | 1,100
| null |
158
|
C
|
Cd and pwd commands
|
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory).
Directories in Vasya's operating system form a traditional hierarchical tree structure. There is a single root directory, denoted by the slash character "/". Every other directory has a name — a non-empty string consisting of lowercase Latin letters. Each directory (except for the root) has a parent directory — the one that contains the given directory. It is denoted as "..".
The command cd takes a single parameter, which is a path in the file system. The command changes the current directory to the directory specified by the path. The path consists of the names of directories separated by slashes. The name of the directory can be "..", which means a step up to the parent directory. «..» can be used in any place of the path, maybe several times. If the path begins with a slash, it is considered to be an absolute path, that is, the directory changes to the specified one, starting from the root. If the parameter begins with a directory name (or ".."), it is considered to be a relative path, that is, the directory changes to the specified directory, starting from the current one.
The command pwd should display the absolute path to the current directory. This path must not contain "..".
Initially, the current directory is the root. All directories mentioned explicitly or passed indirectly within any command cd are considered to exist. It is guaranteed that there is no attempt of transition to the parent directory of the root directory.
|
Implement with stack. If the string begin with '/', let top = 0, else remain the top; Then process the substring one by one, when meeting ".." , top--; else remain the top;
|
[
"*special",
"data structures",
"implementation"
] | 1,400
| null |
158
|
D
|
Ice Sculptures
|
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus $n$ ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular $n$-gon. They are numbered in clockwise order with numbers from 1 to $n$.
The site of the University has already conducted a voting that estimated each sculpture's characteristic of $t_{i}$ — the degree of the sculpture's attractiveness. The values of $t_{i}$ can be positive, negative or zero.
When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:
- the remaining sculptures form a regular polygon (the number of vertices should be between 3 and $n$),
- the sum of the $t_{i}$ values of the remaining sculptures is maximized.
Help the Vice Rector to analyze the criticism — find the maximum value of $t_{i}$ sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.
|
The number of new regular polygon's edges must be the factor of the given polygon. Listing all the factors take O(sqrt(n)) time. Then choose the best point take O(n). So the time complexity is O(n*sqrt(n)).
|
[
"*special",
"brute force",
"number theory"
] | 1,300
| null |
158
|
E
|
Phone Talks
|
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has $n$ calls planned. For each call we know the moment $t_{i}$ (in seconds since the start of the day) when it is scheduled to start and its duration $d_{i}$ (in seconds). All $t_{i}$ are different. Mr. Jackson is a very important person, so he never dials anybody himself, all calls will be incoming.
Mr. Jackson isn't Caesar and he can't do several things at once. If somebody calls him while he hasn't finished the previous conversation, Mr. Jackson puts the new call on hold in the queue. In this case immediately after the end of the current call Mr. Jackson takes the earliest incoming call from the queue and starts the conversation. If Mr. Jackson started the call at the second $t$, and the call continues for $d$ seconds, then Mr. Jackson is busy at seconds $t, t + 1, ..., t + d - 1$, and he can start a new call at second $t + d$. Note that if Mr. Jackson is not busy talking when somebody calls, he can't put this call on hold.
Mr. Jackson isn't Napoleon either, he likes to sleep. So sometimes he allows himself the luxury of ignoring a call, as if it never was scheduled. He can ignore at most $k$ calls. Note that a call which comes while he is busy talking can be ignored as well.
What is the maximum number of seconds Mr. Jackson can sleep today, assuming that he can choose an arbitrary continuous time segment from the current day (that is, with seconds from the 1-st to the 86400-th, inclusive) when he is not busy talking?
Note that some calls can be continued or postponed to the next day or even later. However, the interval for sleep should be completely within the current day.
|
It's a classic DP problem. Array dp[i][j] stands for the min rightmost endpoint when choosing at most j segments from the first i segments . dp[i][j] =dp[i][j] = min(dp[i-1][j-1], max(dp[i-1][j],left[i])+length[i]). When the dp array is completed , find the max value of left[i+1]-dp[i][k] and rightmost point - dp[n][k]. Totally take O(n*n).
|
[
"*special",
"dp",
"sortings"
] | 1,900
| null |
159
|
A
|
Friends or Not
|
Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that user $A$ sent user $B$ a message at time $t_{1}$, and user $B$ sent user $A$ a message at time $t_{2}$. If $0 < t_{2} - t_{1} ≤ d$, then user $B$'s message was an answer to user $A$'s one. Users $A$ and $B$ are considered to be friends if $A$ answered at least one $B$'s message or $B$ answered at least one $A$'s message.
You are given the log of messages in chronological order and a number $d$. Find all pairs of users who will be considered to be friends.
|
Compare every two records and find the right friends. Give every name a unique number so as to avoid counting same friend twice. If a and b is friends, let friend[a][b] = true.
|
[
"*special",
"greedy",
"implementation"
] | 1,400
| null |
159
|
B
|
Matchmaker
|
Polycarpus has $n$ markers and $m$ marker caps. Each marker is described by two numbers: $x_{i}$ is the color and $y_{i}$ is the diameter. Correspondingly, each cap is described by two numbers: $a_{j}$ is the color and $b_{j}$ is the diameter. Cap $(a_{j}, b_{j})$ can close marker $(x_{i}, y_{i})$ only if their diameters match, that is, $b_{j} = y_{i}$. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, $a_{j} = x_{i}$.
Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.
|
Establish two hash tables counting the number of the size (say 2) exiting in set makers and set caps. Obviously the sum of min number of every size in two sets is the first answer. Similarly establish two hash tables in order to count the number of the same size and same color. The hash function can be hash(color, size) = color*1000+size.
|
[
"*special",
"greedy",
"sortings"
] | 1,100
| null |
159
|
C
|
String Manipulation 1.0
|
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name $s$, a user can pick number $p$ and character $c$ and delete the $p$-th occurrence of character $c$ from the name. After the user changed his name, he can't undo the change.
For example, one can change name "arca" by removing the second occurrence of character "a" to get "arc".
Polycarpus learned that some user initially registered under nickname $t$, where $t$ is a concatenation of $k$ copies of string $s$. Also, Polycarpus knows the sequence of this user's name changes. Help Polycarpus figure out the user's final name.
|
Because the length of string is at most 100*2000, so we can build 26 line-segment-trees to count the 26 Latin letters. The way to build tree and find the position of K-th letter is quite simple if you under stand line-segment-tree :)
|
[
"*special",
"binary search",
"brute force",
"data structures",
"strings"
] | 1,400
| null |
159
|
D
|
Palindrome pairs
|
You are given a non-empty string $s$ consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.
In a more formal way, you have to find the quantity of tuples $(a, b, x, y)$ such that $1 ≤ a ≤ b < x ≤ y ≤ |s|$ and substrings $s[a... b]$, $s[x... y]$ are palindromes.
A palindrome is a string that can be read the same way from left to right and from right to left. For example, "abacaba", "z", "abba" are palindromes.
A substring $s[i... j]$ ($1 ≤ i ≤ j ≤ |s|$) of string $s$ = $s_{1}s_{2}... s_{|s|}$ is a string $s_{i}s_{i + 1}... s_{j}$. For example, substring $s[2...4]$ of string $s$ = "abacaba" equals "bac".
|
A dp method is really great~ , sum[i] stands for the number of palindrome string in the first i letters. palindrome[i][j] judges weather the substring i...j is a palindrome string. dp[i] is the answer for the first i letters. dp[i] = dp[i-1]+Sum( palindrome[j][i]*sum[j-1] ) for all j<=i && j>0 . sum[i] = sum[i-1]+Sum(palindrome[j][i]) for all j<=i.
|
[
"*special",
"brute force",
"dp",
"strings"
] | 1,500
| null |
159
|
E
|
Zebra Tower
|
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color $c_{i}$ and size $s_{i}$. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower.
A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
|
sort the array with compare condition (cube[i].color < cube[j].color ||(cube[i].color==cube[j].color && cube[i].size>cube[j].size)). Then for the first i cubes , there is a array Max_cube, Max_cube[j] records the max sum of j cubes' size with same color. To the cube i+1, if it's the k-th largest size of its color. Compare the answer with cube[i+1].size + max(Max_cube[k],Max_cube[k+1],Max_cube[k-1]). The time complexity is O(n*logn).
|
[
"*special",
"data structures",
"greedy",
"sortings"
] | 1,700
| null |
160
|
A
|
Twins
|
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, $n$ coins of arbitrary values $a_{1}, a_{2}, ..., a_{n}$. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.
As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is \textbf{strictly larger} than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the \textbf{minimum number of coins}, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what \textbf{minimum} number of coins you need to take to divide them in the described manner.
|
It's obvious that you should take the most valueable coins. so sort values in non-decreasing order, then take coins from the most valueable to the least, until you get strictly more than half of total value. Time complexity depends on the sorting algorithm you use. O(n^2) is also acceptable, but if you use bogosort which runs in O(n!)...
|
[
"greedy",
"sortings"
] | 900
| null |
160
|
B
|
Unlucky Ticket
|
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an \textbf{even} number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.
But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following \underline{unluckiness criterion} that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is \textbf{strictly less} than the corresponding digit from the second one or each digit from the first half is \textbf{strictly more} than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such \underline{bijective correspondence} between the digits of the first and the second half of the ticket, that either each digit of the first half turns out \textbf{strictly less} than the corresponding digit of the second half or each digit of the first half turns out \textbf{strictly more} than the corresponding digit from the second half.
For example, ticket $2421$ meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is $2 > 1$ and $4 > 2$), ticket $0135$ also meets the criterion (the sought correspondence is $0 < 3$ and $1 < 5$), and ticket $3754$ does not meet the criterion.
You have a ticket in your hands, it contains $2n$ digits. Your task is to check whether it meets the unluckiness criterion.
|
Deal with the situation that "first half is strictly less than second half" first. the other one can be solved accordingly. You can use greedy here: sort digits in first and second half seperately. then if the i-th digit in first half is always less than i-th in second half for 1<=i<=n, answer is YES. Time complexity is as same as problem A. Count sort may run faster in O(n+10), but it's not necessary .
|
[
"greedy",
"sortings"
] | 1,100
| null |
160
|
C
|
Find Pair
|
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing $n$ (not necessarily different) integers $a_{1}$, $a_{2}$, ..., $a_{n}$. We are interested in all possible pairs of numbers ($a_{i}$, $a_{j}$), ($1 ≤ i, j ≤ n$). In other words, let's consider all $n^{2}$ pairs of numbers, picked from the given array.
For example, in sequence $a = {3, 1, 5}$ are $9$ pairs of numbers: $(3, 3), (3, 1), (3, 5), (1, 3), (1, 1), (1, 5), (5, 3), (5, 1), (5, 5)$.
Let's sort all resulting pairs lexicographically by non-decreasing. Let us remind you that pair ($p_{1}$, $q_{1}$) is \underline{lexicographically less} than pair ($p_{2}$, $q_{2}$) only if either $p_{1}$ < $p_{2}$, or $p_{1}$ = $p_{2}$ and $q_{1}$ < $q_{2}$.
Then the sequence, mentioned above, will be sorted like that: $(1, 1), (1, 3), (1, 5), (3, 1), (3, 3), (3, 5), (5, 1), (5, 3), (5, 5)$
Let's number all the pair in the sorted list from $1$ to $n^{2}$. Your task is formulated like this: you should find the $k$-th pair in the ordered list of all possible pairs of the array you've been given.
|
This is a tricky problem. When contest ends, I found there are 12 pages of accepted submissions while 60 pages of "WA on pretest 3" submissions. First of all, sort a[]. A natural consideration is that the answer equals to (a[k/n] , a[k%n]). This algorithm will pass the sample and get "WA on pretest 3". In fact, it works only when all a[i] are distinct. To get an AC, let's make elements distinct and weighted. For example, if there are ten 1s, we remain one of them and set its weight as 10. Now go over the whole array. for each element a[i], we can make weight[i]*n pairs using a[i] as first element. If k doesn't exceed that, go over the array again and find the second element, then print the answer. Otherwise, subtract it from K and go on. Sort algorithm working in O(n log n) is acceptable. Java and Pascal users should beware of anti-quicksort tests.
|
[
"implementation",
"math",
"sortings"
] | 1,700
| null |
160
|
D
|
Edges in MST
|
You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's \underline{spanning tree} is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The \underline{weight} of a tree is defined as the sum of weights of the edges that the given tree contains. The \underline{minimum spanning tree} (\textbf{MST}) of a graph is defined as the graph's spanning tree having the minimum possible weight. For any connected graph obviously exists the minimum spanning tree, but in the general case, a graph's minimum spanning tree is not unique.
Your task is to determine the following for each edge of the given graph: whether it is either included in \textbf{any} MST, or included \textbf{at least in one} MST, or \textbf{not included in any} MST.
|
Let's take a look at Kruskal Algorithm which solve MST in O(m log m) time. Sort the edges first in weight non-decreasing order, then process each edges. if the edge connects two different connected compoments, add this edge to MST then combine two compoments. We use disjoint-set union here to maintain connectivity. The main point is that only those edges with same weight may replace each other in MST. First of all, sort edges as what Kruskal do. To get the answer, we construct MST in weight non-decreasing order, and process all edges with same weight together. Now on each step we are to face some edges with same weight x and a forest of connected compoments. Note that for an edge, what points it connects does not matter, we only need to know what compoments it connects. Now build a new graph G', each point in G' is a connected compoment in the original forest,and edges are added to connect compoments that it connected before. Time complexity is O(|E|) here, with careful implementation. Let's answer queries on these edges. First of all, if an edge in G' is a loop(connects the same compoment), this edge must not appear in any MSTs. If after deleting an edge V in G', G's connectivity is changed (A connected compoment in G' spilt into two. We call these edges bridge), V must be in any of MST. All edges left can appear in some MSTs, but not any. What's left is to get all of V quickly. Maybe you hear about Tarjan before, he invented an algorithm based on DFS to get all bridges in an edge-undirected graph in O(|V|+|E|). Read this page on Wikipedia for detailed information: http://en.wikipedia.org/wiki/Bridge_(graph_theory) Considering those compoments which don't have any edges connected don't need to be appear in G', we have |V|<=2|E|, so time complexity for Tarjan's DFS is O(|E|), where |E| is count of edges weighted x. Because each edge will be used exactly once in G', total time complexity except sorting is O(m).
|
[
"dfs and similar",
"dsu",
"graphs",
"sortings"
] | 2,300
| null |
160
|
E
|
Buses and People
|
The main Bertown street is represented by a straight line. There are $10^{9}$ bus stops located on the line. The stops are numbered with integers from $1$ to $10^{9}$ in the order in which they follow on the road. The city has $n$ buses. Every day the $i$-th bus drives from stop number $s_{i}$ to stop number $f_{i}$ ($s_{i} < f_{i}$), it stops on all intermediate stops and returns only at night. The bus starts driving at time $t_{i}$ and drives so fast that it finishes driving also at time $t_{i}$. The time $t_{i}$ is different for all buses. The buses have infinite capacity.
Bertown has $m$ citizens. Today the $i$-th person should get from stop number $l_{i}$ to stop number $r_{i}$ ($l_{i} < r_{i}$); the $i$-th citizen comes to his initial stop ($l_{i}$) at time $b_{i}$. Each person, on the one hand, wants to get to the destination point as quickly as possible, and on the other hand, definitely does not want to change the buses as he rides. More formally: the $i$-th person chooses bus $j$, with minimum time $t_{j}$, such that $s_{j} ≤ l_{i}$, $r_{i} ≤ f_{j}$ and $b_{i} ≤ t_{j}$.
Your task is to determine for each citizen whether he can ride to the destination point today and if he can, find the number of the bus on which the citizen will ride.
|
As what problem setter say, we sort the people and bus together with non-decreasing order of time first(if a bus and a person has same time, put the person first). Solving it by "For each person find which bus he should take" will become rather difficult, so let's take another idea: For each bus, find who it will take. Abstract a person as a element in currently waiting list. Now, go over the sorted people and buses, we should apply two operations: For a person, add it to the list. For a bus, find all person in list satisfying sj \le li, ri \le fj ,remove them from the list and record the answer.(bi \le tj is hold, because we process these operation by time order.) You will find it easy to solve this using any kind of balanced trees, like AVL or SBT. For each node i on balanced tree, we store r[i] as keyword and l[i] as value, then maintain the maxinum l[i] on every subtrees. Operating on a person is to add him to the tree. When dealing with a bus, we find the node i with maxinum l[i] in the range x<=f[j] (x is keyword), if l[i]>=s[j] is satisfied, delete the node i, set ans[i]=j, update the tree and search again until found l[i]<s[j]. If you are not familiar with balanced tree, discretize every r[i] and f[j], then use a segment tree to solve it. Time complexity is O((n+m) log (n+m)) with balanced trees or segment tree.
|
[
"binary search",
"data structures",
"sortings"
] | 2,400
| null |
161
|
A
|
Dress'em in Vests!
|
The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.
The Two-dimensional kingdom has a regular army of $n$ people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the $i$-th soldier indicated size $a_{i}$. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from $a_{i} - x$ to $a_{i} + y$, inclusive (numbers $x, y ≥ 0$ are specified).
The Two-dimensional kingdom has $m$ vests at its disposal, the $j$-th vest's size equals $b_{j}$. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The $i$-th soldier can put on the $j$-th vest, if $a_{i} - x ≤ b_{j} ≤ a_{i} + y$.
|
Consider troopers in the sorted order, as in the input data. One can prove that for the current (minimal) trooper the best choice is the vest with the minimal possible $b_{j}$. So we can solve this problem using "moving pointers" method. The first pointer iterates over troopers and the second one chooses minimal unused vest that $b_{j} - x \ge a_{i}$. The complexity of the solution is $O(n + m)$.
|
[
"binary search",
"brute force",
"greedy",
"two pointers"
] | 1,300
| null |
161
|
B
|
Discounts
|
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a $50%$ discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them!
Polycarpus has $k$ carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible.
Polycarpus must use all $k$ carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
|
This problem can be solved greedy. Let us have $x$ stools. One can prove that it is always correct to arrange $min(k - 1, x)$ maximal stools into $min(k - 1, x)$ carts one by one. All remaining stools and pencils should be put into remaining empty carts. Finally, we have either zero or one empty cart.
|
[
"constructive algorithms",
"greedy",
"sortings"
] | 1,700
| null |
161
|
C
|
Abracadabra
|
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm:
- On the first step the string consists of a single character "a".
- On the $k$-th step Polycarpus concatenates two copies of the string obtained on the $(k - 1)$-th step, while inserting the $k$-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is "a", the 2-nd — "b", ..., the 26-th — "z", the 27-th — "0", the 28-th — "1", ..., the 36-th — "9".
Let's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings "a" and insert the character "b" between them, resulting in "aba" string. The third step will transform it into "abacaba", and the fourth one - into "abacabadabacaba". Thus, the string constructed on the $k$-th step will consist of $2^{k} - 1$ characters.
Polycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus.
A substring $s[i... j]$ ($1 ≤ i ≤ j ≤ |s|$) of string $s$ = $s_{1}s_{2}... s_{|s|}$ is a string $s_{i}s_{i + 1}... s_{j}$. For example, substring $s[2...4]$ of string $s$ = "abacaba" equals "bac". The string is its own substring.
The longest common substring of two strings $s$ and $t$ is the longest string that is a substring of both $s$ and $t$. For example, the longest common substring of "contest" and "systemtesting" is string "test". There can be several common substrings of maximum length.
|
Consider the case when the maximal character in the string is in the answer. Then the answer equals $min(r_{1}, r_{2}) - max(l_{1}, l_{2})$. Otherwise, we cut both strings around this character (here we might get empty strings) and run the algorithm recursively for every pair of strings we get. One can prove that this solutions works in $O(k)$, where $k$ is the values of the maximal character.
|
[
"divide and conquer"
] | 2,400
| null |
161
|
D
|
Distance in Tree
|
A tree is a connected graph that doesn't contain any cycles.
The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.
You are given a tree with $n$ vertices and a positive number $k$. Find the number of distinct pairs of the vertices which have a distance of exactly $k$ between them. Note that pairs ($v$, $u$) and ($u$, $v$) are considered to be the same pair.
|
This problem can be solved using dynamic programming. Let us hang the tree making it rooted. For every vertex $v$ of the tree, let us calculate values $d[v][lev]$ ($0 \le lev \le k$) - the number of vertices in the subtree, having distance $lev$ to them. Note, that $d[v][0] = 0$. Then we calculate the answer. It equals the sum for every vertex $v$ of two values: The number of ways of length $k$, starting in the subtree of $v$ and finishing in $v$. Obviously, it equals $d[v][k]$. The number of ways of length $k$, starting in the subtree of $v$ and finishing in the subtree of $v$. This equals the sum for every son $u$ of $v$ the value: $0.5\cdot\sum_{x=1}^{x=k-1}d[u][x-1](d[v][k-x]-d[u][k-x-1])$. Accumulate the sum for all vertices and get the solution in $O(n \cdot k)$.
|
[
"dfs and similar",
"dp",
"trees"
] | 1,800
| null |
161
|
E
|
Polycarpus the Safecracker
|
Polycarpus has $t$ safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them.
Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote a prime number in each row of each matrix. To his surprise, he found that all the matrices turned out to be symmetrical (that is, they remain the same after transposition). Now, years later, Polycarp was irritated to find out that he remembers only the prime numbers $p_{i}$, written in the first lines of the password matrices.
For each safe find the number of matrices which can be passwords to it.
The number of digits in $p_{i}$ determines the number of rows and columns of the $i$-th matrix. One prime number can occur in several rows of the password matrix or in several matrices. The prime numbers that are written not in the first row of the matrix may have leading zeros.
|
We need to count the number of symmetric matrices with a given first row, where each row is a prime number. Since the matrix is symmetric, it is determined by its cells above or on the main diagonal. Let's examine all possible values of digits above the main diagonal (at most $10^{6}$ cases). Now the values of the remaining unknown digits (on the main diagonal) are independent of each other because of each of them affects exactly one row of the matrix. Therefore, it is enough to count independently the number of possible values for each of the digits on the diagonal, multiply them and add received number to answer. Moreover, it's possible to pre-calculate such numbers for each position of unknown digit and for each collection of known digits. These observations are enough to pass all the tests. One could go further, examining each next digit above the main diagonal only if it's row and column can be extended to prime numbers by some digits, unknown at moment of this digit placing. Such a solution allows to find answers for all possible tests in the allowed time, but it wasn't required.
|
[
"brute force",
"dp"
] | 2,500
| null |
163
|
A
|
Substring and Subsequence
|
One day Polycarpus got hold of two non-empty strings $s$ and $t$, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "$x$ $y$" are there, such that $x$ is a substring of string $s$, $y$ is a subsequence of string $t$, and the content of $x$ and $y$ is the same. Two pairs are considered different, if they contain different substrings of string $s$ or different subsequences of string $t$. Read the whole statement to understand the definition of different substrings and subsequences.
The length of string $s$ is the number of characters in it. If we denote the length of the string $s$ as $|s|$, we can write the string as $s = s_{1}s_{2}... s_{|s|}$.
A substring of $s$ is a non-empty string $x = s[a... b] = s_{a}s_{a + 1}... s_{b}$ ($1 ≤ a ≤ b ≤ |s|$). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings $s[a... b]$ and $s[c... d]$ are considered to be different if $a ≠ c$ or $b ≠ d$. For example, if $s$="codeforces", $s[2...2]$ and $s[6...6]$ are different, though their content is the same.
A subsequence of $s$ is a non-empty string $y = s[p_{1}p_{2}... p_{|y|}] = s_{p1}s_{p2}... s_{p|y|}$ ($1 ≤ p_{1} < p_{2} < ... < p_{|y|} ≤ |s|$). For example, "coders" is a subsequence of "codeforces". Two subsequences $u = s[p_{1}p_{2}... p_{|u|}]$ and $v = s[q_{1}q_{2}... q_{|v|}]$ are considered different if the sequences $p$ and $q$ are different.
|
The problem could be solved with the following dynamic programming. Let $f[i, j]$ be the number of distinct pairs ("substring starting at position $i$" and "subsequence of the substring $t[j... |t|]$") Then: f[i, j] = f[i, j + 1]; if (s[i] == t[j]) add(f[i, j], f[i + 1, j + 1] + 1)Answer = $\textstyle\sum$ f[i,0]
|
[
"dp"
] | 1,700
|
#include <cstdio>
char s[5005], t[5005];
int a[5005][5005], i, j, ans;
#define mod 1000000007
int main(void) {
gets(s);
gets(t);
for (i = 0; s[i]; i++)
for (j = 0; t[j]; j++)
a[i + 1][j + 1] = (a[i + 1][j] + (t[j] == s[i]) * (a[i][j] + 1)) % mod;
for (i = 0; s[i]; i++)
ans = (ans + a[i + 1][j]) % mod;
printf("%d
", ans);
}
|
163
|
B
|
Lemmings
|
As you know, lemmings like jumping. For the next spectacular group jump $n$ lemmings gathered near a high rock with $k$ comfortable ledges on it. The first ledge is situated at the height of $h$ meters, the second one is at the height of $2h$ meters, and so on (the $i$-th ledge is at the height of $i·h$ meters). The lemmings are going to jump at sunset, and there's not much time left.
Each lemming is characterized by its climbing speed of $v_{i}$ meters per minute and its weight $m_{i}$. This means that the $i$-th lemming can climb to the $j$-th ledge in $\frac{{\dot{j}}\cdot J_{b}}{w_{i}}$ minutes.
To make the jump beautiful, heavier lemmings should jump from higher ledges: if a lemming of weight $m_{i}$ jumps from ledge $i$, and a lemming of weight $m_{j}$ jumps from ledge $j$ (for $i < j$), then the inequation $m_{i} ≤ m_{j}$ should be fulfilled.
Since there are $n$ lemmings and only $k$ ledges ($k ≤ n$), the $k$ lemmings that will take part in the jump need to be chosen. The chosen lemmings should be distributed on the ledges from $1$ to $k$, one lemming per ledge. The lemmings are to be arranged in the order of non-decreasing weight with the increasing height of the ledge. In addition, each lemming should have enough time to get to his ledge, that is, the time of his climb should not exceed $t$ minutes. The lemmings climb to their ledges all at the same time and they do not interfere with each other.
Find the way to arrange the lemmings' jump so that time $t$ is minimized.
|
We need to find the minimal time $T$. Let us find it using binary search. Once the time is fixed, one can arrange lemmings using greedy approach starting either from the top or from the bottom. In this solution we consider the way to start from the bottom. Among all lemmings, that can get on the first ledge, let's choose the lemming with the minimal weight (and among all such lemmings the one with the minimal speed). Why is it correct? Assume that we used some heavier lemming, then we can't use any lighter lemming anywhere, so we could replace it. Among all lemmings with the minimal weight we choose the slowest, as the faster ones can climb higher. To arrange lemmings fast, we can sort them beforehand, comparing first the weight and then the speed. After if, we consider all the lemmings in that order and either choose the current one, if it can get in time, or leave it. It is useless to consider one lemming twice, as we won't be able to use it anyway. So, the solution consists of sorting and a binary search with a linear search inside. The time is $O(N\log X)$. However, that was not enough. One also had to deal with precision problems. Let us evaluate the number of binary search iterations. $0 \le T \le H * K$ (the maximal time does not exceed $10^{9}$). We need to understand how the times can differ. In the case of "N = K = $10^{5}$, H = $10^{4}$, V about $10^{9}$" the times needed for two lemmings to get on some ledges, can differ by $10^{ - 18}$, as the times are fractions like $\textstyle{\frac{X}{Y}}$, where $X$ and $Y$ are about $10^{9}$. So we need to make $log_{2}10^{27} = 90$ iterations. In fact, jury solution made 75 and that was enough, however 70 was not. The idea above shows that 90 will be definitely enough.
|
[
"binary search"
] | 2,000
|
/**
* Author: Sergey Kopeliovich (Burunduk30@gmail.com)
* Date: 2012.03.24
*/
#include <cstdio>
#include <cassert>
#include <algorithm>
using namespace std;
#define forn(i, n) for (int i = 0; i < (int)(n); i++)
const int maxN = (int)1e5;
int N, K, H, m[maxN], v[maxN], p[maxN], o[maxN];
inline bool mless( int i, int j )
{
#define F(x) make_pair(m[x], v[x])
return F(i) < F(j);
}
int solve( double t )
{
int x = 1;
forn(i, N)
if (v[p[i]] * t >= (double)x * H)
o[x++ - 1] = p[i];
return x > K;
}
int main()
{
scanf("%d%d%d", &N, &K, &H);
forn(i, N)
scanf("%d", &m[i]);
forn(i, N)
scanf("%d", &v[i]);
forn(i, N)
p[i] = i;
sort(p, p + N, mless);
double mi = 0, ma = (double)H * K, t;
forn(tt, 100)
if (solve(t = (mi + ma) / 2))
ma = t;
else
mi = t;
assert(solve(ma));
//printf("%.9f
", mi);
forn(i, K)
printf("%d ", o[i] + 1);
return 0;
}
|
163
|
C
|
Conveyor
|
Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.
The conveyor is a looped belt with a total length of $2l$ meters, of which $l$ meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short.
The belt is moving uniformly at speed $v_{1}$ meters per second. Anton will be moving on it in the same direction at the constant speed of $v_{2}$ meters per second, so his speed relatively to the floor will be $v_{1} + v_{2}$ meters per second. Anton will neither stop nor change the speed or the direction of movement.
Here and there there are chocolates stuck to the belt ($n$ chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it.
\begin{center}
{\scriptsize The figure shows an example with two chocolates. One is located in the position $a_{1} = l - d$, and is now on the top half of the belt, the second one is in the position $a_{2} = 2l - d$, and is now on the bottom half of the belt.}
\end{center}
You are given the positions of the chocolates relative to the initial start position of the belt $0 ≤ a_{1} < a_{2} < ... < a_{n} < 2l$. The positions on the belt from $0$ to $l$ correspond to the top, and from $l$ to $2l$ — to the the bottom half of the belt (see example). All coordinates are given in meters.
Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each $i$ from $0$ to $n$ calculate the probability that Anton will pick up exactly $i$ chocolates.
|
Wherever Anton starts, he will run along the conveyor a segment of length $D={\frac{v_{1}x t}{v_{1}+v_{2}}}$. Consider one candy. To eat it, he needs to get on the conveyor in any moment of the segment $[a_{i} - D..a_{i}]$. Consider all points like $a_{i} - D$ and $a_{i}$ (add $2l$ if that is negative). Also add points $0$ and $2l$. Sort these points. Consider two neighboring points: x[i] and x[i+1]. If Anton starts at any moment between them, he will eat the same amount of candies. From now on, we can create one of the solving solutions: Start from every middle of the segment M = (x[i]+x[i+1]) / 2 and use binary search to find the number of candies on the segment $[M..M + D]$. Consider events along a circle like (a[i] - D, +1) and (a[i], -1). One needs to move twice along the circle and use the second run to add the current length to the answer for the current number of candies. The both solutions require $O(N\log N)$ time.
|
[
"sortings",
"two pointers"
] | 2,100
|
/**
* Author: Sergey Kopeliovich (Burunduk30@gmail.com)
* Date: 2012.03.25
*/
#include <cstdio>
#include <cassert>
#include <algorithm>
using namespace std;
#define forn(i, n) for (int i = 0; i < (int)(n); i++)
typedef double dbl;
const int maxN = (int)1e5 + 3;
int dn, n, l, v1, v2;
dbl a[maxN * 2];
dbl dist, d[2 * maxN], p[maxN];
dbl cor( dbl x )
{
return x < 0 ? x + 2 * l : x;
}
int k( dbl L )
{
return lower_bound(a, a + 2 * n, L + dist) - lower_bound(a, a + n, L);
}
int main()
{
scanf("%d%d%d%d", &n, &l, &v1, &v2);
forn(i, n)
scanf("%lf", &a[i]);
sort(a, a + n);
forn(i, n)
a[i + n] = a[i] + 2 * l;
dist = (dbl)v2 * l / (v1 + v2);
d[dn++] = 0, d[dn++] = 2 * l;
forn(i, n)
d[dn++] = a[i], d[dn++] = cor(a[i] - dist);
sort(d, d + dn);
forn(i, dn - 1)
p[k((d[i] + d[i + 1]) / 2)] += d[i + 1] - d[i];
forn(i, n + 1)
printf("%.20f
", (double)p[i] / (2 * l));
return 0;
}
|
163
|
D
|
Large Refrigerator
|
Vasya wants to buy a new refrigerator. He believes that a refrigerator should be a rectangular parallelepiped with integer edge lengths. Vasya calculated that for daily use he will need a refrigerator with volume of at least $V$. Moreover, Vasya is a minimalist by nature, so the volume should be no more than $V$, either — why take up extra space in the apartment? Having made up his mind about the volume of the refrigerator, Vasya faced a new challenge — for a fixed volume of $V$ the refrigerator must have the minimum surface area so that it is easier to clean.
The volume and the surface area of a refrigerator with edges $a$, $b$, $c$ are equal to $V = abc$ and $S = 2(ab + bc + ca)$, correspondingly.
Given the volume $V$, help Vasya find the integer lengths for the refrigerator's edges $a$, $b$, $c$ so that the refrigerator's volume equals $V$ and its surface area $S$ is minimized.
|
The solution consists of three main ideas: $V = ABC$, $A \le B \le C$ then $A \le N^{1 / 3}, B \le (N / A)^{1 / 2}$. $A$ and $B$ are divisors of $V$, as we are already given the factorization of $V$, we can run only through the divisors Given fixed $A$, the optimal real $B$ and $C$ are $(N / A)^{1 / 2}$ (denote this values as $X$). I.e. the square will always be greater than $ \ge 2(2AX + X^{2})$. So we can use this value as a boundary for the answer. If that still was not enough, one could optimize using the following ideas: Border evaluation will be more useful while running through possible values of $A$ in descending order $A$ and $B$ are 32-bit integers. Once we have calculated the answer for $V$, memoize it (this one makes possible maximal test a bit smaller). If anyone needs any theoretical base, here's some statistical information: The maximal number of divisors of numbers from 1 through $10^{18}$ is 103860 (the number 897612484786617600 = $2^{8}3^{4}5^{2}7^{2}11$ ...) Using only first two optimizations, the number of numbers $A$, found by our solution, is $10 471$ (in the case of the number with maximal number of divisors) Using only first two optimizations, the number of pairs of $A$ and $B$, found by our solution, is $128 264$ (in the case of the number with maximal number of divisors)
|
[
"brute force"
] | 2,900
|
/**
* Author: Sergey Kopeliovich (Burunduk30@gmail.com)
* Date: 2012.03.22
*/
#include <ctime>
#include <cmath>
#include <cstdio>
#include <cassert>
#include <map>
using namespace std;
#ifdef _WIN32
# define I64 "%I64d"
#else
# define I64 "%Ld"
#endif
#define forn(i, n) for (int i = 0; i < (int)(n); i++)
#define fornd(i, n) for (int i = (int)(n) - 1; i >= 0; i--)
#define mp make_pair
typedef long long ll;
typedef pair <ll, ll> pll;
double start = clock();
void TimeStamp()
{
fprintf(stderr, "time = %.2f
", (clock() - start) / CLOCKS_PER_SEC);
start = clock();
}
const int maxP = 15;
int pn, mdeg[maxP], s[maxP];
int rn, rs[maxP];
map <ll, pair<pll, pll> > mem;
ll N1, N, C, rS, rA, rB, rC, p[maxP];
int A, B, num;
void go( int restx, int x, int i, int f )
{
if (i == pn || restx < p[i])
{
if (!f)
{
A = x;
N1 = N / A;
long double B = sqrtl(N1);
if (2 * A * B + N1 < rS)
{
forn(i, pn) mdeg[i] -= s[i];
go((ll)sqrt(N1) + 1, 1, 0, 1);
forn(i, pn) mdeg[i] += s[i];
}
}
else
{
B = x, C = N1 / B;
ll curS = (ll)A * (B + C) + N1;
if (curS < rS)
rS = curS, rA = A, rB = B, rC = C;
}
return;
}
int m = 0, _restx[64], _x[64];
while (restx >= 1 && m <= mdeg[i])
{
_restx[m] = restx, _x[m++] = x;
restx /= p[i], x *= p[i];
}
fornd(j, m)
{
if (!f)
s[i] = j;
go(_restx[j], _x[j], i + 1, f);
}
}
int main()
{
#ifdef DEBUG
double tmp_start = clock();
fprintf(stderr, "Start
");
#endif
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d", &pn);
assert(pn <= maxP);
forn(i, pn)
scanf(I64"%d", &p[i], &mdeg[i]);
N = 1, num = 1;
forn(i, pn)
{
forn(j, mdeg[i])
N *= p[i];
num *= mdeg[i] + 1;
}
forn(i, pn)
forn(j, pn - 1)
if (p[j] > p[j + 1])
swap(p[j], p[j + 1]), swap(mdeg[j], mdeg[j + 1]);
if (mem.count(N))
{
pair<pll, pll> p = mem[N];
rS = p.first.first;
rA = p.first.second;
rB = p.second.first;
rC = p.second.second;
}
else
{
rS = 3 * N + 1;
go((ll)pow(N, 1.0 / 3) + 1, 1, 0, 0);
mem[N] = mp(mp(rS, rA), mp(rB, rC));
}
printf(I64" "I64" "I64" "I64"
", 2 * rS, rA, rB, rC);
}
#ifdef DEBUG
fprintf(stderr, "Total time = %.2f
", (clock() - tmp_start) / CLOCKS_PER_SEC);
#endif
return 0;
}
|
163
|
E
|
e-Government
|
The best programmers of Embezzland compete to develop a part of the project called "e-Government" — the system of automated statistic collecting and press analysis.
We know that any of the $k$ citizens can become a member of the Embezzland government. The citizens' surnames are $a_{1}, a_{2}, ..., a_{k}$. All surnames are different. Initially all $k$ citizens from this list are members of the government. The system should support the following options:
- Include citizen $a_{i}$ to the government.
- Exclude citizen $a_{i}$ from the government.
- Given a newspaper article text, calculate how politicized it is. To do this, for every active government member the system counts the number of times his surname occurs in the text as a substring. All occurrences are taken into consideration, including the intersecting ones. The degree of politicization of a text is defined as the sum of these values for all active government members.
Implement this system.
|
We assume that the reader is familiar with the Aho-Corasick algorithm (http://en.wikipedia.org/wiki/Aho-Corasick) Consider a trie of names and suffix links over it. For every vertex $v$ one can calculate the number of names, ending in that vertex ($end[v]$). Then, the "add name $i$" operation is $end[v[i]]$ += 1, where $v[i]$ is ending vertex of $i$-th name. Similarly, "remove name $i$": $end[v[i]]$ -= 1. To answer a request "calculate how politicized the text is", one needs to know, that the suffix links form a tree. Once we move though the text and simultaneously through the trie with suffix links, we add the sum of all $end[v[i]]$ along the path to the root of the tree of suffix links the politicization of the text. Now, there's another problem: we need to calculate the sum of weights along a way to the root, the weights may change. One can do it in the following way: Move the weights from vertices to corresponding edges to vertices' parents Build the Eulerian traversal of the tree, where the down-move will store positive weight of the edge and up-move will store its negation. The sum along a path to the root if the sum on a segment of the Eulerian traversal (the endpoints are any entries of the vertices in the traversal). A fast and short way to calculate the sum on a segment is Fenwick's tree. Here's a solution running in O(|SumLen| * log) time and 26 * |SumLen| memory (the trie will not be compressed).
|
[
"data structures",
"dfs and similar",
"dp",
"strings",
"trees"
] | 2,800
|
#include <cstdio>
#include <cassert>
#include <vector>
using namespace std;
struct node {
int ne[26], suff;
vector <int> rsuff;
int a, b, cur, was;
};
#define maxn 1000100
int fen[maxn * 2], fen_n;
int f_get (int i) {
int res = 0;
while (i >= 0) {
res += fen[i];
i = (i & (i + 1)) - 1;
}
return res;
}
void f_add (int i, int d) {
while (i < fen_n) {
fen[i] += d;
i |= i + 1;
}
}
node arr[maxn];
int arr_n = 0;
node *add (char *s) {
node *v = &arr[0];
while (*s) {
int c = *s++ - 'a';
if (!v->ne[c]) {
v->ne[c] = ++arr_n;
}
v = &arr[v->ne[c]];
}
return v;
}
void fix (node *v, int d) {
if (d == -1 && v->cur == 1 || d == +1 && v->cur == 0) {
f_add (v->a, +d);
f_add (v->b, -d);
v->cur += d;
}
}
int q[maxn], ql, qr;
void aho() {
for (int i = 0; i < 26; i++) {
if (arr[0].ne[i]) {
int x = arr[0].ne[i];
q[qr++] = x;
}
}
while (ql < qr) {
int id = q[ql++];
node *v = &arr[id];
arr[v->suff].rsuff.push_back(id);
for (int i = 0; i < 26; i++) {
int x = arr[v->suff].ne[i];
if (v->ne[i]) {
arr[v->ne[i]].suff = x;
q[qr++] = v->ne[i];
} else {
v->ne[i] = x;
}
}
}
}
char buf[maxn];
void dfs (node *v) {
v->was = 1;
v->a = fen_n++;
for (int i = 0; i < (int)v->rsuff.size(); i++) {
dfs (&arr[v->rsuff[i]]);
}
v->b = fen_n++;
}
node *words[maxn];
int main (void) {
int qn, wn;
scanf ("%d%d", &qn, &wn);
for (int i = 1; i <= wn; i++) {
scanf ("%s", buf);
words[i] = add (buf);
}
aho();
for (int i = 0; i < arr_n; i++) {
if (!arr[i].was) {
dfs (&arr[i]);
}
}
for (int i = 1; i <= wn; i++) {
fix (words[i], +1);
}
for (int i = 0; i < qn; i++) {
char c;
while ((c = getc(stdin)) == ' ' || c == '
');
if (c == '+') {
int x;
scanf ("%d", &x);
fix (words[x], +1);
} else if (c == '-') {
int x;
scanf ("%d", &x);
fix (words[x], -1);
} else {
scanf ("%s", buf);
char *s = buf;
long long res = 0;
node *v = &arr[0];
while (*s) {
v = &arr[v->ne[*s - 'a']];
res += f_get (v->a);
s++;
}
printf ("%I64d
", res);
}
}
return 0;
}
|
165
|
A
|
Supercentral Point
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$. Let's define neighbors for some fixed point from the given set $(x, y)$:
- point $(x', y')$ is $(x, y)$'s right neighbor, if $x' > x$ and $y' = y$
- point $(x', y')$ is $(x, y)$'s left neighbor, if $x' < x$ and $y' = y$
- point $(x', y')$ is $(x, y)$'s lower neighbor, if $x' = x$ and $y' < y$
- point $(x', y')$ is $(x, y)$'s upper neighbor, if $x' = x$ and $y' > y$
We'll consider point $(x, y)$ from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
|
In this problem you should just code what was written in the problem. For every point you can check if it is supercentral. Consider every point consecutively and find neighbors from every side. The complexity is $O(N^{2})$.
|
[
"implementation"
] | 1,000
| null |
165
|
B
|
Burning Midnight Oil
|
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of $n$ lines of code. Vasya is already exhausted, so he works like that: first he writes $v$ lines of code, drinks a cup of tea, then he writes as much as $\left\lfloor{\frac{v}{k}}\right\rfloor$ lines, drinks another cup of tea, then he writes $\textstyle{\left|{\frac{v}{k^{2}}}\right|}$ lines and so on: $\textstyle{\left|{\frac{v}{k^{3}}}\right|}$, $\textstyle{\left|{\frac{v}{k^{4}}}\right|}$, $\textstyle\left|{\frac{v}{k^{5}}}\right|$, ...
The expression $\left\lfloor{\frac{\Omega}{b}}\right\rfloor$ is regarded as the integral part from dividing number $a$ by number $b$.
The moment the current value $\left\lfloor{\frac{v}{k^{p}}}\right\rfloor$ equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.
Vasya is wondering, what minimum allowable value $v$ can take to let him write \textbf{not less} than $n$ lines of code before he falls asleep.
|
This problem can be solved using binary search for the answer. obviously, if number $v$ is an answer than every number $w > v$ is also the answer, because the number of written lines of code could only become more. To check some number $v$ you can use formula given in the problem, because it will have less than $O(logN)$ positive elements. The complexity is $O(log^{2}(N))$.
|
[
"binary search",
"implementation"
] | 1,500
| null |
165
|
C
|
Another Problem on Strings
|
A string is \underline{binary}, if it consists only of characters "0" and "1".
String $v$ is a substring of string $w$ if it has a non-zero length and can be read starting from some position in string $w$. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string $s$. Your task is to find the number of its substrings, containing exactly $k$ characters "1".
|
You was to find number of segments $[lf;rg]$ of the strings on which the sum equals to $k$ (we are working with array of integers $0$ and $1$). We will count array $sum$ where the value $sum[i]$ equals to sum on segment $[0;i]$. We will count the answer going from left to right. Let's say we are in position $pos$. Now we will add the number of segments on which the sum equals to $k$ and ends in position $pos$. To do it we will count array $cnt$ where $cnt[i]$ - number of occurrences of $sum[i]$. Then in position $pos$ we add $cnt[sum[pos] - k]$ to the answer. The complexity is $O(N$).
|
[
"binary search",
"brute force",
"dp",
"math",
"strings",
"two pointers"
] | 1,600
| null |
165
|
D
|
Beard Graph
|
Let's define a non-oriented connected graph of $n$ vertices and $n - 1$ edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it.
Let each edge be either black or white. Initially all edges are black.
You are given the description of the beard graph. Your task is to analyze requests of the following types:
- paint the edge number $i$ black. The edge number $i$ is the edge that has this number in the description. It is guaranteed that by the moment of this request the $i$-th edge is white
- paint the edge number $i$ white. It is guaranteed that by the moment of this request the $i$-th edge is black
- find the length of the shortest path going \textbf{only along the black edges} between vertices $a$ and $b$ or indicate that no such path exists between them (a path's length is the number of edges in it)
The vertices are numbered with integers from $1$ to $n$, and the edges are numbered with integers from $1$ to $n - 1$.
|
Beard-graph is a tree. It consists of one root and several paths from this root. There is a single path between every pair of vertices. That's why you should check whether every edge on the path between two vertices is black. If some edge is white there is no path between two vertices now. The distances could be found separately. For every vertex $v$ precalc such information: index of path from the root where $v$ is situated and $d[v]$ distance between root and $v$. If you know such information you can find distance between any two vertices. To check whether every edge on the path between two vertices is black we will use segment tree. Mark black edge with value $0$ and white with $1$. Than repainting some edge - update in some point. The query - sum on some segment (the path between two vertices). If the sum equals to $0$ there is a single path. Else the answer is -1 now. Complexity is $O(NlogN)$.
|
[
"data structures",
"dsu",
"trees"
] | 2,100
| null |
165
|
E
|
Compatible Numbers
|
Two integers $x$ and $y$ are \underline{compatible}, if the result of their bitwise "AND" equals zero, that is, $a$ $&$ $b = 0$. For example, numbers $90$ $(1011010_{2})$ and $36$ $(100100_{2})$ are compatible, as $1011010_{2}$ $&$ $100100_{2} = 0_{2}$, and numbers $3$ $(11_{2})$ and $6$ $(110_{2})$ are not compatible, as $11_{2}$ $&$ $110_{2} = 10_{2}$.
You are given an array of integers $a_{1}, a_{2}, ..., a_{n}$. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.
|
Consider some number $x$ from the array. Inverse all bits in $x$ and say it is number $y$. Consider an integer $a[i]$ from array. It can be an answer to the number $x$ if for every position of zero bit from $y$ there is zero bit in $a[i]$ in the same position. Other bits in $a[i]$ we can change to ones. Then we will use such dynamic programming $z[mask] = {0, 1}$ which means if we can change some zero bits to ones in some integer from given array $a$ and get mask $mask$. Initial states are all integers from array $a$ ($z[a[i]] = 1$). To go from one state to another we consider every bit in $mask$ and try to change it to one. The length of bit representation of all integers in $a$ is less or equal than 22. To answer the question YES or NO for some number $x$ you need to get value $[z(y)&(1<<22) - 1]$ (inverse all bits in $x$ and make the length of the number 22). If you want to know the exact answer what number $a[i]$ you should choose you can save previous states for every state $z[mask]$ or just save it in $z[mask]$. Complexity $O(2^{K} * K)$, where $K$ - length of bit representation of numbers ($K < = 22$).
|
[
"bitmasks",
"brute force",
"dfs and similar",
"dp"
] | 2,200
| null |
166
|
A
|
Rank List
|
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.
You know the rules of comparing the results of two given teams very well. Let's say that team $a$ solved $p_{a}$ problems with total penalty time $t_{a}$ and team $b$ solved $p_{b}$ problems with total penalty time $t_{b}$. Team $a$ gets a higher place than team $b$ in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team $a$ gets a higher place than team $b$ in the final results' table if either $p_{a} > p_{b}$, or $p_{a} = p_{b}$ and $t_{a} < t_{b}$.
It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of $x$ teams that solved the same number of problems with the same penalty time. Let's also say that $y$ teams performed better than the teams from this group. In this case all teams from the group share places $y + 1$, $y + 2$, $...$, $y + x$. The teams that performed worse than the teams from this group, get their places in the results table starting from the $y + x + 1$-th place.
Your task is to count what number of teams from the given list shared the $k$-th place.
|
This is simple straight-forward problem - you were asked to sort the teams with the following comparator: ($p_{1} > p_{2}$) or ($p_{1} = p_{2}$ and $t_{1} < t_{2}$). After that you can split the teams into groups with equal results and find the group which shares the $k$-th place. Many coders for some reason used wrong comparator: they sorted teams with equal number of problems by descending of time. Such submits accidentally passed pretests but get WA #13.
|
[
"binary search",
"implementation",
"sortings"
] | 1,100
| null |
166
|
B
|
Polygons
|
You've got another geometrical task. You are given two non-degenerate polygons $A$ and $B$ as vertex coordinates. Polygon $A$ is strictly convex. Polygon $B$ is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three consecutively following vertices are located on the same straight line.
Your task is to check whether polygon $B$ is positioned strictly inside polygon $A$. It means that any point of polygon $B$ should be strictly inside polygon $A$. "Strictly" means that the vertex of polygon $B$ cannot lie on the side of the polygon $A$.
|
Polygon A is convex, so it is sufficient to check only that every vertex of polygon B is strictly inside polygon A. In theory the simplest solution is building common convex hull of both polygons. You need to check that no vertex of polygon B belongs to this hull. But there is a tricky detail: if there are many points lying on the same side of convex hull than your convex hull must contain all these points as vertices. So this solution is harder to implement and has some corner case. Another solution: cut polygon A into triangles (by vertex numbers): $(1, 2, 3), (1, 3, 4), (1, 4, 5), ..., (1, n - 1, n)$. The sequences of angles $2 - 1 - 3, 2 - 1 - 4, 2 - 1 - 5, ..., 2 - 1 - n$ is increasing. It means that you can find for each vertex of B to which triangle of A it can belong using binsearch by angle. Similarly you can cut polygon A into trapezoids (with vertical cuts). In this case you'll need a binsearch by $x$-coordinate.
|
[
"geometry",
"sortings"
] | 2,100
| null |
166
|
C
|
Median
|
A median in an array with the length of $n$ is an element which occupies position number $\textstyle{\left|{\frac{n+1}{2}}\right\rfloor}$ after we sort the elements in the non-decreasing order (the array elements are numbered starting with $1$). A median of an array $(2, 6, 1, 2, 3)$ is the number $2$, and a median of array $(0, 96, 17, 23)$ — the number $17$.
We define an expression $\left\lfloor{\frac{\Omega}{b}}\right\rfloor$ as the integer part of dividing number $a$ by number $b$.
One day Vasya showed Petya an array consisting of $n$ integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals $x$. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to $x$.
Petya can add any integers from $1$ to $10^{5}$ to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array.
While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.
|
If the initial array doesn't contain number $x$, than you definitely need to add it (that's +1 to answer). Than do the following. While median is strictly less than $x$ you need to increase it. Obviously the surest way to increase the median is to add a maximal possible number ($10^{5}$). Similarly while the median is strictly more than $x$, add a number $1$ to the array. Constraints are small, so you can add the numbers one by one and recalculate the median after every addition. Also there is a solution without any cases: while the median isn't equal to $x$, just add one more number $x$ to array.
|
[
"greedy",
"math",
"sortings"
] | 1,500
| null |
166
|
D
|
Shoe Store
|
The warehouse in your shop has $n$ shoe pairs. Each pair is characterized by two integers: its price $c_{i}$ and its size $s_{i}$. We know that on this very day all numbers $s_{i}$ are different, that is, there is no more than one pair of each size.
The shop has $m$ customers who came at the same time. The customer number $i$ has $d_{i}$ money and the size of his feet equals $l_{i}$. The customer number $i$ can buy the pair number $j$, if $c_{j} ≤ d_{i}$, and also if $l_{i} = s_{j}$ or $l_{i} = s_{j} - 1$; that is, it is necessary that he has enough money to pay for the shoes. It is also necessary that the size of his feet equals to or is less by $1$ than the size of the shoes he chooses.
Your task is to sell some customers pairs of shoes (a pair per person) so as to maximize the sum of the sold pairs $c_{j}$ that is, the profit. It is guaranteed that each customer buys no more than one pair and each pair will be bought by no more than one customer.
|
Let's sort the people by decreasing of shoes size. Observe that when considering the $i$-th man we are interested in no more than 2 pairs of shoes: with size $l_{i}$ and $l_{i} + 1$. It allows solving with dynamics. The state will be (the number of first unconsidered man $i$, is pair of shoes with size $l_{i}$ available, is pair of shoes with size $l_{i}$ + 1 available). You have 3 options: leave the $i$-th man without shoes or sell him a pair of shoes of one of suitable size (if available).
|
[
"dp",
"graph matchings",
"greedy",
"sortings",
"two pointers"
] | 2,500
| null |
166
|
E
|
Tetrahedron
|
You are given a tetrahedron. Let's mark its vertices with letters $A$, $B$, $C$ and $D$ correspondingly.
An ant is standing in the vertex $D$ of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex $D$ to itself in exactly $n$ steps. In other words, you are asked to find out the number of different cyclic paths with the length of $n$ from vertex $D$ to itself. As the number can be quite large, you should print it modulo $1000000007$ ($10^{9} + 7$).
|
Obvious solution with dynamics: you need to know only how many moves are left and where is the ant. This is $4n$ states, each with 3 options - most of such solution passes. Observe that the vertices A, B, C are equivalent. This allows writing such solution: int zD = 1; int zABC = 0; for (int i = 1; i <= n; i++) { int nzD = zABC * 3LL % MOD; int nzABC = (zABC * 2LL + zD) % MOD; zD = nzD; zABC = nzABC; } cout << zD;Also this problem could be solved by $log(n)$ with binary exponentiation of some $2 \times 2$ matrix into power $n$.
|
[
"dp",
"math",
"matrices"
] | 1,500
| null |
167
|
A
|
Wizards and Trolleybuses
|
In some country live wizards. They love to ride trolleybuses.
A city in this country has a trolleybus depot with $n$ trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of $d$ meters from the depot. We know for the $i$-th trolleybus that it leaves at the moment of time $t_{i}$ seconds, can go at a speed of no greater than $v_{i}$ meters per second, and accelerate with an acceleration no greater than $a$ meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.
Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.
You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.
|
This was the first problem where you had a little bit away from translating statements to a programming language. Because acceleration trolleybuses are all the same and they can slow down immediately, the answer for the next trolleybus is the maximum of the time when it would come if it were not to stop when he reach the rest trolleybuses which was traveling in front of him and the arrival time of the previous trolleybus. It remains only to calculate the arrival time of each trolleybus if ignore others. Here, the easiest way to analyze two cases. If $d>{\frac{w^{2}}{2a}}$, then trolley should accelerate as long as it can and the answer is equal to $\scriptstyle{\frac{1}{a}}+{\frac{d-{\frac{a^{2}}{b_{a}}}}{v}}$. Otherwise the trolley should accelerate all the time and the answer is equal to $\sqrt{\frac{2\,d}{a}}$.
|
[
"implementation",
"math"
] | 1,600
| null |
167
|
B
|
Wizards and Huge Prize
|
One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees.
One of such magic schools consists of $n$ tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've brought with you have space for no more than $k$ huge prizes.
Besides the fact that you want to take all the prizes home, you also want to perform well. You will consider your performance good if you win at least $l$ tours.
In fact, years of organizing contests proved to the organizers that transporting huge prizes is an issue for the participants. Alas, no one has ever invented a spell that would shrink the prizes... So, here's the solution: for some tours the winner gets a bag instead of a huge prize. Each bag is characterized by number $a_{i}$ — the number of huge prizes that will fit into it.
You already know the subject of all tours, so you can estimate the probability $p_{i}$ of winning the $i$-th tour. You cannot skip the tour under any circumstances.
Find the probability that you will perform well on the contest and will be able to take all won prizes home (that is, that you will be able to fit all the huge prizes that you won into the bags that you either won or brought from home).
|
This problem can be solved using dynamic programming. Let d[i][j][m] - the probability we won j of first i days and get bags total capacity of m. For convenience, we assume that the bag is also a prize and the prize is a bag of capacity 0. To do that, retaining a task we must add 1 to all a[i]. Then from d[i][j][m] we can go to the d[i+1][j+1][m+a[i]] with probability p[i]/100, and to d[i+1][j][m] with probability 1-p[i]/100. The answer will be the sum of d[n+1][j][m] for all j,m such that $L \le j \le m + k$. This solution works for $200^{4}$, and do not fit into the time limit. It remains to note that if we have over 200 places for prizes, it does not matter how many exactly. So we need to calculate states with $m \le 200$ and now solution works for $200^{3}$.
|
[
"dp",
"math",
"probabilities"
] | 1,800
| null |
167
|
C
|
Wizards and Numbers
|
In some country live wizards. They love playing with numbers.
The blackboard has two numbers written on it — $a$ and $b$. The order of the numbers is not important. Let's consider $a ≤ b$ for the sake of definiteness. The players can cast one of the two spells in turns:
- Replace $b$ with $b - a^{k}$. Number $k$ can be chosen by the player, considering the limitations that $k > 0$ and $b - a^{k} ≥ 0$. Number $k$ is chosen independently each time an active player casts a spell.
- Replace $b$ with $b mod a$.
If $a > b$, similar moves are possible.
If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.
To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.
|
Consider the position (a, b). Let a < b. From this there is a move to $(b{\mathrm{~mod~}}a,a)$. Recursively check if this position is a winning or a losing. If it is losing, then (a, b) exactly winning. Otherwise, no one will take the remainder. So everyone will subtract from larger number nonnegative degree of smaller. Then the left to learn to solve such problem. You can subtract the nonnegative powers of a from x, and player who cannot move losses. And solve it for $x=\left\lfloor{\frac{b}{a}}\right\rfloor-1$. This problem can be solved as follows. If a is odd, then all odd number are wining. In other all the numbers, giving an odd residue modulo a+1 or -1 residue on the same module are wining. This can be easily proved by induction.
|
[
"games",
"math"
] | 2,300
| null |
167
|
D
|
Wizards and Roads
|
In some country live wizards. They love to build cities and roads.
The country used to have $k$ cities, the $j$-th city ($1 ≤ j ≤ k$) was located at a point ($x_{j}$, $y_{j}$). It was decided to create another $n - k$ cities. And the $i$-th one ($k < i ≤ n$) was created at a point with coordinates ($x_{i}$, $y_{i}$):
- $x_{i} = (a·x_{i - 1} + b) mod (10^{9} + 9)$
- $y_{i} = (c·y_{i - 1} + d) mod (10^{9} + 9)$
Here $a$, $b$, $c$, $d$ are primes. Also, $a ≠ c, b ≠ d$.
After the construction of all $n$ cities, the wizards have noticed something surprising. It turned out that for every two different cities $i$ and $j$, $x_{i} ≠ x_{j}$ and $y_{i} ≠ y_{j}$ holds.
The cities are built, it's time to build roads! It was decided to use the most difficult (and, of course, the most powerful) spell for the construction of roads. Using this spell creates a road between the towns of $u$, $v$ ($y_{u}$ > $y_{v}$) if and only if for any city $w$ which lies strictly inside the corner at the point $u$, $v$ (see below), there is a city $s$ that does not lie in the corner, which is located along the $x$-coordinate strictly between $w$ and $u$ and simultaneously $y_{s} > y_{v}$.
A corner on the points $p_{2}$($x_{2}$, $y_{2}$), $p_{1}$($x_{1}$, $y_{1}$) ($y_{1} < y_{2}$) is the set of points ($x, y$), for which at least one of the two conditions is fulfilled:
- $min(x_{1}, x_{2}) ≤ x ≤ max(x_{1}, x_{2})$ and $y ≥ y_{1}$
- $y_{1} ≤ y ≤ y_{2}$ and $(x - x_{2})·(x_{1} - x_{2}) ≥ 0$
\begin{center}
{\scriptsize The pictures showing two different corners}
\end{center}
In order to test the spell, the wizards will apply it to all the cities that lie on the $x$-coordinate in the interval $[L, R]$. After the construction of roads the national government wants to choose the maximum number of pairs of cities connected by the road, so that no city occurs in two or more pairs. Your task is for each $m$ offered variants of values $L$, $R$ to calculate the maximum number of such pairs after the construction of the roads. Please note that the cities that do not lie in the interval $[L, R]$ on the $x$-coordinate, do not affect the construction of roads in any way.
|
This was the first really hard problem in the contest. One of the challenges was to understand the statement. I hope that we had written the statement as clear as it possible in this problem. Consider this graph. In particular, we consider more closely the point with the largest y. 1) It is connected with the highest points on the left and right of it. 2) It is not connected to all other points. 3) It is inside all corners on points from different sides of it. All three of these properties are seen quite clearly in the pictures. So, 1) Building roads on the left and right sides are independent. 2) The graph is a tree. Once a graph is a tree, the maximum matching in it can be found greedy, or with a simple dynamic. But it works in linear time, which clearly is not enough to answer all of $10^{5}$ queries. But this is not just a tree! Those who know what it is probably already noticed, that it is Cartesian tree (also known as treep). This allows to get a tree for the subsegments in time which is $O(h)$, counting all the necessary dynamics, where h is the height of the tree. Well, since the city built at random points (the method for the construction of cities guarantees this), the height of the tree $h = O(K + logN)$.
|
[
"data structures",
"divide and conquer",
"graph matchings",
"graphs",
"greedy"
] | 3,000
| null |
167
|
E
|
Wizards and Bets
|
In some country live wizards. They like to make weird bets.
Two wizards draw an acyclic directed graph with $n$ vertices and $m$ edges (the graph's vertices are numbered from $1$ to $n$). A source is a vertex with no incoming edges, and a sink is the vertex with no outgoing edges. Note that a vertex could be the sink and the source simultaneously. In the wizards' graph the number of the sinks and the sources is the same.
Wizards numbered the sources in the order of increasing numbers of the vertices from $1$ to $k$. The sinks are numbered from $1$ to $k$ in the similar way.
To make a bet, they, as are real wizards, cast a spell, which selects a set of $k$ paths from all sources to the sinks in such a way that no two paths intersect at the vertices. In this case, each sink has exactly one path going to it from exactly one source. Let's suppose that the $i$-th sink has a path going to it from the $a_{i}$'s source. Then let's call pair $(i, j)$ an inversion if $i < j$ and $a_{i} > a_{j}$. If the number of inversions among all possible pairs $(i, j)$, such that $(1 ≤ i < j ≤ k)$, is even, then the first wizard wins (the second one gives him one magic coin). Otherwise, the second wizard wins (he gets one magic coin from the first one).
Our wizards are captured with feverish excitement, so they kept choosing new paths again and again for so long that eventually they have chosen every possible set of paths for exactly once. The two sets of non-intersecting pathes are considered to be different, if and only if there is an edge, which lies at some path in one set and doesn't lie at any path of another set. To check their notes, they asked you to count the total winnings of the first player for all possible sets of paths modulo a prime number $p$.
|
This task was about the pathes from the sources to sinks. For this pathes there was a condition which made them dependent - they should not interfere at vertexes. But in any combinatorics is much easier when everything is independent. So we should try to get rid of the condition of the absence of crossings at the vertices. It is very easy - just forget about it. Lets understand why the answer will not change: Suppose that a certain set of ways in which the two paths intersect. We show that taking into account this way, we at the same time take into account an another with the opposite sign. To do this, change the endings for paths that intersect. The signum of the permutation in this case has changed, so this set of paths is taken into account with the opposite sign and their sum is 0. How can it helps us? If we fix the permutation, the number of sets of paths that it corresponds well to the product of the number of paths for each pair of corresponding source and sink. Suppose that from the i-th source in the j-th sink there are $cnt_{ij}$ paths. This value can be calculated by depth-first-search and simple dynamic. Then the answer is $a n s=\sum_{p}s i g n(p)\cdot\prod_{i=1}^{n}c n t_{i p}$. This value is called the determinant of matrix cnt, which can be calculated using Gauss method in $O(S^{3})$ time where S is the number of sinks and sources. And we had to remember about isolated vertexes. Deleting one of them either do not change the answer or multiply the answer by -1. It remains to see that after deleting all isolated vertexes $s\leq{\frac{N}{2}}=300$, and $300^{3}$ fine fits into TL.
|
[
"dfs and similar",
"graphs",
"math",
"matrices"
] | 2,900
| null |
168
|
A
|
Wizards and Demonstration
|
Some country is populated by wizards. They want to organize a demonstration.
There are $n$ people living in the city, $x$ of them are the wizards who will surely go to the demonstration. Other city people ($n - x$ people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least $y$ percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only $n$ people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than $y$ percent of the city people.
|
In this task, it was necessary to write exactly what has been described in statement. In particular, it was necessary to have $\textstyle\left[{\frac{N Y}{100}}\right]$ people, who come to the meeting. For this it was necessary to create ${\mathrm{max}}(0,\lceil{\frac{N\cdot Y}{100}}\rceil-X)$ clones.
|
[
"implementation",
"math"
] | 900
| null |
168
|
B
|
Wizards and Minimal Spell
|
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells.
Each spell consists of several lines. The line, whose first non-space character is character "#" is an amplifying line and it is responsible for spell power. The remaining lines are common, and determine the effect of the spell.
You came across the text of some spell. Spell was too long, so you cannot understand its meaning. So you want to make it as short as possible without changing the meaning.
The only way to shorten a spell that you know is the removal of some spaces and line breaks. We know that when it comes to texts of spells, the spaces carry meaning only in the amplifying lines, so we should remove all spaces in other lines. Newlines also do not matter, unless any of the two separated lines is amplifying. Thus, if two consecutive lines are not amplifying, they need to be joined into one (i.e. we should concatenate the second line to the first one). Removing spaces in amplifying lines and concatenating the amplifying lines to anything is forbidden.
Note that empty lines must be processed just like all the others: they must be joined to the adjacent non-amplifying lines, or preserved in the output, if they are surrounded with amplifying lines on both sides (i.e. the line above it, if there is one, is amplifying, and the line below it, if there is one, is amplifying too).
For now those are the only instructions for removing unnecessary characters that you have to follow (oh yes, a newline is a character, too).
The input contains the text of the spell, which should be reduced. Remove the extra characters and print the result to the output.
|
In this problem you had to write exactly what has been described in statment too. Read lines one by one. Also keep the last block of lines that are not amplyfying. If the next line is amplyfying (which can be checked by linear search), we print the last block, if any, and the line itself. Otherwise, remove all spaces from the string and add to the last block. It only remains to distinguish between an empty block and a block of empty lines.
|
[
"implementation",
"strings"
] | 1,700
| null |
173
|
A
|
Rock-Paper-Scissors
|
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).
Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.
Nikephoros and Polycarpus have played $n$ rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.
Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items $A = (a_{1}, a_{2}, ..., a_{m})$, and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: $a_{1}$, $a_{2}$, $...$, $a_{m}$, $a_{1}$, $a_{2}$, $...$, $a_{m}$, $a_{1}$, $...$ and so on. Polycarpus had a similar strategy, only he had his own sequence of items $B = (b_{1}, b_{2}, ..., b_{k})$.
Determine the number of red spots on both players after they've played $n$ rounds of the game. You can consider that when the game began, the boys had no red spots on them.
|
Naive solution in $O(n)$ (some simulation all of n rounds) gets TL. Let's speed up this solution. Let's consider rounds on segments [1..mk], [mk+1..2mk], [2mk+1..3mk] and so on. You can see that results of games on these segments will repeat. So you can simulate over exactly one segment and then take into consideration them [n/(mk)] times ([x] is rounding down). Remainder of n%(mk) last rounds you can simulate separately. So you have $O(mk)$ solution that easily fits into time limits.
|
[
"implementation",
"math"
] | 1,300
| null |
173
|
B
|
Chamber of Secrets
|
"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.
The Chamber of Secrets is an $n × m$ rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.
\begin{center}
{\scriptsize The left light ray passes through a regular column, and the right ray — through the magic column.}
\end{center}
The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.
\begin{center}
{\scriptsize This figure illustrates the first sample test.}
\end{center}
Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.
|
In this problem you should build bipartite graph with n+m vertices. All vertices of the firts part correspond to the rows of the table, vertices of the second part correspond to the columns of the one. Edge connects vertices iff some regular column is placed in the cross of corresponding row and column. Firstly death ray covers only last row of the table that corresponds to one of vertices of our graph. When you are changing regular column into magic one, you are allowing death ray "go" by corresponding edge. Now you can reformulate the statement by this way: "activate" minimal number of edges in biratrite graph, so some path of minimal lenght connects vertex of the last row of the table and vertex of the first row of the table. You can see that required set of edges is just shortest path between these vertices. You can find this path using BFS. If BFS didn't find any path - answer is -1. This solution works in $O((n + m)^{2})$.
|
[
"dfs and similar",
"shortest paths"
] | 1,800
| null |
173
|
C
|
Spiral Maximum
|
Let's consider a $k × k$ square, divided into unit squares. Please note that $k ≥ 3$ and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral.
\begin{center}
{\scriptsize The figure shows examples of spirals for $k = 3, 5, 7, 9$.}
\end{center}
You have an $n × m$ table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals.
|
Let's iterate over all spirals and chose one of them that has maximal sum of elements. Because you have $O(n^{3})$ spirals, you should calculate sum of any of them in $O(1)$. Only in this case your solution will fit into time limits. Let's define a way for iterate over all spirals. Let's fix one of cells and then iterate over all spirals that have own center in that cell in order of increasing side. So, you can recalculate sum for every spiral from previous one in $O(1)$ using following picture: For finding the first "summand", you should in the beginning calculate rectangular partial sums.
|
[
"brute force",
"dp"
] | 1,900
| null |
173
|
D
|
Deputies
|
The Trinitarian kingdom has exactly $n = 3k$ cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.
Some cities are connected by bridges built between them. Each bridge connects two cities that are located on the opposite sides of the river. Between any two cities exists no more than one bridge.
The recently inaugurated King Tristan the Third is busy distributing his deputies among cities. In total there are $k$ deputies and the king wants to commission each of them to control exactly three cities. However, no deputy can be entrusted to manage the cities, which are connected by a bridge — the deputy can set a too high fee for travelling over the bridge to benefit his pocket, which is bad for the reputation of the king.
Help King Tristan the Third distribute the deputies between the cities, if it is possible.
|
You have bipartite graph with $3k$ vertices and should to color its vertices by $k$ colors. Every color should be used exactly 3 times and there should be no edges that connect vertices at same color. At the first, you should find both of parts of our birartite graph using, for example, DFS. Now let's consider sizes of parts. Case 0. If both of sizes divides by 3, you can just split every of parts into groups of 3 vertices and color them. Otherwise we can note then size of the first part is 1 modulo 3 and size of the second part is 2 modulo 3. There are yet another 2 cases: Case 1. You should try to find one vertex from the firts part that have 2 "antiedges" to 2 different vertices of the second part. If you found it, you should color them and reduce the problem to case 0. Case 2. There you should try to find 2 vertices on the second part. Every of them should have 2 "antiedges" that "connect" them with 4 different vertices trom the firts part. If you found such 6 vertices, you can color them by 2 different colors and reduce the problem to case 0. If you doesn't find coloring using this cases, answer is NO. About implementation: it is not clear how to analyse the case 2 in acceptable time. Actually, you can find any two vertices from the second part that have at least two "antiedges". These "antiedges" will conduct to 4 different vertices of the first part because otherwise case 1 would have worked. This solution works in $O(n + m)$.
|
[
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 2,500
| null |
173
|
E
|
Camping Groups
|
A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups.
Club member $i$ has a responsibility value $r_{i}$ and an age value $a_{i}$. A group is a non-empty subset of club members with one member known as group leader. A group leader should be one of the most responsible members of the group (his responsibility value is not less than responsibility of any other group member) and his age absolute difference with any other group member should not exceed $k$.
Some club members are friends and want to be in the same group. They also like their group to be as large as possible. Now you should write a program that answers a series of questions like "What's the largest size of a group containing club member $x$ and club member $y$?". It's possible for $x$ or $y$ to be the group leader.
|
Let's transform all people into points on a plane with coordinates ($x = a_{i}, y = r_{i}$). What the maximal number in group of people that can be formed with some fixed leader? Answer is number of points inside rectangle $(x, y): x_{i} - k \le x \le x_{i} + k, y \le y_{i}$. Let's we allready found size of group for every person. How to find maximal group that contain points $(x_{i}, y_{i})$ and $(x_{j}, y_{j})$ both? The required group should have leader with age in range from $max(x_{i} - k, x_{j} - k)$ then $min(x_{i} + k, x_{j} + k)$ and responsibility at least $max(y_{i}, y_{j})$. From such leaders you should chose one that have maximal size of group. You can see that it is just query for maximum on some rectangle. Well, let's learn to quickly find answers for queries of sums in rectangle. You should compress coordinates $x$ ans build segment tree for sum. Then you should answer all queries in increasing order of coordinate $y$. When you consider some group with same $y$, you should initially do queries of adding values in points, and after that do sum queries on the segments from $x_{i} - k$ to $x_{i} + k$. Queries for maximum you can satisfy fully analogicaly using segment tree for maximum. So, you have $O(n\log n)$ offline solution.
|
[
"data structures",
"sortings"
] | 2,600
| null |
175
|
A
|
Robot Bicorn Attack
|
Vasya plays Robot Bicorn Attack.
The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string $s$. Vasya decided to brag about his achievement to the friends. However, he has forgotten how many points he got for each round. The only thing he remembers is the string $s$.
Help Vasya to find out what is the maximum amount of points he could get. Take into account that Vasya played Robot Bicorn Attack for the first time, so he could not get more than 1000000 ($10^{6}$) points for one round.
|
Go over all possible partitions of the given string into 3 substrings (for example, go over a pair of indexes - the ends of the first and the second substrings). If all three substrings of the partition satisfy constraints (there are no leading zeroes and the corresponding number does not exceed 1000000), then update the current answer with the sum of obtained numbers (if it is necessary). The total amount of partitions is O(N^2), where N is the length of the string. The check of one partition takes O(N).
|
[
"brute force",
"implementation"
] | 1,400
| null |
175
|
B
|
Plane of Tanks: Pro
|
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results.
A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has $n$ records in total.
In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:
- "noob" — if \textbf{more than $50%$ of players have better results};
- "random" — if his result is not worse than the result that $50%$ of players have, but more than $20%$ of players have better results;
- "average" — if his result is not worse than the result that $80%$ of players have, but more than $10%$ of players have better results;
- "hardcore" — if his result is not worse than the result that $90%$ of players have, but more than $1%$ of players have better results;
- "pro" — if his result is not worse than the result that $99%$ of players have.
When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that $50%$ of players have, and the second one is not worse than the result that $100%$ of players have.
Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.
|
The solution is to simulate actions described in the statement. Find the best result for each player and count total amount of players N. Then find a number of players C for each player , those results are not better than best result of the considering player (this can be done by going over all players). Then it is necessary to determine players category using numbers C and N. In order to avoid rounding error use the following approach: if C * 100 >= N * 99, then the player belongs to category "pro" if C * 100 >= N * 90, then the player is "hardcore" if C * 100 >= N * 80, then the player is "average" if C * 100 >= N * 50, then the player is "random" In other case the player is "noob".
|
[
"implementation"
] | 1,400
| null |
175
|
C
|
Geometry Horse
|
Vasya plays the Geometry Horse.
The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value.
There are $n$ types of geometric figures. The number of figures of type $k_{i}$ and figure cost $c_{i}$ is known for each figure type. A player gets $c_{i}·f $ points for destroying one figure of type $i$, where $f$ is the current factor. The factor value can be an integer number from $1$ to $t + 1$, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to $i + 1$ after destruction of $p_{i}$ $(1 ≤ i ≤ t)$ figures, so the $(p_{i} + 1)$-th figure to be destroyed is considered with factor equal to $i + 1$.
Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.
|
Obvious, that figures should be destroyed in the cost increasing order. Sort figures type in ascending order of their costs. Consider two pointers - position i in the array P (current factor) and position j in the array of figures type. Consider the current answer and the number of figures G, those need to be destroyed to move to the next value of factor. If the number of figures F of the current type does not exceed G, then add F * (i + 1) * Cj to the answer and reduce G by F and increase pointer j by 1. In other case add G * (i + 1) * Cj to the answer, reduce F by G, increase i by 1 and set G = Pi - P(i-1). Continue iteration until all figure types are considered.
|
[
"greedy",
"implementation",
"sortings",
"two pointers"
] | 1,600
| null |
175
|
D
|
Plane of Tanks: Duel
|
Vasya plays the Plane of Tanks.
Tanks are described with the following attributes:
- the number of hit points;
- the interval between two gun shots (the time required to recharge the gun);
- the probability that the gun shot will not pierce armor of the enemy tank;
- the damage to the enemy's tank.
The gun damage is described with a segment $[l, r]$, where $l$ and $r$ are integer numbers. The potential gun damage $x$ is chosen with equal probability among all integer numbers of the segment $[l, r]$. If the shot pierces the armor of an enemy's tank then the enemy loses $x$ hit points. If the number of hit points becomes non-positive then the enemy tank is considered destroyed.
It is possible that the shot does not pierce the armor of a tank. In this case the number of hit points doesn't change. The probability that the armor will not be pierced is considered as the shooting tank attribute and does not depend on players' behavior.
The victory is near and there is only one enemy tank left. Vasya is ready for the battle — one more battle between the Good and the Evil is inevitable! Two enemies saw each other and each of them fired a shot at the same moment... The last battle has begun! Help Vasya to determine what is the probability that he will win the battle by destroying the enemy tank?
If both tanks are destroyed (after simultaneous shots), then Vasya is considered a winner. You can assume that each player fires a shot just after the gun recharge and each tank has infinite number of ammo.
|
First consider case when at least one probability of not-piercing is equal to 100%. If Vasya does not pierce the enemy tank with probability 100%, then the answer is 0. If the enemy tank cannot pierce Vasya's tank with probability 100% then the answer is 1. Then consider that the probability of shot does not pierce tank does not exceed 99%. It can be checked that the probability that tank will stay alive after D = 5000 shots is less than 10^-6 (for any damage value, probability of not-piercing and amount of hit points). For each tank calculate the following table dp[i][j] - probability that tank will have j hit points after i shots to him. dp[0][hp] = 1, where hp - is the initial amount of hit points. In order to calculate the line dp[i+1] it is necessary to go over all possible damages for each value of j in the line dp[i], which shot (i+1)-th damages (considering cases when the shot does not pierce the tank armour) and update appropriate values of the line (i+1): dp[i + 1][max(0, j - x)] += dp[i][j] * (1 - p) / (r - l + 1)where p - is the probability of not-piercing, x - possible shot damage. Let's dpv - calculcated table for Vasya's tank and dpe is the table for enemy's tank. Now it is necessary to find probability that enemy's tank will be destroyed after i shots of Vasya's tank: pk[i] = dpe[i][0] - dpe[i-1][0]. Vasya wins the following way: Vasya fired (K - 1) shots and do not destroy enemy tank and is still alive also. After that Vasya fires K-th shot and destroy the enemy. Go over K and calculate the probability of Vasya's victory with the K-th shot. In order to do this find how many shots T can fire the enemy before Vasya makes K-th shot (here is the only place in the solution where we must use the gun recharge speed): T = ((K - 1) * dtv + dte - 1) / dtewhere dtv is the time required to recharge the gun, dte is the time of enemy gun recharge. Then the probability of victory is (1 - dpv[T][0]) * pk[K]. The answer for the problem is the sum all these probabilities for each K from 1 to D. The algorithmic complexity of the algorithm is O(D * hp * (r - l)).
|
[
"brute force",
"dp",
"math",
"probabilities"
] | 2,400
| null |
175
|
E
|
Power Defence
|
Vasya plays the Power Defence.
He must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point $( - ∞, 0)$ to the point $( + ∞, 0)$ of the game world. In the points $(x, 1)$ and $(x, - 1)$, where $x$ is an integer number, Vasya can build towers of three types: fire-tower, electric-tower or freezing-tower. However, it is not allowed to build two towers at the same point. Towers of each type have a certain action radius and the value of damage per second (except freezing-tower). If at some point the Main Villain is in the range of action of $k$ freezing towers then his speed is decreased by $k + 1$ times.
The allowed number of towers of each type is known. It is necessary to determine the maximum possible damage we can inflict on the Main Villain.
All distances in the problem are given in meters. The size of the Main Villain and the towers are so small, that they can be considered as points on the plane. The Main Villain is in the action radius of a tower if the distance between him and tower is less than or equal to the action radius of the tower.
|
If we reflect the position of towers alogn the line OX then the interval where towers will affect the Villain will not change. So, we can consider that towers can be built in the points (_x_, 1), not more than two towers in the same point. If there exists point X that there are towers to the left and to the right from X but in the point X there is no tower, then abscissas of all towers "to the right" can be reduced by 1 and the answer will not become worse. The same way, we can prove that there are no adjacent points with exactly one tower in each one. Now it is easy to check that in order to construct the optimal solution it is enough to check 13 successive points. Go over positions of freezing towers. In the worst case there are approximately 200000 cases to put freezing towers into 13 points. Consider the case when we fixed positions of several freezing towers. Let's calculate how much damage can hit fire-tower or electric-tower in the point for each empty points (points where we can put two towers are splitted into two) and save numbers into the array d (_d_[k].f and d[k].e - damage by fire and electricity in the point k correspondingly). Sort the array d in the order of decreasing of the value d[k].f. Then optimal position of the rest towers can be found using dynamic programming. Designate dp[i][j] - the maximum possible damage, which can be hitted if we have i fire-towers and j electric-towers. Designate p - the amount of towers have been set already: p = cf - i + ce - j. If i = 0 then we used first p values of array d and the answer is the sum of j maximum elemets of d[k].e, starting from index p. Otherwise we put one fire-tower or one electric tower in the position p. It is necessary to put the tower into position p because in the opposite case the d[p].f will decrease. Then: dp[i][j] += max(dp[i - 1][j] + d[p].f, d[i][j - 1] + d[p].e)The answer is the value dp[cf][ce], which is calculated in O(cf * ce * log(ce)) Comment1: exhaustive search can be reduced in 2 times because any two symmetric towers arrangements are equivalent and have the same answer. However, this optimization is not required with a given constraints. Comment2: the formula of Villain speed decrease 1 / (K + 1) allows to calculate the tower damage for a case when all freezing towers are fixed easily. Freezing towers can be taken into account separately.
|
[
"brute force",
"dp",
"geometry",
"greedy"
] | 2,600
| null |
175
|
F
|
Gnomes of Might and Magic
|
Vasya plays a popular game the Gnomes of Might and Magic.
In this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has $m$ main castles $a_{1}, a_{2}, ..., a_{m}$, which form the Good Path. This path consists of roads between the castles $a_{i}, a_{i + 1}$ $(1 ≤ i < m)$ as well as the road between $a_{m}$ and $a_{1}$. There are no other roads between the castles of the Good Path.
In addition, for each pair of neighboring Good Path castles $u$ and $v$ there is exactly one Evil Shortcut — a path that goes along the roads leading from the first castle $(u)$ to the second one $(v)$ and not having any common vertexes with the Good Path except for the vertexes $u$ and $v$. It is known that there are no other roads and castles in the kingdom there, that is, every road and every castle lies either on the Good Path or the Evil Shortcut (castles can lie in both of them). In addition, no two Evil Shortcuts have any common castles, different than the castles of the Good Path.
At the beginning of each week in the kingdom appears one very bad gnome who stands on one of the roads of the kingdom, and begins to rob the corovans going through this road. One road may accumulate multiple very bad gnomes. Vasya cares about his corovans, so sometimes he sends the Mission of Death from one castle to another.
Let's suggest that the Mission of Death should get from castle $s$ to castle $t$. Then it will move from castle $s$ to castle $t$, destroying all very bad gnomes, which are on the roads of the Mission's path. Vasya is so tough that his Mission of Death can destroy any number of gnomes on its way. However, Vasya is very kind, so he always chooses such path between castles $s$ and $t$, following which he will destroy the smallest number of gnomes. If there are multiple such paths, then Vasya chooses the path that contains the smallest number of roads among them. If there are multiple such paths still, Vasya chooses the lexicographically minimal one among them.
Help Vasya to simulate the life of the kingdom in the Gnomes of Might and Magic game.
A path is a sequence of castles, such that each pair of the neighboring castles on the path is connected by a road. Also, path $x_{1}, x_{2}, ... , x_{p}$ is lexicographically less than path $y_{1}, y_{2}, ... , y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or exists such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$.
|
Construct the graph with vertices corresponding to castles and edges to roads. Note, that a degree of each graph vertex does not exceed 4, so the amount of edges does not exceed E <= 2 * N. In order to solve the problem let's find out how we can handle each query with time O(_log_(_N_)). Consider the query to find amount of gnomes destroyed by the Mission of Death. Assume that the edge weight is the amount of gnomes on the appropriate road. We must find the shortest path between two vertices and among them the path with the smallest amount of edges. So, the way is described by two numbers - G and R - amount of gnomes and edges (for now we do not consider lexicographical minimality). One edge between vertex u and v is described by (_C_(_u_,_v_), 1), where C(_u_,_v_) - amount of gnomes on the edge (_u_,_v_). Consider two vertices s and t. We want to find the path between them. The shortest path between them can be one of the following : the path along the Evil Shortcut, if both vertices are on the same Shortcut the path s -> g1 -> g2 -> t, where g1 and g2 - vertices on the Good Path and g1 and s are on the same Shortcut, g2 and t are on the same Shortcut (some of these 4 vertices can be identical). So, it is necessary to determine quickly the shortest path between vertices e1 and e2 along the Evil Shortcut and between vertices g1 and g2 along the Good Path. In order to find distance between vertices along the Evil Shortcut construct for each Evil Shortcut the segment tree etree[i], which can be used to update and get the sum on the segment. For each vertex let's store the number of Evil Shortcut it belongs to and it index number on that Shortcut (it is necessary to consider cases with vertices of the Good Path, because they belong to two Shortcuts). So, the distance between two vertices of one Shortcut is the sum of edges weights of the approproate segment tree with boundaries equal to indexes of considered vertices. Similarly, construct the segment tree gtree for Good Path, by cutting it in the first vertex (for paths where it was inner vertex we will do two queries). For each pair of adjacent vertices of the Good Path we will store the minimum of two distances: distance along the edge of the Good Path or the distance along the Evil Shortcut. So for each two vertices of the Good Path the corresponding query to the segment tree returns the length (a pair of numbers) of the shortest path between two arbitrary vertices. Such a data structure allows to find the shortest path between two arbitrary vertices of the Good Path or one Evil Shortcut in time O(_log_(_N_)). It is necessary to update appropriate element of the tree with value (_0_, 1) for each pair of adjacent vertices of the Good Path initially. Now consider the query for addition of one gnome to the edge. In order to handle this query quickly it is necessary to store amount of gnomes gsum[i] along each road of the Good Path and total number of gnomes esum[i] along each Evil Shortcut. If the gnome stands on the edge i of the Good Path, then increase gsum[i] by 1. Similarly if the gnome stands on the edge i of the Evil Shortcut, then increase esum[i] by 1 and update the appropriate value in the segment tree etree[i]. It is necessary to put new shortest path between corresponding adjacent vertices into the segment tree gtree after any of these actions because it may have changed. Note, that after removal of gnomes from the edge we can do opposite operations with the same asymptotics. So, the query for updating amount of gnomes on the edge can be handled in time O(_log_(_N_)). Now let's figure out how we can find the shortest path between two arbitrary vertices s and t. Construct the vector of the Good Path vertices sg those we can reach from s along the edges of the Evil Shortcut which it belongs to (there will be one or two vertices in the sg ). Similarly, the vector tg contains the vertices of the Good Path those we can reach from t along the edges of the Evil Shortcut. Consider the union of vectors tsg = sg + tg. For each vertex u of the uninon let's find the vertex v1 which is the first one among vertices tsg on the path from u if we move along the edges of Good Path in the order of indexes increasing (i.e. in the order the vertices are given in the input data). Similarly, v2 is the first vertex on the opposite direction. Add to the adjacenty list of the vertex u vertices v1 and v2 with distances to them. Also, find edges (distances along the Evil Shortcuts) from s to the vertices of vector sg, and from vertices of the tg to the vertex t. If vertices s and t are on the same Evil Shortcut (and none of them is on the Good Path), then add one more direct edge from s to t, corresponding to the path along the Evil Shortcut. So we have constructed the graph which consists of not more than 6 vertices and no more than 13 edges. Start the Deijkstra algorithm on that graph to find shortest path from s to t. Note, that paths of the initial graph corresponding to edges of the new graph do not intersect in inner vertices (except, probably, a direct edge from s to t). In order to find lexicographically minimal path it is necessary to know the first inner vertex on the path corresponding to one of the edges. So we can, for example, add one more option to each path of the new graph - the vector of indexes of first vertices of the initial graph when moving along edges of a new graph. In this case 3 options (amount of gnomes, amount of edges and the vector of indexes) uniquely determines the optimal path of the Death Mission. Now it is necessary to print the answer and find out how to handle gnome destruction on the path. Restore vertices on the optimal path. The edge between each pair of adjacent vertices is the path along the Evil Shortcut or the path between two vertices of the Good Path. In order to find gnomes on the Evil Shortcut consider the multiset eset[i] containing indexes of edges with gnomes of that Shortcut for each Evil Shortcut. Then after adding a gnome to the edge it is necessary to add the gnome index to the multiset of the Shortcut. Now all destructions of gnomes from the Evil Shortcut i, between edges l and r, can be handled by searching of iterator of the first gnome, using eset[i]._lower_bound_(_l_) and iteration, saving obtained indexes of gnomes into the list, until the value will not exceed r. After that it is necessary to remove all gnomes in the list using the algorithm described above (similarly to addition). In order to handle paths between two vertices of the Good Path, consider set gset with indexes of vertices of the Good Path that there is no path without gnomes between two adjacent vertices corresponding to indexes. After each set updating (adding/removal of the gnome) it is necessary to add the check: if the minimum distance (corresponding to the value in the segment tree gtree) is 0 (by the amount of gnomes), then it is necessary to remove appropriate index in the gset, in the opposite case it is necessary to add the index. After invocation of similar procedure (invoke gset._lower_bound_ and iterate required amount of times) we will get the list of vertices indexes going through each one we will have to destroy at least one gnome to the path to the next vertex of the Good Path (obvious, that pairs of vertices between those exists a path without gnomes should not be considered because the Death Mission will go along it without destruction of gnomes). Consider index i from this list. If for the correspondent vertex the optimal path to the next vertex of the Good Path is on the Evil Shortcut, i.e. esum[i] < gsum[i], then it is necessary to destroy all gnomes from that Shortcut using the algorithm described above. In the opposite case it is necessary to set gsum[i] = 0 and update corresponding value in the segment tree of the Shortcut gtree. So one gnome can be removed from the path of Death Mission in O(_log_(_N_)). The amount of gnome removals does not exceed amount of added gnomes (i.e. it is not more than Q), so the complexity of one Death Mission handling is also O(_log_(_N_)). The total complexity is O(_log_(_N_) * Q).
|
[
"data structures",
"graphs",
"implementation",
"shortest paths"
] | 3,000
| null |
176
|
A
|
Trading Business
|
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.
The system has $n$ planets in total. On each of them Qwerty can buy or sell items of $m$ types (such as food, medicine, weapons, alcohol, and so on). For each planet $i$ and each type of items $j$ Qwerty knows the following:
- $a_{ij}$ — the cost of buying an item;
- $b_{ij}$ — the cost of selling an item;
- $c_{ij}$ — the number of remaining items.
It is not allowed to buy more than $c_{ij}$ items of type $j$ on planet $i$, but it is allowed to sell any number of items of any kind.
Knowing that the hold of Qwerty's ship has room for no more than $k$ items, determine the maximum profit which Qwerty can get.
|
In this problem some greedy solution expected. Let fix 2 planets: in planet i we will buy items, in planet j we will sell the ones. Profit of item of type k will be b_jk-a_ik. Every item has size 1, so you should greedy take items in order of decreasing of profits of items while you have place in the hold. Scheme of full solution: you should iterate over all pairs of planet, for every pair greedy take items and find total profit. At the end you should find maximal total profit over all pairs and output it.
|
[
"greedy",
"sortings"
] | 1,200
| null |
176
|
B
|
Word Cut
|
Let's consider one interesting word game. In this game you should transform one word into another through special operations.
Let's say we have word $w$, let's split this word into two non-empty parts $x$ and $y$ so, that $w = xy$. A split operation is transforming word $w = xy$ into word $u = yx$. For example, a split operation can transform word "wordcut" into word "cutword".
You are given two words $start$ and $end$. Count in how many ways we can transform word $start$ into word $end$, if we apply exactly $k$ split operations consecutively to word $start$.
Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number $i$ ($1 ≤ i ≤ k$), that in the $i$-th operation of the first sequence the word splits into parts $x$ and $y$, in the $i$-th operation of the second sequence the word splits into parts $a$ and $b$, and additionally $x ≠ a$ holds.
|
You can see that split oparetion is just cyclically shift of string. You can go from any cyclically shift to any other one except the current one. Let's call some cyclically shift good iff it equal to the final string. All others cyclically shifts we will call bad. You can check all shifts in $O(|w|^{2})$ time. Let's you have A good shifts and B bad ones. Let's define dpA[n] as number of ways to get some good shift using n splits and dpB[n] as number of ways to get some bad shift using n splits. dpA[0]=1, dpB[0]=0 or dpA[0]=0, dpB[0]=1 according to the first shift is good or not. All other values of dp you can get using following reccurences: dpA[n] = dpA[n-1] * (A-1) + dpB[n-1] * A dpB[n] = dpA[n-1] * B + dpB[n-1] * (B-1) Answer will be dpA[k]. So you have $O(|w|^{2} + k)$ solution. Also this problem can be solved in $O(|w|+\log k)$ time.
|
[
"dp"
] | 1,700
| null |
176
|
C
|
Playing with Superglue
|
Two players play a game. The game is played on a rectangular board with $n × m$ squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe the rules of the game in more detail.
The players move in turns. The first player begins.
With every move the first player chooses one of his unglued chips, and shifts it one square to the left, to the right, up or down. It is not allowed to move a chip beyond the board edge. At the beginning of a turn some squares of the board may be covered with a glue. The first player can move the chip to such square, in this case the chip gets tightly glued and cannot move any longer.
At each move the second player selects one of the free squares (which do not contain a chip or a glue) and covers it with superglue. The glue dries long and squares covered with it remain sticky up to the end of the game.
If, after some move of the first player both chips are in the same square, then the first player wins. If the first player cannot make a move (both of his chips are glued), then the second player wins. Note that the situation where the second player cannot make a move is impossible — he can always spread the glue on the square from which the first player has just moved the chip.
We will further clarify the case where both chips are glued and are in the same square. In this case the first player wins as the game ends as soon as both chips are in the same square, and the condition of the loss (the inability to move) does not arise.
You know the board sizes and the positions of the two chips on it. At the beginning of the game all board squares are glue-free. Find out who wins if the players play optimally.
|
The second player have easy strategy to hold some chip in position $(X, Y)$ in one of four half-planes - $x \le X + 2$, $x \ge X - 2$, $y \le Y + 2$ and $y \ge Y - 2$. He can chose one of these half-planes by himself. So, in case $max(|x1 - x2|, |y1 - y2|) > 4$ the second player wins - he just holds chips in half-planes that have no common cells. Cases for $max(|x1 - x2|, |y1 - y2|) \le 4$ expected to solve using some bruteforce. You can see that moving chips in way of distancing from each other is not profitable for the first player. Therefore you can bruteforce the game in square no more than $5 \times 5$. If your bruteforce so slow and doesn't fit into 2 sec, you can use precalculation. Also you can write some dp using masks. Also you can check cases $max(|x1 - x2|, |y1 - y2|) \le 4$ by hand. But there you can easy make some mistakes.
|
[
"combinatorics",
"constructive algorithms"
] | 2,000
| null |
176
|
D
|
Hyper String
|
Paul Erdős's prediction came true. Finally an alien force landed on the Earth. In contrary to our expectation they didn't asked the humans to compute the value of a Ramsey number (maybe they had solved it themselves). They asked another question which seemed as hard as calculating Ramsey numbers. Aliens threatened that if humans don't solve this problem in less than 2 hours they will destroy the Earth.
Before telling the problem they introduced the concept of Hyper Strings. A Hyper String is made by concatenation of some base strings. Suppose you are given a list of base strings $b_{1}, b_{2}, ..., b_{n}$. Now the Hyper String made from indices list $i_{1}, i_{2}, ..., i_{m}$ is concatenation of base strings $b_{i1}, b_{i2}, ..., b_{im}$. A Hyper String can be very large and doing operations on it is very costly for computers.
The aliens asked humans to compute the length of the longest common sub-sequence of a Hyper String $t$ with a string $s$.
|
Let's define $dp[pre][len]$ as the minimal prefix of hyperstring that have with prefix of $t$ of length $len$ largest common sequence of length $len$. Then you have see reccurences: $dp[pre][len] = min(dp[pre - 1][len],$ leftmost position of letter $s[pre]$ in $t$ that right than $dp[pre - 1][len - 1])$. For finding value of the second part inside min-function of formula above in $O(1)$, you should calculate some additional dp's: dp1 - for every basic string, positions inside of them and letter you should calculate leftmost position of current letter that right than current position; dp2 - for every element of array of basic strings (it is hyperstring) and letter you should calculate leftmost basic string that have current letter and this string is rinht than current basic string. So you have $O(26\sum|b_{i}|+26m+|s|^{2})$ solution.
|
[
"dp"
] | 2,500
| null |
176
|
E
|
Archaeology
|
This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago.
Overall they've dug out $n$ villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly $n - 1$ roads, and from any village one could get to any other one.
The tribes were not peaceful, and they had many wars. As a result of the wars, some villages were completely destroyed. During more peaceful years, some of the villages were restored.
At each moment of time, people \underline{used} only those roads that belonged to some shortest way between two villages \underline{that existed at the given moment}. In other words, people used the minimum subset of roads in such a way that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly $n - 1$ roads that have been found by the researchers. There never were any other roads.
The researchers think that observing the total sum of used roads' lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions.
You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time.
|
At the first let's try to solve another problem: we have $k$ chosed vertices in the tree and we want to find sum of subtree that "spanned" dy them in time $O(k \log n)$ (with any preprocessing time). Let's sort all $k$ vertices in order of dfs traversal - $v_{1}$, $v_{2}$, ... , $v_{k}$. Consider pathes v1-v2, v2-v3, ... , v(k-1)-vk and vk-v1. You can see that they cover only our requred subtree and every edge is covered exactly two times. So you can just find sum of lengths of these pathes (you can do it in required $O(k \log n)$ time using LCA algo) and divide obtained value by 2. For solving initial problem you should support set of active vertices in ordered state (for example, you can use std::set) and sum of all pathes between all neighbour vertices. Now you can process insert/remove queries in $O(\log n)$, and recalculate sum of pathes by finding no more than 3 new pathes also in $O(\log n)$. So you have $O((n+q)\log n)$ solution.
|
[
"data structures",
"dfs and similar",
"trees"
] | 3,100
| null |
178
|
A1
|
Educational Game
|
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.
One move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).
You are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.
|
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j} \le n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u} \le n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j} \le k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q} \le n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \log n)$.
|
[] | 1,000
| null |
178
|
A2
|
Educational Game
|
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.
One move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).
You are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.
|
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j} \le n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u} \le n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j} \le k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q} \le n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \log n)$.
|
[
"greedy"
] | 1,000
| null |
178
|
A3
|
Educational Game
|
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.
The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some prefix of the sequence) equal to zero for some fixed $k$ $(k < n)$, and this should be done in the smallest possible number of moves.
One move is choosing an integer $i$ ($1 ≤ i ≤ n$) such that $a_{i} > 0$ and an integer $t$ $(t ≥ 0)$ such that $i + 2^{t} ≤ n$. After the values of $i$ and $t$ have been selected, the value of $a_{i}$ is decreased by $1$, and the value of $a_{i + 2^{t}}$ is increased by $1$. For example, let $n = 4$ and $a = (1, 0, 1, 2)$, then it is possible to make move $i = 3$, $t = 0$ and get $a = (1, 0, 0, 3)$ or to make move $i = 1$, $t = 1$ and get $a = (0, 0, 2, 2)$ (the only possible other move is $i = 1$, $t = 0$).
You are given $n$ and the initial sequence $a_{i}$. The task is to calculate the minimum number of moves needed to make the first $k$ elements of the original sequence equal to zero for each possible $k$ $(1 ≤ k < n)$.
|
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes of the sequence will take less steps. Having zeroed $a_{1}$, we will write a current answer and notice that we reduce the task to the smaller one - sequence becomes one element shorter. The complexity of a solution $O(n * \log n)$ or $O(n)$ - depends on implementation. One can solve the task in a different way. To start from, the task can be solved for each element $a_{i}$ separately. In other words, if we fix some $k$, contribution of each $a_{i}$ to an answer can be counted separately. We fix some $a_{i}$. Then we find maximum $j$ so that $i + 2^{j} \le n$. Evidently, that for every $k < i + 2^{j}$, contribution of $a_{i}$ to the answer equals $a_{i}$. In other words, one needs to make $a_{i}$ steps with transition to $a_{i}$. Further we need to find maximum $u$, so that $2^{j} + 2^{u} \le n$. Notice that $u < j$. Contribution of $a_{i}$ to the answer is equal $2 * a_{i}$, for every $k$ that $i + 2^{j} \le k < i + 2^{j} + 2^{u}$. Then we find $q$ that $i + 2^{j} + 2^{u} + 2^{q} \le n$, and so on ... A corresponding sequence of powers of $2$ should be found for each element $a_{i}$. Evidently, that overall complexity of this process is $O(n * \log n)$. Now we need to calculate an answer. It can be done, for example, like that: we will store the array $b_{i}$ - the change of the answer at the transition from $i$ to $4i + 1$. This array is formed in a trivial way during construction of sequences of powers of twos. Then it is easy to get the answer. The overall complexity of the solution equals $O(n * \log n)$.
|
[
"greedy"
] | 1,100
| null |
178
|
B1
|
Greedy Merchants
|
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.
The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.
We say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:
- $t_{1} = c_{1}$
- $t_{p} = c_{2}$
- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road
We know that there existed a path between any two cities in the Roman Empire.
In the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.
Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.
The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.
|
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\cdot\log n)$ and handle one request for $O(\log n)$. The complexity of computations id $O(m+(n+k)\cdot\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.
|
[] | 1,600
| null |
178
|
B2
|
Greedy Merchants
|
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.
The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.
We say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:
- $t_{1} = c_{1}$
- $t_{p} = c_{2}$
- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road
We know that there existed a path between any two cities in the Roman Empire.
In the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.
Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.
The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.
|
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\cdot\log n)$ and handle one request for $O(\log n)$. The complexity of computations id $O(m+(n+k)\cdot\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.
|
[] | 1,600
| null |
178
|
B3
|
Greedy Merchants
|
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.
The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two different cities. Any two cities were connected by no more than one road.
We say that there is a path between cities $c_{1}$ and $c_{2}$ if there exists a finite sequence of cities $t_{1}, t_{2}, ..., t_{p}$ $(p ≥ 1)$ such that:
- $t_{1} = c_{1}$
- $t_{p} = c_{2}$
- for any $i$ $(1 ≤ i < p)$, cities $t_{i}$ and $t_{i + 1}$ are connected by a road
We know that there existed a path between any two cities in the Roman Empire.
In the Empire $k$ merchants lived numbered from $1$ to $k$. For each merchant we know a pair of numbers $s_{i}$ and $l_{i}$, where $s_{i}$ is the number of the city where this merchant's warehouse is, and $l_{i}$ is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.
Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays $d_{i}$ dinars of tax, where $d_{i}$ ($d_{i} ≥ 0$) is the number of roads important for the $i$-th merchant.
The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.
|
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the graph bridges graph is divided for some components of connectivity (maybe one component). Let's build new graph in which recieved components will be nodes and bridges - edges. This graph will be a tree. The graph is connected therefore the tree is connected. The edges correspond to bridges therefore there is no cycles in the tree. Note that the number of denarii means the pay of every merchant - is a distance between some the nodes in a new graph. But as this graph is a tree this distances can be easily find out using LCA search algorithms for two nodes. In this problem one should use the simplest LCA search algorithm which accomplish the preprocess for $O(n\cdot\log n)$ and handle one request for $O(\log n)$. The complexity of computations id $O(m+(n+k)\cdot\log n)$. One can solve this problem easier. Let's build a graph recursive pass-by initial graph and weight its edges. The edges with weight equals 1 will have bridges and others will have weight equals 0. So after all these reductions for solving problem it will be enough to compute the distance between two nodes in the graph recursive pass-by initial graph.
|
[] | 1,800
| null |
178
|
C1
|
Smart Beaver and Resolving Collisions
|
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.
The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \underline{It is guaranteed that the input for this problem doesn't contain such situations}.
The operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.
This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.
Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
|
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\cdot\log h)$, of solution with Fenwick tree - $O(n\cdot\log^{2}h)$.
|
[] | 1,600
| null |
178
|
C2
|
Smart Beaver and Resolving Collisions
|
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.
The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \underline{It is guaranteed that the input for this problem doesn't contain such situations}.
The operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.
This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.
Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
|
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\cdot\log h)$, of solution with Fenwick tree - $O(n\cdot\log^{2}h)$.
|
[] | 1,900
| null |
178
|
C3
|
Smart Beaver and Resolving Collisions
|
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.
We assume that the hash table consists of $h$ cells numbered from $0$ to $h - 1$. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between $0$ and $h - 1$, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.
The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals $t$ and cell $t$ of the table is already occupied. Then we try to add this object to cell $(t + m) mod h$. If it is also occupied, then we try cell $(t + 2·m) mod h$, then cell $(t + 3·m) mod h$, and so on. Note that in some cases it's possible that the new object can not be added to the table. \underline{It is guaranteed that the input for this problem doesn't contain such situations}.
The operation $a mod b$ means that we take the remainder of the division of number $a$ by number $b$.
This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell $(t + i·m) mod h$ $(i ≥ 0)$, then exactly $i$ dummy calls have been performed.
Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.
|
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this property? The element with fixed hash-value will be added into some (next) cell in the corresponding to element's hash-value cycle. So, we can process each cycle separately. To do this effectively (we want to solve large test package) we have to use any tree-structure like segment tree or combination of Fenwick tree with binary search. An effectiveness of solution with segment tree is $O(n\cdot\log h)$, of solution with Fenwick tree - $O(n\cdot\log^{2}h)$.
|
[] | 2,000
| null |
178
|
D1
|
Magic Squares
|
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:
\begin{center}
{\scriptsize Magic squares}
\end{center}
You are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists!
|
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.
|
[] | 1,500
| null |
178
|
D2
|
Magic Squares
|
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:
\begin{center}
{\scriptsize Magic squares}
\end{center}
You are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists!
|
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.
|
[] | 1,900
| null |
178
|
D3
|
Magic Squares
|
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants.
The magic square is a matrix of size $n × n$. The elements of this matrix are integers. The sum of numbers in each row of the matrix is equal to some number $s$. The sum of numbers in each column of the matrix is also equal to $s$. In addition, the sum of the elements on the main diagonal is equal to $s$ and the sum of elements on the secondary diagonal is equal to $s$. Examples of magic squares are given in the following figure:
\begin{center}
{\scriptsize Magic squares}
\end{center}
You are given a set of $n^{2}$ integers $a_{i}$. It is required to place these numbers into a square matrix of size $n × n$ so that they form a magic square. Note that each number must occur in the matrix exactly the same number of times as it occurs in the original set.
It is guaranteed that a solution exists!
|
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on two main ideas: We can determine some square elements during the brute force using already fixed values. For example, if we have fixed three of values on the main diagonal, we can easily determine the fourth value. This trick decrease the number of brute force iterations. We can rotate (or mirror) magic square without breaking his magic properties. The second way use discrete-optimization approach. Let's consider the function $Q = |sum_{1} - s| + ... + |sum_{t} - s|$, where $|x|$ - the absolute value of $x$, $t = 2 * n + 2, sum_{1}, .., sum_{n}$ - the sum of elements in one row, $sum_{n + 1}, sum_{2n}$ - the sum of element in one column, $sum_{t} - 1$ - the sum of elements on the main diagonal, $sum_{t}$ --- the sum of elements on the secondary diagonal. So, we want to find such permutation of the given elements that make our function as small as possible (We want to obtain zero). One way to do this: pick the random permutation. Try to make swaps in this permutation using greedy strategy (try to make swaps that make our function better). Let's do 1000 swaps. If we obtain $Q = 0$ - we have found answer, else $Q > 0$ -- pick another random permutation and repeat this process again.
|
[] | 2,100
| null |
178
|
E1
|
The Beaver's Problem - 2
|
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.
You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.
The white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.
The squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.
\begin{center}
{\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}
\end{center}
|
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.
|
[] | 1,900
| null |
178
|
E2
|
The Beaver's Problem - 2
|
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.
You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.
The white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.
The squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.
\begin{center}
{\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}
\end{center}
|
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.
|
[] | 2,000
| null |
178
|
E3
|
The Beaver's Problem - 2
|
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem.
You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the matrix's size coincides with the size of the image.
The white color on the given image corresponds to the background. Also, the image contains several black geometric shapes. It is known that the image can contain only two types of shapes: squares and circles. Your task is to count the number of circles and the number of squares which the given image contains.
The squares on the image can be rotated arbitrarily. In addition, the image can possibly contain some noise arranged as follows: each pixel of the original image can change its color to the opposite with the probability of $20$%.
\begin{center}
{\scriptsize An example of an image that has no noise and the sides of the squares are parallel to the coordinate axes (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has no noise and the squares are rotated arbitrarily (two circles and three squares).}
\end{center}
\begin{center}
{\scriptsize An example of an image that has noise and the squares are rotated arbitrarily (one circle and three squares).}
\end{center}
|
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of almost all noise on the picture. Then we make inverse opreation replacing all white pixels with black. So we get rid of almost all noise inside the picture. Note, that after all these opreations noise can stay as little black components. And some figures can lose their connectivity. These problems can be solved by deletion little black components and then unite near black components. b. But one can use easier way. Highlight black components and then cast away little ones. If to look closely to the texts in real under even distribution of the noise there is no little black components and it is not losing connectivity. However previous way is more reliable. The simplest way to classificate figures is to compare distributions of the distances from all the figure pixels to centre of the every figure. The centre can be calculated as average of the all points coordinates of the figure. Ditributions can be compared by expectation values and variations.
|
[] | 2,300
| null |
181
|
A
|
Series of Crimes
|
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an $n × m$ rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked there the districts where the first three robberies had been committed as asterisks. Deduction tells Polycarpus that the fourth robbery will be committed in such district, that all four robbed districts will form the vertices of some rectangle, parallel to the sides of the map.
Polycarpus is good at deduction but he's hopeless at math. So he asked you to find the district where the fourth robbery will be committed.
|
Required row is row that have only one star inside. Requred column is comumn that also have only one star inside. So, you can iterate over all rows/columns, calculate number of stars inside them and find the answer.
|
[
"brute force",
"geometry",
"implementation"
] | 800
| null |
181
|
B
|
Number of Triplets
|
You are given $n$ points on a plane. All points are different.
Find the number of different groups of three points $(A, B, C)$ such that point $B$ is the middle of segment $AC$.
The groups of three points are considered unordered, that is, if point $B$ is the middle of segment $AC$, then groups $(A, B, C)$ and $(C, B, A)$ are considered the same.
|
Naive solution $O(n^{3})$ (where you check all triplets) doesn't fin into time limits. You can see that for every two points from triplet (for example, for A and C) you can find place of the third point. So you can find number of requred triplets just inerate over all pairs of points and check middle point between points in every pair. How to fast check position? You can add 1000 for all coordinates (you can see that this operation doesn't change the answer) and mark them in the 2-dimensional boolean array 2001x2001. So you can check every position for point in $O(1)$ time. Obtained solution works in $O(n^{2})$.
|
[
"binary search",
"brute force"
] | 1,300
| null |
183
|
A
|
Headquarters
|
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.
The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made \textbf{exactly} $n$ movements on its way from the headquarters to the stall. A movement can move the car from point $(x, y)$ to one of these four points: to point $(x - 1, y)$ which we will mark by letter "L", to point $(x + 1, y)$ — "R", to point $(x, y - 1)$ — "D", to point $(x, y + 1)$ — "U".
The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".
You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point $(0, 0)$, your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).
|
Ad Hoc I supppose... This problem is equivalent to calculating the number of reachable locations from point (0, 0) by doing the allowed moves. The naive solution is to process the information one by one from first to last, and to keep track on all the reachable positions. Claim: At any moment in time, all reachable locations as described above forms a "diamond". An extremely informal proof is by induction: For instance, let's use the first example: UR UL ULDRInitially, there's only one possible location (namely, (0, 0)). It forms the basis of our induction: a diamond with width=1 and height=1. "UR" (and also "DL") extends the width of the diamond into a 2x1 diamond: Then, "UL" (and also "DR") extends the height of the diamond into a 2x2 diamond: Finally, "ULDR" extends both the height and the width of the diamond into a 3x3 diamond: And so there's 9 possible locations. To see that this claim is true, suppose by induction our locations so far forms a diamond. By symmetry we only need to see that in the "UR" case, its width is increased by one (I'll omit the similarly seen "ULDR" case). The idea is the new possible locations = the previous diamond shifted one step up UNION that diamond shifted one step right. Indeed, the union of these two diamonds accounts for both the "U" and the "R" moves. It's not hard to proof that the union of two diamonds with equal dimension that is displaced by vector (1, 1) forms the same diamond with its width increased by 1. So, the solution is to keep track the dimension of the diamond, starting from a 1x1 diamond. Then, simply return width * height.
|
[
"constructive algorithms",
"math"
] | 1,700
| null |
183
|
B
|
Zoo
|
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has $n$ observation binoculars located at the $OX$ axis. For each $i$ between $1$ and $n$, inclusive, there exists a single binocular located at the point with coordinates $(i, 0)$. There are $m$ flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.
In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.
Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.
|
Geometry Since there are at least one flamingo, all binoculars will be able to see at least one flamingo. When a binocular is able to see more than one flamingos, then those two flamingos and the binocular must form a line. How many such lines are there? Instead of iterating for each pair of binocular and flamingo, we iterate over each pair of flamingos. These two pair of flamingos completely determine the line as described above. If there does not exists a binocular in this line, we can ignore this pair and continue. Otherwise, calculate the number of flamingos in this line, and let it be one of the possible number of flamingos visible from that binocular. After this is done, simply sum the maximum number of flamingos of each binocular. This works in O(M^3). Note that this problem can be made to run in O(M^2 log M), but coding that solution is sort of... boring ;3.
|
[
"brute force",
"geometry"
] | 1,700
|
#include <cstdio>
#include <numeric>
#include <iostream>
#include <vector>
#include <set>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <bitset>
#include <queue>
#include <sstream>
#include <deque>
using namespace std;
#define mp make_pair
#define pb push_back
#define rep(i,n) for(int i = 0; i < (n); i++)
#define re return
#define fi first
#define se second
#define sz(x) ((int) (x).size())
#define all(x) (x).begin(), (x).end()
#define sqr(x) ((x) * (x))
#define sqrt(x) sqrt(abs(x))
#define y0 y3487465
#define y1 y8687969
#define next NEXT
#define fill(x,y) memset(x,y,sizeof(x))
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef double D;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<string> vs;
typedef vector<vi> vvi;
template<class T> T abs(T x) { re x > 0 ? x : -x; }
int n;
int m, u;
int x[250], y[250];
int res[1000001];
int main () {
scanf ("%d%d", &n, &m);
for (int i = 0; i < m; i++) scanf ("%d%d", &x[i], &y[i]);
for (int i = 1; i <= n; i++) res[i] = 1;
for (int i = 0; i < m; i++)
for (int j = i + 1; j < m; j++) {
if (y[j] == y[i] || (ll)(x[j] - x[i]) * y[i] % (y[j] - y[i]) != 0) continue;
ll t = x[i] + (ll)(x[j] - x[i]) * y[i] / (y[j] - y[i]);
if (t >= 1 && t <= n) {
int tmp = 0;
for (int k = 0; k < m; k++)
if ((ll)(x[i] - x[k]) * (y[j] - y[k]) - (ll)(x[j] - x[k]) * (y[i] - y[k]) == 0)
tmp++;
res[t] = max (res[t], tmp);
}
}
int ans = 0;
for (int i = 1; i <= n; i++) ans += res[i];
printf ("%d
", ans);
return 0;
}
|
183
|
C
|
Cyclic Coloring
|
You are given a \textbf{directed} graph $G$ with $n$ vertices and $m$ arcs (\textbf{multiple arcs and self-loops} are allowed). You have to paint each vertex of the graph into one of the $k$ $(k ≤ n)$ colors in such way that for all arcs of the graph leading from a vertex $u$ to vertex $v$, vertex $v$ is painted with the next color of the color used to paint vertex $u$.
The colors are numbered cyclically $1$ through $k$. This means that for each color $i$ $(i < k)$ its next color is color $i + 1$. In addition, the next color of color $k$ is color $1$. Note, that if $k = 1$, then the next color for color $1$ is again color $1$.
Your task is to find and print the largest possible value of $k$ $(k ≤ n)$ such that it's possible to color $G$ as described above with $k$ colors. Note that you don't necessarily use all the $k$ colors (that is, for each color $i$ there does not necessarily exist a vertex that is colored with color $i$).
|
DFS Let's drop the (modulo K). That is, the rule becomes: X->Y implies that Y = X+1 Y->X implies that Y = X-1 Notice that this problem is then equivalent to finding the maximum possible K such that the above equation holds for all edges, modulo K.While we still dropping the "modulo K" thingy, we try to calculate the values of each node. We iterate over each node, and if we haven't processed the node: Number the node 0 (or any other number you like). let's denote this by no[i] = 0. DFS the node: DFS(X): if there exists X->Y, then no[Y] = no[X]+1. This follows from the first rule. DFS(X): if there exists Y->X, then no[Y] = no[X]-1. This follows from the second rule. If Y is renumbered (that is, the algorithm has renumber it in the past and we renumber it again), consider the difference between the two numbers. We claim that this difference, if not zero, must be a multiple of K. To see this, suppose the two numbers are A and B. By the way our algorithm works, that node must be able to be numbered A or B. Hence, A == B (mod K) must holds. But then, A-B == 0 (mod K) implies that (A-B) is a multiple of K. If a non-empty multiple of K (let's say it's CYCLEN) is not found in the step above, we claim that the answer is the maximum possible answer: N. Indeed if no such value is found, it means that renumbering the nodes into no[i] % N be correct, since every edge is already consistent with no[i]. Otherwise, we can simply brute force all divisors of CYCLEN and try each of them. Since "trying" uses O(E) time (that is, by setting each number into no[i] % K and checking whether the two rules holds for all edges) , we have a O(number_of_divisors * E) algorithm, which with the given constraints is less than O(E * sqrt(N)).
|
[
"dfs and similar"
] | 2,200
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <set>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <utility>
#include <cstring>
using namespace std;
typedef long long LL;
#define x1 x1_
#define y1 y1_
template<typename T>
inline T Abs(const T& value) { return value < 0 ? -value : value; }
template<typename T>
inline T Sqr(const T& value) { return value * value; }
const int maxn = 101000;
vector<int> e[maxn];
vector<int> ei[maxn];
int b[maxn];
int d[maxn];
int cand = -1;
vector<int> p;
void Dfs(int v, int k) {
b[v] = 1;
d[v] = k;
for (int i = 0; i < e[v].size(); ++i)
if (!b[e[v][i]])
Dfs(e[v][i], k+1);
else if (b[e[v][i]] == 1) {
if (abs(d[v]-d[e[v][i]]+1) != 0)
cand = abs(d[v] - d[e[v][i]] + 1);
}
for (int i = 0; i < ei[v].size(); ++i)
if (!b[ei[v][i]])
Dfs(ei[v][i], k-1);
else if (b[ei[v][i]] == 1) {
if (abs(d[v] - d[ei[v][i]] - 1))
cand = abs(d[v] - d[ei[v][i]] - 1);
}
b[v] = 2;
}
int col[maxn];
bool DfsCan(int v, int x, int mx) {
col[v] = x;
b[v] = 1;
for (int i = 0; i < e[v].size(); ++i)
if (!b[e[v][i]]) {
DfsCan(e[v][i], (x+1)%mx, mx);
} else {
if (col[e[v][i]] != (col[v]+1)%mx)
return false;
}
for (int i = 0; i < ei[v].size(); ++i)
if (!b[ei[v][i]]) {
DfsCan(ei[v][i], (x+mx-1)%mx, mx);
} else {
if (col[ei[v][i]] != (col[v]+mx-1)%mx)
return false;
}
return true;
}
int n, m;
bool Can(int x) {
memset(col, 0, sizeof(col));
memset(b, 0, sizeof(b));
bool res = true;
for (int i = 1; i <= n; ++i)
if (!b[i])
res = (res && DfsCan(i, 0, x));
return res;
}
int main() {
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
e[u].push_back(v);
ei[v].push_back(u);
}
for (int i = 1; i <= n; ++i)
if (!b[i])
Dfs(i, 1);
if (cand == -1) {
cout << n << endl;
exit(0);
} else {
for (int i = cand; i >= 1; --i)
if (cand%i == 0 && Can(i)) {
cout << i << endl;
exit(0);
}
}
return 0;
}
|
183
|
D
|
T-shirt
|
You are going to work in Codeforces as an intern in a team of $n$ engineers, numbered $1$ through $n$. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are $m$ different sizes, numbered $1$ through $m$, and each engineer will fit in a T-shirt of exactly one size.
You don't know the engineers' exact sizes, so you asked your friend, Gerald. Unfortunately, he wasn't able to obtain the exact sizes either, but he managed to obtain for each engineer $i$ and for all sizes $j$, the probability that the size of the T-shirt that fits engineer $i$ is $j$.
Since you're planning to give each engineer one T-shirt, you are going to bring with you exactly $n$ T-shirts. For those $n$ T-shirts, you can bring any combination of sizes (you can bring multiple T-shirts with the same size too!). You don't know the sizes of T-shirts for each engineer when deciding what sizes to bring, so you have to pick this combination based only on the probabilities given by your friend, Gerald.
Your task is to maximize the expected number of engineers that receive a T-shirt of his size.
This is defined more formally as follows. When you finally arrive at the office, you will ask each engineer his T-shirt size. Then, if you still have a T-shirt of that size, you will give him one of them. Otherwise, you don't give him a T-shirt. You will ask the engineers in order starting from engineer $1$, then engineer $2$, and so on until engineer $n$.
|
Dynamic Programming, Probabilities, and a little Greedy Suppose we have decided to bring N1 T-shirts of size 1, N2 T-shirts of size 2, ... NM T-shirts of size M. By the linearity of expectation, the expected number of engineers that will receive a T-shirt is equal to the sum of the expected number of engineers that will receive a T-shirt of size K, for all K. Suppose we bring Ni T-shirts of size i. Define a random variable Xij as the number of engineer that will receive the j-th T-shirt of size Ni that we bring. Hence, the expected number of engineers that will receive the Ni T-shirts of size i that we bring is equal to the sum of Xij over all j. Since Xij is either 0 or 1, Xij is equal to Pij, the probability that there will be an engineer that will receive the j-th T-shirt of size i that we bring. This is equal to the probability that there will be at least j engineers that fits inside T-shirt of size i. As a result of our discussion, to maximize the expectation, it boils to maximizing the sum over Xij. Hence, we receive our first solution: Calculate the value of all Xij, and pick the N largest value. A DP implementation allows us to accumulate all Xij value in O(N*N*M) time, yielding an O(N*N*M) solution. We will now reduce the time limit to O(N*N + N*M). Notice that the algorithm above only need us to find the N largest values of Xij. Denote by f(n, i, j) the probability that, amongst engineers numbere 1 through n, at least j of them fits inside T-shirt of size i. f(n, i, j) can be computed with the following recurrence: f(n, i, j) = f(n-1, i, j-1) * fit_chance(n, i) + f(n-1, i, j) * (1.0 - fit_change(n, i)) Where fit_chance(t-shirt, engineer) is the probability that engineer fits inside the t-shirt size. The formula above can be inferred from simple logic: if the n-th engineer fits inside t-shirt of size i (with fit_change(n, i) probability), then f(n, i, j) is obviously equal to f(n-1, i, j-1). Otherwise, it'll equal f(n-1, i, j). Now, observe that Xij = f(N, i, j). Indeed, this is one of the possible DPs that can lead to the O(N*N*M) solution. However, we will show that we do not need to compute f(n, i, j) for all possible inputs if we're asked to find only the N largest values of Xij. The key observation is the following obvious fact. If Xij is included in the N largest values, then Xi(j-1) must also be included there. Inductively, Xik for k < j must also be included in the N largest values. Indeed, it's obvious that Xij must be non-increasing with respect to j. Hence the algorithm works as follows. First, we create a pool of numbers Xi1, for all i, totalling M numbers. Then, we iterate N times. In each iteration, we pick the largest number in the pool, say, Xij. Then, we add Xij as one of the K largest values. Then, we take out Xij from the pool, and insert Xi(j+1) as its replacement. That it correctly picks the N largest Xij values follows immediately from our argument in the paragraph preceeding this. Now, if we use the recurrence f(n, i, j) above to compute each Xij, what is the complexity of this algorithm? If we memoize f(n, i, j), we claim that it's O(N*N + N*M). To see this, we notice that the only values required to compute f(n, i, j) using the recurrence above are the values f(m, i, l) such that m <= n and l <= j. However, we notice that due to how our algorithm works, when we need to compute Xij, we must have already computed Xi(j-1) before, so that all values f(m, i, l) for m <= n and l <= j-1 are already available. So the only NEW values that we need to compute are f(m, i, j), m <= n. There are n such values. Since we need to compute at most O(N) values of Xij, the total complexity this part contributes is O(N*N). Depending on how you implement the "pick largest from pool" algorithm, the total complexity can be either O(N*N + N*M) or O(N*N + N*log M). Yes, somebody did this in the contest :).
|
[
"dp",
"greedy",
"probabilities"
] | 2,700
|
#include <stdio.h>
#include <ctype.h>
#include <iostream>
#include <math.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <vector>
#include <utility>
#include <assert.h>
#define MPI 3.141592653589793238462643
#define eps 1e-8
#define inf ((int)1e9)
#define pb push_back
#define mp make_pair
using namespace std;
int n, m;
long double P[3100][310];
long double E[310][3100], S[310];
long double T[3100];
long double sum;
int main()
{
int i, j, id, tmp;
long double cv;
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
scanf("%d%d", &n, &m);
for (i=0; i<n; i++)
for (j=0; j<m; j++)
scanf("%d", &tmp), P[i][j]=((long double)tmp)/1000.0;
for (i=0; i<m; i++)
{
E[i][0]=1.0;
for (cv=E[i][0], j=1; j<=n; j++)
S[i]+=cv*P[j-1][i], cv*=(1.0-P[j-1][i]), cv+=E[i][j];
//cerr<<i<<" "<<S[i]<<endl;
}
//cerr<<n<<endl;
for (int ii=0; ii<n; ii++)
{
id=0;
for (j=1; j<m; j++)
if (S[id]<S[j])
id=j;
//cerr<<id<<" "<<S[id]<<endl;
sum+=S[id], memcpy(T,E[id],sizeof(T)), S[id]=0.0;
cv=E[id][0], E[id][0]=0.0;
for (j=1; j<=n; j++)
E[id][j]=cv*P[j-1][id], cv*=(1.0-P[j-1][id]), cv+=T[j];
for (cv=E[id][0], j=1; j<=n; j++)
S[id]+=cv*P[j-1][id], cv*=(1.0-P[j-1][id]), cv+=E[id][j];
}
printf("%.12lf
", (double)sum);
return 0;
}
|
183
|
E
|
Candy Shop
|
The prestigious Codeforces kindergarten consists of $n$ kids, numbered $1$ through $n$. Each of them are given allowance in rubles by their parents.
Today, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all $i$ between $1$ and $m$, inclusive, it sells a package containing exactly $i$ candies. A candy costs one ruble, so a package containing $x$ candies costs $x$ rubles.
The kids will purchase candies in turns, starting from kid 1. In a single turn, kid $i$ will purchase one candy package. Due to the highly competitive nature of Codeforces kindergarten, during a turn, the number of candies contained in the package purchased by the kid will always be strictly greater than the number of candies contained in the package purchased by the kid in the preceding turn (an exception is in the first turn: the first kid may purchase any package). Then, the turn proceeds to kid $i + 1$, or to kid $1$ if it was kid $n$'s turn. This process can be ended at any time, but at the end of the purchase process, all the kids \underline{must have the same number of candy packages}. Of course, the amount spent by each kid on the candies cannot exceed their allowance.
You work at the candy shop and would like to prepare the candies for the kids. Print the maximum number of candies that can be sold by the candy shop to the kids. If the kids cannot purchase any candy (due to insufficient allowance), print $0$.
|
Very greedy Brute force P: the number of Packages each kid will have at the end. There are at most N/M possible such value. We will assume that P is fixed during our discussion. If we know P, we know that if kid i purchases a total of X candies, then kid i+1 must purchase at least X+P candies (1 more than each package purchased by kid i). Hence, assume that money[i] <= money[i+1] - P. Two consecutive packages purchased by the SAME kid must differ by at least M. Indeed, otherwise there are less than M-1 packages for the other M-1 kids to buy from (Pigeonhole rocks by the way). For the sake of our discussions below, we refer to the following example with N=8, and M=3 kids. The allowances of the kids are 7, 10, and 14. Suppose we know all candies kid 0 purchased (red bags denote the packages kid 0 purchased). We claim that the optimal solution can be computed rather... easily with the following greedy algorithm: (assume that the candy packages kid 0 purchase is sorted in an ascending order). We iterate over the remaining kids, starting from kid 1. First, let the kid purchase the minimum possible candies: Next, if the allowance is still greater than the sum of candies, and if one of his package(s) can still be shifted to the right while maintaining the condition that a possible solution exists, do so. If there are multiple package(s) that can be shifted, shifting any of them does not change the optimal answer. Note: since we've assumed that money[i] <= money[i+1]-P, the only condition is that between the package purchased by kid 1 an the next package purchased by kid 0, there exists at least N-2 packages. For instance, this is illegal, since there is no package that kid 2 will be able to purchase between 4 and 5. We iterate this once more for kid 2, obtaining: And we're done. It's arguably the maximum possible value, since there is no reason why we shouldn't shift a package for a kid to the right if we can (formal proof by contradiction). Claim: If we know the packages for kid 0, the maximum total candies purchased can be computed in O(M), where M is the number of kids. The algorithm simulates our discussion above. However it is not obvious how to do that in O(M). So, suppose kid 0 purchase the candies like this: Now, try putting the other P-1 packages into the minimum possible locations: The packages inside the yellow boxes denote what we will call FREEDOM. Basically FREEDOM is the count on how many times we can at most shift a package to the right as in our discussion above. Now, consider kid 1. First, as in our discussion, kid 1 takes the minimum amount of packages, which is equal to sum[kid 0] + P. Next, he will attempt to shift the packages if possible. Notice that the only thing that affects the overall sum of the candy is only the number of shifts performed, not which package actually got shifted. So, this means that, the amount of shift can be easily calculated by min(money[1] - (sum[kid 0] + P), FREEDOM). And then, FREEDOM is deducted from this value, while the amount of candies purchased by kid 1 is incremented by this value. Hence, simulating the algorithm in our discussion if we're only to output the total amount of candies can be done in O(M). The result of our discussion so far is this. Notice that the last algorithm only depends on how many candies kid 0 purchased, and FREEDOM. Now we will remove the assumption that we know which packages kid 0 decides to purchase. Claim: It is optimal for kid 0 to purchase as many candies as possible. Suppose kid 0 does not purchase the maximum possible of candies he can purchase. Now, consider whether or not kid 1 "shifted" his candies. If he shifted any of them, say package X, then instead of purchasing package X-1, kid 0 should purchase package X, improving the overall amount of candies. That is, instead of It's better to If kid 1 did not "shift" his candies because the amount of money he spent is already equal to his allowance, then the amount of candies purchased by kid 0 must be maximum since money[i] <= money[i+1] - P. Otherwise, we can apply this inductively to kid 2 and so forth. That is, instead of It's better to Okay, now we know the sum of candies that we should give to kid 1. Since the performance of our algorithm increase with FREEDOM, we should next try to maximize FREEDOM. Claim: FREEDOM depends only on the position of the FIRST candy package purchased by kid 0. This can be shown by simple computation, and its equal to N - pos - M*P (or something like that). Hence, we should try to minimize the first candy package purchased by kid 0, while keeping the sum maximum. This can be done in O(1) using a bunch of N*(N+1)/M * P formulas. Hence, since there are N/M package numbers to be brute forced, and each iteration uses O(M) time, the total complexity is O(N/M) * O(M) = O(N).
|
[
"greedy"
] | 2,900
|
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <utility>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
#define REP(i,n) for((i)=0;(i)<(int)(n);(i)++)
#define foreach(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
typedef long long ll;
int N;
ll a[200010];
ll M;
ll func(ll Amin, ll Bmax, ll mindiff, ll maxdiff){
int i;
Bmax = min(Bmax, a[N-1]);
REP(i,N-1) Bmax = min(Bmax, a[i] - i * mindiff + maxdiff);
ll ans = 0;
ll x = Bmax;
for(i=N-1;i>=0;i--){
if(i != N-1) x -= mindiff;
x = min(x,a[i]);
if(x < Amin || Bmax - x > maxdiff) return -1;
ans += x;
}
return ans;
}
int main(void){
int c,i;
cin >> N >> M;
REP(i,N) cin >> a[i];
ll ans = 0;
for(c=1;c*N<=M;c++){
ll tri = (ll)c * (c-1) / 2 * N;
ll Amin = tri + c;
ll Bmax = M * c - tri;
ll mindiff = c;
ll maxdiff = M - c;
ll tmp = func(Amin, Bmax, mindiff, maxdiff);
ans = max(ans,tmp);
}
cout << ans << endl;
return 0;
}
|
185
|
A
|
Plant
|
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.
Help the dwarfs find out how many triangle plants that point "upwards" will be in $n$ years.
|
Let's propose, that after the $i$-th year, there is $x$ triangles up and $y$ triangles down. After another iteration we can see, that amount of triangles became - $3x + y$ up and $x + 3y$ down. Let's see the difference between them: at the $i$-th it's $x - y$ and at the $i + 1$-th - it's $(3x + y) - (x + 3y) = 2 * (x - y)$. We can see, that difference between amount of triangles grown up by 2. Because on the $i$-th year the difference became $2^{i}$ and all amount of triangles is $4^{i}$. We can see, that on the $i$-th year the number of our triangles is $\textstyle{\frac{4+2^{2}}{2}}$. That can be computed by modulo p using the fast-power algorithm.
|
[
"math"
] | 1,300
| null |
185
|
B
|
Mushroom Scientists
|
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates $(x, y, z)$. In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: $\sqrt{x^{2}+y^{2}+z^{2}}$. Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals $x^{a}·y^{b}·z^{c}$.
To test the metric of mushroom scientists, the usual scientists offered them a task: find such $x, y, z$ $(0 ≤ x, y, z; x + y + z ≤ S)$, that the distance between the center of the Universe and the point $(x, y, z)$ is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task.
Note that in this problem, it is considered that $0^{0} = 1$.
|
This problem was made by my love to inequalities. :-)! The answer for this problem is $\left({\frac{d\S}{a+b+c}}\colon{\frac{b\S}{a+b+c}}\cdot{\frac{c\S}{a+b+c}}\right)$. Prove: $x^{a}y^{b}z^{c}=a^{a}b^{b}c^{c}\frac{a}{b}\frac{\bar{c}^{c}}{c}\leq a^{a}b^{b}c^{c}(\frac{a\pi^{a}+b+c}{a+b+c}\bar{c})^{a+b+c}=a^{a}b^{b}c^{c}(\frac{s}{a+b+c})^{a+b+c}$. (This is AM-GM inequality. Link for whom don't know it.) The equality becomes only, when $\underset{^{\sim}}{a}=\frac{y}{b}=\frac{z}{c}$. And you should check on zeroes. If $a = b = c = 0$ - you can choose any good answer - $x + y + z \le S$.
|
[
"math",
"ternary search"
] | 1,800
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.