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
⌀ |
|---|---|---|---|---|---|---|---|
494
|
E
|
Sharti
|
During the last 24 hours Hamed and Malek spent all their time playing "Sharti". Now they are too exhausted to finish the last round. So they asked you for help to determine the winner of this round.
"Sharti" is played on a $n × n$ board with some of cells colored white and others colored black. The rows of the board are numbered from top to bottom using number $1$ to $n$. Also the columns of the board are numbered from left to right using numbers $1$ to $n$. The cell located at the intersection of $i$-th row and $j$-th column is denoted by $(i, j)$.
The players alternatively take turns. In each turn the player must choose a square with side-length at most $k$ with its lower-right cell painted white. Then the colors of all the cells in this square are inversed (white cells become black and vice-versa). The player who cannot perform a move in his turn loses.
You know Hamed and Malek are very clever and they would have played their best moves at each turn. Knowing this and the fact that Hamed takes the first turn, given the initial board as described in the input, you must determine which one of them will be the winner.
|
Let's first solve this problem for another game: Suppose that we've an $n \times n$ table. Each cell have some(possibly zero) marbles on it. During each move the player chooses a square with side-length at most $k$ which its lower-right cell has at least one marble, he removes one marble from it and puts one marble in every other cell of this square. One can notice that in such game each marble is independent of the others and doesn't affect other marbles. So one can see this game as some separate games played on some tables. More formally for each marble placed in a cell such as $(i, j)$ consider the game when played on a $i \times j$ table which the only marble placed on it is at its lower-right cell. Let's denote the Grundy number of this game by $g_{i, j}$. Then according to Grundy theorem the first player has a winning strategy if and only if the xor of $g_{i, j}$ for every cell $(i, j)$ having odd number of marbles on it is positive. To calculate $g_{i, j}$ note that the first move in such game must be choosing a square with its lower-right cell being the lower-right cell of table. So the only thing to decide is the side-length of chosen square at the first move. Let's say we choose the first square width side length $l$. Grundy number of the next state will be equal to xor of $g_{c, d}$ for every $i - l < c \le i, j - l < d \le j$. Using this fact one can calculate $g_{i, j}$ for all $(1 \le i, j \le a)$ ($a$ being an arbitrary integers) in $O(a^{3})$. If we calculated the first values of $g_{i, j}$ one can see a pattern in the Grundy numbers. Then one can prove that $g_{i, j} = min(lowest_bit(i), lowest_bit(j), greatest_bit(k))$ where $lowest_bit(x) =$ the maximum power of $2$ which is a divisor of $x$ and $greatest_bit(x) =$ the maximum power of $2$ which is not greater than $x$. Now let's prove that our first game(the game described in the statement) is actually the same as this game. Suppose that a player has a winning strategy in the first game. Consider a table containing one marble at every cell which is white in the table of the first game. We'll prove that the same player has winning strategy in this game as well. Note that a cell is white in the first game if and only if the parity of marbles in the second game is odd so there is at least one marble on it. So as long as the other player chooses a square with its lower-right cell having odd number of marbles in the second game, his move corresponds to a move in the first game so the player having winning strategy can counter his move. If the other player chooses a square with its lower-right cell having even number of marbles, it means the cell had at least 2 marbles on it so the player can counter it by choosing the same square which makes the parity of every cell to be the same after these 2 moves. And since it can be proven that both of the game will end at some point then the player has winning strategy in this game as well. The reverse of this fact can also be proven the same since if a player has a winning strategy there is also a winning strategy in which this player always chooses squares with lower-right cell having odd number of marbles(since otherwise the other player can counter it as described above) and counters the moves of the other player at which he chose a square with lower-right cell having even number of marbles by choosing the same square(since the Grundy number by countering in this way won't change the Grundy number and thus won't change the player with winning strategy). So if we consider a table having one marble at each of the cells which are in at least one of the rectangles given in the input we only need to calculate the Grundy number of this state and check whether it's positive or not to determine the winner. To do this for each $i(1 \le i \le greatest_bit(k))$ lets define $a_{i}$ as the number of cells $(x, y)$ which are contained in at least one of the given rectangles, $2^{i}|x$ and $2^{i}|y$. Lets also define $a_{greatest_bit(k) + 1} = 0$. Then according the fact we described above about $g_{i, j}$ the number of $2^{i}$s which are xored equals $a_{i} - a_{i + 1}$. Knowing this calculating the Grundy number of the initial state is easy. Calculating $a_{i}$ is identical to a very well-known problem which is given some rectangles count the number of cells in at least one of them and can be solved in $O(mlgm)$ ($m$ being number of rectangles). So overall complexity will be $O(mlgmlgk)$.
|
[
"data structures",
"games"
] | 3,200
| null |
495
|
A
|
Digital Counter
|
Malek lives in an apartment block with $100$ floors numbered from $0$ to $99$. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with $7$ light sticks by turning them on or off. The picture below shows how the elevator shows each digit.
One day when Malek wanted to go from floor $88$ to floor $0$ using the elevator he noticed that the counter shows number $89$ instead of $88$. Then when the elevator started moving the number on the counter changed to $87$. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem.
Suppose the digital counter is showing number $n$. Malek calls an integer $x$ ($0 ≤ x ≤ 99$) \underline{good} if it's possible that the digital counter was supposed to show $x$ but because of some(possibly none) broken sticks it's showing $n$ instead. Malek wants to know number of good integers for a specific $n$. So you must write a program that calculates this number. Please note that the counter \textbf{always} shows two digits.
|
For each digit $x$ you can count the number of digits $y$ that because of some broken sticks $x$ is shown instead of $y$ by hand. for example when $x = 3$, $y$ can be $3$, $8$ and $9$. Let's denote this number by $a_{x}$. Then if the input is $xy$ (the first digit shown in the counter is $x$ and the second is $y$) the answer will be $a_{x} \times a_{y}$.
|
[
"implementation"
] | 1,100
| null |
495
|
B
|
Modular Equations
|
Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define $i$ modulo $j$ as the remainder of division of $i$ by $j$ and denote it by $i\,\mathrm{mod}\,j$. A Modular Equation, as Hamed's teacher described, is an equation of the form $a{\bmod{x}}=b$ in which $a$ and $b$ are two non-negative integers and $x$ is a variable. We call a positive integer $x$ for which $a{\bmod{x}}=b$ a \underline{solution} of our equation.
Hamed didn't pay much attention to the class since he was watching a movie. He only managed to understand the definitions of these equations.
Now he wants to write his math exercises but since he has no idea how to do that, he asked you for help. He has told you all he knows about Modular Equations and asked you to write a program which given two numbers $a$ and $b$ determines how many answers the Modular Equation $a{\bmod{x}}=b$ has.
|
If $a < b$ then there is no answer since $a\operatorname*{mod}x\leq a<b$. If $a = b$ then $x$ can be any integer larger than $a$. so there are infinite number of answers to the equation. The only remaining case is when $a > b$. Suppose $x$ is an answer to our equation. Then $x|a - b$. Also since $a{\bmod{x}}=b$ then $b < x$. These conditions are necessary and sufficient as well. So the answer is number of divisors of $a - b$ which are strictly greater than $b$ which can be solved in $O({\sqrt{a-b}})$.
|
[
"math",
"number theory"
] | 1,600
| null |
496
|
A
|
Minimum Difficulty
|
Mike is trying rock climbing but he is awful at it.
There are $n$ holds on the wall, $i$-th hold is at height $a_{i}$ off the ground. Besides, let the sequence $a_{i}$ increase, that is, $a_{i} < a_{i + 1}$ for all $i$ from 1 to $n - 1$; we will call such sequence a \underline{track}. Mike thinks that the track $a_{1}$, ..., $a_{n}$ has \underline{difficulty} $d=\operatorname*{max}_{1<i<n-1}(a_{i+1}-a_{i})$. In other words, difficulty equals the maximum distance between two holds that are adjacent in height.
Today Mike decided to cover the track with holds hanging on heights $a_{1}$, ..., $a_{n}$. To make the problem harder, Mike decided to remove one hold, that is, remove one element of the sequence (for example, if we take the sequence $(1, 2, 3, 4, 5)$ and remove the third element from it, we obtain the sequence $(1, 2, 4, 5)$). However, as Mike is awful at climbing, he wants the final difficulty (i.e. the maximum difference of heights between adjacent holds after removing the hold) to be as small as possible among all possible options of removing a hold. The first and last holds \textbf{must} stay at their positions.
Help Mike determine the minimum difficulty of the track after removing one hold.
|
For every option of removing an element we run through the remaining elements and find the maximal difference between adjacent ones; print the smallest found answer. The solution has complexity $O(n^{2})$. It can be noticed that after removing an element the difficulty either stays the same or becomes equal to the difference between the neighbours of the removed element (whatever is larger); thus, the difficulty for every option of removing an element can be found in $O(1)$, for the total complexity of $O(n)$. Any of these solutions (or even less efficient ones) could pass the tests.
|
[
"brute force",
"implementation",
"math"
] | 900
| null |
496
|
B
|
Secret Combination
|
You got a box with a combination lock. The lock has a display showing $n$ digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.
You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.
|
We observe that the order of operations is not important: we may first perform all the shifts, and after that all the additions. Note that after $n$ shifts the sequence returns to its original state, therefore it is sufficient to consider only the options with less than $n$ shifts. Also, after 10 times of adding 1 to all digits the sequence does not change; we may consider only options with less than 10 additions. Thus, there are overall $10n$ reasonable options for performing the operations; for every option perform the operations and find the smallest answer among all the options. As performing the operations for every option and comparing two answers to choose the best takes $O(n)$ operations, this solution performs about $10n^{2}$ elementary operations. The multiple of $10$ can be get rid of, if we note that after all shifts are made the best choice is to make the first digit equal to zero, and this leaves us but a single option for the number of additions. However, implementing this optimization is not necessary to get accepted.
|
[
"brute force",
"constructive algorithms",
"implementation"
] | 1,500
| null |
496
|
C
|
Removing Columns
|
You are given an $n × m$ rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
\begin{verbatim}
abcd
edfg
hijk
\end{verbatim}
we obtain the table:
\begin{verbatim}
acd
efg
hjk
\end{verbatim}
A table is called \underline{good} if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.
|
Let's look at the first column of the table. If its letters are not sorted alphabetically, then in any valid choice of removing some columns it has to be removed. However, if its letters are sorted, then for every valid choice that has this column removed it can be restored back to the table; it is clear that the new choice is valid (that is, the rows of the new table are sorted lexicographically) and the answer (that is, the number of removed columns) has just became smaller. Consider all columns from left to right. We have already chosen which columns to remove among all the columns to the left of the current one; if leaving the current column in place breaks the lexicographical order of rows, then we have to remove it; otherwise, we may leave it in place to no harm. Arguing in the way of the previous paragraph we can prove that this greedy method yields an optimal (moreover, the only optimal) solution. The complexity is $O(n^{2})$.
|
[
"brute force",
"constructive algorithms",
"implementation"
] | 1,500
| null |
496
|
D
|
Tennis Game
|
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores $t$ points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of $s$ sets, he wins the match and the match is over. Here $s$ and $t$ are some positive integer numbers.
To spice it up, Petya and Gena choose new numbers $s$ and $t$ before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores $t$ points and the match is over as soon as one of the players wins $s$ sets.
Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers $s$ and $t$ for the given match are also lost. The players now wonder what values of $s$ and $t$ might be. Can you determine all the possible options?
|
Choose some $t$; now emulate how the match will go, ensure that the record is valid for this $t$ and by the way find the corresponding value of $s$. Print all valid options for $s$ and $t$. This solution works in $O(n^{2})$ time, which is not good enough, but we will try to optimize it. Suppose the current set if finished and we have processed $k$ serves by now. Let us process the next set as follows: find $t$-th $1$ and $t$-th $2$ after position $k$. If $t$-th $1$ occurs earlier, then the first player wins the set, and the set concludes right after the $t$-th $1$; the other case is handled symmetrically. If the match is not over yet, and in the rest of the record there are no $t$ ones nor $t$ twos, then the record is clearly invalid. This way, every single set in the record can be processed in $O(\log n)$ time using binary search, or $O(1)$ time using precomputed arrays of positions for each player. Now observe that for any $t$ a match of $n$ serves can not contain more than $n / t$ sets, as each set contains at least $t$ serves. If we sum up the upper limits for the number of sets for each $t$, we obtain the total upper limit for the number of sets we may need to process: $n+n/2+n/3+...\cdot=O(n\log n)$ (which is the famous harmonic sum). Using one of the approaches discussed above, one obtains a solution with complexity of $O(n\log^{2}n)$ or $O(n\log n)$; each of these solutions fits the limit nicely. Obviously, for every $t$ there is no more than one valid choice for $s$; however, maybe a bit unexpected, for a given $s$ there may exist more than one valid choice of $t$. The first test where this takes place is pretest 12. The statement requires that the pairs are printed lexicographically ordered; it is possible to make a mistake here and print the pairs with equal $s$ by descending $t$ (if we fill the array by increasing $t$ and then simply reverse the array).
|
[
"binary search"
] | 1,900
| null |
496
|
E
|
Distributing Parts
|
You are an assistant director in a new musical play. The play consists of $n$ musical parts, each part must be performed by exactly one actor. After the casting the director chose $m$ actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations.
First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, $c_{i}$ and $d_{i}$ ($c_{i} ≤ d_{i}$) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — $a_{j}$ and $b_{j}$ ($a_{j} ≤ b_{j}$) — the pitch of the lowest and the highest notes that are present in the part. The $i$-th actor can perform the $j$-th part if and only if $c_{i} ≤ a_{j} ≤ b_{j} ≤ d_{i}$, i.e. each note of the part is in the actor's voice range.
According to the contract, the $i$-th actor can perform at most $k_{i}$ parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes).
The rehearsal starts in two hours and you need to do the assignment quickly!
|
Sort all the parts and actors altogether by increasing lower bounds (if equal, actors precede parts); process all the enitities in this order. We maintain a set of actors which have already occured in the order; if we meet an entry for an actor, add it to the set. If we currently process a part, we have to assign it to an actor; from the current set of actors we have to choose one such that his $d_{i} \ge b_{j}$ (the $c_{i} \le a_{j}$ constraint is provided by the fact that the $i$-th actor has occured earlier than the $j$-th part); if there are no such actors in the set, no answer can be obtained; if there are several actors satisftying this requirement, we should choose one with minimal $d_{i}$ (intuitively, he will be less useful in the future). Assign the chosen actor with the current part and decrement his $k_{i}$; if $k_{i}$ is now zero, the actor can not be used anymore, thus we remove him from the set. To fit the limits we should implement the set of current actors as some efficient data structure (e.g., an std::set or a treap). The resulting complexity is ${\cal O}((n+m)\log(n+m))$.
|
[
"greedy",
"sortings"
] | 2,100
| null |
497
|
D
|
Gears
|
\url{CDN_BASE_URL/e4fa6a6323e7ecee665f560536ee7fd5}
|
When a collision happens, a vertex of one polygon lands on a side of the other polygon. Consider a reference system such that the polygon $A$ is not moving. In this system the polygon $B$ preserves its orientation (that is, does not rotate), and each of its vertices moves on some circle. Intersect all the circles for vertices of $B$ with all the sides of $A$; if any of them intersect, then some vertex of $B$ collides with a side of $A$. Symmetrically, take a reference system associated with $B$ and check whether some vertex of $A$ collides with a side of $B$. The constraints for the points' coordinates are small enough for a solution with absolute precision to be possible (using built-in integer types). Another approach (which is, in fact, basically the same) is such: suppose there is a collision in a reference system associated with $A$. Then the following equality for vectors holds: $x + y = z$; here $z$ is a vector that starts at $P$ and ends somewhere on the bound of $A$, $x$ is a vector that starts at $Q$ and ends somewhere on the bound of $B$, $y$ is a vector that starts at $P$ and ends somewhere on the circle centered at $P$ that passes through $Q$. Rewrite the equality as $y = z - x$; now observe that the set of all possible values of $z - x$ forms the Minkowski sum of $A$ and reflection of $B$ (up to some shift), and the set of all possible values of $y$ is a circle with known parameters. The Minkowski sum can be represented as a union of $nm$ parallelograms, each of which is the Minkowski sum of a pair of sides of different polygons; finally, intersect all parallelograms with the circle. Both solutions have complexity $O(nm)$. As noted above, it is possible to solve the problem using integer arithemetics (that is, with absolute precision); however, the fact that the points' coordinates are small lets most of the solutions with floating point arithmetics pass. It was tempting to write an approximate numerical solution; we struggled hard not to let such solutions pass, and eventually none of them did. =) Many participants had troubles with pretest 8. It looks as follows (the left spiral revolves around the left point, and the right spiral revolves around the right point):
|
[
"brute force",
"geometry",
"math"
] | 2,900
| null |
497
|
E
|
Subsequences Return
|
Assume that $s_{k}(n)$ equals the sum of digits of number $n$ in the $k$-based notation. For example, $s_{2}(5) = s_{2}(101_{2}) = 1 + 0 + 1 = 2$, $s_{3}(14) = s_{3}(112_{3}) = 1 + 1 + 2 = 4$.
The sequence of integers $a_{0}, ..., a_{n - 1}$ is defined as $a_{j}=s_{k}(j){\bmod{k}}$. Your task is to calculate the number of distinct \underline{subsequences} of sequence $a_{0}, ..., a_{n - 1}$. Calculate the answer modulo $10^{9} + 7$.
Sequence $a_{1}, ..., a_{k}$ is called to be a \underline{subsequence} of sequence $b_{1}, ..., b_{l}$, if there is a sequence of indices $1 ≤ i_{1} < ... < i_{k} ≤ l$, such that $a_{1} = b_{i1}$, ..., $a_{k} = b_{ik}$. In particular, an empty sequence (i.e. the sequence consisting of zero elements) is a subsequence of any sequence.
|
Consider some string; how does one count the number of its distinct subsequences? Let us append symbols to the string consequently and each time count the number of subsequences that were not present before. Let's append a symbol $c$ to a string $s$; in the string $s + c$ there are as many subsequences that end in $c$ as there were subsequences in $s$ overall. Add all these subsequences to the number of subsequnces of $s$; now each subsequence is counted once, except for the subsequences that end in $c$ but were already present in $s$ before; these are counted twice. Thus, the total number of subsequences in the new string is twice the total number of subsequences in the old string minus the number of subsequences in the old string which end in $c$. This leads us to the following solution: for each symbol $c$ store how many subsequences end in $c$, denote $cnt_{c}$. Append symbol $c$; now $cnt_{c}$ becomes equal to the sum of all $cnt$'s plus one (for the empty subsequence), and all the other $cnt$'s do not change. For example, consider the first few symbols of the Thue-Morse sequence: $ \epsilon $ - (0, 0) $ \epsilon $ - (0, 0) $0$ - ( 0 + 0 + 1 = 1, 0) $0$ - ( 0 + 0 + 1 = 1, 0) $01$ - (1, 1 + 0 + 1 = 2) $01$ - (1, 1 + 0 + 1 = 2) $011$ - (1, 1 + 2 + 1 = 4) $011$ - (1, 1 + 2 + 1 = 4) $0110$ - ( 1 + 4 + 1 = 6, 4) $0110$ - ( 1 + 4 + 1 = 6, 4) ... ... Let us put the values of $cnt$ in the coordinates of a vector, and also append a coordinate which is always equal to 1. It is now clear that appending a symbol to the string alters the vector as a multiplication by some matrix. Let us assign a matrix for each symbol, and also for each string as a product of matrices for the symbols of the strings in that order. Now, consider the prefix of the sequence $a_{i}$ of length $k^{m}$. Divide it into $k$ parts of length $k^{m - 1}$; $x$-th ($0$-based) of these parts can be obtained from the $0$-th one by adding $x$ modulo $k$ to all elements of the part. Let us count the matrices (see above) for the prefixes of length $k^{m}$, and also for all strings that are obtained by adding $x$ to all of the prefixes' elements; denote such matrix $A_{m, x}$. It is easy to see that if $m > 0$, then $A_{m.x}=A_{m-1.x}A_{m-1.(x+1)\,\mathrm{mod}\,k\cdot\cdot\cdot A_{m-1.(x+k-1)\,m o d}\,k}$. This formula allows us to count $A_{m, x}$ for all $m\leq\log_{k}n$ and all $x$ from 0 to $k - 1$ in $O(l o g_{k}n\times k\times k\times k^{3})=O(\log n\times k^{5}/l o g k)$ time. Now, upon having all $A_{m, x}$ we can multiply some of them in the right order to obtain the matrix for the prefix of the sequence $a_{i}$ of length $n$. Unfortunately, this is not quite enough as the solution doesn't fit the time limit yet. Here is one way to speed up sufficiently: note that the product in the formula $A_{m.x}=A_{m-1.x}A_{m-1.(x+1)\,\mathrm{mod}\,k\cdot\cdot\cdot A_{m-1.(x+k-1)\,m o d}\,k}$ can be divided as shown: $A_{m - 1, x}... A_{m - 1, k - 1} \times A_{m - 1, 0}... A_{m - 1, x - 1}$ (if $x = 0$, take the second part to be empty). Count all the "prefixes" and "suffixes" products of the set $A_{m, x}$: $P_{m, x} = A_{m, 0}... A_{m, x - 1}$, $S_{m, x} = A_{m, x}... A_{m, k - 1}$. Now $A_{m, x} = S_{m - 1, x}P_{m - 1, x}$. Thus, the computation of $A_{m, x}$ for all $x$ and a given $m$ can be done as computing all $P_{m - 1, x}$, $S_{m - 1, x}$ using $O(k)$ matrix multiplications, and each $A_{m, x}$ is now can be found using one matrix multiplication. Finally, the solution now works in $O(\log n\times k^{4}/\log k)$ time, which fits the limits by a margin.
|
[
"dp",
"matrices"
] | 2,900
| null |
498
|
A
|
Crazy Town
|
Crazy Town is a plane on which there are $n$ infinite line roads. Each road is defined by the equation $a_{i}x + b_{i}y + c_{i} = 0$, where $a_{i}$ and $b_{i}$ are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.
Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).
Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.
|
It can be easily proved that, if two points from statement are placed on different sides of some line, this line will be crossed anyway. So, all we need to do is to cross all these lines, so the answer is the number of these lines. To check if two points lies on different sides of a line one can simply use its coordinates to place in line equation and check if these two values have different signs. Solution complexity - $O(n)$.
|
[
"geometry"
] | 1,700
| null |
498
|
B
|
Name That Tune
|
It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of $n$ songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on.
The $i$-th song of AC/PE has its recognizability $p_{i}$. This means that if the song has not yet been recognized by you, you listen to it for exactly one more second and with probability of $p_{i}$ percent you recognize it and tell it's name. Otherwise you continue listening it. Note that you can only try to guess it only when it is integer number of seconds after the moment the song starts playing.
In all AC/PE songs the first words of chorus are the same as the title, so when you've heard the first $t_{i}$ seconds of $i$-th song and its chorus starts, you immediately guess its name for sure.
For example, in the song Highway To Red the chorus sounds pretty late, but the song has high recognizability. In the song Back In Blue, on the other hand, the words from the title sound close to the beginning of the song, but it's hard to name it before hearing those words. You can name both of these songs during a few more first seconds.
Determine the expected number songs of you will recognize if the game lasts for exactly $T$ seconds (i. e. you can make the last guess on the second $T$, after that the game stops).
\textbf{If all songs are recognized faster than in $T$ seconds, the game stops after the last song is recognized.}
|
Let's numerate all the songs and seconds starting from 0. Problem will be solved using DP approach. State will be described by two integers $(i, j)$: $dp[i][j]$ is probability of that we named exactly $i$ songs, and the last named song was named exactly before $j$'th second (after $j - 1$ seconds). $dp[0][0] = 1$ obviously. To make a move from state $(i, j)$ to state $(i + 1, j + k)$ ($1 \le k < t_{i}$), we must name the song exactly after $k$ seconds its playing - probability of that is $(1 - p_{i})^{k - 1} \cdot p_{i}$. To fixed state $(i + 1, j)$ sum of that moves can be represented as $\sum d p[i][j-k]\cdot(1-p_{i})^{k-1}\cdot p_{i}$. Simple calculation of this value for each state gives $O(nT^{2})$ complexity, so one must notice, that this values can be calculated using two pointers for fixed $i$ (in common case it represent a segment with $t_{i}$ length) for every $j$ in time $O(T)$. This way calculating this type of moves takes $O(nT)$ time. There is also a move to $(i + 1, j + t_{i})$ and a move from $(i, j)$ to $(i, (j + k) = T)$, when we couldn't name current song in time $T$. This types of moves is calculated with $O(nT)$ too. Solution complexity - $O(nT)$.
|
[
"dp",
"probabilities",
"two pointers"
] | 2,400
| null |
498
|
C
|
Array and Operations
|
You have written on a piece of paper an array of $n$ positive integers $a[1], a[2], ..., a[n]$ and $m$ good pairs of integers $(i_{1}, j_{1}), (i_{2}, j_{2}), ..., (i_{m}, j_{m})$. Each good pair $(i_{k}, j_{k})$ meets the following conditions: $i_{k} + j_{k}$ is an odd number and $1 ≤ i_{k} < j_{k} ≤ n$.
In one operation you can perform a sequence of actions:
- take one of the good pairs $(i_{k}, j_{k})$ and some integer $v$ ($v > 1$), which divides both numbers $a[i_{k}]$ and $a[j_{k}]$;
- divide both numbers by $v$, i. e. perform the assignments: $a[i_{k}]={\frac{a[i_{k}]}{n}}$ and $a[j_{k}]={\frac{a[j_{k}]}{\phantom{\alpha}n}}$.
Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations.
|
We will divide only by prime numbers. First, let's build a graph, where each of $n$ numbers have own vertex group: Find all prime factors of current number. Every factor will have its own vertex in a group, furthermore, if some factor $p$ has power of $a_{i}$ in current number, it will have exactly $a_{i}$ vertexes in group. The number of vertexes in such graph is $O(n\log A)$. Now we will make edges in our graph: edge between two vertexes exists if and only if there is a good pair (given in statement) of vertexes group numbers and the prime values of a vertexes are the same. That means that we can divide that group numbers by that prime. The number of edges is $O(m\log^{2}A)$. Good pairs are given the way that our graph is bipartite. After finding maximum matching in this graph we represent the way of doing operations as described in the statement. As soon as solution is using Kuhn's algorithm, its complexity is $O(n m\log^{3}A)$. One could notice that some of the edges are useless and reduce it to $O(n m\log^{2}A)$.
|
[
"flows",
"graph matchings",
"number theory"
] | 2,100
| null |
498
|
D
|
Traffic Jams in the Land
|
Some country consists of $(n + 1)$ cities, located along a straight highway. Let's number the cities with consecutive integers from $1$ to $n + 1$ in the order they occur along the highway. Thus, the cities are connected by $n$ segments of the highway, the $i$-th segment connects cities number $i$ and $i + 1$. Every segment of the highway is associated with a positive integer $a_{i} > 1$ — the period of traffic jams appearance on it.
In order to get from city $x$ to city $y$ ($x < y$), some drivers use the following tactics.
Initially the driver is in city $x$ and the current time $t$ equals zero. Until the driver arrives in city $y$, he perfors the following actions:
- if the current time $t$ is a multiple of $a_{x}$, then the segment of the highway number $x$ is now having traffic problems and the driver stays in the current city for one unit of time (formally speaking, we assign $t = t + 1$);
- if the current time $t$ is not a \textbf{multiple} of $a_{x}$, then the segment of the highway number $x$ is now clear and that's why the driver uses one unit of time to move to city $x + 1$ (formally, we assign $t = t + 1$ and $x = x + 1$).
You are developing a new traffic control system. You want to consecutively process $q$ queries of two types:
- determine the final value of time $t$ after the ride from city $x$ to city $y$ ($x < y$) assuming that we apply the tactics that is described above. Note that for each query $t$ is being reset to $0$.
- replace the period of traffic jams appearing on the segment number $x$ by value $y$ (formally, assign $a_{x} = y$).
Write a code that will effectively process the queries given above.
|
The solution of a problem - 60 (LCM of a numbers from 2 to 6) segment trees. In $v$'th segment tree we will hold for every segment $[l, r]$ the next value: minimum time needed to get from $l$ to $r$ if we start in a moment of time equal to $v$ modulo 60. Using these trees' values it is easy to quickly answer the questions, carefully changing the trees' values.
|
[
"data structures",
"dp",
"number theory"
] | 2,400
| null |
498
|
E
|
Stairs and Lines
|
You are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height $i$ is $w_{i}$ squares. Formally, the figure is created by consecutively joining rectangles of size $w_{i} × i$ so that the $w_{i}$ sides lie on one straight line. Thus, for example, if all $w_{i} = 1$, the figure will look like that (different colors represent different rectangles):
And if $w = {5, 1, 0, 3, 0, 0, 1}$, then it looks like that:
Find the number of ways to color some borders of the figure's inner squares so that no square had all four borders colored. The borders of the squares lying on the border of the figure should be considered painted. The ways that differ with the figure's rotation should be considered distinct.
|
The problem is solved using DP approach $dp[i][mask]$ - the number of ways to paint first $i$ blocks of a ladder the way that the last layer of vertical edges is painted as described in mask $mask$. This could be easily recalculated using matrix $M[mask1][mask2]$ - the number of ways to paint horizontal edges between two neighbour vertical layers painted as represented by masks $mask1$ and $mask2$. For fixed $i$ we have $w_{i}$ layers, so this matrix must be multiplied by itself $w_{i}$ times, which can be quickly done by binary-pow algorithm. After that this matrix is simply used in dynamic described above. Solution complexity - $O(8^{7}\cdot\sum\log w_{i})$.
|
[
"dp",
"matrices"
] | 2,700
| null |
499
|
A
|
Watching a movie
|
You have decided to watch the best moments of some movie. There are two buttons on your player:
- Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.
- Skip exactly $x$ minutes of the movie ($x$ is some fixed positive integer). If the player is now at the $t$-th minute of the movie, then as a result of pressing this button, it proceeds to the minute $(t + x)$.
Initially the movie is turned on in the player on the first minute, and you want to watch exactly $n$ best moments of the movie, the $i$-th best moment starts at the $l_{i}$-th minute and ends at the $r_{i}$-th minute (more formally, the $i$-th best moment consists of minutes: $l_{i}, l_{i} + 1, ..., r_{i}$).
Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?
|
One can solve the problem using greedy algorithm: if we can skip $x$ minutes at current moment without skipping any good moment - we do that, otherwise - watch another minute of the film.
|
[
"greedy",
"implementation"
] | 1,000
| null |
499
|
B
|
Lecture
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
In this task you must find for every string in the text the pair containing that string, and from two strings of that pair output the shortest one.
|
[
"implementation",
"strings"
] | 1,000
| null |
500
|
A
|
New Year Transportation
|
New Year is coming in Line World! In this world, there are $n$ cells numbered by integers from $1$ to $n$, as a $1 × n$ board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of $n - 1$ positive integers $a_{1}, a_{2}, ..., a_{n - 1}$. For every integer $i$ where $1 ≤ i ≤ n - 1$ the condition $1 ≤ a_{i} ≤ n - i$ holds. Next, he made $n - 1$ portals, numbered by integers from 1 to $n - 1$. The $i$-th ($1 ≤ i ≤ n - 1$) portal connects cell $i$ and cell $(i + a_{i})$, and one can travel from cell $i$ to cell $(i + a_{i})$ using the $i$-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell $(i + a_{i})$ to cell $i$ using the $i$-th portal. It is easy to see that because of condition $1 ≤ a_{i} ≤ n - i$ one can't leave the Line World using portals.
Currently, I am standing at cell $1$, and I want to go to cell $t$. However, I don't know whether it is possible to go there. Please determine whether I can go to cell $t$ by only using the construted transportation system.
|
Let's assume that I am in the cell $i$ ($1 \le i \le n$). If $i \le n - 1$, I have two choices: to stay at cell $i$, or to go to cell $(i + a_{i})$. If $i = t$, we are at the target cell, so I should print "YES" and terminate. If $i > t$, I cannot go to cell $t$ because I can't use the portal backwards, so one should print "NO" and terminate. Otherwise, I must go to cell $(i + a_{i})$. Using this method, I visit each cell at most once, and there are $n$ cells, so the problem can be solved in linear time. There are 9 pretests in this problem. There are no test where $n = t$ holds in pretests. Many people didn't handle this case, and got hacked or got Wrong Answer on test 13. Time: $O(n)$ Memory: $O(n)$ (maybe $O(1)$)
|
[
"dfs and similar",
"graphs",
"implementation"
] | 1,000
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef double lf;
typedef unsigned int uint;
typedef long double llf;
typedef pair<int, int> pii;
const int N_ = 30500;
int N, T, A[N_];
int main() {
scanf("%d%d", &N, &T);
for(int i = 1; i < N; i++) {
scanf("%d", &A[i]);
}
A[N] = 1;
for(int cur = 1; cur <= N; cur += A[cur]) {
if(cur == T) return 0 & puts("YES");
}
puts("NO");
return 0;
}
|
500
|
B
|
New Year Permutation
|
User ainta has a permutation $p_{1}, p_{2}, ..., p_{n}$. As the New Year is coming, he wants to make his permutation as pretty as possible.
Permutation $a_{1}, a_{2}, ..., a_{n}$ is prettier than permutation $b_{1}, b_{2}, ..., b_{n}$, if and only if there exists an integer $k$ ($1 ≤ k ≤ n$) where $a_{1} = b_{1}, a_{2} = b_{2}, ..., a_{k - 1} = b_{k - 1}$ and $a_{k} < b_{k}$ all holds.
As known, permutation $p$ is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an $n × n$ binary matrix $A$, user ainta can swap the values of $p_{i}$ and $p_{j}$ ($1 ≤ i, j ≤ n$, $i ≠ j$) if and only if $A_{i, j} = 1$.
Given the permutation $p$ and the matrix $A$, user ainta wants to know the prettiest permutation that he can obtain.
|
It seems that many contestants were confused by the statement, so let me clarify it first. Given a permutation $p_{1}, p_{2}, ..., p_{n}$ and a $n \times n$-sized binary matrix $A$, the problem asks us to find the lexicographically minimum permutation which can be achieved by swapping two distinct elements $p_{i}$ and $p_{j}$ where the condition $A_{i, j} = 1$ holds. (From the statement, permutation $A$ is prettier than permutation $B$ if and only if $A$ is lexicographically less than $B$.) Let's think matrix $A$ as an adjacency matrix of a undirected unweighted graph. If two vertices $i$ and $j$ are in the same component (in other words, connected by some edges), the values of $p_{i}$ and $p_{j}$ can be swapped, using a method similar to bubble sort. Look at the picture below for easy understanding. Because all the two distinct vertices in the same component can be swapped, the vertices in the same component can be sorted. In conclusion, we can solve the problem by the following procedure. Find all the connected components. For each component, sort the elements in the component. Print the resulting permutation. The size limit is quite small, so one can use any algorithm (DFS/BFS/..) for as many times as you want. Time: $O(n^{2})$ - because of the graph traversal. $O(n^{3})$ is okay because of small constraints. Memory: $O(n^{2})$
|
[
"dfs and similar",
"dsu",
"graphs",
"greedy",
"math",
"sortings"
] | 1,600
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
using namespace std;
typedef long long ll;
typedef double lf;
typedef long double llf;
typedef unsigned long long llu;
const int N_ = 1050;
int N;
int P[N_];
char S[N_];
int group[N_];
int find_group(int x) {
if (x == group[x]) return x;
return group[x] = find_group(group[x]);
}
void merge_group(int a, int b) {
a = find_group(a);
b = find_group(b);
if (a != b) group[a] = b;
}
vector<int> pos[N_];
int cnt[N_];
int main() {
scanf("%d", &N);
for (int i = 1; i <= N; i++) group[i] = i;
for (int i = 1; i <= N; i++) scanf("%d", &P[i]);
for (int i = 1; i <= N; i++) {
scanf("%s", S + 1);
for (int j = 1; j <= N; j++) if (S[j] == '1') merge_group(i, j);
}
for (int i = 1; i <= N; i++) pos[find_group(i)].push_back(P[i]);
for (int i = 1; i <= N; i++) sort(pos[i].begin(), pos[i].end());
for (int i = 1; i <= N; i++) {
int g = find_group(i);
printf("%d%c", pos[g][cnt[g]++], (i == N) ? '\n' : ' ');
}
return 0;
}
|
500
|
C
|
New Year Book Reading
|
New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has $n$ books numbered by integers from 1 to $n$. The weight of the $i$-th ($1 ≤ i ≤ n$) book is $w_{i}$.
As Jaehyun's house is not large enough to have a bookshelf, he keeps the $n$ books by stacking them vertically. When he wants to read a certain book $x$, he follows the steps described below.
- He lifts all the books above book $x$.
- He pushes book $x$ out of the stack.
- He puts down the lifted books without changing their order.
- After reading book $x$, he puts book $x$ on the top of the stack.
He decided to read books for $m$ days. In the $j$-th ($1 ≤ j ≤ m$) day, he will read the book that is numbered with integer $b_{j}$ ($1 ≤ b_{j} ≤ n$). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.
After making this plan, he realized that the total weight of books he should lift during $m$ days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?
|
In order to calculate the minimum possible lifted weight, we should find the initial stack first. Let's find the positions one by one. First, let's decide the position of book $b_{1}$. After day 1, book $b_{1}$ will be on the top of the stack, regardless of the order of the initial stack. Therefore, in order to minimize the lifted weight during day 1, book $b_{1}$ must be on the top of the initial stack. (so actually, in day 1, Jaehyun won't lift any book) Next, let's decide the position of book $b_{2}$. (assume that $b_{1} \neq b_{2}$ for simplicity) Currently, $b_{1}$ is on the top of the stack, and it cannot be changed because of the procedure. Therefore, in order to minimize the lifted weight during day 2, book $b_{2}$ must be immediately below book $b_{1}$. Considering this, we can find the optimal strategy to create the initial stack: Scan $b_{1}, b_{2}, ..., b_{m}$ step by step. Let's assume that I am handling $b_{i}$ now. If $b_{i}$ has appeared before (formally, if $b_{i}\in\{b_{1},b_{2},\cdot\cdot\cdot,b_{i-1}\}$), erase $b_{i}$ from the sequence. Otherwise, leave $b_{i}$. The resulting sequence will be the optimal stack. You should note that it is not necessary for Jaehyun to read all the books during 2015, which means the size of the resulting sequence may be smaller than $n$. The books which doesn't appear in the resulting sequence must be in the bottom of the initial stack (obviously). However, this problem doesn't require us to print the initial stack, so it turned out not to be important. In conclusion, finding the initial stack takes $O(n + m)$ time. After finding the initial stack, we can simulate the procedure given in the statement naively. It will take $O(nm)$ time. Time: $O(nm)$ Memory: $O(n + m)$
|
[
"constructive algorithms",
"greedy",
"implementation",
"math"
] | 1,600
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef double lf;
typedef unsigned int uint;
typedef long double llf;
typedef pair<int, int> pii;
const int N_ = 505, M_ = 1050;
int N, M;
int W[N_], D[M_];
bool used[N_];
int pile[N_], pile_n;
int ans;
int main() {
scanf("%d%d", &N, &M);
for(int i = 1; i <= N; i++) {
scanf("%d", &W[i]);
}
for(int i = 1; i <= M; i++) {
scanf("%d", &D[i]);
if(!used[D[i]]) pile[++pile_n] = D[i], used[D[i]] = true;
}
for(int i = 1; i <= N; i++) if(!used[i]) pile[++pile_n] = i;
for(int i = 1; i <= M; i++) {
for(int j = 1; j <= N; j++) {
if(pile[j] == D[i]) {
for(int k = j; k > 1; k--) pile[k] = pile[k - 1];
pile[1] = D[i];
break;
}
ans += W[pile[j]];
}
}
printf("%d\n", ans);
return 0;
}
|
500
|
D
|
New Year Santa Network
|
New Year is coming in Tree World! In this world, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to $n$, and the roads are numbered by integers from $1$ to $n - 1$. Let's define $d(u, v)$ as total length of roads on the path between city $u$ and city $v$.
As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the $i$-th year, the length of the $r_{i}$-th road is going to become $w_{i}$, which is shorter than its length before. Assume that the current year is year $1$.
Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities $c_{1}$, $c_{2}$, $c_{3}$ and make exactly one warehouse in each city. The $k$-th ($1 ≤ k ≤ 3$) Santa will take charge of the warehouse in city $c_{k}$.
It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to $d(c_{1}, c_{2}) + d(c_{2}, c_{3}) + d(c_{3}, c_{1})$ dollars. Santas are too busy to find the best place, so they decided to choose $c_{1}, c_{2}, c_{3}$ randomly uniformly over all triples of distinct numbers from $1$ to $n$. Santas would like to know the expected value of the cost needed to build the network.
However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.
|
The problem asks us to calculate the value of Let's write it down.. So, we need to calculate the value of $\sum_{1<u,v<n,u>v}d(u,v)$. I'll denote the sum as $S$. How should we calculate this? For simplicity, I'll set node 1 as the root of the tree. Let's focus on an edge $e$, connecting two vertices $u$ and $p$. See the picture below. Set $A$ is a set of vertices in the subtree of vertex $u$, and set $B$ is a set of vertices which is not in the subtree of vertex $u$. So, $A\cup B$ is the set of vertices in the tree, and $A\cap B$ is empty. For all pairs of two vertices $(x, y)$ where the condition $x\in A$ and $y\in B$ holds, the shortest path between $x$ and $y$ contains edge $e$. There are $size(A) \times size(B)$ such pairs. So, edge $e$ increases the sum $S$ by $2 \times l_{e} \times size(A) \times size(B)$. (because $d(x, y)$ and $d(y, x)$ both contributes to $S$) $size(A)$ (the size of the subtree whose root is $u$) can be calculated by dynamic programming in trees, which is well known. $size(B)$ equals to $N - size(A)$. So, for each edge $e$, we can pre-calculate how many times does this edge contributes to the total sum. Let's define $t(e) = size(A) \times size(B)$, ($A$ and $B$ is mentioned above). If the length of a certain road $e$ decreases by $d$, $S$ will decrease by $t(e) \times d$. So we can answer each query. Time: $O(n)$ (pre-calculation) + $O(q)$ (query) Memory: $O(n)$ ($O(n + q)$ is okay too)
|
[
"combinatorics",
"dfs and similar",
"graphs",
"trees"
] | 1,900
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
#include <list>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef double lf;
typedef unsigned int uint;
typedef long double llf;
typedef pair<int, int> pii;
const int N_ = 100500;
int N;
vector<int> tree[N_];
int parent[N_];
int sz[N_];
ll cnt[N_];
int num[N_];
int length[N_];
int nd[N_];
int Q;
void dfs (int u, int p = -1) {
sz[u] = 1;
parent[u] = p;
for(int e = 0; e < tree[u].size(); e++) {
int v = tree[u][e];
if(v == p) continue;
dfs(v, u);
sz[u] += sz[v];
cnt[v] = (ll)sz[v] * (N - sz[v]) * 2;
length[u] ^= length[v];
num[u] ^= num[v];
}
}
int main() {
scanf("%d", &N);
for(int i = 1; i <= N-1; i++) {
int u, v, l; scanf("%d%d%d", &u, &v, &l);
tree[u].push_back(v);
tree[v].push_back(u);
length[u] ^= l;
length[v] ^= l;
num[u] ^= i;
num[v] ^= i;
}
dfs(1);
ll ans = 0;
for(int i = 2; i <= N; i++) {
ans += cnt[i] * length[i];
nd[num[i]] = i;
}
lf factor = 3. / ((lf)N * (N-1));
scanf("%d", &Q);
while(Q--) {
int e, d; scanf("%d%d", &e, &d);
int u = nd[e];
ans += cnt[u] * (d - length[u]);
length[u] = d;
printf("%.10lf\n", (lf)ans * factor);
}
return 0;
}
|
500
|
E
|
New Year Domino
|
Celebrating the new year, many people post videos of falling dominoes; Here's a list of them: https://www.youtube.com/results?search_query=New+Years+Dominos
User ainta, who lives in a 2D world, is going to post a video as well.
There are $n$ dominoes on a 2D Cartesian plane. $i$-th domino ($1 ≤ i ≤ n$) can be represented as a line segment which is parallel to the $y$-axis and whose length is $l_{i}$. The lower point of the domino is on the $x$-axis. Let's denote the $x$-coordinate of the $i$-th domino as $p_{i}$. Dominoes are placed one after another, so $p_{1} < p_{2} < ... < p_{n - 1} < p_{n}$ holds.
User ainta wants to take a video of falling dominoes. To make dominoes fall, he can push a single domino to the right. Then, the domino will fall down drawing a circle-shaped orbit until the line segment totally overlaps with the x-axis.
Also, if the $s$-th domino touches the $t$-th domino while falling down, the $t$-th domino will also fall down towards the right, following the same procedure above. Domino $s$ touches domino $t$ if and only if the segment representing $s$ and $t$ intersects.
See the picture above. If he pushes the leftmost domino to the right, it falls down, touching dominoes (A), (B) and (C). As a result, dominoes (A), (B), (C) will also fall towards the right. However, domino (D) won't be affected by pushing the leftmost domino, but eventually it will fall because it is touched by domino (C) for the first time.
The picture above is an example of falling dominoes. Each red circle denotes a touch of two dominoes.
User ainta has $q$ plans of posting the video. $j$-th of them starts with pushing the $x_{j}$-th domino, and lasts until the $y_{j}$-th domino falls. But sometimes, it could be impossible to achieve such plan, so he has to lengthen some dominoes. It costs one dollar to increase the length of a single domino by $1$. User ainta wants to know, for each plan, the minimum cost needed to achieve it. Plans are processed independently, i. e. if domino's length is increased in some plan, it doesn't affect its length in other plans. Set of dominos that will fall except $x_{j}$-th domino and $y_{j}$-th domino doesn't matter, but the initial push should be on domino $x_{j}$.
|
From the statement, it is clear that, when domino $i$ falls to the right, it makes domino $j$ also fall if and only if $p_{i} < p_{j} \le p_{i} + l_{i}$. For each domino $i$, let's calculate the rightmost position of the fallen dominoes $R[i]$ when we initially pushed domino $i$. From the definition, $R[i]=\operatorname*{max}\{p_{i}+l_{i},\operatorname*{max}\{R[j]\mid p_{i}<p_{j}\leq p_{i}+l_{i}\}\}$. This can be calculated by using a segment tree or using a stack, in decreasing order of $i$ (from right to left). After that, we define $U[i]$ as the smallest $j$ where $R[i] < p_{j}$ holds. (In other words, the smallest $j$ where domino $j$ is not affected by pushing domino $i$) Now, the problem becomes: Calculate $P[U[x_{i}]] - R[x_{i}] + P[U[U[x_{i}]]] - R[U[x_{i}]] + ...$, until $U[x_{i}] \le y_{i}$. Because $i < U[i]$, this task can be solved by precalculating 'jumps' of $2^{something}$ times, using the method described in here. You must read the "Another easy solution in <O(N logN, O(logN)>" part.. Formally, let's define $U^{n + 1}[k] = U[U^{n}[k]]$ and $S^{n + 1}[k] = S^{n}[k] + (P[U^{n + 1}[k]] - R[U^{n}[k]])$. So, $S^{n}[k]$ means the sum of domino length extensions when we initially push domino $i$ and we prolonged the length exactly $n$ times. $U^{2i + 1}[k] = U^{2i}[U^{2i}[k]]$, and $S^{2i + 1}[k] = S^{2i}[k] + S^{2i}[U^{2i}[k]]$ holds. (If you don't understand this part, I suggest you to read the article linked above) Time : $O(n\log n+q\log n)$ or $O(n+q\log n)$. Memory : $O(n\log n)$
|
[
"data structures",
"dp",
"dsu"
] | 2,300
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef double lf;
typedef unsigned int uint;
typedef long double llf;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
const int N_ = 200500;
const int LEAF = 131072;
const int Q_ = 300500;
const int lgN_ = 18;
int N, P[N_], L[N_];
namespace rmq {
int tree[N_];
void upd (int x, int v) {
while(x <= N) {
tree[x] = max(tree[x], v);
x += x & -x;
}
}
int get (int x) {
int ret = 0;
while(x > 0) {
ret = max(ret, tree[x]);
x -= x & -x;
}
return ret;
}
};
int rightmost[N_];
int nxt[lgN_][N_];
int tb[lgN_][N_];
int Q;
int main() {
scanf("%d", &N);
for(int i = 1; i <= N; i++) scanf("%d%d", &P[i], &L[i]);
for(int i = N; i > 0; i--) {
rightmost[i] = max(
P[i] + L[i],
rmq::get(upper_bound(P+1, P+N+1, P[i]+L[i]) - P - 1)
);
nxt[0][i] = upper_bound(P+1, P+N+1, rightmost[i]) - P;
tb[0][i] = max(P[nxt[0][i]] - rightmost[i], 0);
rmq::upd(i, rightmost[i]);
}
nxt[0][N+1] = N+1;
for(int k = 1; k < lgN_; k++) {
nxt[k][N+1] = N+1;
for(int i = 1; i <= N; i++) {
nxt[k][i] = nxt[k-1][nxt[k-1][i]];
tb[k][i] = tb[k-1][i] + tb[k-1][nxt[k-1][i]];
}
}
scanf("%d", &Q);
while(Q--) {
int x, y; scanf("%d%d", &x, &y);
int ret = 0;
for(int k = lgN_-1; k >= 0; k--) {
if(nxt[k][x] <= y) {
ret += tb[k][x];
x = nxt[k][x];
}
}
printf("%d\n", ret);
}
return 0;
}
|
500
|
F
|
New Year Shopping
|
Dohyun is running a grocery store. He sells $n$ items numbered by integers from 1 to $n$. The $i$-th ($1 ≤ i ≤ n$) of them costs $c_{i}$ dollars, and if I buy it, my happiness increases by $h_{i}$. Each item can be displayed only for $p$ units of time because of freshness. As Dohyun displays the $i$-th item at time $t_{i}$, the customers can buy the $i$-th item only from time $t_{i}$ to time $t_{i} + (p - 1)$ inclusively. Also, each customer cannot buy the same item more than once.
I'd like to visit Dohyun's grocery store and buy some items for the New Year Party, and maximize my happiness. Because I am a really busy person, I can visit the store only once, and for very short period of time. In other words, if I visit the store at time $t$, I can only buy the items available at time $t$. But I can buy as many items as possible, if the budget holds. I can't buy same item several times due to store rules. It is not necessary to use the whole budget.
I made a list of $q$ pairs of integers $(a_{j}, b_{j})$, which means I may visit the store at time $a_{j}$, and spend at most $b_{j}$ dollars at the store. For each pair, I'd like to know the maximum happiness I can obtain. But there are so many pairs that I can't handle them. Can you help me?
|
The $i$-th item is available during $[t_{i}, t_{i} + p - 1]$. In other words, at time $T$, item $i$ is available if and only if $t_{i} \le T \le t_{i} + p - 1$. This can be re-written as ($t_{i} \le T$ and $T - p + 1 \le t_{i}$), which is $T - p + 1 \le t_{i} \le T$. With this observation, we can transform the item's purchasable range into a dot, and the candidate's visit time into a range: From now on, item $i$ is only available at time $t_{i}$. and each candidate pair $(a_{j}, b_{j})$ means that I can visit the store during $[a_{j} - p + 1, a_{j}]$, and my budget is $b_{j}$ dollars at that visit. This transformation makes the problem easier to solve. Each red circled point denotes an item which is sold at that time, and each black interval denotes a candidate. Let's only consider the intervals which passes time $T$. All the intervals' length is exactly $p$, so the left bound of the interval is $(T - p)$ and the right bound of the interval is $(T + p)$. For each interval, we'd like to solve the 0/1 knapsack algorithm with the items that the interval contains. How can we do that effectively? There is an important fact that I've described above: all the interval passes time $T$. Therefore, the interval $[a_{j} - p + 1, a_{j}]$ can be split into two intervals: $[a_{j} - p + 1, T - 1]$ and $[T, a_{j}]$. So, let's solve the 0/1 knapsack problem for all intervals $[x, T - 1]$ ($T - p \le x \le T - 1$) and $[T, y]$ ($T \le y \le T + p$). Because one of the endpoints is fixed, one can run a standard dynamic programming algorithm. Therefore, the time needed in precalculation is $O(S \times W)$, where $S$ is the number of items where the condition $t_{i}\in[T-p,T+p]$ holds. Let's define $h(I, b)$, as the maximum happiness I can obtain by buying the items where the condition $t_{i}\in I$ holds, using at most $b$ dollars. For each candidate $(a_{j}, b_{j})$, we have to calculate $h([a_{j} - p + 1, a_{j}], b_{j})$, which is equal to $max_{0 \le k \le b}{h([a_{j} - p + 1, T - 1], k) + h([T, a_{j}], b - k)}$. So it takes $O(b_{j}) = O(W)$ time to solve each query. The only question left is: How should we choose the value of $T$? We have two facts. (1) The length of intervals is exactly $p$. (2) The algorithm covers intervals which passes time $T$. Therefore, to cover all the intervals given in the input, we should let $T$ be $p, 2p, 3p, 4p, ...$ (of course, one by one), and run the algorithm described above. Then, what is the total time complexity? Think of intervals $[0, 2p], [p, 3p], [2p, 4p], [3p, 5p], ...$. For each point, there will be at most two intervals which contains the point. Therefore, each item is reflected in the pre-calculation at most twice, so the time needed to precalculate is $O(n \times W)$. The time needed to solve each query is $O(b_{j})$, and the answer of the query is calculated at most once. Therefore, the time needed to answer all the queries is $O(q \times W$). Time : $O((n + q) \times W)$. Memory : $O(n \times W)$ Implementations: 9335699 (ainta), 9335703 (ainu7) , 9335710 (.o., using a different approach), 9335709 (.o., using a divide and conquer approach) Let's assume that $t_{1} \le t_{2} \le ... \le t_{n}$. We can easily know that at time $T$, the indexes of all the available items forms a segment $[l, r]$. (in other words, item $l$, item $l + 1$, ..., item $r - 1$, item $r$ is available) We can use this fact to solve all the queries. Let's assume that item $l_{j}$, item $l_{j} + 1$, ..., item $r_{j} - 1$, item $r_{j}$ is available at time $a_{j}$. Define a function $solve(L, R)$. This function calculates the answer for queries where the condition $L \le l_{j} \le r_{j} \le R$ holds. Let's assume that $L < R$ holds. (In the case $L \ge R$, the answer can be calculated easily) Let $M={\left[{\frac{L+R}{2}}\right]}$. Call $solve(L, M)$ and $solve(M + 1, R)$. After that, the queries needed to be calculated, satisfies the condition $l_{j} \le M < r_{j}$, which means all the intervals(queries) passes item $M$. Now, to calculate the answer for such queries, we can use the method described at the dynamic programming approach. The time complexity is $O(n\cdot b\log n+q\times b)$, because $T(n)=O(n\cdot b)+2T(n/2)=O(n\cdot b\log n)$ and the answer of the queries can be calculated in $O(b_{j})$ per query. Time : $O((n\log n+q)\times W)$. Memory : $O(n \times W)$
|
[
"divide and conquer",
"dp"
] | 2,700
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <assert.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <functional>
#include <vector>
#include <numeric>
#include <deque>
#include <utility>
#include <bitset>
#include <limits.h>
#include <iostream>
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef double lf;
typedef unsigned int uint;
typedef long double llf;
typedef pair<int, int> pii;
const int lgN_ = 12;
const int N_ = 4105;
const int M_ = 20005;
const int MAXW = 4105;
const int MAXD = 200505;
int N, Q, P;
struct item {
int h, c, t;
item (int h = 0, int c = 0, int t = 0) : h(h), c(c), t(t) { }
bool operator < (const item &i) const {
return t < i.t;
}
} D[N_];
int tb[N_][MAXW];
int L[MAXD], R[MAXD];
vector<int> marked[lgN_][N_];
int budget[M_], when[M_];
int answer[M_];
void precalc (int l, int r, int h) {
int m = (l + r) >> 1;
if(l >= r) return;
{ // left
for(int j = 0; j < D[m].c; j++) tb[m][j] = 0;
for(int j = D[m].c; j < MAXW; j++) tb[m][j] = D[m].h;
for(int i = m-1; i >= l; i--) {
for(int j = 1; j < MAXW; j++) {
tb[i][j] = max(tb[i + 1][j], tb[i][j - 1]);
if(j >= D[i].c) tb[i][j] = max(tb[i][j], tb[i + 1][j - D[i].c] + D[i].h);
}
}
}
{ // right
if(m+1 <= r) {
for(int j = 0; j < D[m+1].c; j++) tb[m+1][j] = 0;
for(int j = D[m+1].c; j < MAXW; j++) tb[m+1][j] = D[m+1].h;
}
for(int i = m+2; i <= r; i++) {
for(int j = 1; j < MAXW; j++) {
tb[i][j] = max(tb[i - 1][j], tb[i][j - 1]);
if(j >= D[i].c) tb[i][j] = max(tb[i][j], tb[i - 1][j - D[i].c] + D[i].h);
}
}
}
for(int w = 0; w < marked[h][l].size(); w++) {
int q = marked[h][l][w];
int x = L[when[q]], y = R[when[q]], b = budget[q];
int &ans = answer[q];
if(x <= m && m == y) ans = tb[x][b];
else if(x == m+1 && m+1 <= y) ans = tb[y][b];
else if(x <= m && m+1 <= y) {
for(int i = 0; i <= b; i++) ans = max(ans, tb[x][i] + tb[y][b - i]);
}else {
assert(0);
}
}
#undef tb
if(l < r) {
precalc(l, m-1, h + 1);
precalc(m+1, r, h + 1);
}
}
void mark (int l, int r, int h, int x, int y, int q) {
int m = (l + r) >> 1;
if(x > y) return;
if(x <= m+1 && m <= y) {
marked[h][l].push_back(q);
return;
}
if(y < m) mark(l, m-1, h+1, x, y, q);
if(m < x) mark(m+1, r, h+1, x, y, q);
}
int main() {
scanf("%d%d", &N, &P);
for(int i = 1; i <= N; i++) {
scanf("%d%d%d", &D[i].c, &D[i].h, &D[i].t);
R[D[i].t]++;
L[D[i].t + P]++;
}
sort(D + 1, D + N + 1);
L[1] = 1;
for(int i = 1; i < MAXD; i++) {
L[i] += L[i-1];
R[i] += R[i-1];
}
scanf("%d", &Q);
for(int i = 1; i <= Q; i++) {
int a, b; scanf("%d%d", &a, &b);
when[i] = a; budget[i] = b;
if(L[a] < R[a])
mark(1, N, 0, L[a], R[a], i);
else if(L[a] == R[a])
answer[i] = (D[L[a]].c <= budget[i]) ? D[L[a]].h : 0;
}
precalc(1, N, 0);
for(int i = 1; i <= Q; i++) {
printf("%d\n", answer[i]);
}
return 0;
}
|
500
|
G
|
New Year Running
|
New Year is coming in Tree Island! In this island, as the name implies, there are $n$ cities connected by $n - 1$ roads, and for any two distinct cities there always exists exactly one path between them. For every person in Tree Island, it takes exactly one minute to pass by exactly one road.
There is a weird New Year tradition for runnners in Tree Island, which is called "extreme run". This tradition can be done as follows.
A runner chooses two distinct cities $a$ and $b$. For simplicity, let's denote the shortest path from city $a$ to city $b$ as $p_{1}, p_{2}, ..., p_{l}$ (here, $p_{1} = a$ and $p_{l} = b$ holds). Then following happens:
- The runner starts at city $a$.
- The runner runs from city $a$ to $b$, following the shortest path from city $a$ to city $b$.
- When the runner arrives at city $b$, he turns his direction immediately (it takes no time), and runs towards city $a$, following the shortest path from city $b$ to city $a$.
- When the runner arrives at city $a$, he turns his direction immediately (it takes no time), and runs towards city $b$, following the shortest path from city $a$ to city $b$.
- Repeat step 3 and step 4 forever.
In short, the course of the runner can be denoted as: $p_{1}\rightarrow p_{2}\rightarrow\cdot\cdot\cdot\cdot\cdot\rightarrow p_{l-1}\rightarrow p_{l}\rightarrow p_{l-1}\rightarrow p_{l-2}\rightarrow\cdot\cdot\cdot\cdot\rightarrow p_{2}\rightarrow p_{1}$ $\rightarrow p_{2}\rightarrow\cdot\cdot\cdot\cdot\cdot\cdot\rightarrow p_{l-1}\rightarrow p_{l}\rightarrow p_{l-1}\rightarrow p_{l-2}\rightarrow\cdot\cdot\cdot\cdot\rightarrow p_{2}\rightarrow p_{1}\rightarrow\cdot\cdot\cdot\cdot\cdot.$
Two runners JH and JY decided to run "extremely" in order to celebrate the New Year. JH has chosen two cities $u$ and $v$, and JY has chosen two cities $x$ and $y$. They decided to start running at the same moment, and run until they meet at the same city for the first time. Meeting on a road doesn't matter for them. Before running, they want to know the amount of time they will run.
It is too hard for JH and JY to calculate this, so they ask you for help.
|
Before starting the editorial, I'd like to give a big applause to Marcin_smu, who solved the problem for the first time! Warning: The editorial is very long and has many mistakes. There are lots of lots of mistakes.. Keep calm, and please tell me by comments, if you discovered any errors. This problem can be solved by an online algorithm. Let's focus on a single query $(u, v, x, y)$. This means that JH runs between $u$ and $v$, and JY runs between $x$ and $y$. Just like when we solve many problems with undirected trees, let vertex 1 be the root of the tree. Also, we will assume that they won't stop after when they meet, but they will continue running, in order to explain easily. Some definitions: Path $(a, b)$: the shortest path between vertex $a$ and vertex $b$. $d(a, b)$: the length of Path $(a, b)$. $LCA(a, b)$: the lowest common ancestor of vertex $a$ and vertex $b$. If there is no common vertex between Path $(u, v)$ and Path $(x, y)$, the answer will be obviously $- 1$. So, let's find the common vertices first. Because the path between two vertices is always unique, the common vertices also form a path. So, I'll denote the path of the common vertices as Path $(c_{1}, c_{2})$. $c_{1}$ and $c_{2}$ may be equal to: $u$, $v$, $x$, $y$, and even each other. The possible endpoints are $P_{1} = LCA(u, v)$, $P_{2} = LCA(x, y)$, $P_{3} = LCA(u, x)$, $P_{4} = LCA(u, y)$, $P_{5} = LCA(v, x)$, and $P_{6} = LCA(v, y)$. Figure out by drawing some examples. (some of you might think it's obvious :D) See the pictures above, and make your own criteria to check whether the two paths intersects :D A small hint. Let's assume that we already know, that a vertex $a$ lies on path $(x, y)$. If $a$ lies on path $(u, v)$, $a$ is a common vertex of two paths. What if $a$ is guaranteed to be an end point of the common path? Let's denote JH's running course is: $\dot{\boldsymbol{u}}=\rightarrow\ C_{1}--\sum{\boldsymbol{C_{2}}}-\dots\ \nabla$. Then, there are two possible courses for JY: $\displaystyle{\mathcal{L}}\,=\,\sim\,C_{1}\,-\,-\sim\,C_{2}\,-\,-\,\sim\,y$ and $\textstyle y-\to\,C_{1}\ -\to\,C_{2}\ -\to\,X\,$). $f_{JH}$ : the time needed to run the course $u=\sim\ u--\sim\ u$. $f_{JY}$ : the time needed to run the course $\textstyle x\ -\lnot\ 9\ U-\lnot\ 9\ X$. $t_{1}$ : the first time when JH passes vertex $c_{1}$, moving towards $c_{2}$. $t_{2}$ : the first time when JH passes vertex $c_{2}$, moving towards $c_{1}$. $t_{3}$ : the first time when JY passes vertex $c_{1}$, moving towards $c_{2}$. $t_{4}$ : the first time when JY passes vertex $c_{2}$, moving towards $c_{1}$. Obviously, they must meet at vertex $c_{1}$ or vertex $c_{2}$ for the first time. Without loss of generality, let's assume that they meet at vertex $c_{1}$. In this case, both of them is moving towards vertex $c_{2}$. (You can use the method similarly for $c_{2}$) Let's assume that JH and JY meets at time $T$. Because the movements of both runners are periodic, $T$ must satisfy the conditions below: $T\equiv t_{1}(\mathrm{mod}f_{J H})$ $T\equiv t_{3}({\mathrm{mod}}f_{J Y})$ Among possible $T$-s, we have to calculate the smallest value. How should we do? From the first condition, we can let $T = f_{JH} \times p + t_{1}$, where $p$ is a non-negative integer. With this, we can write the second condition as: $f_{J H}\times p+t_{1}\equiv t_{3}(\mathrm{mod}f_{J Y})$. In conclusion, we have to find the smallest $p$ which satisfies the condition $f_{J H}\times p\equiv t_{3}-t_{1}(\mathrm{mod}f_{J Y})$ Using the Extended Euclidean algorithm is enough to calculate the minimum $p$. With $p$, we can easily calculate the minimum $T$, which is the first time they meet. If there is no such $p$, they doesn't meet forever, so the answer is $- 1$. In this case, they will meet at a vertex lying on Path $(c_{1}, c_{2})$. Without loss of generality, let's assume that JH is going from $c_{1}$ to $c_{2}$, and JY is going from $c_{2}$ to $c_{1}$. I'll assume that JH and JY meets at time $T$. [1] Let's see how JH moves: For all non-negative integer $p$, At time $f_{JH} \times p + t_{1}$, he is at vertex $c_{1}$, moving towards $c_{2}$. At time $f_{JH} \times p + t_{1} + d(c_{1}, c_{2})$, he is at vertex $c_{2}$. Therefore, when $f_{JH} \times p + t_{1} \le $ (current time) $ \le f_{JH} \times p + t_{1} + d(c_{1}, c_{2})$, JH is on Path $(c_{1}, c_{2})$. So, $T$ must satisfy the condition: $f_{JH} \times p + t_{1} \le T \le f_{JH} \times p + t_{1} + d(c_{1}, c_{2})$ [2] Let's see how JY moves: Similar to JH, for all non-negative integer $q$, At time $f_{JY} \times q + t_{4}$, he is at vertex $c_{2}$, moving towards $c_{1}$. At time $f_{JY} \times q + t_{4} + d(c_{2}, c_{1})$, he is at vertex $c_{1}$. Therefore, when $f_{JY} \times q + t_{4} \le $ (current time) $ \le f_{JY} \times q + t_{4} + d(c_{2}, c_{1})$, JY is on Path $(c_{2}, c_{1})$. So, $T$ must satisfy the condition: $f_{JY} \times q + t_{4} \le T \le f_{JY} \times q + t_{4} + d(c_{1}, c_{2})$ [3] These two conditions are not enough, because in this case, they can meet on an edge, but they cannot meet on a vertex. We'd like to know when do they meet on a vertex, like the picture below. As you see from the picture above, in this case, the condition $d(c_{1}, a) + d(a, c_{2}) = d(c_{1}, c_{2})$ holds. If this picture was taken at time $s$, this condition can be written as: ${s - (f_{JH} \times p + t_{1})} + {s - (f_{JY} \times q + t_{4})} = d(c_{1}, c_{2})$ $2s - (f_{JH} \times p + f_{JY} \times q) - (t_{1} + t_{4}) = d(c_{1}, c_{2})$ $s = {d(c_{1}, c_{2}) + (f_{JH} \times p + f_{JY} \times q) + (t_{1} + t_{4})} / 2$ Because JH and JY both travel their path back and forth, $f_{JH}$ and $f_{JY}$ are all even. Therefore, in order to make $s$ an integer, $d(c_{1}, c_{2}) + t_{1} + t_{4}$ must be even. This can be written as $d(c_{1},c_{2})+t_{1}+t_{4}\equiv0(\mathrm{mod{2}})$ [4] Merging [1], [2] and [3], we can conclude that if these two conditions holds, $t_{1}-t_{4}\equiv d(c_{1},c_{2})(\mathrm{mod}2)$ $max{f_{JH} \times p + t_{1}, f_{JY} \times q + t_{4}} \le min{f_{JH} \times p + t_{1} + d(c_{1}, c_{2}), f_{JY} \times p + t_{4} + d(c_{1}, c_{2})}$ JH and JY meets on a certain vertex lying on path $(c_{1}, c_{2})$. The first condition can be easily checked, so let's focus on the second condition. The second condition holds if and only if: $f_{JY} \times q + t_{4} - t_{1} - d \le f_{JH} \times p \le f_{JY} \times q + t_{4} - t_{1} + d$ You can check this by changing "$f_{JH} \times p$" to the lower bound and the upper bound of the inequality. Therefore, the problem is to find the smallest $p$ which satisfies the condition above. Let's define a function $g(M, D, L, R)$, where $M, D, L, R$ are all non-negative integers. The function returns the smallest non-negative integer $m$ which satisfies $L\leq D\cdot m\leq R(\mathrm{mod}M)$. This function can be implemented as follows. If $L = 0$, $g(M, D, L, R) = 0$. (because $L = 0 \le D \cdot 0$) If $\left|\frac{L-1}{\operatorname*{gcd(M,D)}}\right|\ge\left|\frac{R}{\operatorname*{gcd(M,D)}}\right|$, it is "obvious" that there is no solution. If $2D > M$, $g(M, D, L, R) = g(M, M - D, M - R, M - L)$. If there exists an non-negative integer $m$ which satisfies $L \le D \cdot m \le R$ (without modular condition), $g(M, D, L, R) = m$. Obviously, we should take the smallest $m$. Otherwise, there exists an integer $m$ which satisfies $D \cdot m < L \le R < D \cdot (m + 1)$. We should use this fact.. If $L\leq D\cdot m\leq R(\mathrm{mod}M)$ holds, there exists an non-negative integer $k$ which satisfies $L + Mk \le D \cdot m \le R + Mk$. Let's write down.. $D \cdot m - R \le M \cdot k \le D \cdot m - L$ $- R \le M \cdot k - D \cdot m \le - L$ $L \le D \cdot m - M \cdot k \le R$Because $L+M\cdot k\leq D\cdot m\leq R+M\cdot k(\operatorname{mod}M)$, we can write the inequality as $L\,\mathrm{mod}\,D\leq(-M\cdot k)\,\mathrm{mod}\,D\leq R\,\mathrm{mod}\,D(\mathrm{mod}\,D)$ Therefore the minimum $k$ among all possible solutions is equal to $q(D,-M\mathrm{~mod~}D,L\mathrm{~mod~}D,R\mathrm{~mod~}D)$. We can easily calculate the smallest $p$ using $k$. $D \cdot m - R \le M \cdot k \le D \cdot m - L$ $- R \le M \cdot k - D \cdot m \le - L$ $L \le D \cdot m - M \cdot k \le R$ $L\,\mathrm{mod}\,D\leq(-M\cdot k)\,\mathrm{mod}\,D\leq R\,\mathrm{mod}\,D(\mathrm{mod}\,D)$ Then, what is the time complexity of calculating $g(M, D, L, R)$? Because $2D \le M$ (the $2D > M$ case is handled during step 3), the problem size becomes half, so it can be executed in $O(\log_{2}M)$. For each query, we have to consider both Case 1) and Case 2), with all possible directions. Both cases can be handled in $O(\log_{2}n)$, so the time complexity per query is $O(\log_{2}n)$, and it has really huge constant. Time: $O((n+q)\log n)$ Memory: $O(n\log n)$
|
[
"number theory",
"trees"
] | 3,200
|
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
#define N_ 200010
#define INF 99999999999999999LL
vector<int>E[N_];
int n, Q;
int Dep[N_];
int par[18][N_];
void DFS(int node, int dep, int pp){
int i, x;
Dep[node] = dep;
par[0][node] = pp;
for (i = 0; i < E[node].size(); i++){
x = E[node][i];
if (x != pp)DFS(x, dep + 1, node);
}
}
void make_List(){
int i, j;
for (i = 0; i < 17; i++){
for (j = 1; j <= n; j++)par[i + 1][j] = par[i][par[i][j]];
}
}
int LCA(int u, int v){
if (Dep[u] < Dep[v])return LCA(v, u);
int d = Dep[u] - Dep[v], i = 0;
while (d){
if (d & 1) u = par[i][u];
d >>= 1; i++;
}
for (i = 17; i >= 0; i--){
if (par[i][u] != par[i][v])u = par[i][u], v = par[i][v];
}
if (u != v)u = par[0][u];
return u;
}
int Lower(int a, int b){ // a�� b�� ���� ����?
if (Dep[a] < Dep[b])return b;
return a;
}
int dist(int u, int v){ // Ʈ������ u�� v�� �Ÿ�
int L = LCA(u, v);
return Dep[u] + Dep[v] - 2 * Dep[L];
}
int gcd(int a, int b){
return b ? gcd(b, a%b) : a;
}
long long First(long long M, long long D, long long g){//Dx = g(mod M)�� �ּ��� �� �ƴ� ���� x�� ���ΰ�?
if (g == 0)return 0;
long long T = First(D, M%D, g%D);
T = (g - T*M) / D;
if (T < 0){
T += (-T) / M*M;
T += M;
}
return T % M;
}
long long SameDir(int T1, int d1, int T2, int d2, int L){ //���� �������� ������, T1 * x = d2 - d1 (mod T2) �� �ּ� x?
int g = gcd(T1, T2), M = d2 - d1;
long long TT = T1;
if (M < 0) M = T2 + M;
if (M % g != 0)return INF;
T1 /= g, M /= g, T2 /= g;
return First(T2, T1, M) * TT + d1;
}
int Gap(int M, int D, int L, int R){// L <= Dx <= R(mod M)�� �Ǵ� �ּ��� �� �ƴ� ���� x�� ���ΰ�? O(log M)�� ����غ���.
D %= M;
if (D * 2 > M){
return Gap(M, M - D, M - R, M - L);
}
int t = L / D, rr = M%D, q = M / D, o;
long long a, b;
if (L == t * D)return t;
if (t * D + D <= R)return t + 1;
a = Gap(D, D - rr, L%D, R%D);
a = (a * M - 1) / D + 1;
b = a * D % M;
a += (R - b) / D;
return a;
}
long long Do(int M, int D, int L, int R){// L <= Dx <= R(mod M)�� �Ǵ� �ּ��� �� �ƴ� ���� x�� ���ΰ�?�� �غ� �ܰ�
int Res = INF;
if (L == 0){
Res = M / gcd(M, D);
L = 1;
}
if ((L - 1) / gcd(M, D) >= R / gcd(M, D)){
return INF;
}
return min(Res, Gap(M, D, L, R));
}
long long DiffDir(int T1, int d1, int T2, int d2, int L){ // �ݴ� �������� ������, d2 - d1 - L <= T1 * x <= d2 - d1 + L ( mod T2)�� �ּ� x?
int be = d2 - d1 - L, ed = d2 - d1 + L;
long long P;
if (be < 0) be += (-be) / T2 * T2;
if (ed < 0)ed += (-ed) / T2*T2;
be = (be + T2) % T2, ed = (ed + T2) % T2;
if (be & 1)return INF;
if (T2 == L * 2){
return d1 + ed / 2;
}
if (be > ed || be == 0)return d1 + ed / 2;
P = Do(T2, T1, be, ed);
if (P == INF)return INF;
return T1*P + d1 + L - (P * T1 % T2 - be) / 2;
}
long long Query(int u, int v, int x, int y){
int P1 = LCA(u, v), P2 = LCA(x, y), P3 = LCA(u, x), P4 = LCA(u, y), P5 = LCA(v, x), P6 = LCA(v, y);
int pp, a, b, d1, d2, d3, d4, d5, d6, d;
pp = Lower(P1, P2);
a = Lower(P3, P4);
b = Lower(P5, P6);
if (Dep[a] < Dep[pp] && Dep[b] < Dep[pp])return -1;
if (Dep[a] < Dep[pp]) a = pp;
else if (Dep[b] < Dep[pp]) b = pp;
d1 = dist(u, v), d4 = dist(x, y);
d2 = dist(u, a), d3 = dist(u, b);
d5 = dist(x, a), d6 = dist(x, b);
d = dist(a, b);
if (d2 <= d3) d3 = d1 * 2 - d3;
else d2 = d1 * 2 - d2;
if (d5 <= d6) d6 = d4 * 2 - d6;
else d5 = d4 * 2 - d5;
long long Res = INF;
//d1 : u-v �Ÿ�, d2 : x-y �Ÿ�
//������ : a-b
//d2, d3, d5, d6 : (u,v) - (a,b) �Ÿ�
Res = min(SameDir(d1 * 2, d2, d4 * 2, d5, d), Res);
Res = min(SameDir(d1 * 2, d3, d4 * 2, d6, d), Res);
Res = min(DiffDir(d1 * 2, d2, d4 * 2, d6, d), Res);
Res = min(DiffDir(d1 * 2, d3, d4 * 2, d5, d), Res);
if (Res == INF)return -1;
return Res;
}
void Output(){
int u, v, x, y, T;
scanf("%d", &Q);
while (Q--){
scanf("%d%d%d%d", &u, &v, &x, &y);
printf("%lld\n", Query(u, v, x, y));
}
}
void input(){
int i, a, b;
scanf("%d", &n);
for (i = 1; i < n; i++){
scanf("%d%d", &a, &b);
E[a].push_back(b);
E[b].push_back(a);
}
}
int main()
{
input();
DFS(1, 0, 0);
make_List();
Output();
}
|
501
|
A
|
Contest
|
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs $a$ points and Vasya solved the problem that costs $b$ points. Besides, Misha submitted the problem $c$ minutes after the contest started and Vasya submitted the problem $d$ minutes after the contest started. As you know, on Codeforces the cost of a problem reduces as a round continues. That is, if you submit a problem that costs $p$ points $t$ minutes after the contest started, you get $\Pi\mathrm{d}\lambda\chi\left({\frac{3p}{10}},p-{\frac{p}{250}}\chi\ d\right)$ points.
Misha and Vasya are having an argument trying to find out who got more points. Help them to find out the truth.
|
In this problem one need to determine the number of points for both guys and find out who got more points. Time complexity: $O(1)$.
|
[
"implementation"
] | 900
| null |
501
|
B
|
Misha and Changing Handles
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
|
The problem can be formulated as follows: The directed graph is given, its vertices correspond to users' handles and edges - to requests. It consists of a number of chains, so every vertex ingoing and outgoing degree doesn't exceed one. One need to find number of chains and first and last vertices of every chain. The arcs of this graph can be stored in dictionary(one can use std::map\unoredered_map in C++ and TreeMap\HashMap in Java) with head of the arc as the key and the tail as the value. Each zero ingoing degree vertex corresponds to unique user as well as first vertex of some chain. We should iterate from such vertices through the arcs while it's possible. Thus we find relation between first and last vertices in the chain as well as relation between the original and the new handle of some user. Time complexity: $O(q\log q\times l e n)$.
|
[
"data structures",
"dsu",
"strings"
] | 1,100
|
#include <bits/stdc++.h>
#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define ford(i, n) for(int i=(n)-1; i>=0; i--)
#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)
#define in(x) int (x); input((x));
#define x first
#define y second
#define less(a,b) ((a) < (b) - EPS)
#define more(a,b) ((a) > (b) + EPS)
#define eq(a,b) (fabs((a) - (b)) < EPS)
#define remax(a, b) ((a) = (b) > (a) ? (b) : (a))
#define remin(a, b) ((a) = (b) < (a) ? (b) : (a))
using namespace std;
template <typename T>
T gcd(T a, T b) {
while (b > 0) {
a %= b;
swap(a, b);
}
return a;
}
typedef long double ld; typedef unsigned int uint; template <class _T> inline _T sqr(const _T& x) {return x * x;} template <class _T> inline string tostr(const _T& a) {ostringstream os(""); os << a; return os.str();} const ld PI = 3.1415926535897932384626433832795L; const double EPS = 1e-9; char TEMPORARY_CHAR;
typedef long long ll; typedef unsigned long long ull; typedef set < int > SI; typedef vector < int > VI; typedef vector < vector < int > > VVI; typedef map < string, int > MSI; typedef pair < int, int > PII; const int INF = 1e9; inline void input(int &a) {a = 0; while (((TEMPORARY_CHAR = getchar()) > '9' || TEMPORARY_CHAR < '0') && (TEMPORARY_CHAR != '-')){} char neg = 0; if (TEMPORARY_CHAR == '-') {neg = 1; TEMPORARY_CHAR = getchar();} while (TEMPORARY_CHAR <= '9' && TEMPORARY_CHAR >= '0') {a = 10 * a + TEMPORARY_CHAR - '0'; TEMPORARY_CHAR = getchar();} if (neg) a = -a;} inline void out(long long a) {if (!a) putchar('0'); if (a < 0) {putchar('-'); a = -a;} char s[20]; int i; for(i = 0; a; ++i) {s[i] = '0' + a % 10; a /= 10;} ford(j, i) putchar(s[j]);} inline int nxt() {in(ret); return ret;}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#else
#endif
ios_base::sync_with_stdio(false);
int q;
cin >> q;
map <string, string> edges;
set <string> nonBegin;
for (int i = 0; i < q; ++i) {
string OLD, NEW;
cin >> OLD >> NEW;
edges[OLD] = NEW;
nonBegin.insert(NEW);
}
vector <pair <string, string> > ans;
fori(p,edges) {
if (nonBegin.count(p->first)) {
continue;
}
string cur = p->first;
while (edges.count(cur)) {
cur = edges[cur];
}
ans.push_back(make_pair(p->first, cur));
}
cout << ans.size() << endl;
fori(p, ans) {
cout << p->first << " " << p->second << endl;
}
#ifdef LOCAL
cerr << "Time elapsed: " << (double)clock() / CLOCKS_PER_SEC * 1000 << " ms.\n";
#endif // LOCAL
return 0;
}
|
501
|
C
|
Misha and Forest
|
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of $n$ vertices. For each vertex $v$ from $0$ to $n - 1$ he wrote down two integers, $degree_{v}$ and $s_{v}$, were the first integer is the number of vertices adjacent to vertex $v$, and the second integer is the XOR sum of the numbers of vertices adjacent to $v$ (if there were no adjacent vertices, he wrote down $0$).
Next day Misha couldn't remember what graph he initially had. Misha has values $degree_{v}$ and $s_{v}$ left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.
|
Note that every non-empty forest has a leaf(vertex of degree $1$). Let's remove edges one by one and maintain actual values $(degree_{v}, s_{v})$ as long as graph is not empty. To do so, we can maintain the queue(or stack) of the leaves. On every iteration we dequeue vertex $v$ and remove edge $(v, s_{v})$ and update values for vertex $s_{v}$: $degree_{sv}$ -= $1$ and $s_{sv}$ ^= $v$. If degree of vertex $s_{v}$ becomes equal to $1$, we enqueue it. When dequeued vertex has zero degree, just ignore it because we have already removed all edges of corresponding tree. Time complexity: $O(n)$
|
[
"constructive algorithms",
"data structures",
"greedy",
"sortings",
"trees"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int degree[n], xorsum[n];
queue <int> Q;
int used = 0;
for(int i = 0; i < n; ++i)
{
cin >> degree[i] >> xorsum[i];
if (degree[i] == 1)
Q.push(i);
if (degree[i] == 0)
{
if (xorsum[i] != 0)
assert(false);
used++;
}
}
vector < pair<int, int> > ans;
while(!Q.empty())
{
int from = Q.front();
Q.pop();
used++;
if (degree[from] == 0)
{
if (xorsum[from] != 0)
assert(false);
continue;
}
degree[from]--;
int to = xorsum[from];
xorsum[from] = 0;
if (to >= n)
assert(false);
ans.push_back(make_pair(from, to));
xorsum[to] ^= from;
if (degree[to] == 0)
assert(false);
degree[to]--;
if (degree[to] == 1)
Q.push(to);
}
if (used != n)
assert(false);
cout << ans.size() << endl;
for(size_t i = 0; i < ans.size(); ++i)
cout << ans[i].first << " " << ans[i].second << endl;
return 0;
}
|
501
|
D
|
Misha and Permutations Summation
|
Let's define the sum of two permutations $p$ and $q$ of numbers $0, 1, ..., (n - 1)$ as permutation $P e r m((O r d(p)+O r d(q))\bmod{n!})$, where $Perm(x)$ is the $x$-th lexicographically permutation of numbers $0, 1, ..., (n - 1)$ (counting from zero), and $Ord(p)$ is the number of permutation $p$ in the lexicographical order.
For example, $Perm(0) = (0, 1, ..., n - 2, n - 1)$, $Perm(n! - 1) = (n - 1, n - 2, ..., 1, 0)$
Misha has two permutations, $p$ and $q$. Your task is to find their sum.
Permutation $a = (a_{0}, a_{1}, ..., a_{n - 1})$ is called to be lexicographically smaller than permutation $b = (b_{0}, b_{1}, ..., b_{n - 1})$, if for some $k$ following conditions hold: $a_{0} = b_{0}, a_{1} = b_{1}, ..., a_{k - 1} = b_{k - 1}, a_{k} < b_{k}$.
|
To solve the problem, one need to be able to find the index of given permutation in lexicographical order and permutation by its index. We will store indices in factorial number system. Thus number $x$ is represented as $\sum_{k=1}^{n}d_{k}\times k!$. You can find the rules of the transform here. To make the transform, you may need to use data structures such as binary search tree or binary indexed tree (for maintaining queries of finding $k$-th number in the set and finding the amount of numbers less than given one). So, one need to get indices of the permutations, to sum them modulo $n!$ and make inverse transform. You can read any accepted solution for better understanding. Time complexity: $O(n\log n)$ or $O(n\log^{2}n)$.
|
[
"data structures"
] | 2,000
| null |
501
|
E
|
Misha and Palindrome Degree
|
Misha has an array of $n$ integers indexed by integers from $1$ to $n$. Let's define palindrome degree of array $a$ as the number of such index pairs $(l, r)(1 ≤ l ≤ r ≤ n)$, that the elements from the $l$-th to the $r$-th one inclusive can be rearranged in such a way that the \textbf{whole} array will be a palindrome. In other words, pair $(l, r)$ should meet the condition that after some rearranging of numbers on positions from $l$ to $r$, inclusive (it is allowed not to rearrange the numbers at all), for any $1 ≤ i ≤ n$ following condition holds: $a[i] = a[n - i + 1]$.
Your task is to find the palindrome degree of Misha's array.
|
Note that if the amount of elements, which number of occurrences is odd, is greater than one, the answer is zero. On the other hand, if array is the palindrome, answer is $\textstyle{\frac{n(n+1)}{2}}$. Let's cut equal elements from the end and the beginning of array while it is possible. Let's call remaining array as $b$ and its length as $m$. We are interested in segments $[l, r]$ which cover some prefix or suffix of $b$. We need to find the minimum length of such prefix and suffix. Prefix and suffix can overlap the middle of $b$ and these cases are needed to maintain. To find minimum length you can use binary search or simply iterating over array and storing the amount of every element to the left and right from the current index. Let's call minimum length of prefix as $pref$ and as $suf$ of suffix. So $a n s w e r=(\frac{n-m}{2}+1)\times(\frac{n-m}{2}+2m+1-p r e f-s u f)$. Time complexity: $O(n)$ or $O(n\log n)$.
|
[
"binary search",
"combinatorics",
"implementation"
] | 2,500
| null |
504
|
D
|
Misha and XOR
|
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number $x$ to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals $x$?
If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket.
Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number $0$, the second integer takes number $1$ and so on.
Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.
|
Firstly, we convert each number into a binary system: it can be done in $O(MAXBITS^{2})$, where $MAXBITS \le 2000$ with rather small constant(we store number in system with big radix). To solve the problem we need to modify Gauss elimination algorithm. For each row we should store set of row's indices which we already XORed this row to get row echelon form (we can store it in bitset), also for each bit $i$ we store index $p[i]$ of row, which lowest set bit is $i$ in row echelon form. Maintaining the query we try to reset bits from lowest to highest using array $p$ and save information, which rows were XORed with current number. If we can reset whole number, the answer is positive and we know indices of answer. We update array $p$, otherwise. Time complexity: $O(m \times MAXBITS \times (MAXBITS + m))$ with small constant due to bit compression.
|
[
"bitmasks"
] | 2,700
| null |
504
|
E
|
Misha and LCP on Tree
|
Misha has a tree with characters written on the vertices. He can choose two vertices $s$ and $t$ of this tree and write down characters of vertices lying on a path from $s$ to $t$. We'll say that such string corresponds to pair $(s, t)$.
Misha has $m$ queries of type: you are given $4$ vertices $a$, $b$, $c$, $d$; you need to find the largest common prefix of the strings that correspond to pairs $(a, b)$ and $(c, d)$. Your task is to help him.
|
Let's build heavy-light decomposition of given tree and write all strings corresponding to heavy paths one by one in one string $T$, every path should be written twice: in the direct and reverse order. Maintaining query we can split paths $(a, b)$ and $(c, d)$ into parts, which completely belongs to some heavy paths. There can be at most $O(\log n)$ such parts. Note that every part corresponds to some substring of $T$. Now we only need to find longest common prefix of two substrings in string $T$. It can be done building suffix array of string $T$ and lcp array. So, we can find longest common prefix of two substring in $O(1)$ constructing rmq sparse table on lcp array. Time complexity: $O(n\log n+m\log n)$ P.S. One can uses hashes instead of suffix array. ADD: There is another approach to solve this problem in $O(m\log n+n\log n)$ but it's rather slow in practice. We can do binary search on answer and use hashes, but we do it for all queries at one time. The only problem is to find $k$-th vertex on the path, we can do it offline for all queries in $O(n + m)$ time. We run dfs and maintain stack of vertices.
|
[
"binary search",
"dfs and similar",
"hashing",
"string suffix structures",
"trees"
] | 3,000
|
#include <bits/stdc++.h>
#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define For(i, st, en) for(int i=(st); i<=(int)(en); i++)
#define Ford(i, st, en) for(int i=(st); i>=(int)(en); i--)
#define forn(i, n) for(int i=0; i<(int)(n); i++)
#define ford(i, n) for(int i=(n)-1; i>=0; i--)
#define fori(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); it++)
#define in(x) int (x); input((x));
#define x first
#define y second
#define less(a,b) ((a) < (b) - EPS)
#define more(a,b) ((a) > (b) + EPS)
#define eq(a,b) (fabs((a) - (b)) < EPS)
#define remax(a, b) ((a) = (b) > (a) ? (b) : (a))
#define remin(a, b) ((a) = (b) < (a) ? (b) : (a))
using namespace std;
template <typename T>
T gcd(T a, T b) {
while (b > 0) {
a %= b;
swap(a, b);
}
return a;
}
typedef long double ld; typedef unsigned int uint; template <class _T> inline _T sqr(const _T& x) {return x * x;} template <class _T> inline string tostr(const _T& a) {ostringstream os(""); os << a; return os.str();} const ld PI = 3.1415926535897932384626433832795L; const double EPS = 1e-9; char TEMPORARY_CHAR;
typedef long long ll; typedef unsigned long long ull; typedef set < int > SI; typedef vector < int > VI; typedef vector < vector < int > > VVI; typedef map < string, int > MSI; typedef pair < int, int > PII; const int INF = 1e9; inline void input(int &a) {a = 0; while (((TEMPORARY_CHAR = getchar()) > '9' || TEMPORARY_CHAR < '0') && (TEMPORARY_CHAR != '-')){} char neg = 0; if (TEMPORARY_CHAR == '-') {neg = 1; TEMPORARY_CHAR = getchar();} while (TEMPORARY_CHAR <= '9' && TEMPORARY_CHAR >= '0') {a = 10 * a + TEMPORARY_CHAR - '0'; TEMPORARY_CHAR = getchar();} if (neg) a = -a;} inline void out(long long a) {if (!a) putchar('0'); if (a < 0) {putchar('-'); a = -a;} char s[20]; int i; for(i = 0; a; ++i) {s[i] = '0' + a % 10; a /= 10;} ford(j, i) putchar(s[j]);} inline int nxt() {in(ret); return ret;}
const int MAXN = 1000000;
const int LOG = 1000;
namespace suf_array {
static const int MAXLEN = MAXN * 2;
static const int LOG = 20;
char s[MAXLEN + 1];
int n;
int sa[MAXLEN];
int lcp[MAXLEN];
int logTable[MAXLEN];
int rank[MAXLEN];
int rmq[LOG + 1][MAXLEN];
int order[MAXLEN];
int r[MAXLEN];
int cnt[MAXLEN];
int st[MAXLEN];
bool cmp(int i, int j) {
return s[i] < s[j];
}
void process()
{
for (int i = 0; i < n; i++)
order[i] = n - 1 - i;
stable_sort(order, order + n, cmp);
for (int i = 0; i < n; i++) {
sa[i] = order[i];
rank[i] = s[i];
}
for (int len = 1; len < n; len <<= 1) {
memcpy(r, rank, n * sizeof(int));
for (int i = 0; i < n; i++) {
rank[sa[i]] = (i > 0 && r[sa[i - 1]] == r[sa[i]] &&
sa[i - 1] + len < n && r[sa[i - 1] + len / 2] == r[sa[i] + len / 2])
? rank[sa[i - 1]]
: i;
}
for (int i = 0; i < n; i++)
cnt[i] = i;
memcpy(st, sa, sizeof(int) * n);
for (int i = 0; i < n; i++) {
int s1 = st[i] - len;
if (s1 >= 0)
sa[cnt[rank[s1]]++] = s1;
}
}
}
void calc_lcp() {
for (int i = 0; i < n; i++)
rank[sa[i]] = i;
for (int i = 0, h = 0; i < n; i++) {
if (rank[i] < n - 1) {
int j = sa[rank[i] + 1];
while(max(i, j) + h < n && s[i + h] == s[j + h])
++h;
lcp[rank[i] + 1] = h;
if (h > 0)
--h;
}
}
logTable[0] = 0;
logTable[1] = 0;
for (int i = 2; i < n; i++)
logTable[i] = logTable[i >> 1] + 1;
for (int i = 0; i < n; ++i)
rmq[0][i] = lcp[i];
for (int k = 1; (1 << k) < n; ++k) {
for (int i = 0; i + (1 << k) <= n; i++) {
int x = rmq[k - 1][i];
int y = rmq[k - 1][i + (1 << k - 1)];
rmq[k][i] = min(x, y);
}
}
}
int get_lcp(int l, int r) {
l = rank[l];
r = rank[r];
if (l > r) {
swap(l, r);
}
if (l == r) {
return n - sa[l];
}
++l;
int k = logTable[r - l];
int x = rmq[k][l];
int y = rmq[k][r - (1 << k) + 1];
return min(x, y);
}
};
namespace hld {
vector <int> g[MAXN];
int sz[MAXN];
int p[MAXN];
int pos_up[MAXN];
int pos_down[MAXN];
int r[MAXN];
int root[MAXN];
int rt[MAXN];
int tin[MAXN];
int tout[MAXN];
int timer = 0;
int pos[MAXN];
vector <int> c[MAXN];
int pathCount = 0;
void dfs(int v, int par) {
p[v] = par;
sz[v] = 1;
tin[v] = timer++;
for (int i = 0; i < (int)g[v].size(); ++i) {
int to = g[v][i];
if (to == par) {
continue;
}
dfs(to, v);
sz[v] += sz[to];
}
tout[v] = timer++;
}
void decomp(int v, int par, int k) {
pos[v] = c[k].size();
c[k].push_back(v);
root[v] = rt[k];
r[v] = k;
int x = 0, y = -1;
for (int i = 0; i < (int)g[v].size(); ++i) {
int to = g[v][i];
if (to == par)
continue;
if (sz[to] > x) {
x = sz[to];
y = to;
}
}
if (y != -1) decomp(y, v, k);
for (int i = 0; i < (int)g[v].size(); ++i) {
int to = g[v][i];
if (to != par && to != y) {
rt[pathCount] = to;
decomp(to, v, pathCount++);
}
}
}
void initSA(char * s, char * data) {
int len = 0;
for (int i = 0; i < pathCount; ++i) {
for (int j = 0; j < (int)c[i].size(); ++j) {
int v = c[i][j];
s[pos_down[v] = len++] = data[v];
}
for (int j = (int)c[i].size() - 1; j >= 0; --j) {
int v = c[i][j];
s[pos_up[v] = len++] = data[v];
}
}
}
inline bool upper(int a, int b) {
return tin[a] <= tin[b] && tout[a] >= tout[b];
}
pair <int, int> up[LOG];
pair <int, int> down[LOG];
int getHeavySegments(int a, int b, pair <int, int> * res) {
int sup = 0;
int sdown = 0;
while (!upper(root[a], b)) {
up[sup++] = make_pair(pos_up[a], pos_up[root[a]]);
a = p[root[a]];
}
while (!upper(root[b], a)) {
down[sdown++] = make_pair(pos_down[root[b]], pos_down[b]);
b = p[root[b]];
}
assert(r[a] == r[b]);
if (upper(a, b)) {
down[sdown++] = make_pair(pos_down[a], pos_down[b]);
} else {
up[sup++] = make_pair(pos_up[a], pos_up[b]);
}
for (int i = 0; i < sup; ++i) {
*res++ = up[i];
}
for (int i = sdown - 1; i >= 0; --i) {
*res++ = down[i];
}
return sup + sdown;
}
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#else
#endif
ios_base::sync_with_stdio(false);
int n;
scanf("%d", &n);
char data[n + 1];
scanf("%s", data);
for (int i = 0; i + 1 < n; ++i) {
int a, b;
scanf("%d%d", &a, &b);
--a, --b;
hld::g[a].push_back(b);
hld::g[b].push_back(a);
}
hld::dfs(0, -1);
hld::decomp(0, -1, hld::pathCount++);
hld::initSA(suf_array::s, data);
suf_array::n = 2 * n;
suf_array::process();
suf_array::calc_lcp();
int m;
scanf("%d", &m);
pair <int, int> segsL[LOG];
pair <int, int> segsR[LOG];
while (m--) {
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
--a, --b, --c, --d;
int lsize = hld::getHeavySegments(a, b, segsL);
int rsize = hld::getHeavySegments(c, d, segsR);
int i = 0, j = 0;
int len = 0;
while (i < lsize && j < rsize) {
int lcp = suf_array::get_lcp(segsL[i].first, segsR[j].first);
lcp = min(lcp, segsL[i].second - segsL[i].first + 1);
lcp = min(lcp, segsR[j].second - segsR[j].first + 1);
len += lcp;
segsL[i].first += lcp;
segsR[j].first += lcp;
bool ok = false;
if (segsL[i].first > segsL[i].second) {
++i;
ok = true;
}
if (segsR[j].first > segsR[j].second) {
++j;
ok = true;
}
if (!ok) {
break;
}
}
printf("%d\n", len);
}
#ifdef LOCAL
cerr << "Time elapsed: " << (double)clock() / CLOCKS_PER_SEC * 1000 << " ms.\n";
#endif // LOCAL
return 0;
}
|
505
|
A
|
Mr. Kitayuta's Gift
|
Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly one lowercase English letter into $s$ to make it a palindrome. A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.
You can choose any lowercase English letter, and insert it to any position of $s$, possibly to the beginning or the end of $s$. You have to insert a letter even if the given string is already a palindrome.
If it is possible to insert one lowercase English letter into $s$ so that the resulting string will be a palindrome, print the string after the insertion. Otherwise, print "NA" (without quotes, case-sensitive). In case there is more than one palindrome that can be obtained, you are allowed to print any of them.
|
Since the string is short (at most 10 characters), you can simply try every possible way of inserting a letter ("where" and "what" to insert), and check if the resulting string is a palindrome.
|
[
"brute force",
"implementation",
"strings"
] | 1,100
|
// Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define all(x) (x).begin(),(x).end()
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define pb push_back
#define sec second
#define sz(x) ((int)(x).size())
using namespace std;
typedef istringstream iss;
typedef long long ll;
typedef pair<ll,ll> pi;
typedef stringstream sst;
typedef vector<ll> vi;
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
string s;
cin >> s;
rep(i, sz(s) + 1) rep2(c, 'a', 'z' + 1) {
string t = s.substr(0, i) + string(1, c) + s.substr(i);
string u = t;
reverse(all(u));
if(t == u){
cout << t << endl;
return 0;
}
}
cout << "NA" << endl;
}
|
505
|
B
|
Mr. Kitayuta's Colorful Graph
|
Mr. Kitayuta has just bought an undirected graph consisting of $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.
Mr. Kitayuta wants you to process the following $q$ queries.
In the $i$-th query, he gives you two integers — $u_{i}$ and $v_{i}$.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex $u_{i}$ and vertex $v_{i}$ directly or indirectly.
|
Since neither the graph nor the number of queries is too large, for each query you can simply count the number of the "good" colors (the colors that satisfies the condition) by checking if each color is "good". To do that, you can perform Depth First Search (or Breadth First Search) and verify whether you can reach $v_{i}$ from $u_{i}$ traversing only the edges of that color. If you prefer using Union-Find, it will also do the job.
|
[
"dfs and similar",
"dp",
"dsu",
"graphs"
] | 1,400
| null |
505
|
C
|
Mr. Kitayuta, the Treasure Hunter
|
The Shuseki Islands are an archipelago of $30001$ small islands in the Yutampo Sea. The islands are evenly spaced along a line, numbered from $0$ to $30000$ from the west to the east. These islands are known to contain many treasures. There are $n$ gems in the Shuseki Islands in total, and the $i$-th gem is located on island $p_{i}$.
Mr. Kitayuta has just arrived at island $0$. With his great jumping ability, he will repeatedly perform jumps between islands to the east according to the following process:
- First, he will jump from island $0$ to island $d$.
- After that, he will continue jumping according to the following rule. Let $l$ be the length of the previous jump, that is, if his previous jump was from island $prev$ to island $cur$, let $l = cur - prev$. He will perform a jump of length $l - 1$, $l$ or $l + 1$ to the east. That is, he will jump to island $(cur + l - 1)$, $(cur + l)$ or $(cur + l + 1)$ (if they exist). The length of a jump must be positive, that is, he cannot perform a jump of length $0$ when $l = 1$. If there is no valid destination, he will stop jumping.
Mr. Kitayuta will collect the gems on the islands visited during the process. Find the maximum number of gems that he can collect.
|
Below is the explanation from yosupo, translated by me. [From here] Let $m$ be the number of the islands (that is, $30001$). First, let us describe a solution with time and memory complexity of $O(m^{2})$. We will apply Dynamic Programming. let $dp[i][j]$ be the number of the gems that Mr. Kitayuta can collect after he jumps to island $i$, when the length of his previous jump is $j$ (let us assume that he have not collect the gems on island $i$). Then, you can calculate the values of the table $dp$ by the following: $dp[i][j] = 0$, if $i \ge m$ (actually these islands do not exist, but we can suppose that they exist and when Mr. Kitayuta jumps to these islands, he stops jumping) $dp[i][j] =$ (the number of the gems on island $i$) $+ max(dp[i + j][j], dp[i + j + 1][j + 1])$, if $i < m, j = 1$ (he cannot perform a jump of length $0$) $dp[i][j] =$ (the number of the gems on island $i$) $+ max(dp[i + j - 1][j - 1], dp[i + j][j], dp[i + j + 1][j + 1])$, if $i < m, j \ge 2$ This solution is unfeasible in terms of both time and memory. However, the following observation makes it an Accepted solution: there are only $491$ values of $j$ that we have to consider, which are $d - 245, d - 244, d - 243, ..., d + 244$ and $d + 245$. Why? First, let us find the upper bound of $j$. Suppose Mr. Kitayuta always performs the "$l + 1$" jump ($l$: the length of the previous jump). Then, he will reach the end of the islands before he performs a jump of length $d + 246$, because $d + (d + 1) + (d + 2) + ... + (d + 245) \ge 1 + 2 + ... + 245 = 245 \cdot (245 + 1) / 2 = 30135 > 30000$. Thus, he will never be able to perform a jump of length $d + 246$ or longer. Next, let us consider the lower bound of $j$ in a similar way. If $d \le 246$, then obviously he will not be able to perform a jump of length $d - 246$ or shorter, because the length of a jump must be positive. Suppose Mr. Kitayuta always performs the "$l - 1$" jump, where $d \ge 247$. Then, again he will reach the end of the islands before he performs a jump of length $d - 246$, because $d + (d - 1) + (d - 2) + ... + (d - 245) \ge 245 + 244 + ... + 1 = 245 \cdot (245 + 1) / 2 = 30135 > 30000$. Thus, he will never be able to perform a jump of length $d - 246$ or shorter. Therefore, we have obtained a working solution: similar to the $O(m^{2})$ one, but we will only consider the value of $j$ between $d - 245$ and $d + 245$. The time and memory complexity of this solution will be $O(m^{1.5})$, since the value "$245$" is slightly larger than $\sqrt{2m}$. This solution can be implemented by, for example, using a "normal" two dimensional array with a offset like this: dp[i][j - offset]. The time limit is set tight in order to fail most of naive solutions with search using std::map or something, so using hash maps (unordered_map) will be risky although the complexity will be the same as the described solution.
|
[
"dfs and similar",
"dp",
"two pointers"
] | 1,900
| null |
505
|
D
|
Mr. Kitayuta's Technology
|
Shuseki Kingdom is the world's leading nation for innovation and technology. There are $n$ cities in the kingdom, numbered from $1$ to $n$.
Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, that is, a teleportation pipe from city $x$ to city $y$ cannot be used to travel from city $y$ to city $x$. The transportation within each city is extremely developed, therefore if a pipe from city $x$ to city $y$ and a pipe from city $y$ to city $z$ are both constructed, people will be able to travel from city $x$ to city $z$ instantly.
Mr. Kitayuta is also involved in national politics. He considers that the transportation between the $m$ pairs of city $(a_{i}, b_{i})$ ($1 ≤ i ≤ m$) is important. He is planning to construct teleportation pipes so that for each important pair $(a_{i}, b_{i})$, it will be possible to travel from city $a_{i}$ to city $b_{i}$ by using one or more teleportation pipes (but not necessarily from city $b_{i}$ to city $a_{i}$). Find the minimum number of teleportation pipes that need to be constructed. So far, no teleportation pipe has been constructed, and there is no other effective transportation between cities.
|
Let $G_{1}$ be the directed graph built from the input, and $G_{2}$ be a directed graph that satisfies the given conditions. What we seek is the minimum number of edges in $G_{2}$. Also, we say that two vertices $u$ and $v$ in a directed graph are "weakly connected" if we can reach $v$ from $u$ by traversing edges, not considering their directions. If a pair $(u, v)$ is present in the input, then vertices $u$ and $v$ must be weakly connected in $G_{2}$. Therefore, for each weakly connected component (abbreviated to wcc) in $G_{1}$, the vertices in that component must also be in the same wcc in $G_{2}$. We can "merge" multiple wccs in $G_{1}$ and create a larger wcc in $G_{2}$, but for now, let us find the minimum number of edges required in $G_{2}$ for each wcc in $G_{1}$ when we do not "merge" them. There are two cases to consider: If a wcc in $G_{1}$ does not have cycles, then we can perform topological sort on that wcc, and we can make a "chain" (see the image below) using the topological order to satisfy the conditions. We need (the number of the vertices in the wcc) $- 1$ edges, which is the minimum required number since any connected graph with $V$ vertices has at least $V - 1$ edges. If a wcc in $G_{1}$ has cycles, then topological sort cannot be applied. We need at least (the number of the vertices in the wcc) edges this time, since any connected graph with $V$ vertices and $V - 1$ edges is a tree, which does not contain cycles. Actually, this number (the number of the vertices in the wcc) is always achievable by connecting the vertices into a "ring" (see the image below), thus it is the minimum required number that we seek. We have found the minimum required number of edges for each wcc in $G_{1}$ when we do not "merge" them. Let us show that "merging" wccs in $G_{1}$ do not reduce the number of required edges. Suppose we combine $k( > 1)$ wccs $C_{1}, C_{2}, ..., C_{k}$ in $G_{1}$ into one wcc $C$ in $G_{2}$. Again, there are two cases to consider: If none of $C_{1}, C_{2}, ..., C_{k}$ contains cycles, then $C$ will need $|C_{1}| + |C_{2}| + ... + |C_{k}| - 1$ edges. However, if we do not combine them, we will only need $(|C_{1}| - 1) + (|C_{2}| - 1) + ... + (|C_{k}| - 1)$ edges in total, which is fewer. If some of $C_{1}, C_{2}, ..., C_{k}$ contain cycles, then $C$ will need $|C_{1}| + |C_{2}| + ... + |C_{k}|$ edges. However, if we do not combine them, we will need $(|C_{1}| - noCycles(C_{1})) + (|C_{2}| - noCycles(C_{2})) + ... + (|C_{k}| - noCycles(C_{k})$ $ \le |C_{1}| + |C_{2}| + ... + |C_{k}|$ edges (here, $noCycles(C_{i})$ is $1$ if $C_{i}$ do not contain cycles, otherwise $0$), thus combining them does not reduce the number of required edges. Thus, we do not need to combine multiple wccs into one wcc in $G_{2}$ in order to obtain the optimal solution. That is, the final answer to the problem is the sum of the minimum required number of edges for each wcc in $G_{1}$, when they are considered separately. As for the implementation, detecting cycles in a directed graph with $10^{5}$ vertices and edges might be a problem if this is your first encounter with it. One possible way is to paste a code that decomposes a graph into strongly connected components. If the size of a strongly connected component is more than one, then that means the component contains cycles.
|
[
"dfs and similar"
] | 2,200
|
// Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define pb push_back
#define sec second
#define sz(x) ((int)(x).size())
using namespace std;
typedef istringstream iss;
typedef long long ll;
typedef pair<ll,ll> pi;
typedef stringstream sst;
typedef vector<ll> vi;
const int N = 100010;
int n, m;
vi g[N];
vi rg[N];
vi vs;
bool used[N];
int cmp[N], cmpsize[N];
void add_edge(int from, int to){
g[from].pb(to);
rg[to].pb(from);
}
void dfs(int v){
used[v] = 1;
rep(i, sz(g[v])){
if(!used[g[v][i]]) dfs(g[v][i]);
}
vs.pb(v);
}
void rdfs(int v, int k){
used[v] = 1;
cmp[v] = k;
rep(i, sz(rg[v])){
if(!used[rg[v][i]]) rdfs(rg[v][i], k);
}
}
int scc(){
memset(used, 0, sizeof(used));
vs.clear();
rep(v, n){
if(!used[v])
dfs(v);
}
memset(used, 0, sizeof(used));
int k = 0;
for(int i = sz(vs) - 1; i >= 0; i--){
if(!used[vs[i]]) rdfs(vs[i], k++);
}
return k;
}
int dfs2(int v){
used[v] = 1;
int res = cmpsize[cmp[v]] == 1;
rep(i,sz(g[v])) if(!used[g[v][i]]){
res &= dfs2(g[v][i]);
}
rep(i,sz(rg[v])) if(!used[rg[v][i]]){
res &= dfs2(rg[v][i]);
}
return res;
}
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> m;
rep(i, m){
int a, b;
cin >> a >> b;
add_edge(a-1, b-1);
}
scc();
memset(cmpsize, 0, sizeof(cmpsize));
rep(i, n){
cmpsize[cmp[i]]++;
}
memset(used, 0, sizeof(used));
int ans = n;
rep(i, n) if(!used[i]){
ans -= dfs2(i);
}
cout << ans << endl;
}
|
505
|
E
|
Mr. Kitayuta vs. Bamboos
|
Mr. Kitayuta's garden is planted with $n$ bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the $i$-th bamboo is $h_{i}$ meters, and it grows $a_{i}$ meters at the end of each day.
Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground.
He can use Magical Hammer at most $k$ times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by $p$ meters. If the height would become negative by this change, it will become $0$ meters instead (it does not disappear). In other words, if a bamboo whose height is $h$ meters is beaten with Magical Hammer, its new height will be $max(0, h - p)$ meters. It is possible to beat the same bamboo more than once in a day.
Mr. Kitayuta will fight the bamboos for $m$ days, starting today. His purpose is to minimize the height of the tallest bamboo after $m$ days (that is, $m$ iterations of "Mr. Kitayuta beats the bamboos and then they grow"). Find the lowest possible height of the tallest bamboo after $m$ days.
|
Below is the explanation from yosupo, translated by me. [From here] Let us begin by applying Binary Search. The problem becomes: "is it possible that all the bamboos are at most $X$ meters after $m$ days?" It is complicated by the fact that the height does not become negative; the excessive decrease will be wasted. We have found two approaches to this problem. Solution 1 Mr. Kitayuta must beat the $i$-th bamboo at least $max(0, \lceil (h_{i} + m \cdot a_{i} - X) / P \rceil )$ times (let this number $t_{i}$). Actually, it is not necessary for him to beat it more than this number of times. Thus, let us assume that he beat the $i$-th bamboo exactly $t_{i}$ times. Also, for each $j$ ($1 \le j \le t_{i}$), find the day $d_{i, j}$ such that, if the $j$-th beat on the $i$-th bamboo is performed before day $d_{i}$, it will be no longer possible to keep the $i$-th bamboo's height after $m$ days at most $X$ (it can be found by doing simple math). If Mr. Kitayuta can beat the bamboos under this constraint, all the bamboos' heights will become $X$ meters or less after $m$ days. Otherwise, some bamboos' heights will exceed $X$ meters. The time complexity of this solution will be $O((n+k m)\log(h_{m a x}+a_{m a x}\cdot m))$, if we first calculate only $t_{i}$, then if the sum of $t_{i}$ exceeds $km$, we skip finding $d_{i, j}$ (the answer is "NO"). Solution 2 This problem becomes simpler if we simulate Mr. Kitayuta's fight backwards, that is, from day $m$ to day $1$. It looks like this: [Problem'] There are $n$ bamboos. At the moment, the height of the $i$-th bamboo is $X$ meters, and it shrinks $a_{i}$ meters at the beginning of each day. Mr. Kitayuta will play a game. He can use Magic Hammer at most $k$ times per day to increase the height of a bamboo by $p$ meters. If some bamboo's height becomes negative at any moment, he will lose the game immediately. Also, in order for him to win the game, the $i$-th bamboo's height must be at least $h_{i}$ meters after $m$ days. Is victory possible? Below is an illustration of this "reverse simulation": This version is simpler because he is increasing the heights instead of decreasing, thus we do not need to take into account the "excessive decrease beyond $0$ meters" which will be wasted. Let us consider an optimal strategy. If there exist bamboos whose heights would become negative after day $m$, he should beat the one that is the earliest to make him lose. Otherwise, he can choose any bamboo whose height would be less than $h_{i}$ meters after day $m$. Repeat beating the bamboos following this strategy, and see if he can actually claim victory. The writer's implementation of this solution uses a priority queue, and its time complexity is $O((n+k m)\lg n\log(h_{m a x}+a_{m a x}\cdot m))$.
|
[
"binary search",
"greedy"
] | 2,900
|
// Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define pb push_back
#define sec second
#define sz(x) ((int)(x).size())
using namespace std;
typedef istringstream iss;
typedef long long ll;
typedef pair<ll,ll> pi;
typedef stringstream sst;
typedef vector<ll> vi;
int n, m, k, p;
ll h[100010], a[100010];
ll l[100010];
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> m >> k >> p;
rep(i,n) cin >> h[i] >> a[i];
rep(i,n){
l[i] = h[i] + a[i] * m;
}
ll lo = 0, hi = 2e13;
while(lo + 1 < hi){
ll mi = (lo + hi) / 2;
bool ok = 1;
ll total = 0;
rep(i,n){
total += max(0LL, (l[i] - mi + p - 1) / p);
}
if(total > m * k){
ok = 0;
}else{
int t[10010] = {};
rep(i,n) if(l[i] > mi){
for(ll target = (l[i] - mi) % p == 0 ? p : (l[i] - mi) % p; target <= l[i] - mi; target += p){
if(target - h[i] <= 0){
t[0]++;
}else if(target - h[i] > a[i] * (m-1)){
ok = 0;
goto end;
}else{
t[(target - h[i] + a[i] - 1) / a[i]]++;
}
}
}
int rest = 0;
rep(i,m){
rest += t[i];
rest = max(0, rest - k);
}
ok = rest == 0;
}
end:;
(ok ? hi : lo) = mi;
}
cout << hi << endl;
}
|
506
|
D
|
Mr. Kitayuta's Colorful Graph
|
Mr. Kitayuta has just bought an undirected graph with $n$ vertices and $m$ edges. The vertices of the graph are numbered from 1 to $n$. Each edge, namely edge $i$, has a color $c_{i}$, connecting vertex $a_{i}$ and $b_{i}$.
Mr. Kitayuta wants you to process the following $q$ queries.
In the $i$-th query, he gives you two integers - $u_{i}$ and $v_{i}$.
Find the number of the colors that satisfy the following condition: the edges of that color connect vertex $u_{i}$ and vertex $v_{i}$ directly or indirectly.
|
Below is the explanation from hogloid. [From here] For each color, make a new graph that consists of the edges of the color and vertices connected by the edges. Make UnionFind for each graph, and you can check whether a color connects vertex $A$ and $B$ , using it. For each query, find a vertex which has smaller degree(let this vertex $A$, and the other vertex $B$) For each colors such that a edge of the color connects to $A$, check whether $A$ and $B$ is connected by the color. After answering the query, memorize its tuple - $(A, B, answer)$. If the same query is requested, answer using this information. This will lead to $O(m\log m{\sqrt{q}})$ solution. For each query, the complexity is $O(d e c g(A)\log m)$ (For each color connects $A$, find a vertex of $B$ of the color & check whether they are connected) The queries that require longest computing time are, to ask every pair among ${\sqrt{q}}$ vertices which have largest degrees. Let the indices of the ${\sqrt{q}}$ vertices be $1,2,...,k(={\sqrt{q}})$, and degrees of the ${\sqrt{q}}$ vertices be $d_{1}, d_{2}, ...d_{k}$. Now, let's fix vertex $B$ as $i$. The total computing time of the queries such that $B$ is vertex $i$ is $O((d_{1}+d_{2}+\ldots+d_{i-1})\log m)\leq$ $O(s u m_{-}o f_{-}d e g r e e s_{-}o f_{-}t h e_{-}\sqrt{q}_{-}v e r t i c e s\cdot\log m)$. Vertex $B$ can vary from $2$ to $k$. Hence, the total complexity is at most $O(\sqrt{q}\cdot s u m_{-}o f_{-}d e g r e e s_{-}o f_{-}t h e_{-}\sqrt{q}_{-}v e r t i c e s\cdot\log m)$. This complexity is at most $O({\sqrt{q}}m\log m)$. By the way, in C++, using unordered_map, total complexity would be $O(m{\sqrt{q}})$. [End] There will be many other solutions. I will briefly explain one of them which I think is typical. Let $c_{i}$ be the number of colors of the edges incident to vertex $i$. The sum of all $c_{i}$ does not exceed $2m$ since each edge increases this sum by at most 2. Thus, there will be at most $450$ values of $i$ such that $c_{i} \ge 450$ (let $B = 450$). We will call these vertices large, and the remaining ones small. Using $O(m / B \cdot m) = O(m^{2} / B)$ time and memory, we can precalculate and store the answer for all the possible queries where at least one of $u_{i}$ and $v_{i}$ is large, then we can immediately answer these queries. For the remaining queries, both $u_{i}$ and $v_{i}$ will be small, therefore it is enough to directly count the color that connects vertices $u_{i}$ and $v_{i}$ in $O(B)$ time. The total time required will be $O(m^{2} / B + Bq)$. If we choose $B=m/{\sqrt{q}}$, we can solve the problem in $O(m^{2}/(m/\sqrt{q})+q\cdot m/\sqrt{q})=O(m\sqrt{q})$ time.
|
[
"brute force",
"dfs and similar",
"dsu",
"graphs"
] | 2,400
|
// Enjoy your stay.
#include <bits/stdc++.h>
#define EPS 1e-9
#define INF 1070000000LL
#define MOD 1000000007LL
#define fir first
#define foreach(it,X) for(auto it=(X).begin();it!=(X).end();it++)
#define ite iterator
#define mp make_pair
#define mt make_tuple
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<(n);i++)
#define pb push_back
#define sec second
#define sz(x) ((int)(x).size())
using namespace std;
typedef istringstream iss;
typedef long long ll;
typedef pair<ll,ll> pi;
typedef stringstream sst;
typedef vector<ll> vi;
const int N = 100010;
//
int par_uf[N],rank_uf[N];
void init(int n){
for(int i = 0; i < n; i++){
par_uf[i] = i;
rank_uf[i] = 0;
}
}
int find(int x){
if(par_uf[x] == x)return x;
else return par_uf[x] = find(par_uf[x]);
}
void unite(int x, int y){
x=find(x); y=find(y);
if(x == y) return;
if(rank_uf[x] < rank_uf[y]) par_uf[x] = y;
else{
par_uf[y]=x;
if(rank_uf[x] == rank_uf[y]) rank_uf[x]++;
}
}
bool same(int x, int y){
return find(x) == find(y);
}
//
int n, m, q, qa[N], qb[N];
vector< pair<int,int> > edge[N];
vector< vector<int> > comp;
vector<int> appear[N];
const int B = 450;
vector<int> big;
int bigID[N];
int table[B+10][N];
int used[N];
vector<int> temp[N];
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> m;
rep(i, m){
int a, b, c;
cin >> a >> b >> c;
a--; b--; c--;
edge[c].pb(mp(a, b));
}
cin >> q;
rep(i, q){
cin >> qa[i] >> qb[i];
qa[i]--; qb[i]--;
}
init(n);
rep(c, N){
rep(i, sz(edge[c])){
int a = edge[c][i].fir, b = edge[c][i].sec;
unite(a, b);
}
rep(i, sz(edge[c])){
int a = edge[c][i].fir, b = edge[c][i].sec;
if(!used[a]){
temp[find(a)].pb(a);
used[a] = 1;
}
if(!used[b]){
temp[find(b)].pb(b);
used[b] = 1;
}
}
rep(i, sz(edge[c])){
int a = edge[c][i].fir, b = edge[c][i].sec;
if(sz(temp[a]) > 0){
comp.pb(temp[a]);
temp[a].clear();
}
if(sz(temp[b]) > 0){
comp.pb(temp[b]);
temp[b].clear();
}
used[a] = 0;
used[b] = 0;
par_uf[a] = a;
par_uf[b] = b;
rank_uf[a] = 0;
rank_uf[b] = 0;
}
}
rep(i, sz(comp)){
rep(j, sz(comp[i])){
appear[comp[i][j]].pb(i);
}
}
rep(i, n){
if(sz(appear[i]) > B){
bigID[i] = sz(big);
big.pb(i);
}else{
bigID[i] = -1;
}
}
rep(i, sz(big)){
int b = big[i];
rep(j, sz(appear[b])){
int c = appear[b][j];
rep(k, sz(comp[c])){
table[i][comp[c][k]]++;
}
}
}
rep(_,q){
int a = qa[_], b = qb[_];
if(bigID[a] == -1){
swap(a, b);
}
if(bigID[a] != -1){
cout << table[bigID[a]][b] << endl;
}else{
int cur1 = 0, cur2 = 0, res = 0;
while(cur1 < sz(appear[a]) && cur2 < sz(appear[b])){
if(appear[a][cur1] == appear[b][cur2]){
res++;
cur1++;
cur2++;
}else if(appear[a][cur1] < appear[b][cur2]){
cur1++;
}else{
cur2++;
}
}
cout << res << endl;
}
}
}
|
506
|
E
|
Mr. Kitayuta's Gift
|
Mr. Kitayuta has kindly given you a string $s$ consisting of lowercase English letters. You are asked to insert exactly $n$ lowercase English letters into $s$ to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.) You can choose any $n$ lowercase English letters, and insert each of them to any position of $s$, possibly to the beginning or the end of $s$. You have to insert exactly $n$ letters even if it is possible to turn $s$ into a palindrome by inserting less than $n$ letters.
Find the number of the palindromes that can be obtained in this way, modulo $10007$.
|
First of all, let us note that we are asked to count the resulting palindromes, not the ways to obtain them. For example, if we are to insert "b" into "abba", there are 5 possible positions, but only 3 strings will be produced ("babba", "abbba" and "abbab"). Rather than trying to count the ways of inserting a letter $n$ times and removing the duplicated results, we should directly count the resulting palindrome. To do that, let us reformulate the problem: [Problem'] Given a string $s$ and an integer $n$, find the number of the palindromes of length $|s| + n$ (let this number be $N$) that contains $s$ as a subsequence (not necessarily contiguous). Consider constructing a palindrome from both ends, and matching it to $s$ from both left and right. For example, let $s =$"abaac" and $N = 11$. Let us call the final resulting string $t$. We first decide what letter to use as $t_{1}$ and $t_{11}$ (they must be equal in order for $t$ to be a palindrome). Let us say 'c' is chosen. Now, we have to construct the remaining part of $t$, that is, $t_{2}..t_{10}$, so that $t_{2}..t_{10}$ contains "abaa" as a substring (note that the 'c' at the end of $s$ is discarded). Again, we decide what letter to use as $t_{2}$ and $t_{10}$. This time we choose 'a'. Then, we have to construct $t_{3}..t_{9}$, so that it contains "ba" as a substring (this time the two 'a's at the both ends of $s$ are discarded). We choose $t_{3} = t_{9} =$'c'. Next, we construct $t_{4}..t_{8}$, so that it contains "ba" as a substring (this time $s$ remains unchanged). We choose $t_{4} = t_{8} =$'b'. Then, we construct $t_{5}..t_{7}$, so that it contains "a" as a substring. We choose $t_{5} = t_{7} =$'a' (it is becoming repetitive, isn't it?). The last part of $t$, that is, $t_{6}$, has no restriction (this time we choose a letter for only one position of $t$, not two). We choose 'd', and we have obtained a palindrome "cacbadabcac" that contains $s$ = "abaac" as a subsequence. This problem is mostly about analyzing this process carefully. The most naive solution other than literally enumerating all palindromes of length $N$ would be the following Dynamic Programming: let $dp[i][left][right]$ be the number of the palindromes $t$ that can be obtained if you have already decided the leftmost and the rightmost $i$ letters ($2i$ in total), and the substring $s_{left}s_{left + 1}..s_{right}$ of $s$ remains unmatched. Each value in this table can be computed in $O(1)$ time. Of course, since $i$ can be up to $ \lfloor n / 2 \rfloor $ ($n \le 10^{9}$), this solution is far from our goal. Notice that the transitions from $dp[i]$ to $dp[i + 1]$ are the same regardless of $i$, thus we can calculate the table by matrix exponentiation. However, since there are $O(|s|^{2})$ possible pairs for $(left, right)$, we will need $O(|s|^{6}\log n)$ time, which is actually worse than the naive calculation considering that $|s|$ can be up to $200$. This is where we need to observe the process which we have gone through at the beginning more carefully. Let us build a automaton corresponding to the process (the image below). (*) An self-loop with a number means that there are actually that number of edges. A process of producing a palindrome of length $N$ that contains $s$ as a subsequence corresponds to a path of length $ \lceil N / 2 \rceil $ from the upper-right vertex to the lower-left vertex. Each red vertex has 24 self-loops since the letters at the both ends of the remaining part of $s$ is different, which correspond to two non-self-loop transitions. Similarly, each green vertex has 25 self-loops since the first letter and the last letter of the remaining string is the same, and the blue vertex, the destination, has 26 self-loops, as there are no more non-self-loop transitions available. Here is an important fact: there are not so many possible combination of $(n24, n25)$, where $n24$ and $n25$ are the number of times a path from START to GOAL visits a red vertex (with 24 self-loops) and a green vertex (with 25 self-loops), respectively. Why? Each time we leave a red vertex, the length of the remaining unmatched part of $s$ decreases by 1, since exactly one of the two letters at the ends of the remaining part is matched and discarded. Similarly, each time we leave a green vertex, the length of the remaining string decreases by 2, since both of the two letters at the ends are matched and discarded. There is a exception, however: if the length of the remaining string is 1, then it will be a green vertex, but in this case the length will decrease by 1. Thus, for any path from START to GOAL, $n24 + 2 \cdot n25$ will be equal to either $|s|$ or $|s| + 1$. If we fix $n24$, then $n25$ will be uniquely determined by $n25 = \lceil (|s| - n24) / 2 \rceil $. Since $n24$ can only take the value between $0$ and $|s| - 1$, there are at most $|s|$ possible pairs of $(n24, n25)$. With this fact, we are ready to count the paths: let us classify them by the value of $n24$. For each possible pair of $(n24, n25)$, let us count the number of corresponding paths. To do that, we divide each paths into two parts: first we count the number of paths from START to GOAL, using only non-self-loop transitions. Then, we count the ways of inserting self-loop transitions into each of these paths. The product of these two numbers will be the number that we seek. The first part is straightforward to solve: let $dp[left][right][n24]$ be the number of paths from the vertex that corresponds to the substring $s_{left}s_{left + 1}..s_{right}$, visiting exactly $n24$ red vertices using only non-self-loop transitions. Each value of the table can be found in $O(1)$ time, thus the whole table can be computed in $O(|s|^{3})$ time, which is fast enough for the input size ($|s| \le 200$). The main obstacle will be the second part. For example, let us consider the case where $s =$"abaac", $N = 11, n24 = 2$, which corresponds to the example at the beginning. From the fact we found earlier, $n25 = \lceil (|s| - n24) / 2 \rceil = \lceil (5 - 2) / 2 \rceil = 2$. Thus, we have to insert $ \lceil N / 2 \rceil - n24 - n25 = 6 - 2 - 2 = 2$ self-loop transitions into this path (the image): The order in which red, green and blue vertices appears in this path does not affect the number of ways of insertion, and can be arbitrary. The number of ways to insert $2$ self-loop transitions will be equal to the number of the path of length $ \lceil N / 2 \rceil = 6$ from START to GOAL in this automaton (we have to take into account the non-self-loop transitions in it), which can be calculated by matrix exponentiation. Are we done? No! Consider the case $s =$"abbb..($|s| - 1$ times)..bb". There are $|s| - 1$ possible values of $n24$ ($n24 = 1$ corresponds to the case where you match and discard the 'a' first, and $n24 = |s| - 1$ corresponds to the case where you keep the 'a' until $s$ becomes "ab"). Thus, you need to perform matrix exponentiation $|s| - 1$ times, which results in a total of $O(|s|^{4}\log n)$ time, which will be too much under the given constraints. There is still hope, though, and here is the climax. Notice that these automata are very similar to each other, and they differ only in the number of the red and green vertices. We can combine these automata into one larger automaton like this (the image): The combined automaton should have $|s| - 1$ red, $ \lceil |s| / 2 \rceil $ green and $ \lceil |s| / 2 \rceil $ blue vertices. By performing matrix exponentiation on this automaton instead of many small automata, we can find all the required value in $O(|s|^{3}\log n)$ time, which should be enough. We recommend speeding up matrix multiplication by noticing that the matrix will be upper triangular (6 times faster on paper), since the time limit is not so generous (in order to reject $O(|s|^{4}\log n)$ solutions). The problem is almost solved, but there is one more challenge. When $N$ is odd, the situation becomes a little complicated: as we have seen at the beginning, in the last ($ \lceil N / 2 \rceil $-th) step of producing a palindrome we choose a letter for only one position of the resulting string, that is, the center of that string. In other words, the last transition in the path in the automaton we have first built must not be one from a green vertex with a string of length 2 (for example, "aa") to GOAL. Let us find the number of the paths that violates this condition and subtract it from the answer. As previously mentioned, for each path $n24 + 2 \cdot n25$ will be equal to either $|s|$ or $|s| + 1$, and if we fix the value of $n24$, $n25$ will be uniquely determined by $n25 = \lceil (|s| - n24) / 2 \rceil $. If $|s| - n24$ is odd, then it means that the last non-self-loop transition is one from a green vertex with a string of length 1, therefore in this case no path will violate the condition. If $|s| - n24$ is even, then the last non-self-loop trantision is from a green vertex with a string of length 2, thus the paths that does not contain the self-loop from GOAL to itself violate the condition. It will be equal to the number of the paths of length $ \lceil N / 2 \rceil - 1$ from START to the vertex just before GOAL, which can be found in a similar way to the second part of the solution. The journey has finally come to an end. Actually, it is also possible to solve this problem in $O(|s|^{3}+\log n)$ time without matrix exponentiation, but this margin is too small to explain it. I will just paste the link to the code.
|
[
"combinatorics",
"dp",
"matrices",
"strings"
] | 3,000
|
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <utility>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
#define REP(i,n) for((i)=0;(i)<(int)(n);(i)++)
#define snuke(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++)
#define MOD 10007
int N;
string s;
int dp[210][210][210]; // L, R, diagonals
typedef vector <vector <int> > matrix;
matrix mat_prod(matrix &A, matrix &B){
int N=A.size(),i,j,k;
matrix C(N, vector <int> (N, 0));
REP(i,N) REP(j,N){
int tmp = 0;
REP(k,N){
tmp += A[i][k] * B[k][j];
if((k&15) == 15) tmp %= MOD;
}
C[i][j] = tmp % MOD;
}
return C;
}
matrix mat_power(matrix &A, int K){
int N=A.size(),i,j;
matrix ans(N, vector <int> (N, 0));
REP(i,N) ans[i][i] = 1;
for(i=30;i>=0;i--) if(K&(1<<i)) break;
for(;i>=0;i--){
ans = mat_prod(ans, ans);
if(K&(1<<i)) ans = mat_prod(ans, A);
}
return ans;
}
matrix A,B;
void pre(int K){
int i;
matrix C(310, vector <int> (310, 0));
REP(i,309) C[i][i+1] = 1;
REP(i,205) C[i][i] = 24;
REP(i,105) C[205+i][205+i] = 25;
A = mat_power(C, K);
matrix D(311, vector <int> (311, 0));
REP(i,310) D[i][i+1] = 1;
REP(i,205) D[i][i] = 24;
D[205][205] = 26;
REP(i,105) D[206+i][206+i] = 25;
B = mat_power(D, K);
}
int func2(int K, int moves, int stay24, int stay25, int stay26){
if(stay26 == 0) return A[205-stay24][204+stay25];
return B[205-stay24][205+stay25];
}
int func(int K, bool odd){
int ans=0,i,j,k;
REP(i,N+1) REP(j,N+1) if(i == j || i == j + 1 || (i == j - 1 && odd)){
REP(k,210) if(dp[i][j][k] != 0){
int moves = N - (j - i) - k;
int stay25 = k;
int stay24 = moves - k;
int stay26 = 0;
if(i >= j) stay26++; else stay25++;
int tmp = func2(K, moves, stay24, stay25, stay26);
if(odd && i >= j) tmp = tmp * 26 % MOD;
ans = (ans + tmp * dp[i][j][k]) % MOD;
}
}
return ans;
}
int main(void){
int i,j,k,d;
int K;
cin >> s >> K;
N = s.length();
dp[0][N][0] = 1;
for(d=N;d>=1;d--) REP(i,N-d+1){
j = i + d;
REP(k,210) if(dp[i][j][k] != 0){
if(s[i] == s[j-1]){
dp[i+1][j-1][k+1] = (dp[i+1][j-1][k+1] + dp[i][j][k]) % MOD;
} else {
dp[i+1][j][k] = (dp[i+1][j][k] + dp[i][j][k]) % MOD;
dp[i][j-1][k] = (dp[i][j-1][k] + dp[i][j][k]) % MOD;
}
}
}
K += N;
pre(K/2);
int ans = func(K/2, (K % 2 == 1));
cout << ans << endl;
return 0;
}
|
507
|
A
|
Amr and Music
|
Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has $n$ instruments, it takes $a_{i}$ days to learn $i$-th instrument. Being busy, Amr dedicated $k$ days to learn how to play the maximum possible number of instruments.
Amr asked for your help to distribute his free days between instruments so that he can achieve his goal.
|
Problem: We have to split the number $k$ into maximum number of elements of $a_{i}$ such that their sum is less than or equal to $k$. Hint: To maximize the answer we have to split the number into the smallest numbers possible. Solution: So and since the limits are small we can pick up the smallest element of the array and subtract it from $k$, and we keep doing this $n$ times or until the smallest number is larger than $k$. Another solution is to sort the array in non-decreasing order and go on the same way. Time complexity: $O(n^{2})\,$ or $O(n\ l o g\ n)$
|
[
"greedy",
"implementation",
"sortings"
] | 1,000
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 9223372036854775807
#define INF 2000000000
#define PI acos(-1.0)
#define EPS 1e-9
#define LL long long
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define setzero(a) memset(a,0,sizeof(a))
#define setdp(a) memset(a,-1,sizeof(a))
using namespace std;
pair<int,int> A[105];
vector<int> ans;
int main()
{
int n,days;
cin >> n >> days;
for(int i=0;i<n;i++)
scanf("%d",&A[i].first),A[i].second = i;
sort(A,A+n);
for(int i=0;i<n;i++)
{
if(days < A[i].first)
break;
ans.push_back(A[i].second + 1);
days-=A[i].first;
}
sort(ans.begin(), ans.end());
cout << ans.size() << endl;
for(int i=0;i<ans.size();i++)
{
if(i) printf(" ");
printf("%d",ans[i]);
}
return 0;
}
|
507
|
B
|
Amr and Pins
|
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius $r$ and center in point $(x, y)$. He wants the circle center to be in new position $(x', y')$.
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps.
|
Problem: We have a circle with radius $R$ at position $(x, y)$ and we want to move it to $(x', y')$ with minimum moves possible. A move is to choose an arbitrary point on the border of the circle and rotate the circle around it with arbitrary angle. Hint: What is the shortest path between two points? A direct line. So moving the center on that line with maximum move possible each time will guarantee minimal number of moves. Solution: Let's draw a straight line between the two centers. Clearly to move the center with maximum distance we need to rotate it around the intersection of the line and the circle with $180$ degrees. So the maximum distance we can move the center each time is $2 * R$. Let's continue moving the center with $2 * R$ distance each time until the two circles intersects. Now obviously we can make the center moves into its final position by rotating it around one of the intersection points of the two circles until it reaches the final destination. Every time we make the circle moves $2 * R$ times except the last move it'll be $ \le 2 * R$. Assume that the initial distance between the two points is $d$ So the solution to the problem will be $c e i l({\frac{d}{2\pi R}})$. Time complexity: $O(1)$ You have to be careful of precision errors. Here is a code that used only integer arithmetic operations 9529147.
|
[
"geometry",
"math"
] | 1,400
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class ok {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
long r;
int x, y, xx, yy;
r = in.nextInt();
x = in.nextInt();
y = in.nextInt();
xx = in.nextInt();
yy = in.nextInt();
r*=2;
long dist = (x - xx) * 1L * (x - xx) + (y - yy) * 1L * (y - yy);
r *= r;
int L = 0, R = 1000000;
while(R > L)
{
int mid = L + (R - L) / 2;
BigInteger temp = BigInteger.valueOf(mid);
temp = temp.multiply(BigInteger.valueOf(mid));
temp = temp.multiply(BigInteger.valueOf(r));
int test = temp.compareTo(BigInteger.valueOf(dist));
if(test == 0 || test == 1)
R = mid;
else L = mid + 1;
}
System.out.println(R);
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(FileReader stream) {
reader = new BufferedReader(stream);
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
|
507
|
C
|
Guess Your Way Out!
|
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height $h$. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.
Let's index all the leaf nodes from the left to the right from 1 to $2^{h}$. The exit is located at some node $n$ where $1 ≤ n ≤ 2^{h}$, the player doesn't know where the exit is so he has to guess his way out!
Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules:
- Character 'L' means "go to the left child of the current node";
- Character 'R' means "go to the right child of the current node";
- If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node;
- If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command;
- If he reached a leaf node that is not the exit, he returns to the parent of the current node;
- If he reaches an exit, the game is finished.
Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
|
Hint: Simulate the algorithm until we reach a leaf node assume that it's not the exit. Now the question is Are there some nodes that are guaranteed to be visited before trying to reach the exit again? Solution: The first observation is that in order to return to a parent we will have to visit all nodes of the right or the left subtree of some node first. Now imagine we are in the situation below where $E$ is the exit. By applying the algorithm we'll reach node $X$. Both the $E$ and $X$ are in different subtrees of the root. Which means before going to the proper subtree in which the Exit exists we'll have to visit all the nodes of the left subtree (marked in red). This means we have to get the node which the Exit and the current leaf node $X$ are in different subtrees which will be the least common ancestor (LCA) of the two nodes. Assume the subtree height is $h_{1}$. This means we visited $\sum_{i=0}^{h_{1}-1}2^{i}$ node. By adding the nodes above the subtree which we visited during executing the string for the first time the total number of visited nodes will be $(\sum_{i=0}^{h_{1}-1}2^{i})+h-h_{1}$. Now let's go to the other subtree. Obviously we don't need any other nodes except this subtree. So let's do the same we did to the original tree to this subtree. Execute the algorithm until we reach a leaf node, get the LCA, add to the solution $(\bar{\sum_{i=0}^{h_{2}-1}}2^{i})+h_{1}-h_{2}$ where $h_{2}$ is the height of the subtree of the LCA node where the leaf node exists. And so on we keep applying the rules until after executing the algorithm we will reach the exit. Also we can do the same operations in $O(h)$ by beginning to move from the root, if the exit is located to the left we go to the left and ans++ and then set the next command to 'R' else if it is located to the right we will visited the whole left subtree so we add the left subtree nodes to the answer $a n s+=\sum_{i=0}^{h-2}2^{i}+1$ and then set the next command to 'L' and so on. Time complexity: $O(h^{2})\,$ or $O(h)$ Challenge: What if the pattern is given as an input (e.g. "LRRLLRRRLRLRLRR..."), How can this problem be solved?
|
[
"implementation",
"math",
"trees"
] | 1,700
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 9223372036854775807
#define INF 2000000000
#define PI acos(-1.0)
#define EPS 1e-9
#define LL long long
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define setzero(a) memset(a,0,sizeof(a))
#define setdp(a) memset(a,-1,sizeof(a))
using namespace std;
vector<LL> anc;
LL sum[51];
int main()
{
ios_base::sync_with_stdio(0);
int h;
LL n;
cin >> h >> n;
sum[0] = 1;
for(int i=1;i<51;i++)
sum[i] = sum[i-1] + (1LL << i);
n+=sum[h-1];
LL x = n;
anc.push_back(x);
while(x != 1)
{
x = x / 2;
anc.push_back(x);
}
LL res = 0;
LL node = 1;
bool choice = false;
while(node != n)
{
vector<LL> ance;
for(int i=0;i<h;i++)
{
ance.push_back(node);
if(!choice)
node = node * 2;
else node = node * 2 + 1;
choice = !choice;
}
if(n == node)
{
res+=h;
break;
}
ance.push_back(node);
reverse(ance.begin(), ance.end());
for(int i=1;i<=h;i++)
{
if(anc[i] == ance[i])
{
res+=sum[i - 1] + h - i + 1;
h = i - 1, node = ance[i - 1];
if(node == ance[i] * 2)
node = ance[i] * 2 + 1, choice = 0;
else node = ance[i] * 2, choice = 1;
break;
}
}
}
cout << res;
return 0;
}
|
507
|
D
|
The Maths Lecture
|
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.
First he gave Amr two positive integers $n$ and $k$. Then he asked Amr, how many integer numbers $x > 0$ exist such that:
- Decimal representation of $x$ (without leading zeroes) consists of exactly $n$ digits;
- There exists some integer $y > 0$ such that:
- $y{\bmod{k}}=0$;
- decimal representation of $y$ is a suffix of decimal representation of $x$.
As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number $m$.
Can you help Amr escape this embarrassing situation?
|
Hint: Dynamic programming problem. To handle repetitions we have to construct the number from right to the left and calculate the answer when we reach a number equivalent to $0$ modulo $k$. Solution: Let's define $c o u n t(i\,,j)$ as a recursive functions calculates the number of numbers consisting of $n$ digits satisfying the conditions of the problem and with a specific suffix of length $i$ $S_{i}$ such that $S_{i}\equiv j{\mathrm{~(mod\,}}k)$. We want to avoid repetition so by constructing the number from the right to the left when we reach a state with $j = 0$ with suffix $ \neq 0$ we return the answer immediately so any other suffix that contains this suffix won't b calculated. So the base cases are $c o u n t(n,0)=1$, $c o u n t(i,0)=9*10^{n-i-1}:i<n$. So state transitions will be $c o u n t(i,j)=\sum_{x=0}^{9}c o u n t(i+1,(j+(x*10^{i}))\surd_{0}k)$ (We add a digit to the left). And we can handle $j = 0$ case coming from a zero suffix easily with a boolean variable we set to true when we use a digit $ \neq 0$ in constructing the number. Time complexity: $O(n*k)$
|
[
"dp",
"implementation"
] | 2,200
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 9223372036854775807LL
#define INF 1000000000
#define PI acos(-1.0)
#define EPS 1e-9
#define LL long long
//#define mod 1000000007
#define pb push_back
#define mp make_pair
#define setzero(a) memset(a,0,sizeof(a))
#define setdp(a) memset(a,-1,sizeof(a))
using namespace std;
int mod;
int DP[1005][105][2];
int powers[1005],powers2[1005],k,n;
int solve(int ind,int rem, bool change)
{
if(rem == 0 && change) return (ind != n ? ((powers[n - ind - 1] * 1LL * 9) % mod) : 1);
if(ind == n || (rem == 0 && change)) return 0;
int &temp = DP[ind][rem][change];
if(temp != -1) return temp;
temp = 0;
for(int i=0;i<10;i++)
temp+=solve(ind + 1, (rem + (i * 1LL * powers2[ind]) % k) % k,change || i != 0),temp%=mod;
return temp;
}
int main()
{
ios_base::sync_with_stdio(0);
cin >> n >> k >> mod;
setdp(DP);
LL y = 1;
for(int i=0;i<=n;i++)
{
powers[i] = y;
y*=10;
y%=mod;
}
y = 1;
for(int i=0;i<=n;i++)
{
powers2[i] = y;
y*=10;
y%=k;
}
cout << solve(0, 0, 0);
return 0;
}
|
507
|
E
|
Breaking Good
|
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.
Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of $n$ cities with $m$ bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads.
The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.
The gang is going to rob a bank! The bank is located in city $1$. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city $n$. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.
First of all the path which they are going to use on their way back from city $1$ to their headquarters $n$ must be \underline{as short as possible}, since it is important to finish operation as fast as possible.
Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional.
If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.
Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).
Can you help Walter complete his task and gain the gang's trust?
|
Hint: Consider we've chosen a certain path with length $d$ where $d$ is the length of the shortest path from $1$ to $n$ and it has $x$ edges that are working. Assume that $y$ is the total number of edges that are working in the whole country. So we need to make $d - x$ changes (to make the malfunctioning edges on the path work) and $y - x$ changes (to blow up all other edges that don't lie on the path). So we will totally make $d + y - 2 * x$ changes where $d$ and $y$ are constants. So the optimal solution will depend only on number of working edges along the path. So we'll have to maximize this number! Solution: We will use dynamic programming on all nodes that lies on some shortest path. In other words, every node $x$ that satisfies that the shortest path from $1$ to $x$ + the shortest path from $x$ to $n$ equals $d$ where $d$ is the length of the shortest path from $1$ to $n$. Let's define $Max[x]$ is the maximum number of working edges along some shortest path from $1$ to $x$. We can calculate the value $Max[x]$ for all nodes by dynamic programming by traversing the nodes in order of increasing shortest path from node $1$. So at the end we'll make $d + y - 2 * Max[n]$ changes. We can get them easily by retrieving the chosen optimal path. Time complexity: $O(n+m)$
|
[
"dfs and similar",
"dp",
"graphs",
"shortest paths"
] | 2,100
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 9223372036854775807LL
#define INF 1000000000
#define PI acos(-1.0)
#define EPS 1e-9
#define LL long long
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define setzero(a) memset(a,0,sizeof(a))
#define setdp(a) memset(a,-1,sizeof(a))
using namespace std;
struct edge
{
int to;
bool s;
edge(int y, bool z)
{
to = y, s = z;
}
};
vector<vector<edge > > graph(100005);
int D1[100005], DN[100005], MaxOp[100005], parent[100005], path[100005];
int from[100005], to[100005];
bool opened[100005], visited[100005];
int main()
{
ios_base::sync_with_stdio(0);
int n, m, counter = 0;
cin >> n >> m;
for(int i=0;i<m;i++)
{
cin >> from[i] >> to[i] >> opened[i];
graph[from[i]].pb(edge(to[i], opened[i]));
graph[to[i]].pb(edge(from[i], opened[i]));
counter+=opened[i];
}
setdp(D1);
setdp(DN);
setdp(MaxOp);
queue<int> q;
q.push(1);
D1[1] = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
for(int i=0;i<graph[node].size();i++)
{
edge e = graph[node][i];
if(D1[e.to] != -1) continue;
D1[e.to] = D1[node] + 1;
q.push(e.to);
}
}
q.push(n);
DN[n] = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
for(int i=0;i<graph[node].size();i++)
{
edge e = graph[node][i];
if(DN[e.to] != -1) continue;
DN[e.to] = DN[node] + 1;
q.push(e.to);
}
}
int d = D1[n];
q.push(1);
MaxOp[1] = 0;
while(!q.empty())
{
int node = q.front();
q.pop();
if(visited[node]) continue;
visited[node] = true;
for(int i=0;i<graph[node].size();i++)
{
edge e = graph[node][i];
if(D1[e.to] + DN[e.to] != d || D1[node] + 1 + DN[e.to] != d || visited[e.to]) continue;
if(MaxOp[e.to] != -1 && MaxOp[e.to] >= MaxOp[node] + e.s) continue;
q.push(e.to);
parent[e.to] = node;
MaxOp[e.to] = MaxOp[node] + e.s;
}
}
int node = n;
while(node != 1)
{
path[node] = parent[node];
node = path[node];
}
cout << counter + d - 2 * MaxOp[n] << '\n';
for(int i=0;i<m;i++)
{
if(path[from[i]] == to[i] || path[to[i]] == from[i])
{
if(!opened[i]) cout << from[i] << " " << to[i] << " 1" << '\n';
}
else if(opened[i]) cout << from[i] << " " << to[i] << " 0" << '\n';
}
return 0;
}
|
508
|
A
|
Pasha and Pixels
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of $n$ row with $m$ pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a $2 × 2$ square consisting of black pixels is formed.
Pasha has made a plan of $k$ moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers $i$ and $j$, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the $2 × 2$ square consisting of black pixels is formed.
|
To solve this problem let's create matrix with type $bool$ and dimensions $n$ on $m$. Cell $(x, y)$ of this matrix is $true$ - if this cell painted in black color. Let on move number $k$ Pasha paints pixel in position $(i, j)$. Then game ending on this move, if square $2 \times 2$ formed from black cells appears, and cell $(i, j)$ will upper-left, upper-right, bottom-left or bottom-right of this squares. Only this squares we need to check on current move. If we haven't such squares after $k$ moves, print $0$. Asymptotic behavior of this solution - $O(k)$, where $k$ - number of moves.
|
[
"brute force"
] | 1,100
| null |
508
|
B
|
Anton and currency you all know
|
Berland, 2016. The exchange rate of \underline{currency you all know} against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of \underline{currency you all know} against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an \underline{odd} positive integer $n$. Help Anton to determine the exchange rate of \underline{currency you all know} for tomorrow!
|
Because of specified number is odd (that mean that last digit of this number is odd) we need to swap last digit with some even digit. How to maximize number after this swap? If number consists only from odd digits print $- 1$. Else, we need to find first even digit, which less than last digit if we will iterate from most significant digit. If we find such digit - swap it with last digit and we have an answer. Else, we need to find first even digit, which more than last digit if we will iterate from less significant digit. If we find such digit - swap it with last digit and we have an answer. Asymptotic behavior of this solution - $O(n)$, where $n$ - count of digits in specified number.
|
[
"greedy",
"math",
"strings"
] | 1,300
| null |
508
|
C
|
Anya and Ghosts
|
Anya loves to watch horror movies. In the best traditions of horror, she will be visited by $m$ ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly $t$ seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly $t$ seconds and then goes out and can no longer be used.
For each of the $m$ ghosts Anya knows the time at which it comes: the $i$-th visit will happen $w_{i}$ seconds after midnight, all $w_{i}$'s are distinct. Each visit lasts exactly one second.
What is the minimum number of candles Anya should use so that during each visit, at least $r$ candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. \textbf{That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.}
|
This problem can be solved with help of greedy algorithm. Let's iterate on moments when ghosts will appears. We need to use use array, in wich we will mark moments of time, in wich we lighted candles (for example, put in corresponding positions $1$). Than for every new ghost will count how many candles lights in time of his visit from our array. If ghost appears in moment of time $w_{i}$, iterate on out array from $w_{i} - 1$ to $w_{i} - t$, where $t$ - count of seconds, which candle burns, and count the number of ones. If this count is not less than $r$, continue iterating on ghosts. Else, iterate on our array from $w_{i} - 1$ to $w_{i} - t$, and, if in current second candle didn't lighted - make it, and put in this position in array $1$. We need to do such operation, while count of ones in this section of our array will not be equals to $r$. If we can't do this fore some ghost, we can print $- 1$. Answer to this problem - count of ones in our array. Asymptotic behavior of this solution - $O(mt)$, where $m$ - count of ghosts, $t$ - the duration of a candle's burning.
|
[
"constructive algorithms",
"greedy"
] | 1,600
| null |
508
|
D
|
Tanya and Password
|
While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of $n + 2$ characters. She has written all the possible $n$ three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with $n$ pieces of paper.
Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.
|
At first, let's convert data from input in directed graph. Vertexes in this graph will all strings with length equals to 2 and consisting of uppercase and lowercase letters of the latin alphabet. For all 3-letters strings from input - $s_{i}$'s, let's add edge from vertex $s_{i}[0]s_{i}[1]$ to $s_{i}[1]s_{i}[2]$. Now we need to find in this graph Euler path. For this we can use Fleury's algorithm. It is worth noting, that Euler path consists, if count of vertexes, in wich in-degree and out-degree differs by one, less then 3, and in-degree and out-degree of others vertexes - even. If we can't find Euler path - print $NO$. Asymptotic behavior of this solution - $O(m)$, where $m$ - count of different 3-letters strings from input. It equals to number of edges in graphs.
|
[
"dfs and similar",
"graphs"
] | 2,500
| null |
508
|
E
|
Arthur and Brackets
|
Notice that the memory limit is non-standard.
Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length $2n$. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.
All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the $i$-th opening bracket he remembers the segment $[l_{i}, r_{i}]$, containing the distance to the corresponding closing bracket.
Formally speaking, for the $i$-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment $[l_{i}, r_{i}]$.
Help Arthur restore his favorite correct bracket sequence!
|
This problem can be solved with help of dynamic dynamic programming. Let's create squre matrix $Z$ with sizes $n \times n$, where $n$ - count of open brackets in sequence. Main hint - if open bracket is in position $l$, and corresponding for her close bracket - in position $r$, than from position $l + 1$ to position $r - 1$ must stay a regular bracket sequence. In array $Z$ first parametr $lf$ - number of open bracket, second parametr $rg$ - number of last open bracket, which can be in a regular bracket sequence, which will exists between open bracket with number $lf$ and corresponding for it close bracket. $Z[lf][rg] = true$ if it is possible to construct such sequence. Otherwise $Z[lf][rg] = false$. For current $lf$ and $rg$ let's iterate on $cnt$ - how many open brackets and corresponding them close brackets in a regular bracket sequence will stay between open bracket number $lf$ and corresponding for it close bracket. If this count falls in the given interval for open bracket $lf$, recurcively run dynamic from two segments - $(lf + 1, lf + cnt)$ and $(lf + cnt + 1, rg)$. If for both segments we can construct regular bracket sequences, appropriate to data-in from input, put in $Z[lf][rg]$ value $true$. To restore answer, we must move from segment $(lf, rg)$ in segments $(lf + 1, lf + cnt)$ and $(lf + cnt + 1, rg)$, if for both this segments we can construct regular bracket sequences and recursively restore asnwer. If $Z[0][n - 1]$ equals to $false$, print $IMPOSSIBLE$. Asymptotic behavior of this solution - $O(n^{3})$.
|
[
"dp",
"greedy"
] | 2,200
| null |
509
|
A
|
Maximum in Table
|
An $n × n$ table $a$ is defined as follows:
- The first row and the first column contain ones, that is: $a_{i, 1} = a_{1, i} = 1$ for all $i = 1, 2, ..., n$.
- Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula $a_{i, j} = a_{i - 1, j} + a_{i, j - 1}$.
These conditions define all the values in the table.
You are given a number $n$. You need to determine the maximum value in the $n × n$ table defined by the rules above.
|
In this problem one needed to implement what was written in the statement: create matrix (two-dimensional array) using given rules and find maximal value in the table. It is also possible to see that maximal element is always in bottom-right corner. Easier solution with recursion also was enough to get AC: One may see the Pascal's triangle in the given matrix and understand that answer is equal to $\textstyle{\binom{2n-2}{n-1}}$
|
[
"brute force",
"implementation"
] | 800
| null |
509
|
B
|
Painting Pebbles
|
There are $n$ piles of pebbles on the table, the $i$-th pile contains $a_{i}$ pebbles. Your task is to paint each pebble using one of the $k$ given colors so that for each color $c$ and any two piles $i$ and $j$ the difference between the number of pebbles of color $c$ in pile $i$ and number of pebbles of color $c$ in pile $j$ is at most one.
In other words, let's say that $b_{i, c}$ is the number of pebbles of color $c$ in the $i$-th pile. Then for any $1 ≤ c ≤ k$, $1 ≤ i, j ≤ n$ the following condition must be satisfied $|b_{i, c} - b_{j, c}| ≤ 1$. It isn't necessary to use all $k$ colors: if color $c$ hasn't been used in pile $i$, then $b_{i, c}$ is considered to be zero.
|
Suppose there are two piles with number of pebbles differed by more than $k$, then there is no solution: $a_{i}=\sum_{c=1}^{k}b_{i,c}\leq\sum_{c=1}^{k}(b_{j,c}+1)=a_{j}+k$ Now let $M = max a_{i} \le min a_{i} + k = m + k$. There's a way to construct correct coloring: Chose $m$ peebles from each pile and assign first color to them. In each pile assign different colors to all other pebbles (you may use first color once more) (It's possible bacause there are no more than $k$ uncolored pebbles. Now there are $m$ or $m + 1$ pebbles of first color and 0 or 1 pebbles of any other color in each pile.
|
[
"constructive algorithms",
"greedy",
"implementation"
] | 1,300
| null |
509
|
C
|
Sums of Digits
|
Vasya had a \textbf{strictly increasing} sequence of positive integers $a_{1}$, ..., $a_{n}$. Vasya used it to build a new sequence $b_{1}$, ..., $b_{n}$, where $b_{i}$ is the sum of digits of $a_{i}$'s decimal representation. Then sequence $a_{i}$ got lost and all that remained is sequence $b_{i}$.
Vasya wonders what the numbers $a_{i}$ could be like. Of all the possible options he likes the one sequence with the minimum possible last number $a_{n}$. Help Vasya restore the initial sequence.
It is guaranteed that such a sequence always exists.
|
The algorithm is greedy: first, take the minimal number with sum of digits $a_{1}$ - call it $b_{1}$. Then, on the $i$-th step take $b_{i}$ as the minimal number with sum of digits $a_{i}$, which is more than $b_{i - 1}$. It can be easily proven that this algorithm gives an optimal answer. But how to solve the subproblem: given $x$ and $y$, find the minimal number with sum of digits $x$, which is more than $y$? We use a standard approach: iterate through the digits of $y$ from right to left, trying to increase the current digit and somehow change the digits to the right in order to reach the sum of digits equal to $x$. Note that if we are considering the $(k + 1)$-th digit from the right and increase it, we can make the sum of $k$ least significant digits to be any number between $0$ and $9k$. When we find such position, that increasing a digit in it and changing the least significant digits gives us a number with sum of digits $x$, we stop the process and obtain the answer. Note that if $k$ least significant digits should have sum $m$ (where $0 \le m \le 9k$), we should obtain the answer greedily, going from the right to the left and putting to the position the largest digit we can. Let us bound the maximal length of the answer, i.e. of $b_{n}$. If some $b_{i}$ has at least $40$ digits, than we take the minimal $k$ such that $10^{k} \ge b_{i}$. Than between $10^{k}$ and $10^{k + 1}$ there exist numbers with any sum of digits between $1$ and $9k$. If $k \ge 40$, than $9k \ge 300$, which is the upper bound of all $b_{i}$. So, in the constraints of the problem, $b_{i + 1}$ will be less than $10^{k + 1}$. Than, similarly, $b_{i + 2} < 10^{k + 2}$ and so on. So, the length of the answer increases by no more than one after reaching the length of $40$. Consequently, the maximal length of the answer can't be more than $340$. The complexity of solution is $O(n \cdot maxLen)$. Since $n \le 300$, $maxLen \le 340$, the solution runs much faster the time limit.
|
[
"dp",
"greedy",
"implementation"
] | 2,000
| null |
509
|
D
|
Restoring Numbers
|
Vasya had two arrays consisting of non-negative integers: $a$ of size $n$ and $b$ of size $m$. Vasya chose a positive integer $k$ and created an $n × m$ matrix $v$ using the following formula:
\[
v_{i,j}=(a_{i}+b_{j})\bmod k
\]
Vasya wrote down matrix $v$ on a piece of paper and put it in the table.
A year later Vasya was cleaning his table when he found a piece of paper containing an $n × m$ matrix $w$. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix $v$ from those days. Your task is to find out if the matrix $w$ that you've found could have been obtained by following these rules and if it could, then for what numbers $k, a_{1}, a_{2}, ..., a_{n}, b_{1}, b_{2}, ..., b_{m}$ it is possible.
|
First we note that if the sequences $a_{i}$ and $b_{i}$ are a valid solution, then so are the sequences $a_{i} - P$ and $b_{i} + P$ for any integer $P$. This means that we can consider $a_{1}$ to be equal to 0 which allows us to recover the sequence $b_{i}$ by simply taking the first row of the matrix. Knowing $b_{i}$ we can also recover $a_{i}$ (for example by subtracting $b_{1}$ from the first column of the matrix) At this stage we allow $a_{i}$ and $b_{i}$ to contain negative numbers, which can be later fixed by adding $K$ a sufficient amount of times. Now we consider the "error" matrix $e$: $e_{i,j}=|a_{i}+b_{j}-w_{i,j}|$. If $e$ consists entirely of 0s, then we've found our solution by taking a sufficiently large $K$. That is: $K > max_{i, j}(w_{i, j})$. Otherwise, we note that $e_{i, j} = 0(modK)$ which implies that $K$ is a divisor of $g = gcd_{i, j}(e_{i, j})$. The greatest such number is $g$ itself, so all that remains is to check if $g$ is strictly greater than all the elements of the matrix $w$. If that is the case, then we've found our solution by setting $K = g$. Otherwise, there's no solution.
|
[
"constructive algorithms",
"math"
] | 2,200
| null |
509
|
E
|
Pretty Song
|
When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.
Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.
More formally, let's define the function $vowel(c)$ which is equal to $1$, if $c$ is a vowel, and to $0$ otherwise. Let $s_{i}$ be the $i$-th character of string $s$, and $s_{i..j}$ be the substring of word $s$, staring at the $i$-th character and ending at the $j$-th character ($s_{is}_{i + 1}... s_{j}$, $i ≤ j$).
Then the simple prettiness of $s$ is defined by the formula:
\[
s i m p l e(s)={\frac{\sum_{i=1}^{\operatorname{op}}v o w e l(s_{i})}{\operatorname{ini}}}
\]
The prettiness of $s$ equals
\[
\sum_{1\leq i\leq j\leq|s|}s i m p l e(s_{i\cdot j}).
\]
Find the prettiness of the given song title.
We assume that the vowels are $I, E, A, O, U, Y$.
|
We first calculate the prefix sums of $vowel(s_{i})$ which allows to calculate the sum of $vowel(s_{i})$ on any substring in $O(1)$ time. For all $m$ from $1$ to $\left|\,\S\right|_{\sim}\right|_{\sim}$, we will calculate the sum of simple pretinesses of all substrings of that length, let's call it $SP_{m}$. For that purpose, let's calculate the number of times the $i$-th character of the string $s$ is included in this sum. For $m = 1$ and $m = |s|$, every character is included exactly 1 time. For $m = 2$ and $m = |s| - 1$, the first and the last character are included 1 time and all other characters are included 2 times. For $m = 3$ and $m = |s| - 2$ the first and the last character are included 1 time, the second and the pre-last character are included 2 times and all others are included 3 times, and so on. In general, the $i$-th character is included $min(m, |s| - m + 1, i, |s| - i + 1)$ times. Note that when moving from substrings of length $m$ to substrings of length $m + 1$, there are 2 ways in which the sum $SP$ can change: If $m > |s| - m + 1$, then $SP$ is decreased by the number of vowel occurrences in the substring from $|s| - m + 1$ to $m$. Otherwise, $SP$ is increased by the number of vowel occurrences in the substring from $m$ to $|s| - m + 1$. This way we can easily recalculate $SP_{m + 1}$ using $SP_{m}$ by adding (subtracting) the number of vowel occurrences on a substring (which is done in $O(1)$ time). The complexity of this solution is $O(N)$.
|
[
"math",
"strings"
] | 2,000
| null |
509
|
F
|
Progress Monitoring
|
Programming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:
You are given a tree $T$ with $n$ vertices, specified by its adjacency matrix $a[1... n, 1... n]$. What is the output of the following pseudocode?
\begin{verbatim}
used[1 ... n] = {0, ..., 0};
procedure dfs(v):
print v;
used[v] = 1;
for i = 1, 2, ..., n:
if (a[v][i] == 1 and used[i] == 0):
dfs(i);
dfs(1);
\end{verbatim}
In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree $T$ such that the result is his favorite sequence $b$. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees $T$ such that the result of running the above pseudocode with $T$ as input is exactly the sequence $b$. Can you help him?
Two trees with $n$ vertices are called different if their adjacency matrices $a_{1}$ and $a_{2}$ are different, i. e. there exists a pair $(i, j)$, such that $1 ≤ i, j ≤ n$ and $a_{1}[i][j] ≠ a_{2}[i][j]$.
|
Consider a tree with $n$ vertices rooted at vertex 1 and let $b$ be the pseudocode's (DFS) resulting sequence. Then $b[l_{v}..l_{v} + size_{v} - 1]$, represents vertex $v$'s subtree, where $l_{v}$ is the index of $v$ in $b$ and $size_{v}$ is the size of $v$'s subtree. Let's solve the problem using this fact and Dynamic Programming. Let $e[l, r]$ be the number of trees consisting of vertices $a[l], a[l + 1], \dots , a[r]$ such that running DFS starting from $a[l]$ will result in a sequence with vertices in the same order as their order in $a$. The base case is when $l = r$ and $e[l, r] = 1$. Otherwise, $e[l,r]=\sum\prod_{i=1}^{k}e[p o s_{i},p o s_{i+1}-1]$ where the sum is taken over all partitions of the segment $[l + 1, r]$, that is, over all $k;pos_{1}, ..., pos_{k + 1}$, such that $l + 1 = pos_{1} < pos_{2} < ... < pos_{k + 1} = r$, $1 \le k \le r - l$, $a[pos_{1}] < a[pos_{2}] < ... < a[pos_{k}]$. Each such partition represents a different way to distribute the vertices among $a[l]$'s children's subtrees. A solution using this formula for calculating $e[l, r]$ will have an exponential running time. The final idea is to introduce $d[l, r]: = e[l - 1, r], 2 \le l \le r \le n$. It follows that: $d[l, r]$ = $e[l,r]+\sum_{p o s=l+1}^{r}\,e[l,p o s-1]*d[p o s,r]\ast[a[l]<a[p o s]]$ ([statement] is equal to 1 if the statement is true, 0 otherwise) and $e[l, r] = d[l + 1, r]$. This way $d[l, r]$ and $e[l, r]$ can be calculated in linear time for any segment $[l, r]$. The answer to the problem is $e[1, n]$. Overall complexity is $O(n^{3})$.
|
[
"dp",
"trees"
] | 2,300
| null |
510
|
A
|
Fox And Snake
|
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a $n$ by $m$ table. Denote $c$-th cell of $r$-th row as $(r, c)$. The tail of the snake is located at $(1, 1)$, then it's body extends to $(1, m)$, then goes down $2$ rows to $(3, m)$, then goes left to $(3, 1)$ and so on.
Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').
Consider sample tests in order to understand the snake pattern.
|
There are 2 different ways to solve this kind of task: First one is to simulate the movement of the snake head, and you draw '#'s on the board. The code will look like: Another way is to do some observation about the result, you can find this pattern:
|
[
"implementation"
] | 800
|
#include <bits/stdc++.h>
using namespace std;
int MAIN()
{
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
bool haveSnake = false;
if(i % 2 == 1) haveSnake = true;
else
{
if(i % 4 == 2) haveSnake = (j == m);
if(i % 4 == 0) haveSnake = (j == 1);
}
cout << (haveSnake ? "#" : ".");
}
cout << endl;
}
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
510
|
B
|
Fox And Two Dots
|
Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size $n × m$ cells, like this:
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots $d_{1}, d_{2}, ..., d_{k}$ a \underline{cycle} if and only if it meets the following condition:
- These $k$ dots are different: if $i ≠ j$ then $d_{i}$ is different from $d_{j}$.
- $k$ is at least 4.
- All dots belong to the same color.
- For all $1 ≤ i ≤ k - 1$: $d_{i}$ and $d_{i + 1}$ are adjacent. Also, $d_{k}$ and $d_{1}$ should also be adjacent. Cells $x$ and $y$ are called adjacent if they share an edge.
Determine if there exists a \underline{cycle} on the field.
|
This task is essentially ask if there is a cycle in an undirected graph: treat each cell as a node, and add an edge if two cells are neighborhood and have some color. There are lots of ways to do this, for example: Run dfs / bfs, if an edge lead you to a visited node, then there must be a cycle. For each connected component, test if $|#edges| = |#nodes| - 1$, if not then there must be a cycle.
|
[
"dfs and similar"
] | 1,500
|
#include <bits/stdc++.h>
using namespace std;
int n, m;
string board[51];
bool visited[51][51];
bool findCycle = false;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
void dfs(int x, int y, int fromX, int fromY, char needColor)
{
if(x < 0 || x >= n || y < 0 || y >= m) return;
if(board[x][y] != needColor) return;
if(visited[x][y])
{
findCycle = true;
return;
}
visited[x][y] = true;
for(int f = 0; f < 4; f++)
{
int nextX = x + dx[f];
int nextY = y + dy[f];
if(nextX == fromX && nextY == fromY) continue;
dfs(nextX, nextY, x, y, needColor);
}
}
int MAIN()
{
cin >> n >> m;
for(int i = 0; i < n; i++)
cin >> board[i];
memset(visited, false, sizeof(visited));
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(!visited[i][j])
dfs(i, j, -1, -1, board[i][j]);
cout << (findCycle ? "Yes" : "No") << endl;
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
510
|
C
|
Fox And Names
|
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the \underline{lexicographical} order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in \underline{lexicographical} order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes \underline{lexicographical}!
She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the \underline{lexicographical} order. If so, you should find out any such order.
\underline{Lexicographical} order is defined in following way. When we compare $s$ and $t$, first we find the leftmost position with differing characters: $s_{i} ≠ t_{i}$. If there is no such position (i. e. $s$ is a prefix of $t$ or vice versa) the shortest string is less. Otherwise, we compare characters $s_{i}$ and $t_{i}$ according to their order in alphabet.
|
Let's first think about what $S < T$ can tell us: suppose $S = abcxyz$ and $T = abcuv$. Then we know that $S < T$ if and only if $x < u$ by the definition. So we can transform the conditions $name_{1} < name_{2}$, $name_{2} < name_{3}$ ... into the order of letters. Then the question become: do we have a permutation that satisfy those conditions. It is actually the classic topological order question. One trick in this task is that, if we have something like $xy < x$ then there is no solution. This is not covered in pretests. :)
|
[
"dfs and similar",
"graphs",
"sortings"
] | 1,600
|
#include <bits/stdc++.h>
using namespace std;
int n;
int e[27][27];
string s[101];
bool visited[27];
int getID(char c)
{
if(c == ' ') return 0;
return c - 'a' + 1;
}
int MAIN()
{
memset(e, 0, sizeof(e));
for(int i = 1; i <= 26; i++)
e[0][i] = true;
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> s[i];
s[i] += " ";
}
for(int i = 1; i < n; i++)
{
int pos = 0;
while(s[i][pos] == s[i+1][pos]) pos ++;
e[getID(s[i][pos])][getID(s[i+1][pos])] = true;
}
for(int k = 0; k <= 26; k++)
for(int i = 0; i <= 26; i++)
for(int j = 0; j <= 26; j++)
e[i][j] |= e[i][k] & e[k][j];
bool haveCycle = false;
for(int i = 0; i <= 26; i++)
haveCycle |= e[i][i];
if(haveCycle)
cout << "Impossible" << endl;
else
{
memset(visited, 0, sizeof(visited));
for(int i = 0; i <= 26; i++)
{
int now = 0;
for(int j = 0; j <= 26; j++)
{
bool valid = (!visited[j]);
for(int k = 0; k <= 26; k++)
if(visited[k] == false && e[k][j])
valid = false;
if(valid)
{
now = j;
break;
}
}
if(i > 0)
cout << char('a' + now - 1);
visited[now] = true;
}
cout << endl;
}
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
510
|
D
|
Fox And Jumping
|
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also $n$ cards, each card has 2 attributes: length $l_{i}$ and cost $c_{i}$. If she pays $c_{i}$ dollars then she can apply $i$-th card. After applying $i$-th card she becomes able to make jumps of length $l_{i}$, i. e. from cell $x$ to cell $(x - l_{i})$ or cell $(x + l_{i})$.
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
|
This task equals to: what is the minimal sum of costs that we can select k cards, so their GCD is 1. First observation is that: $GCD(x_{1}, x_{2}, ..., x_{k}) = 1$ means that for any prime $p$, there exist i such that $x_{i}$ is not dividable by $p$. So we only care about what prime factors a number contain. (So for example, 12 -> {2, 3}, 6 -> {2, 3}, 9 -> {3]}) The second observation is: If $x \le 10^{9}$ then it has at most 9 prime factors. So after we select one number, we only care about these 9 or less primes. Then this problem equals to set covering problem (SCP), it can be done by mask DP. It can run in about O(2^9 * n^2).
|
[
"bitmasks",
"brute force",
"dp",
"math"
] | 1,900
|
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <map>
#include <set>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
int n, N;
int x[301];
int cost[301];
int ans = 1000000000;
int m[301];
int DP[301][1<<9];
int dp(int cur, int mask)
{
if(cur == n+1)
{
if(mask == (1<<N)-1)
return 0;
return 1000000000;
}
int &ret = DP[cur][mask];
if(ret != -1) return ret;
ret = 1000000000;
ret = min(ret, dp(cur + 1, mask));
ret = min(ret, dp(cur + 1, mask | m[cur]) + cost[cur]);
return ret;
}
int MAIN()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> x[i];
}
for(int i = 1; i <= n; i++)
cin >> cost[i];
for(int i = 1; i <= n; i++)
{
vector <int> pFactors;
int t = x[i];
for(int j = 2; j*j <= t; j++)
if(t % j == 0)
{
pFactors.push_back(j);
while(t % j == 0)
t /= j;
}
if(t > 1)
pFactors.push_back(t);
N = pFactors.size();
for(int j = 1; j <= n; j++)
{
m[j] = 0;
for(int k = 0; k < N; k++)
if(x[j] % pFactors[k] != 0)
m[j] |= (1<<k);
}
memset(DP, 0xff, sizeof(DP));
ans = min(ans, cost[i] + dp(1, 0));
}
if(ans == 1000000000)
ans = -1;
cout << ans << endl;
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
510
|
E
|
Fox And Dinner
|
Fox Ciel is participating in a party in Prime Kingdom. There are $n$ foxes there (include Fox Ciel). The i-th fox is $a_{i}$ years old.
They will have dinner around some round tables. You want to distribute foxes such that:
- Each fox is sitting at some table.
- Each table has at least 3 foxes sitting around it.
- The sum of ages of any two adjacent foxes around each table should be a prime number.
If $k$ foxes $f_{1}$, $f_{2}$, ..., $f_{k}$ are sitting around table in clockwise order, then for $1 ≤ i ≤ k - 1$: $f_{i}$ and $f_{i + 1}$ are adjacent, and $f_{1}$ and $f_{k}$ are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
|
First finding is: if $a + b$ is a prime, then one of them is an odd number, another is an even number. (that's why we set $2 \le x_{i}$) Then we could find: every odd number have exactly 2 even number as neighborhood, and every even number have exactly 2 odd number as neighborhood. And that means we need $|#even| = |#odd|$ to have a solution. So it looks like bipartite graph matching, but every element matched 2 elements. And in fact it can be handled by maxflow: For each odd number, we add a node on the left side and link it from source with capacity equals to 2, and for each even number, we add a node on the right side and link it to sink with capacity equals to 2. And if sum of two numbers is a prime number, we link them with capacity equals to 1. Then we solve the max flow, it have solution if and only if $maxflow = 2 * |#even|$. We can construct the answer(cycles) from the matches.
|
[
"flows"
] | 2,300
|
#include <bits/stdc++.h>
using namespace std;
int n;
int x[201];
vector <int> id1;
vector <int> idOdd, idEven;
#define MAXN 200001
int maxint = ~0U>>1;
int flow;
int pi[MAXN+1], v[MAXN+1];
int S, T;
struct etype
{
int t, c;
etype* next;
etype* pair;
etype(){next=0;}
etype(int _t, int _c, etype* _n){t=_t, c=_c, next=_n;}
}*e[MAXN+1], *eb[MAXN+1], *Pe, *Pool;
int aug(int w, int lim)
{
int t;
v[w] = 1;
if(w == T)
{
flow += lim;
return lim;
}
for(etype *& i=e[w]; i; i = i->next)
if(i->c && !v[i->t] && pi[w] == pi[i->t] + 1)
if(t = aug(i->t, min(lim, i->c)))
return i->c -= t, i->pair->c += t, t;
return 0;
}
bool fix()
{
int t = maxint;
for(int i = S; i <= T; i++)
if(v[i])
{
for(etype *j = eb[i]; j; j = j->next)
if(j->c && !v[j->t])
t = min(t, pi[j->t] + 1 - pi[i]);
}
if(t == maxint)
return 0;
for(int i = S; i <= T; i++)
if(v[i])
e[i] = eb[i], pi[i] += t;
return 1;
}
etype* addedge(int s, int t, int c)
{
etype * ret;
++Pe;
ret = Pe;
Pe->t = t, Pe->c = c, Pe->next = e[s];
e[s] = Pe;
++Pe;
Pe->t = s, Pe->c = 0, Pe->next = e[t];
e[t] = Pe;
e[s]->pair=e[t];
e[t]->pair=e[s];
return ret;
}
void prepare()
{
if(Pool == NULL)
Pool = new etype[1000001];
Pe = Pool;
memset(e, 0, sizeof(e));
}
int MaxFlow()
{
flow = 0;
memcpy(eb, e, sizeof(e));
memset(pi, 0, sizeof(pi));
do
{
do
memset(v, 0, sizeof(v));
while(aug(S, maxint));
}
while(fix());
return flow;
}
/* Note
1. Set maxNodes here: #define MAXN 200001
2. Set maxEdges here: Pool = new etype[1000001];
3. S must be the min id, T must be the max id
*/
/* Eaxmple
prepare();
S = 1, T = 2;
addedge(1, 2, 3);
cout << MaxFlow() << endl;
*/
int isPrime(int x)
{
if(x < 2) return false;
for(int i = 2; i * i <= x; i++)
if(x % i == 0)
return false;
return true;
}
vector <int> e2[201];
etype *flowEdge[201][201];
bool visited[201];
int MAIN()
{
cin >> n;
int nOdd = 0, nEven = 0;
for(int i = 1; i <= n; i++)
{
cin >> x[i];
if(x[i] > 1 && x[i] % 2 == 0)
{
nEven ++;
idEven.push_back(i);
}
if(x[i] > 1 && x[i] % 2 == 1)
{
nOdd ++;
idOdd.push_back(i);
}
}
int needOne = nEven - nOdd;
int oneIn = 0, oneOut = 0;
for(int i = 1; i <= n; i++)
if(x[i] == 1)
{
if(needOne > 0)
{
idOdd.push_back(i);
oneIn ++;
needOne --;
}
else
{
id1.push_back(i);
oneOut ++;
}
}
if((oneIn == false && (oneOut == 1 || oneOut == 2)) || (idOdd.size() != idEven.size()))
{
cout << "Impossible" << endl;
return 0;
}
//cout << oneIn << " / " << oneOut << endl;
int eachSide = idOdd.size();
S = 1;
T = 2 * (1 + eachSide);
prepare();
for(int i = 0; i < eachSide; i++)
addedge(S, 2 + i, 2);
for(int i = 0; i < eachSide; i++)
addedge(2 + eachSide + i, T, 2);
for(int i = 0; i < eachSide; i++)
for(int j = 0; j < eachSide; j++)
if(isPrime(x[idOdd[i]] + x[idEven[j]]))
{
if(x[idOdd[i]] == 1 && oneIn > 0 && oneOut > 0)
{
flowEdge[i][j] = addedge(2 + i, 2 + eachSide + j, 2);
}
else
flowEdge[i][j] = addedge(2 + i, 2 + eachSide + j, 1);
//cout << i << " " << j << " : " << x[idOdd[i]] << " + " << x[idEven[j]] << endl;
}
else
flowEdge[i][j] = NULL;
int f = MaxFlow();
if(f != 2 * eachSide)
{
cout << "Impossible" << endl;
}
else
{
vector< vector <int> > ans, one;
if(id1.size() != 0)
{
if(oneIn > 0)
one.push_back(id1);
else
ans.push_back(id1);
}
for(int i = 0; i < eachSide; i++)
for(int j = 0; j < eachSide; j++)
if(flowEdge[i][j] != NULL)
if(flowEdge[i][j] -> pair -> c > 0)
{
int a = idOdd[i];
int b = idEven[j];
e2[a].push_back(b);
e2[b].push_back(a);
}
memset(visited, false, sizeof(visited));
for(int i = 1; i <= n; i++)
if(visited[i] == false && e2[i].size() > 0)
{
vector <int> t;
int cur = i;
visited[cur] = true;
t.push_back(i);
while(true)
{
if(visited[e2[cur][0]] == false)
cur = e2[cur][0];
else if(e2[cur].size() > 1 && visited[e2[cur][1]] == false)
cur = e2[cur][1];
else
break;
t.push_back(cur);
visited[cur] = true;
}
int pos1 = -1;
for(int j = 0; j < t.size(); j++)
if(x[t[j]] == 1)
pos1 = j;
if(pos1 == -1 || oneIn == false || oneOut == false)
ans.push_back(t);
else
{
vector <int> t2;
for(int j = pos1; j < t.size(); j++)
t2.push_back(t[j]);
for(int j = 0; j < pos1; j++)
t2.push_back(t[j]);
one.push_back(t2);
}
}
if(one.size() > 0)
{
vector <int> t;
for(int i = 0; i < one.size(); i++)
for(int j = 0; j < one[i].size(); j++)
t.push_back(one[i][j]);
ans.push_back(t);
}
cout << ans.size() << endl;
for(int i = 0; i < ans.size(); i++)
{
cout << ans[i].size() << " ";
for(int j = 0; j < ans[i].size(); j++)
{
cout << ans[i][j] << (j == ans[i].size() - 1 ? "\n" : " ");
}
}
}
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
512
|
D
|
Fox And Travelling
|
Fox Ciel is going to travel to New Foxland during this summer.
New Foxland has $n$ attractions that are linked by $m$ undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has $k$ days to visit this city and each day she will visit exactly one attraction.
There is one important rule in New Foxland: you can't visit an attraction if it has more than one adjacent attraction that you haven't visited yet.
At the beginning Fox Ciel haven't visited any attraction. During her travelling she may move aribtrarly between attraction. After visiting attraction $a$, she may travel to \textbf{any} attraction $b$ satisfying conditions above that hasn't been visited yet, even if it is not reachable from $a$ by using the roads (Ciel uses boat for travelling between attractions, so it is possible).
She wants to know how many different travelling plans she can make. Calculate this number modulo $10^{9} + 9$ for every $k$ from $0$ to $n$ since she hasn't decided for how many days she is visiting New Foxland.
|
We could find that some nodes cannot be visited. And more specific, if one node is in a cycle then it cannot be visited. So what about the structure of nodes that we can visit? Let's first find a way to get all nodes that could be visited. We can deal with this by something like biconnected decomposition, but that is not easy to implement. In fact we can use this simple method: each time we pick one node that have at most 1 neighborhood and delete it. Repeat this process until we can't do it anymore. We could find these nodes are actually belonging to these 2 kinds: 1. A tree. 2. Rooted tree. (that means, the root is attached to a cycle) The rooted tree case is simple: we can solve it by tree DP. The state will be dp[i][j] = the way to remove j nodes in the subtree rooted at i. Then how to solve the unrooted tree case? The way to deal with that is to transform it into rooted case. We have 2 solution: We select one unvisited node as the root by some rules: for example, we select one with minimal index. Then we just need to modify the DP a bit to adjust this additional condition. We could find if the tree has n nodes and we visit k nodes in the end, then there will be max(1, n-k) ways to choose the root. That means if we choose every node as the root and sum up them, we will count this case exactly max(1, n-k) times. So we just do the rooted DP for from node n times, and divide max(1, n-k) for ans[k]. The overall complicity is $O(n^{4})$, and it can be optimize into $O(n^{3})$ if you like.
|
[
"dp",
"trees"
] | 2,900
|
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <map>
#include <set>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
const int MAXN = 101; // (mod - 1) % MAXN == 0
const int MAXM = 1000001;
long long mod = 1000000009LL;
long long power(long long a, long long b)
{
long long ret = 1;
while(b)
{
if(b&1)
ret = (ret * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return ret;
}
long long inv(long long x)
{
return power(x, mod - 2);
}
long long factorial[MAXN];
long long invFactorial[MAXN];
long long C(int aPlusb, int a)
{
int b = aPlusb - a;
if(a < 0 || b < 0) return 0;
long long ret = invFactorial[a] * invFactorial[b];
ret %= mod;
ret *= factorial[aPlusb];
ret %= mod;
return ret;
}
struct dpValue
{
long long x[MAXN];
dpValue()
{
memset(x, 0, sizeof(x));
}
};
int cntCombine = 0;
dpValue combine(dpValue A, dpValue B)
{
int maxNonZeroA = 0;
int maxNonZeroB = 0;
for(int i = 0; i < MAXN; i++)
{
if(A.x[i] != 0)
maxNonZeroA = i;
if(B.x[i] != 0)
maxNonZeroB = i;
}
cntCombine ++;
dpValue ret;
for(int i = 0; i <= maxNonZeroA; i++)
for(int j = 0; j <= maxNonZeroB && i+j < MAXN; j++)
{
ret.x[i+j] += ((A.x[i] * B.x[j]) % mod) * C(i+j, i);
ret.x[i+j] %= mod;
}
return ret;
}
vector <int> nodeList;
vector <int> e[MAXN];
int cntNodes[MAXN];
dpValue dp[MAXN];
void dfsForSon(int cur, int from)
{
nodeList.push_back(cur);
cntNodes[cur] = 1;
for(int i = 0; i < e[cur].size(); i++)
{
int t = e[cur][i];
if(t == from) continue;
dfsForSon(t, cur);
cntNodes[cur] += cntNodes[t];
}
}
void prepare()
{
factorial[0] = 1;
for(int i = 1; i < MAXN; i++)
factorial[i] = (factorial[i-1] * i) % mod;
for(int i = 0; i < MAXN; i++)
invFactorial[i] = inv(factorial[i]);
}
dpValue pointwiseSum(dpValue A, dpValue B)
{
dpValue ret;
for(int i = 0; i < MAXN; i++)
ret.x[i] = (A.x[i] + B.x[i]) % mod;
return ret;
}
dpValue dfs(int cur, int from)
{
dpValue ret;
ret.x[0] = 1;
for(int i = 0; i < e[cur].size(); i++)
{
int t = e[cur][i];
if(t == from) continue;
ret = combine(ret, dfs(t, cur));
}
for(int i = 0; i < MAXN; i++)
if(ret.x[i] == 0)
{
ret.x[i] = ret.x[i-1];
break;
}
/*cout << cur << " " << from << " : ";
for(int i = 0; i <= 2; i++)
cout << ret.x[i] << " ";
cout << endl;*/
return ret;
}
dpValue solve(int cur, bool rooted)
{
dfsForSon(cur, -1);
if(rooted == true)
{
nodeList.clear();
return dfs(cur, -1);
}
int totalNodes = cntNodes[cur];
dpValue sum;
for(int i = 0; i < nodeList.size(); i++)
{
sum = pointwiseSum(sum, dfs(nodeList[i], -1));
}
for(int i = 0; i <= totalNodes; i++)
{
long long v = sum.x[i];
v *= inv(max(1, totalNodes - i));
v %= mod;
sum.x[i] = v;
}
nodeList.clear();
return sum;
}
int n, m;
int eA[MAXM];
int eB[MAXM];
vector <int> edge[MAXN];
int deg[MAXN];
int q[2 * MAXM], now , z;
bool inQ[MAXN];
bool canReach[MAXN];
bool visited[MAXN];
void parse(int cur, int from)
{
visited[cur] = true;
for(int i = 0; i < edge[cur].size(); i++)
{
int t = edge[cur][i];
if(t == from) continue;
e[cur].push_back(t);
e[t].push_back(cur);
parse(t, cur);
}
}
int MAIN()
{
prepare();
cin >> n >> m;
memset(canReach, false, sizeof(canReach));
memset(visited, false, sizeof(visited));
memset(inQ, false, sizeof(inQ));
for(int i = 1; i <= m; i++)
{
cin >> eA[i] >> eB[i];
deg[eA[i]] ++;
deg[eB[i]] ++;
edge[eA[i]].push_back(eB[i]);
edge[eB[i]].push_back(eA[i]);
}
now = 1, z = 0;
for(int i = 1; i <= n; i++)
if(deg[i] <= 1)
{
inQ[i] = true;
q[++z] = i;
}
while(now <= z)
{
int x = q[now];
canReach[x] = true;
for(int i = 0; i < edge[x].size(); i++)
{
int t = edge[x][i];
deg[t] --;
if(deg[t] <= 1 && inQ[t] == false)
{
inQ[t] = true;
q[++z] = t;
}
}
++ now;
}
dpValue finalResult;
finalResult.x[0] = 1;
for(int i = 1; i <= m; i++)
{
if(canReach[eA[i]] != canReach[eB[i]])
{
if(canReach[eB[i]])
swap(eA[i], eB[i]);
parse(eA[i], eB[i]);
finalResult = combine(finalResult, solve(eA[i], true));
}
}
for(int i = 1; i <= n; i++)
if(visited[i] == false && canReach[i] == true)
{
parse(i, -1);
finalResult = combine(finalResult, solve(i, false));
}
for(int i = 0; i <= n; i++)
{
long long v = finalResult.x[i];
cout << v << endl;
}
//cout << "time = " << clock() - start << endl;
//cout << "# " << cntCombine << endl;
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
512
|
E
|
Fox And Polygon
|
Fox Ciel just designed a puzzle game called "Polygon"! It is played using triangulations of a regular $n$-edge polygon. The goal is to transform one \underline{triangulation} to another by some tricky rules.
\underline{Triangulation} of an $n$-edge poylgon is a set of $n - 3$ diagonals satisfying the condition that no two diagonals share a common internal point.
For example, the initial state of the game may look like (a) in above figure. And your goal may look like (c). In each step you can choose a diagonal inside the polygon (but not the one of edges of the polygon) and \underline{flip} this diagonal.
Suppose you are going to \underline{flip} a diagonal $a – b$. There always exist two triangles sharing $a – b$ as a side, let's denote them as $a – b – c$ and $a – b – d$. As a result of this operation, the diagonal $a – b$ is replaced by a diagonal $c – d$. It can be easily proven that after \underline{flip} operation resulting set of diagonals is still a \underline{triangulation} of the polygon.
So in order to solve above case, you may first \underline{flip} diagonal $6 – 3$, it will be replaced by diagonal $2 – 4$. Then you \underline{flip} diagonal $6 – 4$ and get figure (c) as result.
Ciel just proved that for any starting and destination triangulations this game has a solution. She wants you to solve it in no more than $20 000$ steps for any puzzle satisfying $n ≤ 1000$.
|
Triangulation of polygon is something hard to think about. So the first key observation is that, we can transform this task into operations on rooted trees! One Triangulation of polygon can be mapping to one rooted tree. And the flip operation can be mapping to the rotation of trees. (It is the operation we used to balance our BST) You can find the mapping from above picture. The red lines indicate the edge that will be flipped and the nodes we rotated. Then we should find a standard shape of the tree, and solve this task: how to rotate any tree into this standard shape? My solution is to choose the balanced tree as standard shape. The way to do that is this: find the node that the index is the middle number, rotate it to the top(that what we did for splay tree), and do the same thing for each subtree. It is easy to see it could work in $O(nlogn)$ steps.
|
[
"constructive algorithms",
"divide and conquer"
] | 2,900
|
#include <bits/stdc++.h>
using namespace std;
int n;
vector <int> e[1001];
bool have[1001];
struct node
{
int leftMark, rightMark;
node* sonLeft, *sonRight;
void updateMark()
{
leftMark = sonLeft->leftMark;
rightMark = sonRight->rightMark;
}
}*start, *want;
struct step
{
int fromA, fromB;
int toA, toB;
};
node* addNode(int L, int R, int from)
{
node *t = new node();
t->leftMark = L;
t->rightMark = R;
if(L == R+1)
{
return t;
}
for(int i = 0; i < e[L].size(); i++)
if(e[L][i] != from)
have[e[L][i]] = true;
int M = -1;
for(int j = 0; j < e[R].size(); j++)
if(e[R][j] != from)
if(have[e[R][j]])
M = e[R][j];
for(int i = 0; i < e[L].size(); i++)
have[e[L][i]] = false;
t->sonLeft = addNode(L, M, R);
t->sonRight = addNode(M, R, L);
return t;
}
node* input()
{
for(int i = 1; i <= n; i++)
e[i].clear();
for(int i = 1; i <= n-3; i++)
{
int a, b;
cin >> a >> b;
e[a].push_back(b);
e[b].push_back(a);
}
for(int i = 1; i <= n; i++)
{
int j = i+1;
if(i == n) j = 1;
e[i].push_back(j);
e[j].push_back(i);
}
return addNode(n, 1, -1);
}
void print(node *p, string append)
{
cout << append << p->leftMark << " " << p->rightMark << endl;
if(p->sonLeft != NULL)
print(p->sonLeft, append + "\t");
if(p->sonRight != NULL)
print(p->sonRight, append + "\t");
}
vector <step> record;
void rotateToRight(node *r)
{
step t;
node *s = r->sonLeft;
node *a = s->sonLeft;
node *b = s->sonRight;
node *c = r->sonRight;
t.fromA = s->leftMark;
t.fromB = s->rightMark;
r->sonLeft = a;
r->sonRight = s;
s->sonLeft = b;
s->sonRight = c;
s->updateMark();
r->updateMark();
t.toA = s->leftMark;
t.toB = s->rightMark;
record.push_back(t);
}
void rotateToLeft(node *r)
{
step t;
node *s = r->sonRight;
node *a = r->sonLeft;
node *b = s->sonLeft;
node *c = s->sonRight;
t.fromA = s->leftMark;
t.fromB = s->rightMark;
r->sonLeft = s;
r->sonRight = c;
s->sonLeft = a;
s->sonRight = b;
s->updateMark();
r->updateMark();
t.toA = s->leftMark;
t.toB = s->rightMark;
record.push_back(t);
}
void rotateMiddleToRoot(node *p, int middle)
{
int myMiddle = p->sonLeft->rightMark;
if(myMiddle == middle)
return;
if(myMiddle < middle)
{
rotateMiddleToRoot(p->sonLeft, middle);
rotateToRight(p);
}
else if(myMiddle > middle)
{
rotateMiddleToRoot(p->sonRight, middle);
rotateToLeft(p);
}
}
void normalize(node *p)
{
if(p->leftMark - p->rightMark <= 2) return;
int middle = (p->leftMark + p->rightMark) / 2;
rotateMiddleToRoot(p, middle);
normalize(p->sonLeft);
normalize(p->sonRight);
}
int MAIN()
{
memset(have, 0, sizeof(have));
cin >> n;
start = input();
normalize(start);
vector <step> record1 = record;
record.clear();
want = input();
normalize(want);
cout << record.size() + record1.size() << endl;
for(int i = 0; i < record1.size(); i++)
cout << record1[i].fromA << " " << record1[i].fromB << endl;
for(int i = record.size()-1; i >= 0; i--)
cout << record[i].toA << " " << record[i].toB << endl;
return 0;
}
int main()
{
#ifdef LOCAL_TEST
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
ios :: sync_with_stdio(false);
cout << fixed << setprecision(16);
return MAIN();
}
|
514
|
A
|
Chewbaсca and Number
|
Luke Skywalker gave Chewbacca an integer number $x$. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit $t$ means replacing it with digit $9 - t$.
Help Chewbacca to transform the initial number $x$ to the minimum possible \textbf{positive} number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.
|
It is obvious that all the digits, which are greater than 4, need to be inverted. The only exception is 9, if it's the first digit. Complexity: $O(\mathrm{number~length})$
|
[
"greedy",
"implementation"
] | 1,200
| null |
514
|
B
|
Han Solo and Lazer Gun
|
There are $n$ Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates $(x, y)$ on this plane.
Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point $(x_{0}, y_{0})$. In one shot it can can destroy all the stormtroopers, situated on some line that crosses point $(x_{0}, y_{0})$.
Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.
The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.
|
Let's run through every point, where the stormtroopers are situated. If in current point stormtroopers are still alive, let's make a shot and destroy every stormtrooper on the same line with gun and current point. Points $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, $(x_{3}, y_{3})$ are on the same line, if $(x_{2} - x_{1})(y_{3} - y_{1}) = (x_{3} - x_{1})(y_{2} - y_{1})$. Complexity: $O(N^{2})$
|
[
"brute force",
"data structures",
"geometry",
"implementation",
"math"
] | 1,400
| null |
514
|
C
|
Watto and Mechanism
|
Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with $n$ strings. Then the mechanism should be able to process queries of the following type: "Given string $s$, determine if the memory of the mechanism contains string $t$ that consists of the same number of characters as $s$ and differs from $s$ in exactly one position".
Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of $n$ initial lines and $m$ queries. He decided to entrust this job to you.
|
While adding a string to the set, let's count its polynomial hash and add it to an array. Then let's sort this array. Now, to know the query answer, let's try to change every symbol in the string and check with binary search if its hash can be found in the array (recounting hashes with $O(1)$ complexity). If the hash is found in the array, the answer is "YES", otherwise "NO". Complexity: $O(L\log n)$, where $L$ is total length of all strings.
|
[
"binary search",
"data structures",
"hashing",
"string suffix structures",
"strings"
] | 2,000
| null |
514
|
D
|
R2D2 and Droid Army
|
An army of $n$ droids is lined up in one row. Each droid is described by $m$ integers $a_{1}, a_{2}, ..., a_{m}$, where $a_{i}$ is the number of details of the $i$-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has $m$ weapons, the $i$-th weapon can affect all the droids in the army by destroying one detail of the $i$-th type (if the droid doesn't have details of this type, nothing happens to it).
A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most $k$ shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?
|
To destroy all the droids on a segment of $l$ to $r$, we need to make $\sum_{j=1}^{m}\operatorname*{max}_{l\leq l\leq r}(c n t[i]|j])$ shots, where $cnt[i][j]$ - number of $j$-type details in $i$-th droid. Let's support two pointers - on the beginning and on the end of the segment, which we want to destroy all the droids on. If we can destroy droids on current segment, let's increase right border of the segment, otherwise increase left border, updating the answer after every segment change. Let's use a queue in order to find the segment maximum effectively. Complexity: $O(N M)$
|
[
"binary search",
"data structures",
"two pointers"
] | 2,000
| null |
514
|
E
|
Darth Vader and Tree
|
When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly $n$ sons, at that for each node, the distance between it an its $i$-th left child equals to $d_{i}$. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most $x$ from the root. The distance is the sum of the lengths of edges on the path between nodes.
But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' — you may ask. It's just that he feels superior knowing that only he can solve this problem.
Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo $10^{9} + 7$.
|
It's easy to realize that $d p[i]=\sum_{j=1}^{100}c n t[j]\cdot d p[i-j]$, where $dp[i]$ is number of vertices, which are situated on a distance $i$ from the root, and $cnt[j]$ is number of children, which are situated on a distance $j$. Answer $a n s=\sum_{i=0}^{x}d p[i]$. Let the dynamics condition Let's build a transformation matrix of $101 \times 101$ size Now, to move to the next condition, we need to multiply A by B. So, if matrix $C = A \cdot B^{x - 100}$, then the answer will be situated in the very right cell of this matrix. For $x < 100$ we'll find the answer using dynamics explained in the beginning. In order to find $B^{k}$ let's use binary power. Complexity: $O(101^{3}\log x)$
|
[
"dp",
"matrices"
] | 2,200
| null |
515
|
A
|
Drazil and Date
|
Someday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point $(0, 0)$ and Varda's home is located in point $(a, b)$. In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position $(x, y)$ he can go to positions $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$ or $(x, y - 1)$.
Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to $(a, b)$ and continue travelling.
Luckily, Drazil arrived to the position $(a, b)$ successfully. Drazil said to Varda: "It took me exactly $s$ steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from $(0, 0)$ to $(a, b)$ in exactly $s$ steps. Can you find out if it is possible for Varda?
|
If Drazil chooses the shortest path from (0,0) to (a,b), it takes $|a| + |b|$ steps. So we know that all numbers less than $|a| + |b|$ are impossible to be the number of steps that Drazil took. Now consider when the number of steps is not less than $|a| + |b|$. When Drazil arrives at $(a, b)$, he can take two more steps such as $(a, b)$ -> $(a, b + 1)$ -> $(a, b)$ to remain at the same position. So we know that for all $s$ such that $s \ge |a| + |b|$ and $(s - (|a| + |b|))%2 = 0$, there exists a way for Drazil to get to $(a, b)$ in exactly $s$ steps. The last part we should prove is that it's impossible for Drazil to arrive at (a,b) in exactly $s$ steps when $(s - (|a| + |b|))%2 = 1$. We can color all positions $(x, y)$ where $(x + y)%2 = 0$ as white and color other points as black. After each step, the color of the position you're at always changes. So we know that it's impossible for Drazil to get to $(a, b)$ in odd/even steps if the color of $(a, b)$ is white/black. Conclusion: If $s \ge |a| + |b|$ and $(s - (|a| + |b|))%2 = 0$ print "Yes", Otherwise print "No". Time Complexity: $O(1)$.
|
[
"math"
] | 1,000
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 1e6+10;
int main(){
DRIII(a,b,n);
if(n<abs(a)+abs(b)||(n-abs(a)-abs(b))%2)puts("No");
else puts("Yes");
return 0;
}
|
515
|
B
|
Drazil and His Happy Friends
|
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\bmod n)$-th boy and $(i\bmod m)$-th girl to have dinner together (as Drazil is programmer, $i$ starts from $0$). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.
Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.
|
You may notice that Drazil invites his friends periodically, and the period of invitation patterns is at most $n * m$ (because there are only $n * m$ possible pairs of boys and girls). So if no one changes from unhappy to happy in consecutive $n * m$ days, there won't be any changes anymore since then. We can simulate the process of having dinner until there are no status changes in consecutive $n * m$ days. Because there are only n+m people, it's easy to prove the simulation requires O($(n + m) * n * m$) days. But in fact, the simulation takes only O($n * m$) days.(More accurately, the bound is $(min(n, m) + 1) * (max(n, m) - 1)$ ) What happens? You can do some experiments by yourself. =) (you can suppose that only one person is happy in the beginning.) In fact, this problem can be solved in $O(n + m)$. Let $g$ be the greatest common divisor of $n$ and $m$. If the $i$-th person is happy, then all people with number $x$ satisfying $x\equiv i({\mod{g}})$ will become happy some day because of this person. So for each $0 \le i \le g - 1$, we only need to check if there exists at least one person whose number mod $g$ is $i$ and is happy. If it exists for all $i$, the answer is 'Yes', otherwise the answer is 'No'.
|
[
"brute force",
"dsu",
"meet-in-the-middle",
"number theory"
] | 1,300
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 1e6+10;
int h[SIZE];
int main(){
DRII(n,m);
int gg=__gcd(n,m);
DRI(hn);
REP(i,hn){
DRI(x);
h[x%gg]=1;
}
DRI(hm);
REP(i,hm){
DRI(x);
h[x%gg]=1;
}
REP(i,gg){
if(!h[i]){
puts("No");
return 0;
}
}
puts("Yes");
return 0;
}
|
515
|
C
|
Drazil and Factorial
|
Drazil is playing a math game with Varda.
Let's define $\operatorname{F}(x)$ for positive integer $x$ as a product of factorials of its digits. For example, $\mathbf{F}(\,135)=\,1!*31*51=720$.
First, they choose a decimal number $a$ consisting of $n$ digits that contains at least one digit larger than $1$. This number may possibly start with leading zeroes. Then they should find maximum positive number $x$ satisfying following two conditions:
1. $x$ doesn't contain neither digit $0$ nor digit $1$.
2. $\operatorname{F}(x)$ = $\mathbf{F}(a)$.
Help friends find such number.
|
Conclusion first: First, we transform each digit of the original number as follows: 0, 1 -> empty 2 -> 2 3 -> 3 4 -> 322 5 -> 5 6 -> 53 7 -> 7 8 -> 7222 9 -> 7332 Then, sort all digits in decreasing order as a new number, then it will be the answer. Proof: We can observe that our answer won't contain digits 4,6,8,9, because we can always transform digits 4,6,8,9 to more digits as in the conclusion, and it makes the number larger. Then, how can we make sure that the result is the largest after this transformation? We can prove the following lemma: For any positive integer $x$, if it can be written as the form $(2!)^{c2} * (3!)^{c3} * (5!)^{c5} * (7!)^{c7}$, there will be only one unique way. Suppose that there exists two ways to write down x in this form, we can assume that the two ways are $(2!)^{a2} * (3!)^{a3} * (5!)^{a5} * (7!)^{a7}$ and $(2!)^{b2} * (3!)^{b3} * (5!)^{b5} * (7!)^{b7}$. We find the largest $i$ such that $a_{i} \neq b_{i}$, Then we know there exists at least one prime number whose factor is different in the two ways. But according to the Fundamental Theorem of Arithmetic, there is only one prime factorization of each integer. So we get a contradiction. After getting the result, we don't need to worry about other numbers being larger than ours. Time Complexity: $O(n)$.
|
[
"greedy",
"math",
"sortings"
] | 1,400
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 1e6+10;
string ch[10]={"","","2","3","223","5","53","7","7222","7332"};
int main(){
DRI(n);
string str,an;
cin>>str;
REP(i,SZ(str))an+=ch[str[i]-'0'];
sort(ALL(an));
reverse(ALL(an));
cout<<an<<endl;
return 0;
}
|
515
|
D
|
Drazil and Tiles
|
Drazil created a following problem about putting $1 × 2$ tiles into an $n × m$ grid:
"There is a grid with some cells that are empty and some cells that are occupied. You should use $1 × 2$ tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."
But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".
Drazil found that the constraints for this task may be much larger than for the original task!
Can you solve this new problem?
Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.
|
Again we give conclusion first: First, view each cell as a vertex and connect two adjacent cells by an edge. Then, build a queue and push all vertices of degree 1 in it. Finally, in each iteration, we pop a vertex from the queue until the queue is empty. If the vertex is used, go to the next iteration. Otherwise, we put a tile on the vertex and its adjacent vertex, and erase these two vertices from the graph. If it yields a new vertex with degree 1, push it into the queue. When the queue is empty, if there are still some cells not covered by any tiles, the answer will be "Not unique." It's easy to understand that if we can put tiles on all cells by the above steps, the result is correct. But how about the remaining cases? We will prove that when the degrees of all vertices are at least two, the solution is never unique. Suppose there is at least one solution. According to this solution, we can color those edges covered by tiles as black and color other edges as white. We can always find a cycle without any adjacent edges having the same colors. (I'll leave it as an exercise. You should notice that the graph is a bipartite graph first.) Then we can move the tiles from black edges to white edges. So if there is at least one solution, there are in fact at least two solutions. Time Complexity: $O(nm)$
|
[
"constructive algorithms",
"greedy"
] | 2,000
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int SIZE = 2e3+10;
char s[SIZE][SIZE];
int deg[SIZE][SIZE];
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
char fl[2][8]={"^<v>","v>^<"};
pair<int,int>bfs[SIZE*SIZE];
int main(){
int ll=0,rr=0;
DRII(n,m);
REP(i,n)RS(s[i+1]+1);
int sp=0;
REPP(i,1,n+1)REPP(j,1,m+1){
REP(k,4){
int nx=i+dx[k];
int ny=j+dy[k];
if(s[nx][ny]=='.')deg[i][j]++;
}
if(s[i][j]=='.'){
sp++;
if(deg[i][j]==1)bfs[rr++]=MP(i,j);
}
}
while(ll<rr){
int x=bfs[ll].F;
int y=bfs[ll].S;
if(s[x][y]=='.'){
int nx,ny;
int id=-1;
bool suc=0;
REP(k,4){
nx=x+dx[k];
ny=y+dy[k];
id=k;
if(s[nx][ny]=='.'){
suc=1;
break;
}
}
if(!suc){
puts("Not unique");
return 0;
}
s[x][y]=fl[0][id];
s[nx][ny]=fl[1][id];
deg[x][y]=0;
deg[nx][ny]=0;
REP(k,4){
int nnx=nx+dx[k];
int nny=ny+dy[k];
deg[nnx][nny]--;
if(deg[nnx][nny]==1)bfs[rr++]=MP(nnx,nny);
}
}
ll++;
}
REP(i,n)REP(j,m)if(s[i+1][j+1]=='.'){
puts("Not unique");
return 0;
}
REP(i,n)puts(s[i+1]+1);
return 0;
}
|
515
|
E
|
Drazil and Park
|
Drazil is a monkey. He lives in a circular park. There are $n$ trees around the park. The distance between the $i$-th tree and ($i + 1$)-st trees is $d_{i}$, the distance between the $n$-th tree and the first tree is $d_{n}$. The height of the $i$-th tree is $h_{i}$.
Drazil starts each day with the morning run. The morning run consists of the following steps:
- Drazil chooses two different trees
- He starts with climbing up the first tree
- Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it
- Then he finally climbs down the second tree.
But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.
If the two trees Drazil chooses are $x$-th and $y$-th, we can estimate the energy the morning run takes to him as $2(h_{x} + h_{y}) + dist(x, y)$. Since there are children on exactly one of two arcs connecting $x$ and $y$, the distance $dist(x, y)$ between trees $x$ and $y$ is uniquely defined.
Now, you know that on the $i$-th day children play between $a_{i}$-th tree and $b_{i}$-th tree. More formally, if $a_{i} ≤ b_{i}$, children play around the trees with indices from range $[a_{i}, b_{i}]$, otherwise they play around the trees with indices from $[a_{i},n]\cup[1,b_{i}]$.
Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.
|
There are many methods for this problem. I'll only explain the one that I used. Let's split a circle at some point (for example between 1 and n) and draw a picture twice (i. e. 1 2 3 ... n 1 2 3 ... n), thus changing the problem from a circle to a line. Remember that if two trees Drazil chooses are x and y, the energy he consumes is $d_{x} + d_{x + 1} + ... + d_{y - 1} + 2 * (h_{x} + h_{y})$. Now rewrite this formula to $(d_{1} + d_{2} + ... + d_{y - 1} + 2 * h_{y}) + (2 * h_{x} - (d_{1} + d_{2} + ... + d_{x - 1}))$ Denote $(d_{1} + d_{2} + ... + d_{k - 1} + 2 * h_{k})$ as $R_{k}$ and denote $(2 * h_{k} - (d_{1} + d_{2} + ... + d_{k - 1}))$ as $L_{k}$ When a query about range $[a, b]$ comes (The range $[a, b]$ is where Drazil can choose, but not the range where the children are playing), it's equivalent to querying the maximum value of $L_{u} + R_{v}$, where $u$ and $v$ are in $[a, b]$ and $u < v$. Another important thing is that $L_{u} + R_{v}$ always bigger than $L_{v} + R_{u}$ when $u < v$. So we can almost solve the problem just by finding the maximum value of $L_{u}$ and $R_{v}$ by RMQ separately and sum them up. However, there is a special case: $u = v$, but we can handle it by making RMQ find the two maximum values. Time Complexity: $O(n + m)$. (implement with $O(n\log n+m)$) More information about RMQ: editorial from Topcoder
|
[
"data structures"
] | 2,300
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int SIZE = 4e5+10;
int d[SIZE],h[SIZE];
pair<LL,int> W[2][19][SIZE][2];
int two[SIZE];
pair<LL,int> INF=MP(-1e18,-1);
void fresh(pair<LL,int> target[],pair<LL,int> v){
if(v.S==target[0].S||v.S==target[1].S)return;
if(v.F>target[0].F){
target[1]=target[0];
target[0]=v;
}
else if(v.F>target[1].F){
target[1]=v;
}
}
LL query(int x,int y){
pair<LL,int>res[2][2];
int lv=two[y-x+1];
REP(i,2){
REP(j,2)res[i][j]=W[i][lv][x][j];
REP(j,2)fresh(res[i],W[i][lv][y-(1<<lv)+1][j]);
}
if(res[0][0].S!=res[1][0].S)return res[0][0].F+res[1][0].F;
return max(res[0][0].F+res[1][1].F,res[0][1].F+res[1][0].F);
}
int main(){
REP(i,19)two[1<<i]=i;
REPP(i,1,SIZE)
if(!two[i])two[i]=two[i-1];
DRII(n,m);
REP(i,n){
RI(d[i]);
d[i+n]=d[i];
}
REP(i,n){
RI(h[i]);
h[i+n]=h[i];
}
LL now=0;
REP(i,n*2){
W[0][0][i][0]=MP(now+h[i]*2,i);
W[1][0][i][0]=MP(-now+h[i]*2,i);
W[0][0][i][1]=W[1][0][i][1]=INF;
now+=d[i];
}
REP(j,2){
REPP(i,1,19){
REP(k,n*2){
REP(k2,2)W[j][i][k][k2]=W[j][i-1][k][k2];
if(k+(1<<(i-1))<n*2){
fresh(W[j][i][k],W[j][i-1][k+(1<<(i-1))][0]);
fresh(W[j][i][k],W[j][i-1][k+(1<<(i-1))][1]);
}
}
}
}
while(m--){
DRII(x,y);
x--;y--;
int rx=(y+1)%n;
int ry=(x-1+n)%n;
if(ry<rx)ry+=n;
printf("%I64d\n",query(rx,ry));
}
return 0;
}
|
516
|
D
|
Drazil and Morning Exercise
|
Drazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.
Let's consider rooms and small tunnels as the vertices and edges in a graph. This graph is a \underline{tree}. In the other words, any pair of vertices has an unique path between them.
Each room that is \underline{leaf} in the graph is connected with a ground by a vertical tunnel. Here, \underline{leaf} is a vertex that has only one outgoing edge in the graph.
Each room is large enough only to fit one earthworm living in it. Earthworm can't live in a tunnel.
Drazil and Varda have a plan to educate their children. They want all their children to do morning exercises immediately after getting up!
When the morning is coming, all earthworm children get up in the same time, then each of them chooses the \textbf{farthest} path to the ground for gathering with others (these children are lazy, so they all want to do exercises as late as possible).
Drazil and Varda want the difference between the time first earthworm child arrives outside and the time the last earthworm child arrives outside to be not larger than $l$ (otherwise children will spread around the ground and it will be hard to keep them exercising together).
Also, The rooms that are occupied by their children should form a \underline{connected} set. In the other words, for any two rooms that are occupied with earthworm children, all rooms that lie on the path between them should be occupied with earthworm children too.
How many children Drazil and Varda may have at most in order to satisfy all conditions above? Drazil and Varda want to know the answer for many different choices of $l$.
(Drazil and Varda don't live in the hole with their children)
|
We can use dfs twice to get the farthest distance from each node to any leaves (detail omitted here), and denote the longest distance from the $i$-th node to any leaves as $d_{i}$. Then we choose a node with minimum value of $d_{i}$ as the root. We will find that for any node $x$, $d_{x}$ isn't greater than $d_{y}$ for any node $y$ in the subtree of node $x$. Next, we solve the problem when there's only one query of $L$. In all valid groups of nodes, where node $x$ is the nearest to the root, obviously we can choose all nodes with $d_{i} \le d_{x} + L$ into the group. Now we want to enumerate all nodes as the nearest node to the root. We denote the group of nodes generated from node $i$ as $G_{i}$. We can do it in $O(n\log n)$ using dfs only once. (if the length of every edge is $1$, we can do it in $O(n)$) Imagine that $G_{i}$ will almost be as same as the union of all $G_{j}$ where node $j$ is a child of node $i$, but some nodes which are too far from node $i$ are kicked out. Each node will be kicked out from the groups we considered at most once in the whole process. Now we want to know when it happens. We solve it as follows: When we do dfs, we reserve a stack to record which nodes we have visited and still need to come back to. Yes, it's just like the implementation of recursive functions. Then we can just use binary search to find the node in the stack that when we go back to it, the current node will be kicked out (the closest node with $|d_{x} - d_{i}| \ge L$). So the time complexity of the above algorithm is $O(q n\log n)$ Now we provide another algorithm with O($qn \alpha (n) + nlog(n)$) by union find. (Thanks Shik for providing this method.) First, sort all nodes by $d_{i}$. Then for each query, consider each node one by one from larger $d_{i}$'s to smaller $d_{i}$'s. At the beginning, set each node as a group of its own. We also need to record how many nodes each group contains. When handling a node $x$, union all groups of itself and its children. At the same time, for each node $j$ with $d_{j} > d_{x} + L$, we minus $1$ from the record of how many nodes $j$'s group has. By doing these, we can get the number of nodes $j$ in $x$'s subtree with $d_{j} < = d_{x} + L$. That's exactly what we want to know in the last algorithm. (implement with O($qn \alpha (n) + nlog(n))$))
|
[
"dfs and similar",
"dp",
"dsu",
"trees",
"two pointers"
] | 2,800
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
const int MOD = 1e9+7;
const int SIZE = 1e5+10;
vector<pair<int,LL> >e[SIZE];
LL dp[SIZE][2],far[SIZE];
void dfs1(int x,int lt){
REP(i,SZ(e[x])){
int y=e[x][i].F;
if(y==lt)continue;
dfs1(y,x);
if(dp[y][0]+e[x][i].S>dp[x][0]){
dp[x][1]=dp[x][0];
dp[x][0]=dp[y][0]+e[x][i].S;
}
else if(dp[y][0]+e[x][i].S>dp[x][1]){
dp[x][1]=dp[y][0]+e[x][i].S;
}
}
}
void dfs2(int x,int lt,LL v){
far[x]=max(v,dp[x][0]);
REP(i,SZ(e[x])){
int y=e[x][i].F;
if(y==lt)continue;
if(dp[y][0]+e[x][i].S==dp[x][0])dfs2(y,x,max(v,dp[x][1])+e[x][i].S);
else dfs2(y,x,max(v,dp[x][0])+e[x][i].S);
}
}
void add(int x,int y,int v){
e[x].PB(MP(y,v));
e[y].PB(MP(x,v));
}
int father[SIZE];
void dfs(int x,int lt){
father[x]=lt;
REP(i,SZ(e[x])){
int y=e[x][i].F;
if(y==lt)continue;
dfs(y,x);
}
}
struct Union_Find{
int d[SIZE],num[SIZE],v[SIZE];
void init(int n){
REP(i,n){
d[i]=i;
num[i]=1;
v[i]=1;
}
}
int find(int x){
return (x!=d[x])?(d[x]=find(d[x])):x;
}
bool uu(int x,int y){
x=find(x);
y=find(y);
if(x==y)return 0;
if(num[x]<num[y]){
num[y]+=num[x];
v[y]+=v[x];
d[x]=y;
}
else{
num[x]+=num[y];
v[x]+=v[y];
d[y]=x;
}
return 1;
}
}U;
int main(){
DRI(n);
REPP(i,1,n){
DRIII(x,y,v);
x--;y--;
add(x,y,v);
}
dfs1(0,0);
dfs2(0,0,0);
int root;
LL mi=1e18;
LL ma=0;
REP(i,n){
if(far[i]<mi){
mi=far[i];
root=i;
}
ma=max(ma,far[i]);
}
fprintf(stderr,"[%I64d]\n",ma-mi);
dfs(root,root);
vector<pair<LL,int> >pp;
REP(i,n){
pp.PB(MP(far[i],i));
}
sort(ALL(pp));
DRI(Q);
while(Q--){
LL L;
scanf("%I64d",&L);
int an=0;
int it=SZ(pp)-1;
U.init(n);
for(int i=SZ(pp)-1;i>=0;i--){
int me=pp[i].S;
REP(j,SZ(e[me])){
int y=e[me][j].F;
if(y==father[me])continue;
U.uu(me,y);
}
while(pp[it].F-pp[i].F>L){
U.v[U.find(pp[it].S)]--;
it--;
}
an=max(an,U.v[U.find(me)]);
}
printf("%d\n",an);
}
return 0;
}
|
516
|
E
|
Drazil and His Happy Friends
|
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are $n$ boys and $m$ girls among his friends. Let's number them from $0$ to $n - 1$ and $0$ to $m - 1$ separately. In $i$-th day, Drazil invites $(i\bmod n)$-th boy and $(i\bmod m)$-th girl to have dinner together (as Drazil is programmer, $i$ starts from $0$). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if it is happy originally), he stays happy forever.
Drazil wants to know on which day all his friends become happy or to determine if they won't become all happy at all.
|
Simplifying this question, suppose that $n$ and $m$ are coprime. If $n$ and $m$ are not coprime and the gcd of $n$ and $m$ is $g$, then we can divide all people into $g$ groups by the values of their id mod $g$ and find the maximum answer between them. Obviously, If there is at least one group of friends which are all unhappy in the beginning, the answer is -1. Now we determine the last one becoming happy, for boys and girls separately. In fact, there's an easy way to explain this problem - finding the shortest path! View all friends as points, and add another point as the source. For all friends, we will view the distance from the source as the time becoming happy. And define two types of edges. (1) There is a fact: If a girl $x$ become happy in time $t$, then the girl $(x + n)%m$ will become happy in time $t + n$. So we can build a directed edge from point $x$ to $(x + n)%m$ with length $n$. Similar for boys. (2) If the $i$-th boy/girlfriend is happy originally, we can connect it to the source with an edge of length $i$. At the same time, we also connect the source to $i%n$-th boy($i%m$ for girl) with an edge of length $i$. You can imagine that the same gender of friends form a cycle. (eg. the $(i * m)%n$-th boy is connected to the $((i + 1) * m)%n)$-th boy for $i$ from 0 to $n - 1$) With these two types of edges, we can find that if a friend is unhappy originally, he/she will become happy at the time value which is the length of the shortest path from the source. The only question is that there are too many points and edges! We can solve this problem by considering only some "important" points. And we can combine some consecutive edges of the first type to a new edge. The group of edges is the maximal edges that contain deleted points.(These deleted points always form a line). Finally we find the maximum value of the shortest path from the source to these friends which is unhappy originally in the reduced graph. Time complexity: ${\cal O}((n+m)\log(n+m)\}$
|
[
"math",
"number theory"
] | 3,100
|
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
typedef long long LL;
using namespace std;
LL INF = 2e18;
int n,m;
vector<int>d[100000][2];
// a*x+b*y=z
struct gcd_t {long long x,y,z;}gg;
LL inv[2],sz[2];
gcd_t gcd(long long a,long long b) {
if(b==0)return (gcd_t){1,0,a};
gcd_t t=gcd(b,a%b);
return (gcd_t){t.y,t.x-t.y*(a/b),t.z};
}
void fresh(LL &x,LL v){
x=min(x,v);
}
void mii(map<int,LL>&mi,LL x,LL v){
if(mi.count(x))fresh(mi[x],v);
else mi[x]=v;
}
void proccess(LL& now,map<int,LL>& mi,int round){
map<int,LL>::iterator it=mi.begin();
while(it!=mi.end()){
fresh(it->S,now);
fresh(now,it->S);
int me=it->F;
it++;
int you;
if(it!=mi.end())you=it->F;
else you=mi.begin()->F+sz[round];
now+=(you-me)*sz[round^1]*gg.z;
}
}
LL f(vector<int>v[]){
LL res=-1;
int n=SZ(v[0])+SZ(v[1]);
n<<=1;
REP(round,2){
set<int>H;
map<int,LL>mi;
REP(k,2){
REP(i,SZ(v[k])){
int me=v[k][i]*inv[round]%sz[round];
if(k==round)H.insert(me);
mii(mi,(me+sz[round]-1)%sz[round],INF);
mii(mi,me,v[k][i]*gg.z);
}
}
LL now=INF;
proccess(now,mi,round);
proccess(now,mi,round);
set<int>::iterator it1=H.begin();
map<int,LL>::iterator it2=mi.begin();
while(it2!=mi.end()){
while(it1!=H.end()&&*it1<it2->F)it1++;
if(it1==H.end()||*it1!=it2->F)res=max(res,it2->S);
it2++;
}
}
if(res==-1)return -INF;
return res;
}
int main(){
RII(n,m);
gg=gcd(n,m);
if(gg.z>100000){
puts("-1");
return 0;
}
sz[0]=n/gg.z;
sz[1]=m/gg.z;
inv[1]=(gg.x%sz[1]+sz[1])%sz[1];
inv[0]=(gg.y%sz[0]+sz[0])%sz[0];
REP(k,2){
DRI(m);
REP(i,m){
DRI(x);
d[x%gg.z][k].PB(x/gg.z);
}
}
REP(i,gg.z){
if(SZ(d[i][0])+SZ(d[i][1])==0){
puts("-1");
return 0;
}
}
LL an=0;
REP(i,gg.z){
an=max(an,f(d[i])+i);
}
cout<<an<<endl;
return 0;
}
|
518
|
A
|
Vitaly and Strings
|
Vitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time.
During the last lesson the teacher has provided two strings $s$ and $t$ to Vitaly. The strings have the same length, they consist of lowercase English letters, string $s$ is lexicographically smaller than string $t$. Vitaly wondered if there is such string that is lexicographically larger than string $s$ and at the same is lexicographically smaller than string $t$. This string should also consist of lowercase English letters and have the length equal to the lengths of strings $s$ and $t$.
Let's help Vitaly solve this easy problem!
|
To solve this problem we can, for example, find string $next$, which lexicographically next to string $s$ and check that string $next$ is lexicographically less than string $t$. If string $next$ is lexicographically smaller than string $t$, print string $next$ and finish algorithm. If string $next$ is equal to string $t$ print $No such string$. To find string $next$, which lexicographically next to string $s$, at first we need to find maximal suffix of string $s$, consisting from letters $'z'$, change all letters $'z'$ in this suffix on letters $'a'$, and then letter before this suffix increase on one. I.e. if before suffix was letter, for example, $'d'$, we need to change it on letter $'e'$. Asymptotic behavior of this solution - $O(|s|)$, where $|s|$ - length of string $s$.
|
[
"constructive algorithms",
"strings"
] | 1,600
| null |
518
|
B
|
Tanya and Postcard
|
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string $s$ of length $n$, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string $s$. The newspaper contains string $t$, consisting of uppercase and lowercase English letters. We know that the length of string $t$ greater or equal to the length of the string $s$.
The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some $n$ letters out of the newspaper and make a message of length exactly $n$, so that it looked as much as possible like $s$. If the letter in some position has correct value and correct letter case (in the string $s$ and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".
Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.
|
To solve this problem at first will count array $cnt[]$, where $cnt[c]$ - how many times letter $c$ found in string $t$. We will count two numbers $ans1$ and $ans2$ - how many times Tanya will shouts joyfully $YAY!$ and how many times Tanya will says $WHOOPS$. Let's iterate on string $s$ and if $cnt[s[i]] > 0$, then increase $ans1$ on one and decrease $cnt[s[i]]$ on one. Then let's again iterate on string $s$. Let $c$ is letter which equal to $s[i]$,but in the opposite case for it. I. e. if $s[i] = 'w'$, then $c = 'W'$. Now, if $cnt[c] > 0$, then increase $ans2$ on one and decrease $cnt[c]$ on one. Now, print two numbers - $ans1$ and $ans2$. Asymptotic behavior of this solution - $O(|s| + |t|)$, where $|s|$ - length of string $s$ and $|t|$ - length of string $t$.
|
[
"greedy",
"implementation",
"strings"
] | 1,400
| null |
518
|
C
|
Anya and Smartphone
|
Anya has bought a new smartphone that uses \underline{Berdroid} operating system. The smartphone menu has exactly $n$ applications, each application has its own icon. The icons are located on different screens, one screen contains $k$ icons. The icons from the first to the $k$-th one are located on the first screen, from the $(k + 1)$-th to the $2k$-th ones are on the second screen and so on (the last screen may be partially empty).
Initially the smartphone menu is showing the screen number $1$. To launch the application with the icon located on the screen $t$, Anya needs to make the following gestures: first she scrolls to the required screen number $t$, by making $t - 1$ gestures (if the icon is on the screen $t$), and then make another gesture — press the icon of the required application exactly once to launch it.
After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number $1$.
All applications are numbered from $1$ to $n$. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. \underline{Berdroid} is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.
Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order?
Note that one application may be launched multiple times.
|
To solve this problem we will store two arrays - $a[]$ and $pos[]$. In array $a[]$ will store current order of icons, i. e. in $a[i]$ store number of application, icon which stay on position $i$. In array $pos[]$ will store on which place in list stays icons, i. e. in $pos[i]$ store in which position of array $a[]$ stay icon of application number $i$. We will count answer in variable $ans$. Let's iterate on applications which we need to open. Let current application has number $num$. Then to $ans$ we need add ($pos[num] / k + 1$). Now, if icon of application number $num$ doesn't stay on first position in list of applications, we make the following - swap $a[pos[num]]$ and $a[pos[num] - 1]$ and update values in array $pos[]$ for indexes of two icons which numbers $a[pos[num]]$ and $a[pos[num] - 1]$ . Asymptotic behavior of this solution - $O(n + m)$, where $n$ - number of applications, $m$ - number of requests to start applications.
|
[
"constructive algorithms",
"data structures",
"implementation"
] | 1,600
| null |
518
|
D
|
Ilya and Escalator
|
Ilya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor.
Let's assume that $n$ people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability $p$, or the first person in the queue doesn't move with probability $(1 - p)$, paralyzed by his fear of escalators and making the whole queue wait behind him.
Formally speaking, the $i$-th person in the queue cannot enter the escalator until people with indices from $1$ to $i - 1$ inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after $t$ seconds.
Your task is to help him solve this complicated task.
|
To solve this problem let's use dynamic programming. We will store two-dimensional array $z[][]$ with type $double$. In $z[i][j]$ will store the likelihood that after $i$ seconds $j$ people are on escalator. In dynamic will be following transitions. If $j = n$, i. e. all $n$ people already on escalator then we make transition $z[i + 1][j] + = z[i][j]$. Else, or person number $j$ go to escalator in $i + 1$ second, i. e. $z[i + 1][j + 1] + = z[i][j] * p$, or person number $j$ stays on his place, i. e. $z[i + 1][j] + = z[i][j] * (1 - p)$. Now we need to count answer - it is sum on $j$ from $0$ to $n$ inclusive $z[t][j] * j$. Asymptotic behavior of this solution - $O(t * n)$, where $t$ - on which moment we must count answer, $n$ - how many people stay before escalator in the beginning.
|
[
"combinatorics",
"dp",
"math",
"probabilities"
] | 1,700
| null |
518
|
E
|
Arthur and Questions
|
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length $n$ ($a_{1}, a_{2}, ..., a_{n})$, consisting of integers and integer $k$, not exceeding $n$.
This sequence had the following property: if you write out the sums of all its segments consisting of $k$ consecutive elements $(a_{1} + a_{2} ... + a_{k}, a_{2} + a_{3} + ... + a_{k + 1}, ..., a_{n - k + 1} + a_{n - k + 2} + ... + a_{n})$, then those numbers will form strictly increasing sequence.
For example, for the following sample: $n = 5, k = 3, a = (1, 2, 4, 5, 6)$ the sequence of numbers will look as follows: ($1 + 2 + 4, 2 + 4 + 5, 4 + 5 + 6$) = ($7, 11, 15$), that means that sequence $a$ meets the described property.
Obviously the sequence of sums will have $n - k + 1$ elements.
Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum $|a_{i}|$, where $|a_{i}|$ is the absolute value of $a_{i}$.
|
At first let's take two sums $a_{1} + a_{2} + ... + a_{k}$ and $a_{2} + a_{3} + ... + a_{k + 1}$. It is correct that $a_{1} + a_{2} + ... + a_{k} < a_{2} + a_{3} + ... + a_{k + 1}$. If move from right to left all elements apart from $a_{k + 1}$, all of them will reduce and will left only $a_{1} < a_{k + 1}$. If write further all sums we will obtain that sequence disintegrate on $k$ disjoint chains: $a_{1} < a_{k + 1} < a_{2k + 1} < a_{3k + 1}..., a_{2} < a_{k + 2} < a_{2k + 2} < a_{3k + 2}..., ..., a_{k} < a_{2k} < a_{3k}...$. We will solve the problem for every chain separately. Let's iterate on first chain and find all pair of indexes $i, j$ $(i < j)$, that $a[i]$ and $a[j]$ are numbers (not questions) in given sequence, and for all $k$ from $i + 1$ to $j - 1$ in $a[k]$ stay questions. All this questions we need to change on numbers so does not violate the terms of the increase and minimize sum of absolute values of this numbers. Between indexes $i$ and $j$ stay $j - i - 1$ questions, we can change them on $a[j] - a[i] - 1$ numbers. If $j - i - 1$ > $a[j] - a[i] - 1$, then we need to print $Incorrect$ $sequence$ and finish algorithm. Else we need to change all this questions to numbers in greedy way. Here we have several cases. Will review one case when $a[i] > = 0$ and $a[j] > = 0$. Let current chain ($3, ?, ?, ?, 9$), $i = 1$, $j = 5$. We need to change questions on numbers in the following way - ($3, 4, 5, 6, 9$). In other cases (when $a[i] < = 0$, $a[j] < = 0$ and when $a[i] < = 0$, $a[j] > = 0$) we need to use greedy similary to first so does not violate the terms of the increase and minimize sum of absolute values of this numbers. Asymptotic behavior of this solution - $O(n)$, where $n$ - count of elements in given sequence.
|
[
"greedy",
"implementation",
"math",
"ternary search"
] | 2,200
| null |
518
|
F
|
Pasha and Pipe
|
On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city.
The city is an $n × m$ rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are denoted by character '$.$', occupied squares are denoted by character '$#$'.
The pipe must meet the following criteria:
- the pipe is a polyline of width $1$,
- the pipe goes in empty squares,
- the pipe starts from the edge of the field, but not from a corner square,
- the pipe ends at the edge of the field but not in a corner square,
- the pipe has at most $2$ turns ($90$ degrees),
- the border squares of the field must share \textbf{exactly two} squares with the pipe,
- if the pipe looks like a single segment, then the end points of the pipe must lie on distinct edges of the field,
- for each non-border square of the pipe there are \textbf{exacly two} side-adjacent squares that also belong to the pipe,
- for each border square of the pipe there is \textbf{exactly one} side-adjacent cell that also belongs to the pipe.
Here are some samples of \textbf{allowed} piping routes:
\begin{verbatim}
....# ....# .*..#
***** ****. .***.
..#.. ..#*. ..#*.
#...# #..*# #..*#
..... ...*. ...*.
\end{verbatim}
Here are some samples of \textbf{forbidden} piping routes:
\begin{verbatim}
.**.# *...# .*.*#
..... ****. .*.*.
..#.. ..#*. .*#*.
#...# #..*# #*.*#
..... ...*. .***.
\end{verbatim}
In these samples the pipes are represented by characters '$ * $'.
You were asked to write a program that calculates the number of distinct ways to make exactly one pipe in the city.
The two ways to make a pipe are considered distinct if they are distinct in at least one square.
|
At first let's count two two-dimensional arrays of prefix sums $sumv[][]$ and $sumg[][]$. In $sumv[i][j]$ store how many grids are in column $j$ beginning from row $1$ to row $i$. In $sumg[i][j]$ store how many grid are in row $i$ beginning from column $1$ to column $j$. Let's count $ans0$ - how many pipes without bending we can pave. Count how many vertical pipes - we can pave. Iterate on $j$ from $2$ to $m - 1$ and, if $sumg[n][j] - sumg[n][0] = 0$ (i. e. in this column zero grids), increase $ans0$ on one. Similary count number of horizontal pipes. Let's count $ans1$ - how many pipes with $1$ bending we can pave. We need to brute cell, in which will bending. There are four cases. Let's consider first case, others we can count similary. This case - pipe begin in left column, go to current cell in brute and then go to top row. If brute cell in row $i$ and column $j$ then to $ans1$ we need to add one, if $(sumg[i][j] - sumg[i][0]) + (sumv[i][j] - sumv[0][j]) = 0$. Let's count $ans2$ - how many pipes with $2$ bendings we can pave. Let's count how many tunes begin from top row and end in top or bottom row and add this number to $ans2$. Then rotate our matrix three times on $90$ degrees and after every rotate add to $ans2$ count of pipes, which begin from top row and end in top or bottom row. Then we need divide $ans2$ to $2$, because every pipe will count twice. How we can count to current matrix how many pipes begin from top row and end in top or bottom row? Let's count four two-dimension arrays $lf[][]$, $rg[][]$, $sumUp[][]$, $sumDown[][]$. If $i$ - number of row, $j$ - number of column of current cell, then in position ($i, lf[i][j]$) in matrix are nearest from left grid for cell ($i, j$), and in position ($i, rg[i][j]$) in matrix are nearest from right grid for cell ($i, j$). $sumUp[i][j]$ - how many columns without grids are in submatrix from ($1, 1$) to ($i, j$) of given matrix. $sumDown[i][j]$ - how many columns without grids are in submatrix from ($i, 1$) to ($n, j$) of given matrix. Then let's brute cell in which will be the first bending of pipe (pipe goes from top row and in this cell turned to left or to right), check, that in column $j$ above this cell $0$ grids, with help of arrays $lf$ and $rg$ find out as far as pipe can go to left or to right and with help of arrays $sumUp$ and $sumDown$ carefully update answer. Now print number $ans1 + ans2 + ans3$. Asymptotic behavior of this solution - $O(n * m * const)$, where $n$ - hoew many rows in given matrix, $m$ - how many columns in given matrix, $const$ takes different values depending on the implementation, in solution from editorial $const = 10$.
|
[
"binary search",
"brute force",
"combinatorics",
"dp",
"implementation"
] | 2,300
| null |
519
|
A
|
A and B and Chess
|
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
- the queen's weight is 9,
- the rook's weight is 5,
- the bishop's weight is 3,
- the knight's weight is 3,
- the pawn's weight is 1,
- the king's weight isn't considered in evaluating position.
The player's weight equals to the sum of weights of all his pieces on the board.
As A doesn't like counting, he asked you to help him determine which player has the larger position weight.
|
This problem asked to determine whose chess position is better. Solution: Iterate over the board and count scores of both player. Then just output the answer. Complexity: $O(n^{2})$, where n is the length of the side of the board (8 here)
|
[
"implementation"
] | 900
|
/****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
char s[10][10];
char name[6] = {'Q', 'R', 'B', 'N', 'P', 'K'};
char weight[6] = {9, 5, 3, 3, 1, 0};
int scoreWhite, scoreBlack;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
for (int i = 0; i < 8; i++) {
gets(s[i]);
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
for (int k = 0; k < 6; k++) {
if (toupper(s[i][j]) == name[k]) {
if (isupper(s[i][j])) {
scoreWhite += weight[k];
} else {
scoreBlack += weight[k];
}
break;
}
}
}
}
if (scoreWhite > scoreBlack) {
puts("White");
} else if (scoreWhite < scoreBlack) {
puts("Black");
} else {
puts("Draw");
}
return 0;
}
|
519
|
B
|
A and B and Compilation Errors
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed $n$ compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
|
In this problem you were given three arrays. Second array is the same as the first array without one element, third array is the same as second array without first element. You were asked to find deleted elements. Solution: I'll describe easiest solution for this problem: Let's denote $a$ as sum of all elements of first array, $b$ as sum of all elements of second array and $c$ as sum of all elements of third array. Then answer is $a - b$ and $b - c$ There are also some other solutions for this problem which use map, xor, etc. Complexity: $O(N)$
|
[
"data structures",
"implementation",
"sortings"
] | 1,100
|
/****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
int n, x;
long long a, b, c;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
a += x;
}
for (int i = 0; i < n - 1; i++) {
scanf("%d", &x);
b += x;
}
for (int i = 0; i < n - 2; i++) {
scanf("%d", &x);
c += x;
}
printf("%I64d\n%I64d\n", a - b, b - c);
return 0;
}
|
519
|
C
|
A and B and Team Training
|
A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.
A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.
However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.
As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.
There are $n$ experienced members and $m$ newbies on the training session. Can you calculate what maximum number of teams can be formed?
|
In this problem we should split $n$ experienced participants and $m$ newbies into teams. Solution: Let's denote number teams with 2 experienced partisipants and 1 new participant as $type1$ and teams with 1 experienced participant and 2 new participants as $type2$. Let's fix number of teams of $type1$ and denote it as $i$. Their amount is not grater than $m$. Then number of teams of $type2$ is $min(m - 2 * i, n - i)$. Check all possible $i$' and update answer. Complexity: $O(N)$
|
[
"greedy",
"implementation",
"math",
"number theory"
] | 1,300
|
/****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
int n, m, ans;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++) {
int cur = i;
int leftn = n - i;
int leftm = m - 2 * i;
if (leftm >= 0) {
cur += min(leftm, leftn / 2);
ans = max(ans, cur);
}
}
printf("%d\n", ans);
return 0;
}
|
519
|
D
|
A and B and Interesting Substrings
|
A and B are preparing themselves for programming contests.
After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.
A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes).
B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).
Also, A and B have a string $s$. Now they are trying to find out how many substrings $t$ of a string $s$ are interesting to B (that is, $t$ starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.
Naturally, A and B have quickly found the number of substrings $t$ that are interesting to them. Can you do it?
|
In this problem you were asked to find number of substrings of given string, such that each substring starts and finishes with one and the same letter and sum of weight of letters of that substring without first and last letter is zero. Solution: Let's denote $sum[i]$ as sum of weights of first $i$ letters. Create 26 $map < longlong, int >$'s, 1 for each letter. Suppose we are on position number $i$ and current character's map is $m$. Then add $m[sum[i - 1]]$ to the answer and add $sum[i]$ to the $m$. Complexity: $O(NlogN)$, where $N$ - the length of input string.
|
[
"data structures",
"dp",
"two pointers"
] | 1,800
|
/****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
const int MAXN = 100010;
template <typename T>
inline T sqr(T n) {
return n * n;
}
int cnt[26];
vector <int> pos[MAXN];
char s[MAXN];
int n;
long long sum[MAXN], ans;
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
for (int i = 0; i < 26; i++) {
scanf("%d", &cnt[i]);
}
getchar();
gets(s + 1);
n = strlen(s + 1);
for (int i = 1; i <= n; i++) {
sum[i] = cnt[s[i] - 'a'];
sum[i] += sum[i - 1];
pos[s[i] - 'a'].push_back(i);
}
for (int cc = 0; cc < 26; cc++) {
map <long long, int> Map;
for (size_t i = 0; i < pos[cc].size(); i++) {
int p = pos[cc][i];
ans += Map[sum[p - 1]];
Map[sum[p]]++;
}
Map.clear();
}
printf("%I64d\n", ans);
return 0;
}
|
519
|
E
|
A and B and Lecture Rooms
|
A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has $n$ rooms connected by $n - 1$ corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from $1$ to $n$.
Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.
As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following $m$ days.
|
In this problem we have to answer to the following queries on tree: for given pairs of vertices your program should output number of eqidistand vertices from them. Let's denote: $dist(a, b)$ as distance between vertices $a$ and $b$. $LCA(a, b)$ as lowest common ancestor of vertices $a$ and $b$. $depth[a]$ as distance between root of the tree and vertex $a$. $size[a]$ as size of subtree of vertex $a$. On each picture green nodes are equidistant nodes, blue nodes - nodes from query. Preprocessing: Read edges of tree and build data structure for LCA (it is more convenient to use binary raise, becase we will use it further for other purposes). Complexity: $O(NlogN)$ Queries: We have to consider several cases for each query: 1) $a = b$. In that case answer is $n$. 2) $dist(a, b)$ is odd. Then answer is $0$. 3) $dist(a, l) = dist(b, l)$, where $l = LCA(a, b)$. Find children of $l$, which are ancestors of $a$ and $b$ (let's denote them as $aa$ and $bb$). Answer will be $n - size[aa] - size[bb]$. 4) All other cases. Assume that $depth[a] > depth[b]$. Then using binary raise find $dist(a, b) / 2$-th ancestor of $a$ (let's denote it as $p1$), $dist(a, b) / 2 - 1$-th ancestor of vertex $a$ (denote it as $p2$). Answer will be $size[p1] - size[p2]$. Complexity: $O(logN)$ for each query, $O(MlogN)$ for all queries. Resulting complexity:: $O(MlogN + NlogN)$
|
[
"binary search",
"data structures",
"dfs and similar",
"dp",
"trees"
] | 2,100
|
/****************************************
** Solution by Bekzhan Kassenov **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
const int MAXN = 100010;
const int LG = 30;
template <typename T>
inline T sqr(T n) {
return n * n;
}
vector <int> g[MAXN];
int n, x, y;
int depth[MAXN], size[MAXN], anc[MAXN][LG];
int tin[MAXN], tout[MAXN], timer;
int q, a, b;
void dfs(int v, int par = 1, int d = 0) {
depth[v] = d;
size[v] = 1;
tin[v] = timer++;
anc[v][0] = par;
for (int i = 1; i < LG; i++) {
anc[v][i] = anc[anc[v][i - 1]][i - 1];
}
for (size_t i = 0; i < g[v].size(); i++) {
int to = g[v][i];
if (to != par) {
dfs(to, v, d + 1);
size[v] += size[to];
}
}
tout[v] = timer++;
}
bool ancestor(int a, int b) {
return tin[a] <= tin[b] && tout[b] <= tout[a];
}
int go_up(int a, int b) {
for (int i = LG - 1; i >= 0; i--) {
if (!ancestor(anc[a][i], b)) {
a = anc[a][i];
}
}
return a;
}
int lca(int a, int b) {
int result = -1;
if (ancestor(a, b)) {
result = a;
} else if (ancestor(b, a)) {
result = b;
} else {
result = anc[go_up(a, b)][0];
}
return result;
}
int query(int a, int b) {
int l = lca(a, b);
int result = -1;
if (a == b) {
result = n;
} else if (depth[a] - depth[l] == depth[b] - depth[l]) {
a = go_up(a, l);
b = go_up(b, l);
result = n - size[a] - size[b];
} else {
if (depth[a] < depth[b]) {
swap(a, b);
}
int to = a;
int dist = depth[a] + depth[b] - 2 * depth[l];
if (dist % 2 == 1) {
result = 0;
} else {
dist /= 2;
for (int i = LG - 1; i >= 0; i--) {
if (depth[a] - depth[anc[to][i]] < dist) {
to = anc[to][i];
}
}
int mid = anc[to][0];
result = size[mid] - size[to];
}
}
return result;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in", "r", stdin);
#endif
scanf("%d", &n);
for (int i = 0; i < n - 1; i++) {
scanf("%d%d", &x, &y);
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1);
scanf("%d", &q);
while (q--) {
scanf("%d%d", &a, &b);
printf("%d\n", query(a, b));
}
return 0;
}
|
520
|
A
|
Pangram
|
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.
|
To check that every letter is present in the string we can just make a boolean array of size 26 and for every letter set the corresponding variable to TRUE. In the end check that there are 26 TRUEs. That is an $O(n)$ solution. Also don't forget to change all letters to lowercase (or all to uppercase). To make all the letters lowercase, one could use standard functions, like tolower in Python. Also, it is known that the letters from a to z have consecutive ASCII numbers, as well as A to Z; an ASCII number of symbol is ord(c) in most languages. So, to get the number of a lowercase letter in the alphabet one can use ord(c) - ord('a') in most languages, or simply c - 'a' in C++ or C (because a char in C/C++ can be treated as a number); to check if a letter is lowercase, the inequality ord('a') <= ord(c) && ord(c) <= ord('z') should be checked.
|
[
"implementation",
"strings"
] | 800
| null |
520
|
B
|
Two Buttons
|
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number $n$.
Bob wants to get number $m$ on the display. What minimum number of clicks he has to make in order to achieve this result?
|
The simplest solution is simply doing a breadth-first search. Construct a graph with numbers as vertices and edges leading from one number to another if an operation can be made to change one number to the other. We may note that it is never reasonable to make the number larger than $2m$, so under provided limitations the graph will contain at most $2 \cdot 10^{4}$ vertices and $4 \cdot 10^{4}$ edges, and the BFS should work real fast. There is, however, an even faster solution. The problem can be reversed as follows: we should get the number $n$ starting from $m$ using the operations "add 1 to the number" and "divide the number by 2 if it is even". Suppose that at some point we perform two operations of type 1 and then one operation of type 2; but in this case one operation of type 2 and one operation of type 1 would lead to the same result, and the sequence would contain less operations then before. That reasoning implies that in an optimal answer more than one consecutive operation of type 1 is possible only if no operations of type 2 follow, that is, the only situation where it makes sense is when $n$ is smaller than $m$ and we just need to make it large enough. Under this constraint, there is the only correct sequence of moves: if $n$ is smaller than $m$, we just add 1 until they become equal; else we divide $n$ by 2 if it is even, or add 1 and then divide by 2 if it is odd. The length of this sequence can be found in $O(\log n)$.
|
[
"dfs and similar",
"graphs",
"greedy",
"implementation",
"math",
"shortest paths"
] | 1,400
| null |
520
|
C
|
DNA Alignment
|
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings $s$ and $t$ have the same length $n$, then the function $h(s, t)$ is defined as the number of positions in which the respective symbols of $s$ and $t$ are the same. Function $h(s, t)$ can be used to define the function of Vasya distance $ρ(s, t)$:
\[
\rho(s,t)=\sum_{i=0}^{n-1}\sum_{j=0}^{n-1}h(\mathrm{shift}(s,i),\mathrm{shift}(t,j)),
\]
where ${\mathrm{shift}}(s,i)$ is obtained from string $s$, by applying left circular shift $i$ times. For example, \[
ρ("AGC", "CGT") =
\]
\[
h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +
\]
\[
h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +
\]
\[
h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =
\]
\[
1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6
\]
Vasya found a string $s$ of length $n$ on the Internet. Now he wants to count how many strings $t$ there are such that the Vasya distance from the string $s$ attains maximum possible value. Formally speaking, $t$ must satisfy the equation: $\rho(s,t)=\operatorname*{max}_{u\dagger u\dagger=i\leq s\dagger}\rho(s,u)$.
Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo $10^{9} + 7$.
|
What is $ \rho (s, t)$ equal to? For every character of $s$ and every character of $t$ there is a unique cyclic shift of $t$ that superposes these characters (indeed, after 0, $...$, $n - 1$ shifts the character in $t$ occupies different positions, and one of them matches the one of the character of $s$); therefore, there exist $n$ cyclic shifts of $s$ and $t$ that superpose these characters (the situation is symmetrical for every position of the character of $s$). It follows that the input in $ \rho $ from a single character $t_{i}$ is equal to $n \times $(the number of characters in $s$ equal to $t_{i}$). Therefore, $ \rho (s, t)$ is maximal when every character of $t$ occurs the maximal possible number of times in $s$. Simply count the number of occurences for every type of characters; the answer is $K^{n}$, where $K$ is the number of character types that occur in $s$ most frequently. This is an $O(n)$ solution.
|
[
"math",
"strings"
] | 1,500
| null |
520
|
D
|
Cubes
|
Once Vasya and Petya assembled a figure of $m$ cubes, each of them is associated with a number between $0$ and $m - 1$ (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the $OX$ is the ground, and the $OY$ is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.
The figure turned out to be \underline{stable}. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch \textbf{by a side or a corner}. More formally, this means that for the cube with coordinates $(x, y)$ either $y = 0$, or there is a cube with coordinates $(x - 1, y - 1)$, $(x, y - 1)$ or $(x + 1, y - 1)$.
Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the $m$-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.
Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo $10^{9} + 9$.
|
Basically, the first player should maximize the lexicographical order of numbers, and the second player should minimize it. Thus, at every move the first player should choose the largest available number, and the second should choose the minimal one. First of all, how do we check if the cube can be removed? It is impossible only if there is some cube "supported" by it (i.e., it has coordinates $(x - 1, y + 1)$, $(x, y + 1)$, $(x + 1, y + 1)$) such that our cube is the only one supporting it. This can be checked explicitly. The large coordinates' limitations do not allow us to store a simply array for that, so we should use an associative array, like a set in C++. Now we should find the maximal/minimal number that can be removed. A simple linear search won't work fast enough, so we store another data structure containing all numbers available to remove; the structure should allow inserting, erasing and finding global minimum/maximum, so the set C++ structure fits again. When we've made our move, some cubes may have become available or unavailable to remove. However, there is an $O(1)$ amount of cubes we have to recheck and possibly insert/erase from our structure: the cubes $(x \pm 1, y)$ and $(x \pm 2, y)$ may have become unavailable because some higher cube has become dangerous (that is, there is a single cube supporting it), and some of the cubes $(x - 1, y - 1)$, $(x, y - 1)$ and $(x + 1, y - 1)$ may have become available because our cube was the only dangerous cube that it has been supporting. Anyway, a simple recheck for these cubes will handle all the cases. This solution is $O(n\log n)$ if using the appropriate data structure.
|
[
"games",
"greedy",
"implementation"
] | 2,100
| null |
520
|
E
|
Pluses everywhere
|
Vasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out $n$ numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.
The lesson was long, and Vasya has written all the correct ways to place exactly $k$ pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo $10^{9} + 7$. Help him!
|
Consider some way of placing all the pluses, and a single digit $d_{i}$ (digits in the string are numbered starting from 0 from left to right). This digit gives input of $d_{i} \cdot 10^{l}$ to the total sum, where $l$ is the distance to the nearest plus from the right, or to the end of string if there are no pluses there. If we sum up these quantities for all digits and all ways of placing the pluses, we will obtain the answer. For a given digit $d_{i}$ and some fixed $l$, how many ways are there to place the pluses? First of all, consider the case when the part containing the digit $d_{i}$ is not last, that is, $i + l < n - 1$. There are $n - 1$ gaps to place pluses in total; the constraint about $d_{i}$ and the distance $l$ means that after digits $d_{i}$, $...$, $d_{i + l - 1}$ there are no pluses, while after the digit $d_{i + l}$ there should be a plus. That is, the string should look as follows: $\cdot\cdot\cdot d_{i-1}{}^{\gamma}\underbrace{d_{i}\cdot d_{i+1}\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot d_{i+l-1}}_{\mathrm{distance~1}}+d_{i+l+1}{}^{+d_{i+1}+\cdot\cdot\cdot\cdot\cdot}\ .$ Here a dot means a gap without a plus, and a question mark means that it's not important whether there is a plus or not. So, out of $n - 1$ possible gaps there are $l + 1$ gaps which states are defined, and there is one plus used in these gaps. That means that the other $(n - 1) - (l + 1) = n - l - 2$ gaps may contain $k - 1$ pluses in any possible way; that is, the number of such placements is $\textstyle{\binom{n-l-2}{k-1}}$. A similar reasoning implies that if the digit $d_{i}$ is in the last part, that is, $i + l = n - 1$, the number of placements is ${\binom{n-l-1}{k}}=\binom{i}{k}$. To sum up, the total answer is equal to $\begin{array}{c}{{\displaystyle\sum\!\!\!\!\!\!\slash^{n-1}\left(\sum\!\!\!\!\!\slash^{n-2-i}\left(\binom{n-j\!\!\!\slash^{-}}{k-1}\right)\cdot d_{i}|\left(\!\!\slash^{i}\right)\!\!\!\slash^{j}\right)\!\!\!\!\slash^{j}\!\!\!\slash\:\!\!\ J^{j}\!\!\!\slash\:\!\!\!\slash^{j}\!\!\!\slash\:\!\!\!\slash}\!\!\slash^{j}\!\!\!\slash\:\!\!\!\slash}\!\!\slash\end{array}$ Let us transform the sum: $\textstyle{\sum_{l=0}^{n-2}\left(10^{l}{\binom{n-l-2}{k-1}}\sum_{i=0}^{n-l-2}d_{i}\right)+\sum_{i=0}^{n-1}\left(d_{i}10^{n-1-i}\left({\frac{i}{k}}\right)\right).$ To compute these sums, we will need to know all powers of 10 up to $n$-th (modulo $10^{9} + 7$), along with the binomial coefficients. To compute the binomials, recall that ${\binom{n}{k}}={\frac{n!}{k!(n-k)!}}$, so it is enough to know all the numbers $k!$ for $k$ upto $n$, along with their modular inverses. Also we should use the prefix sums of $d_{i}$, that is, the array $s d_{i}=\sum_{j=0}^{t}d_{j}$. The rest is simple evaluation of the above sums. The total complexity is $O(n\log p)$, because the common algorithms for modular inverses (that is, Ferma's little theorem exponentiation or solving a diophantine equation using the Euclid's algorithm) have theoritcal worst-case complexity of $O(\log p)$. However, one can utilize a neat trick for finding modular inverses for first $n$ consecutive numbers in linear time for a total complexity of $O(n)$; for the description of the method refer to this comment by Kaban-5 (not sure why it has a negative rating, I found this quite insightful; maybe anyone can give a proper source for this method?).
|
[
"combinatorics",
"dp",
"math",
"number theory"
] | 2,200
| null |
521
|
D
|
Shop
|
Vasya plays one very well-known and extremely popular MMORPG game. His game character has $k$ skill; currently the $i$-th of them equals to $a_{i}$. Also this game has a common rating table in which the participants are ranked according to the \textbf{product} of all the skills of a hero in the descending order.
Vasya decided to 'upgrade' his character via the game store. This store offers $n$ possible ways to improve the hero's skills; Each of these ways belongs to one of three types:
- assign the $i$-th skill to $b$;
- add $b$ to the $i$-th skill;
- multiply the $i$-th skill by $b$.
Unfortunately, a) every improvement can only be used once; b) the money on Vasya's card is enough only to purchase not more than $m$ of the $n$ improvements. Help Vasya to reach the highest ranking in the game. To do this tell Vasya which of improvements he has to purchase and in what order he should use them to make his rating become as high as possible. If there are several ways to achieve it, print any of them.
|
Suppose the only type of upgrades we have is multiplication. It doesn't even matter for the answer which particular skill we are going to multiply, so we just choose several upgrades with greatest values of $b_{i}$. Now we have additions as well; set multiplications aside for a moment. It is clear that for every skill we should choose several largest additions (maybe none). Let us sort the additions for every skill by non-increasing; now we should choose several first upgrades for each type. Now, for some skill the (non-increasing) sorted row of $b$'s is $b_{1}$, $...$, $b_{l}$, and the initial value of the skill is $a$. Now, as we have decided to take some prefix of $b$'s, we know that if we take the upgrade $b_{i}$, the value changes from $a + b_{1} + ... + b_{i - 1}$ to $a + b_{1} + ... + b_{i - 1} + b_{i}$. That is, the ratio by which the value (and the whole product of values) is going to be multiplied by is the fraction $\frac{a+b_{1}+....+b_{i-1}+b_{i}}{a+b_{1}+...+b_{i-1}}$. Now, with that ratio determined unambigiously for each addition upgrade, every addition has actually become a multiplication. =) So we have to compute the ratios for all additions (that is, we sort $b$'s for each skill separately and find the fractions), and then sort the multiplications and additions altogether by the ratio they affect the whole product with. Clearly, all multiplications should be used after all the additions are done; that is, to choose which upgrades we use we should do the ratio sorting, but the order of actual using of upgrades is: first do all the additions, then do all the multiplications. Finally, let's deal with the assignment upgrades. Clearly, for each skill at most one assignment upgrade should be used, and if it used, it should the assignment upgrade with the largest $b$ among all assignments for this skill. Also, if the assignment is used, it should be used before all the additions and multiplications for this skill. So, for each skill we should simply determine whether we use the largest assignment for this skill or not. However, if we use the assignment, the ratios for the additions of current skill become invalid as the starting value of $a$ is altered. To deal with this problem, imagine that we have first chosen some addition upgrades, and now we have to choose whether we use the assignment upgrade or not. If we do, the value of the skill changes from $a + b_{1} + ... + b_{k}$ to $b + b_{1} + ... + b_{k}$. That is, the assignment here behaves pretty much the same way as the addition of $b - a$. The only difference is that once we have chosen to use the assignment, we should put it before all the additions. That is, all largest assigments for each skill should be made into additions of $b - a$ and processed along with all the other additions, which are, as we already know, going to become multiplications in the end. =) Finally, the problem is reduced to sorting the ratios for all upgrades. Let us estimate the numbers in the fractions. The ratio for a multiplication is an integer up to $10^{6}$; the ratio for an addition is a fraction of general form $\frac{a+b_{1}+...+b_{k}}{a+b_{1}+...+b_{k-1}}$. As $k$ can be up to $10^{5}$, and $b_{i}$ is up to $10^{6}$, the numerator and denominator of such fraction can go up to $10^{11}$. To compare fractions $\overset{\stackrel{\rightarrow}}{b}$ and $\frac{\epsilon}{a}$ we should compare the products $ad$ and $bc$, which can go up to $10^{22}$ by our estimates. That, unfortunately, overflows built-in integer types in most languages. However, this problem can be solved by subtracting 1 from all ratios (which clearly does not change the order of ratios), so that the additions' ratios will look like $\frac{b_{k}}{a+b_{1}+\ldots+b_{k-1}}$. Now, the numerator is up to $10^{6}$, the products in the comparison are up to $10^{17}$, which fits in 64-bit integer type in any language.
|
[
"greedy"
] | 2,800
| null |
521
|
E
|
Cycling City
|
You are organizing a cycling race on the streets of the city. The city contains $n$ junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.
You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route — the chain of junctions, consecutively connected by roads. Routes must meet the following conditions:
- all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same);
- to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes);
- no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit).
Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.
|
We have to find two vertices in an undirected graph such that there exist three vertex- and edge-independent paths between them. This could easily be a flow problem if not for the large constraints. First of all, we can notice that all the paths between vertices should lie in the same biconnected component of the graph. Indeed, for every simple cycle all of its edges should lie in the same biconnected component, and the three-paths system is a union of cycles. Thus, we can find all the biconnected components of the graph and try to solve the problem for each of them independently. The computing of biconnected components can be done in linear time; a neat algorithm for doing this is described in the Wikipedia article by the link above. Now, we have a biconnected component and the same problem as before. First of all, find any cycle in this component (with a simple DFS); the only case of a biconnected component that does not contain a cycle is a single edge, which is of no interest. Suppose that no vertex of this cycle has an adjacent edge that doesn't lie in the cycle; this means the cycle is not connected to anything else in the component, so the component is this cycle itself, in which case there is clearly no solution. Otherwise, find a vertex $v$ with an adjacent edge $e$ that doesn't lie in the cycle (denote it $c$). If we can find a path $p$ starting with $e$ that arrives at a cycle vertex $u$ (different from $v$), then we can find three vertex-distinct paths between $v$ and $u$: one path is $p$, and two others are halves of the initial cycle. To find $p$, start a DFS from the edge $e$ that halts when it arrives to vertex of $c$ (that is different from $v$) and recovers all the paths. What if we find that no appropriate path $p$ exists? Denote $C$ the component traversed by the latter DFS. The DFS did not find any path between vertices of $C\ {v}$ and $c\ {v}$, therefore every such path should pass through $v$. That means that upon deletion of $v$, the component $C\ {v}$ becomes separated from all vertices of $c\ {v}$, which contradicts with the assumption that the component was biconnected. That reasoning proves that the DFS starting from $e$ will always find the path $p$ and find the answer if only a biconnected component was not a cycle nor a single edge. Finally, we obtain that the only case when the answer is non-existent is when all the biconnected components are single edges or simple cycles, that is, the graph is a union of disconnected cactuses. Otherwise, a couple of DFS are sure to find three vertex-disjoint paths. This yields an $O(n + m)$ solution; a few logarithmic factors for simplification here and there are also allowed.
|
[
"dfs and similar",
"graphs"
] | 3,100
| null |
524
|
C
|
The Art of Dealing with ATM
|
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most $k$ bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations $10$, $50$, $100$, $500$, $1000$ and $5000$ burles, then at $k = 20$ such ATM can give sums $100 000$ burles and $96 000$ burles, but it cannot give sums $99 000$ and $101 000$ burles.
Let's suppose that the country uses bills of $n$ distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash $q$ times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the $q$ of requests for cash withdrawal.
|
Intended solution has the complexity $O(n k\log(n k)+q n k)$ or $O(n k\log(n k)+q n k\log(n k))$. For each possible value $x$ that we can get write a pair $(x, m)$ where $m$ is number of bills to achieve this value. Sort this array in ascending order of $x$ and leave only the best possible number of bills for each value of $x$. Then to answer a query we should iterate over the first summand in resulting sum and look for the remainder using binary search. The alternate way is the method of two pointers for looking in an array for a pair of numbers with a given sum that works in amortized $O(1)$ time. Check that we used no more than $k$ bills totally and relax the answer if needed.
|
[
"binary search",
"sortings"
] | 1,900
| null |
524
|
D
|
Social Network
|
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.
But wait, something is still known, because that day a record was achieved — $M$ simultaneous users online! In addition, Polycarpus believes that if a user made a request at second $s$, then he was online for $T$ seconds after that, that is, at seconds $s$, $s + 1$, $s + 2$, ..., $s + T - 1$. So, the user's time online can be calculated as the union of time intervals of the form $[s, s + T - 1]$ over all times $s$ of requests from him.
Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:
- the number of different users online did not exceed $M$ at any moment,
- at some second the number of distinct users online reached value $M$,
- the total number of users (the number of distinct identifiers) was as much as possible.
Help Polycarpus cope with the test.
|
Let's follow greedily in following way. Iterate over all requests in a chronological order. Let's try to associate each query to the new person. Of course we can't always do that: when there are already $M$ active users on a site, we should associate this request with some existing person. Now we need to choose, who it will be. Let's show that the best way is to associate a request with the most recently active person. Indeed, such "critical" state can be represented as a vector consisting of $M$ numbers that are times since the last request for each of the active people in descending order. If we are currently in the state $(a_{1}, a_{2}, ..., a_{M})$, then we can move to the one of the $M$ new states $(a_{1}, a_{2}, ..., a_{M - 1}, 0)$, $(a_{1}, a_{2}, ..., a_{M - 2}, a_{M}, 0)$, $...$ , $(a_{2}, a_{3}, ..., a_{M}, 0)$ depending on who we will associate the new request with. We can see that the first vector is component-wise larger then other ones, so it is better than other states (since the largest number in some component of vector means that this person will probably disappear earlier giving us more freedom in further operations). So, all we have to do is to simulate the process keeping all active people in some data structure with times of their last activity. As a such structure one can use anything implementing the priority queue interface (priority_queue, set, segment tree or anything else). Complexity of such solution is $O(n\log n)$.
|
[
"greedy",
"two pointers"
] | 2,100
| null |
524
|
E
|
Rooks and Rectangles
|
Polycarpus has a chessboard of size $n × m$, where $k$ rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated $q$ rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected.
|
Let's understand what does it mean that some cell isn't attacked by any rook. It means that there exists row and column of the rectangle without rooks on them. It's hard to check this condition, so it is a good idea to check the opposite for it. We just shown that the rectangle is good if on of the two conditions holds: there should be a rook in each row of it or there should be a rook in each column. We can check those conditions separately. How can we check that for a set of rectangles there is a point in each row? This can be done by sweeping vertical line from left to right. Suppose we are standing in the right side of a rectangle located in rows from $a$ to $b$ with the left side in a column $y$. Then if you denote as $last[i]$ the position of the last rook appeared in a row number $i$, the criteria for a rectangle looks like $\operatorname*{min}_{a\leq i\leq b}l a s t[i]\geq x$. That means that we can keep the values $last[i]$ in a segment tree and answer for all rectangles in logarithmic-time. Similarly for columns. This solution answers all queries in off-line in time $O((q + k)log(n + m))$.
|
[
"data structures",
"sortings"
] | 2,400
| null |
524
|
F
|
And Yet Another Bracket Sequence
|
Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations:
- adding any bracket in any position (in the beginning, the end, or between any two existing brackets);
- cyclic shift — moving the last bracket from the end of the sequence to the beginning.
Polycarpus can apply any number of operations to his sequence and adding a cyclic shift in any order. As a result, he wants to get the correct bracket sequence of the minimum possible length. If there are several such sequences, Polycarpus is interested in the lexicographically smallest one. Help him find such a sequence.
Acorrect bracket sequence is a sequence of opening and closing brackets, from which you can get a correct arithmetic expression by adding characters "1" and "+" . Each opening bracket must correspond to a closed one. For example, the sequences "(())()", "()", "(()(()))" are correct and ")(", "(()" and "(()))(" are not.
The sequence $a_{1}$ $a_{2}... a_{n}$ is lexicographically smaller than sequence $b_{1}$ $b_{2}... b_{n}$, if there is such number $i$ from $1$ to $n$, that$a_{k} = b_{k}$ for $1 ≤ k < i$ and $a_{i} < b_{i}$. Consider that "(" $ < $ ")".
|
The main idea is that the bracket sequence can be seen as a sequence of prefix balances, i. e sequence $(a_{i})$ such that $a_{i + 1} = a_{i} \pm 1$. Calculate the number of opening brackets $A$ and closing brackets $B$ in original string. It is true that if $A > = B$ then the string can be fixed by adding $A - B$ closing brackets at the end and shifting the resulting string to the point of balance minimum, and if $A \le B$, then the string can be similarly fixed by adding $B - A$ opening brackets to the beginning and then properly shifting the whole string. It's obvious that it is impossible to fix the string by using the less number of brackets. So we know the value of the answer, now we need to figure out how it looks like. Suppose that we first circularly shift and only then add brackets. Suppose that we add $x$ closing brackets. Consider the following two facts: If it is possible to fix a string by adding closing bracket to some $x$ positions then it is possible to fix it by adding $x$ closing brackets to the end of the string. From all strings obtained from a give one by adding closing brackets to $x$ positions, the minimum is one that obtained by putting $x$ closing brackets to the end. Each of those statements is easy to prove. They give us the fact that in the optimal answer we put closing brackets at the end of the string (after rotating the initial string). So we have to consider the set of the original string circular shifts such that they transform to the correct bracket sequence by adding $x = A - B$ closing brackets to the end and choose the lexicographically least among them. Comparing circular shifts of the string is the problem that can be solved by a suffix array. The other way is to find lexicographical minimum among them by using hashing and binary search to compare two circular shifts. The case when $A \le B$ is similar except that opening brackets should be put into the beginning of the string. So, overall complexity is $O(n\log n)$.
|
[
"data structures",
"greedy",
"hashing",
"string suffix structures",
"strings"
] | 2,700
| null |
525
|
A
|
Vitaliy and Pie
|
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with $n$ room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the ($n - 1$)-th room to the $n$-th room. Thus, you can go to room $x$ only from room $x - 1$.
The potato pie is located in the $n$-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room $x$ from room $x - 1$, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type $t$ can open the door of type $T$ if and only if $t$ and $T$ are the same letter, written in different cases. For example, key f can open door F.
Each of the first $n - 1$ rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room $n$.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room $n$, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
|
To solve this problem we need to use array $cnt[]$. In this array we will store number of keys of every type, which we already found in rooms, but didn't use. Answer will store in variable ans. Now, we iterate on string. If current element of string $s_{i}$ is lowercase letter (key), we make $cnt[s_{i}]$++. Else if current element of string $s_{i}$ uppercase letter (door) and $cnt[tolower(s_{i})] > 0$, we make $cnt[tolower(s_{i})]$--, else we make $ans$++. It remains only to print ans. Asymptotic behavior of this solution - O($|s|$), where $|s|$ - length of string $s$.
|
[
"greedy",
"hashing",
"strings"
] | 1,100
| null |
525
|
B
|
Pasha and String
|
Pasha got a very beautiful string $s$ for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to $|s|$ from left to right, where $|s|$ is the length of the given string.
Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent $m$ days performing the following transformations on his string — each day he chose integer $a_{i}$ and \textbf{reversed} a piece of string (a segment) from position $a_{i}$ to position $|s| - a_{i} + 1$. It is guaranteed that $2·a_{i} ≤ |s|$.
You face the following task: determine what Pasha's string will look like after $m$ days.
|
At first we need to understand next fact - it doesn't matter in wich order make reverses, answer will be the same for all orders. Let's numerate elements of string from one. To solve given problem we need to count how many reverses will begin in every position of string. Then we need to count array $sum[]$. In $sum[i]$ we need to store count of reverses of substrings, which begin in positions which not exceeding $i$. Now iterate for $i$ from $1$ to $n / 2$ and if $sum[i]$ is odd swap $s_{i}$ and $s_{n - i + 1}$. After that it remains only to print string $s$. Asymptotic behavior of this solution - O($n$ + $m$), where $n$ - length of string $s$, $m$ - count of reverses.
|
[
"constructive algorithms",
"greedy",
"math",
"strings"
] | 1,400
| null |
525
|
C
|
Ilya and Sticks
|
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of $n$ sticks and an instrument. Each stick is characterized by its length $l_{i}$.
Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.
Sticks with lengths $a_{1}$, $a_{2}$, $a_{3}$ and $a_{4}$ can make a rectangle if the following properties are observed:
- $a_{1} ≤ a_{2} ≤ a_{3} ≤ a_{4}$
- $a_{1} = a_{2}$
- $a_{3} = a_{4}$
A rectangle can be made of sticks with lengths of, for example, $3 3 3 3$ or $2 2 4 4$. A rectangle cannot be made of, for example, sticks $5 5 5 7$.
Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length $5$ can either stay at this length or be transformed into a stick of length $4$.
You have to answer the question — what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?
|
This problem can be solved with help of greedy. At first count array $cnt[]$. In $cnt[i]$ will store how many sticks with length $i$ we have. Now iterate for len from maximal length of sticks to minimal. If $cnt[len]$ is odd and we have sticks with length $len - 1$ (that is $cnt[len - 1] > 0$), make $cnt[len]$-- and $cnt[len - 1]$++. If $cnt[len]$ is odd and we have no sticks with length $len - 1$ (that is $cnt[len - 1] = 0$), make $cnt[len]$--. In this way we properly done all sawing which we need and guaranteed that all $cnt[len]$ is even. After that iterate similary on length of sticks and greedily merge pairs from $2$ sticks with the same length in fours. It will be length of sides of sought-for rectangles, left only summarize their squares in answer. In the end can left $2$ sticks without pair, we must not consider them in answer. For example, if $cnt[5] = 6$, $cnt[4] = 4$, $cnt[2] = 4$, we need to merge this sticks in following way - ($5, 5, 5, 5$), ($5, 5, 4, 4$), ($4, 4, 2, 2$). Two sticks with length $2$ are left, we must not count them. Asymptotic behavior of this solution - O($n + maxlen - minlen$), where $n$ - count of sticks, $maxlen$ - maximal length of stick, $minlen$ - minimal length of stick.
|
[
"greedy",
"math",
"sortings"
] | 1,600
| null |
525
|
D
|
Arthur and Walls
|
Finally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.
Plan of the apartment found by Arthur looks like a rectangle $n × m$ consisting of squares of size $1 × 1$. Each of those squares contains either a wall (such square is denoted by a symbol "*" on the plan) or a free space (such square is denoted on the plan by a symbol ".").
Room in an apartment is a maximal connected area consisting of free squares. Squares are considered adjacent if they share a common side.
The old Arthur dream is to live in an apartment where all rooms are rectangles. He asks you to calculate minimum number of walls you need to remove in order to achieve this goal. After removing a wall from a square it becomes a free square. While removing the walls it is possible that some rooms unite into a single one.
|
To solve this problem we need to observe next fact. If in some square whith size $2 \times 2$ in given matrix there is exactly one asterisk, we must change it on dot. That is if in matrix from dots and asterisks is not square $2 \times 2$ in which exactly one asterisk and three dots, then all maximum size of the area from dots connected by sides represent rectangles. Now solve the problem with help of bfs and this fact. Iterate on all asterisks in given matrix and if only this asterisk contains in some $2 \times 2$ square, change this asterisk on dot and put this position in queue. Than we need to write standart bfs, in which we will change asterisks on dots in all come out $2 \times 2$ squares with exactly one asterisk. Asymptotic behavior of this solution - O($n * m$), where $n$ and $m$ sizes of given matrix.
|
[
"constructive algorithms",
"data structures",
"graphs",
"greedy",
"shortest paths"
] | 2,400
| null |
525
|
E
|
Anya and Cubes
|
Anya loves to fold and stick. Today she decided to do just that.
Anya has $n$ cubes lying in a line and numbered from $1$ to $n$ from left to right, with natural numbers written on them. She also has $k$ stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.
Anya can stick an exclamation mark on the cube and get the factorial of the number written on the cube. For example, if a cube reads $5$, then after the sticking it reads $5!$, which equals $120$.
You need to help Anya count how many ways there are to choose some of the cubes and stick on some of the chosen cubes at most $k$ exclamation marks so that the sum of the numbers written on the chosen cubes after the sticking becomes equal to $S$. Anya can stick at most one exclamation mark on each cube. Can you do it?
Two ways are considered the same if they have the same set of chosen cubes and the same set of cubes with exclamation marks.
|
To solve this problem we need to use meet-in-the-middle. At first sort given array in increasing order and divide it in two parts. In first part must be first $n / 2$ elements, in second part - other. Iterate all submasks of all masks of elements from first part. That is iterate which cubes from first part we take and on which from them we paste exclamation marks. In this way we iterated all possible sums, which we can get with cubes from first part. Let for current submask we get sum sum_lf and use $t_{lf}$ exclamation marks. To store all such sums we use associative arrays $map < long long > cnt[k$ + $1]$, where $k$ - count of exclamation marks which we have in the beginning. After that similary iterate all submasks of all masks of elements from second part. Let for current submask sum is $sum_{rg}$ and number of used exclamation marks is $t_{rg}$. Then from first part we need to get sum ($s - sum_{rg}$) and we can use only ($k - t_{rg}$) exclamation marks, where $s$ - sum which we must get by condition of the problem. Then iterate how many exclamation marks we will use in first part (let it be variable cur) and increase answer on $cnt[cur][s - sum_{rg}]$. To accelerate our programm we may increase answer only if $cnt[cur].count(s - sum_{rg}) = true$. For submasks in iterate we can cut off iteration on current sum for submask (it must be less or equal to given $s$) and on current count of exclamation marks (it must be less or equal to given $k$). Also we should not paste exclamation marks on cubecs with numbers larger than $18$, because $19!$ more than $10^{16}$ - maximal value of $s$. Asymptotic behavior of this solution - O($3^{((n + 1) / 2)} * log(maxcnt) * k$), where $n$ - count of cubes, $maxcnt$ - maximal size of associative array, $k$ - count of exclamation marks.
|
[
"binary search",
"bitmasks",
"brute force",
"dp",
"math",
"meet-in-the-middle"
] | 2,100
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.