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
⌀ |
|---|---|---|---|---|---|---|---|
325
|
C
|
Monsters and Diamonds
|
Piegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are $n$ types of monsters, each with an ID between $1$ and $n$. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. Monsters may be able to split in multiple ways.
At the begining Piegirl has exactly one monster. She begins by feeding the monster a pie. She continues feeding pies to monsters until no more monsters are left. Then she collects all the diamonds that were created.
You will be given a list of split rules describing the way in which the various monsters can split. Every monster can split in at least one way, and if a monster can split in multiple ways then each time when it splits Piegirl can choose the way it splits.
For each monster, determine the smallest and the largest number of diamonds Piegirl can possibly collect, if initially she has a single instance of that monster. Piegirl has an unlimited supply of pies.
|
First part of the problem is to find minimum number of diamonds one can achieve by starting with a given monster. To do so, we will be using Dijkstra algorithm. Originally we don't know the minimum for any monster. For every rule we will maintain how many monsters with unknown minimums it has (let's call it $k_{i}$ for the $i$-th rule). Let's take every rule that has only diamonds in it (i.e. which has $k_{i} = 0$), and assign number of diamonds in that rule as a tentative minimum for the monster (if a monster has several diamonds-only rules, take the smallest one). Then take the monster, that has the smallest tentative minimum currently assigned. For that monster the tentative value is the actual minimum due to the same reasoning we use when we prove correctness of Dijkstra algorithm. Now, since we know the minimum for that monster, for every rule $i$ that has that monster in its result subtract 1 from $k_{i}$ for every occurrence of the monster in the result of that rule. If for any rule the value of $k_{i}$ becomes zero, update the tentative minimum for the monster that rule belongs to with the sum of minimum values for each monster that rule generates plus the number of diamonds that rule generates. Then from all the monsters for which we don't known the minimum yet, but for which we know the tentative minimum, pick the one with the smallest tentative minimum, and continue on. At the end we will end up in a state, when each monster either has an actual minimum value assigned, or has no tentative value assigned. The latter monsters will have $- 1 - 1$ as their answer. For the former monsters we know the minimum, but don't know the maximum yet. The second part of the problem is to find all the rules, after applying which we are guaranteed to never get rid of all the monsters. We will call such a rule bad. It is easy to show, that the rule bad if and only if it generates at least one monster with minimum value of -1. Remove all the bad rules from the set of rules. When bad rules are removed, finding maximums is trivial. Starting from every node for which maximum is not assigned yet, we traverse all the monsters in a DFS order. For a given monster, we consider every rule. For a given rule, for each monster it generates, we call DFS to find its maximum value, and then sum them up, add number of diamonds for the rule, and check if this rule gives bigger max value than the one currently known for the monster. If we ever call DFS for a monster, for which we already have a DFS call on the stack, that means that that monster has some way of producing itself (directly or indirectly) and some non-zero number of diamonds (this is why problem statement has a constraint that every rule generates at least one diamond), so the answer for the monster is -2. If, processing any rule, we encounter a monster with max value -2, we immediately assign -2 as a max value for the monster the rule belongs to and return from the DFS. As an exercise, think of a solution for the same problem, if rules are not guarantee to have at least one diamond in them.
|
[
"dfs and similar",
"graphs",
"shortest paths"
] | 2,600
| null |
325
|
D
|
Reclamation
|
In a far away land, there exists a planet shaped like a cylinder. There are three regions in this planet: top, bottom, and side as shown in the following picture.
Both the top and the bottom areas consist of big cities. The side area consists entirely of the sea.
One day, a city decides that it has too little space and would like to reclamate some of the side area into land. The side area can be represented by a grid with $r$ rows and $c$ columns — each cell represents a rectangular area in the side area. The rows are numbered 1 through $r$ from top to bottom, while the columns are numbered 1 through $c$ from left to right. Two cells are adjacent if they share a side. In addition, two cells located on the same row — one in the leftmost column, and the other in the rightmost column — are also adjacent.
Initially, all of the cells are occupied by the sea. The plan is to turn some of those cells into land one by one in a particular order that will be given to you.
However, the sea on the side area is also used as a major trade route. More formally, it is not allowed to reclamate the sea cells into land in such way that there does not exist a sequence of cells with the following property:
- All cells in the sequence are occupied by the sea (i.e., they are not reclamated).
- The first cell in the sequence is in the top row.
- The last cell in the sequence is in the bottom row.
- Consecutive cells in the sequence are adjacent.
Thus, the plan is revised. Each time a cell is going to be turned from sea to land, the city first needs to check whether or not it would violate the above condition by doing that. If it would, then the cell is not turned into land and the plan proceeds into the next cell. Otherwise, the cell is turned into land.
Your job is to simulate this and output the number of cells that were successfully turned into land.
|
Assume there's an extra sea cells on a row above the topmost row, and a row below the bottom most row. Hence, we can assume that the top and bottom row consists entirely of sea. We claim that: There does not exist a sea route if and only if there exists a sequence of land cells that circumfere the planet (2 cells are adjacent if they share at least one point). The "sufficient" part of the proof is easy -- since there exists such a sequence, it separates the sea into the northern and southern hemisphere and this forms a barrier disallowing passage between the two. The "necessary" part. Suppose there does not exist such route. Then, if you perform a flood fill from any of the sea cell in the top row, you obtain a set of sea cells. Trace the southern boundary of these set of cells, and you obtain the sequence of land circumfering the planet. Thus, the algorithm works by simulating the reclamations one by one. Each time a land is going to be reclamated, we check if it would create a circumefering sequence. We will show that there's a way to do this check very quickly -- thus the algorithm should work within the time limit. Stick two copies of the grid together side-by-side, forming a Rx(2*C) grid. The leftmost and rightmost cells of any row in this new grid are also adjacent, similar to the given grid. Each time we're going to reclamate a land in row r and column c, we check if by doing so we would create a path going from (r, c) to (r, c + C). If it would, then we cancel the reclamation. Otherwise, we perform it, and add a land in cell (r, c) and (r, c+C). This "is there a path from node X to node Y" queries can be answered very very quickly using union find -- we check whether is it possible to go from one of the 8 neighbors of (r, c) to one of the 8 neighbors of (r, c+C). Correctness follows from the following: There exists a circumefering sequence IFF there exists a path from (r, c) to (r, c+C). Sufficient is easy. Suppose there exist a path from (r, c) to (r, c+C). We can form our circumfering sequence by overlapping the path from (r, c) to (r, c+C) with the same path, but going from (r, c+C) to (r, c) (we can do this since the grid is a two copies of the same grid sticked together). Necessary. Suppose there exists a circumfering sequence. We claim that there must exist a path to go from (r, c) to (r, c+C). Consider the concatenation of an infinite number of our initial grid, forming an Rx(infinite * C) grid. If there exists a circumfering sequence, we claim that within this grid, there exists a path from (r, c) to (r, c+C). Suppose there does not exist such a path. Since there exists a circumfering sequence, it must be possible to go from (r, c) to (r, c+ t * C), where t is an integer >= 2. Now, you should overlap all the paths taken to go from (r, c) to (r, c+t*C) in the grid (r', c' + C) (the grid immediately to the right of the grid where (r, c) is located). There must be a path from (r, c) to (r, c+C) in this new overlapped path. Proofing the final part is difficult without interactive illustration -- basically since t >= 2, there exists a path that goes from the left side to the right side of the grid (r', c' + C). This path must intersect with one of the overlapping paths, and that path must be connected to (r, c+C). The details are left as... exercise :p.
|
[
"dsu"
] | 2,900
| null |
325
|
E
|
The Red Button
|
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of $n$ nodes, numbered from 0 to $n$ - 1. In order to deactivate the button, the $n$ nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node $i$, the next node to be disarmed must be either node $(2·i)$ modulo $n$ or node $(2·i) + 1$ modulo $n$. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
|
In this part of editorial, all numbers we speak are in modulo $N$. So, if I say 10, it actually means 10 modulo $N$. First, observe that this problem asks us to find a cycle that visits each node exactly once, i.e., a hamiltonian cycle. Thus, for each node $X$, there exists one other node that we used to go to node $X$, and one node that we visit after node $X$. We call them bef(X) and aft(X) (shorthand for before and after). First we will show that if $N$ is odd, then the answer is $- 1$. Proof...? Consider node $0$. What nodes points to node $0$? Such node $H$ must satisfy either of the following conditions: $2H = 0$ $2H + 1 = 0$ The first condition is satisfied only by $H = 0$. The second condition is satisfied only by one value of $H$: $floor(N / 2)$. So, since we need a hamiltonian cycle, pre[0] must be floor(N/2), and aft[floor(N/2)] = 0 Now, consider node $N - 1$. What nodes points to node $N - 1$? $2H = N - 1$ $2H + 1 = N - 1$ The second condition is satisfied only by $H = N - 1$. The first condition is satisfied only by $H = floor(N / 2)$ But we need a hamiltonian cycle, so aft[floor(N/2)] must be $N - 1$. This is a contradiction with that aft[floor(N/2)] must be 0. Now, $N$ is even. This case is much more interesting. Consider a node $X$. It is connected to $2X$ and $2X + 1$. Consider the node $X + N / 2$. It is connected to $2X + N$ and $2X + 1 + N$, which reduces to $2X$ and $2X + 1$. So, apparently node $X$ and node $X + N / 2$ are connected to the same set of values. Now, notice that each node $X$ will have exactly two nodes pointing to it. This is since such node $H$ must satisfy $2H = X$ $2H + 1 = X$ modulo $N$, each of those two equations have exactly one solution. So, this combined with that node $X$ and $X + N / 2$ have the same set of connected nodes means that the only way to go to node $2X$ or $2X + 1$ is from nodes $X$ and $X + N / 2$. Thus, if you choose to go from node $X$ to node $2X$, you HAVE to go from node $X + N / 2$ to node $2X + 1$ (or vice versa). Now, try to follow the rule above and generate any such configuration. This configuration will consists of cycles, possibly more than 1. Can we join them into a single large cycle, visiting all nodes? Yes we can, since those cycles are special. Weird theorem: If there are $2 +$ cycles, then there must exist $X$ and such node $X$ and node $X + N / 2$ are in different cycles. Proof: Suppose not. We show that there must exist one cycle in that case. Since node $X$ and $X + N / 2$ are in the same cycle, they must also be in the same cycle as node $2X$ and $2X + 1$. In particular, node $X$ and $2X$ and $2X + 1$ are all in the same cycle. It is possible to go from any node $X$ to any node $Y$ by following this pattern (left as exercise). Now, consider the $X$ such that node $X$ and node $X + N / 2$ are in different cycles. Suppose we go from node $X$ to node $2X + A$, and from $X + N / 2$ to $2X + B$ (such that $A + B = 1$). Switch the route -- we go from node $X$ to $2X + B$ and $X + N / 2$ to $2X + A$ instead. This will merge the two cycles -- very similar to how we merge two cycles when finding an eulerian path. Thus, we can keep doing this to obtain our cycle! ...It's not entirely obvious to do that in $O(N)$ time. An example solution: use DFS. DFS from node $0$. For each node $X$: if it has been visited, return if $X + N / 2$ has been visited, go to either $2X$ or $2X + 1$ and recurse, depending on which route used by node $X + N / 2$ otherwise, we go to node $2X$ and recurse. Then, check if $X + N / 2$ was visited in the recursion. If it was not, then the two of them forms two different cycles. We merge them by switching our route to $2X + 1$ instead, and recurse again.
|
[
"combinatorics",
"dfs and similar",
"dsu",
"graphs",
"greedy"
] | 2,800
| null |
327
|
A
|
Flipping Game
|
Iahub got bored, so he invented a game to be played on paper.
He writes $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices $i$ and $j$ ($1 ≤ i ≤ j ≤ n$) and flips all values $a_{k}$ for which their positions are in range $[i, j]$ (that is $i ≤ k ≤ j$). Flip the value of $x$ means to apply operation $x = 1$ - $x$.
The goal of the game is that after \textbf{exactly} one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub.
|
I'll present here the O(N ^ 3) algorithm, which is enough to solve this task. Then, for those interested, I'll show a method to achieve O(N) complexity. O(N ^ 3) method: The first thing to observe is that constrains are slow enough to allow a brute force algorithm. Using brute force, I can calculate for each possible single move the number of 1s resulting after applying it and take maximum. For consider each move, I can just generate with 2 FOR loops all indices i, j such as i <= j. So far we have O(N ^ 2) complexity. Suppose I have now 2 fixed vaIues i and j. I need to calculate variable cnt (initially 0) representing the number of ones if I do the move. For do this, I choose another indice k to go in a[] array (taking O(N) time, making the total of O(N ^ 3) complexity). We have two cases: either k is in range [i, j] (this means i <= k AND k <= j) or not (if that condition is not met). If it's in range, then it gets flipped, so we add to count variable 1 - a[k] (observe that it makes 0 to 1 and 1 to 0). If it's not in range, we simply add to cnt variable a[k]. The answer is maximum of all cnt obtained. O(N) method: For achieve this complexity, we need to make an observation. Suppose I flip an interval (it does not matter what interval, it can be any interval). Also suppose that S is the number of ones before flipiing it. What happens? Every time I flip a 0 value, S increases by 1 (I get a new 1 value). Every time I flip a 1 value, S decreases by 1 (I loose a 1 value). What would be the "gain" from a flip? I consider winning "+1" when I get a 0 value and "-1" when I get a 1 value. The "gain" would be simply a sum of +1 and -1. This gives us idea to make another vector b[]. B[i] is 1 if A[i] is 0 and B[i] is -1 if A[i] is 1. We want to maximize S + gain_after_one_move sum. As S is constant, I want to maximize gain_after_one_move. In other words, I want to find a subsequence in b[] which gives the maximal sum. If I flip it, I get maximal number of 1s too. This can be founded trivially in O(N ^ 2). How to get O(N)? A relative experienced programmer in dynamic programming will immediately recognize it as a classical problem "subsequence of maximal sum". If you never heard about it, come back to this approach after you learn it.
|
[
"brute force",
"dp",
"implementation"
] | 1,200
| null |
327
|
B
|
Hungry Sequence
|
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of $n$ integers.
A sequence $a_{1}$, $a_{2}$, ..., $a_{n}$, consisting of $n$ integers, is Hungry if and only if:
- Its elements are in increasing order. That is an inequality $a_{i} < a_{j}$ holds for any two indices $i, j$ $(i < j)$.
- For any two indices $i$ and $j$ $(i < j)$, $a_{j}$ must \textbf{not} be divisible by $a_{i}$.
Iahub is in trouble, so he asks you for help. Find a Hungry sequence with $n$ elements.
|
We'll present two different solutions for this task. Solution 1. What if we solve a more general task? What if each hungry number from the solution isn't allowed to be divided by any number smaller than it (except 1, which is divides every natural number). If this more general condition would be met, then the "hungry" condition would be met, too (as a[i] won't be divided by a number smaller than it (except 1), it won't be divided by a[j], too, with j < i, assuming that a[j] is different from 1). Now how to find numbers for this more general condition? We can rephrase it as: each number from more general condition has 2 divisors: 1 and itself. So if we print N numbers with 2 divisors in increasing order, that would be a good solution. As you probably know, numbers with 2 divisors are called "prime numbers". The task reduces to finding first N prime numbers. This can be done via brute force, or via Sieve of Eratosthenes (however, not necessarily to get an AC solution). Solution 2. Suppose we are given the number N. We can observe that for big enough consecutive numbers, the array is always hungry. For example, we can print 3 * N + 0, 3 * N + 1, 3 * N + 2, \dots , 3 * N + (N - 1). Magic, isn't it? Why does it work now? Pick an arbitrary a[i]. The solution would be bad if one of numbers 2 * a[i], 3 * a[i], 4 * a[i] and so on would be in a[] array. However, it will never happen. The smallest multiple from that ones will be 2 * 3 * N = 6 * N. There is not possible to obtain a smallest multiple than that one. On the other hand, the biggest number from a[] array would be 3 * N + N - 1 = 4 * N - 1. Since smallest multiple is bigger than biggest term of the array, it (and of course other multiples bigger than it) will never exist in a[] array. So the above solution is correct also.
|
[
"math"
] | 1,200
| null |
327
|
C
|
Magic Five
|
There is a long plate $s$ containing $n$ digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by $5$. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways he can obtain magic number, modulo $1000000007$ ($10^{9} + 7$). Two ways are different, if the set of deleted positions in $s$ differs.
Look at the input part of the statement, $s$ is given in a special form.
|
Property: A number is divisible by 5 if and only if its last digit is either 0 or 5. A first solution: Suppose you're given a plate S, not so big, so we can iterate all its elements. Can we get the answer? I build a new array sol[]. In explanation, both S and sol will be 1-based. Denote N = size of S. Also, denote sol[i] = the number of ways to delete digits from plate S such as we obtain a magic number which has the last digit on position i. The answer is sol[1] + sol[2] + \dots + sol[N]. Let's focus now on calculating sol[i]. If S[i] (digit of the plate corresponding to ith position) is different than 0 or 5, then sol[i] is 0 (see "property"). Otherwise we have to ask ourself: in how many ways I can delete digits in "left" and in "right" of position i. In the "right", we have only one way: delete all digits (if one digit from right still stands, then the number isn't ending at position i). Now in the "left": there are digits on positions 1, 2, \dots , i - 1. We can either delete a digit or keep it - anyhow he'd do we still get a magic number. So on position 1 I have 2 ways (delete or keep it), on position 2 I have also 2 ways, \dots , on position i - 1 I have also 2 ways. Next, we apply what mathematics call "rule of product" and we get 2 * 2 * 2 \dots * 2 (i - 1 times) = 2 ^ (i - 1). Applying "rule of product" on both "left" and "right" I get 2 ^ (i - 1) * 1 = 2 ^ (i - 1). To sum it up: If S[i] is 0 or 5 we add to the answer 2 ^ (i - 1). Otherwise, we add nothing. The only problem remained for this simple version is how we calculate A ^ B modulo one number. This is a well known problem as well, called "Exponentiation by squaring". Coming back to our problem: So what's different in our problem? It's the fact that we can't iterate all elements of plate. However, we can use "concatenation" property. We know that if an element is a position i in the first copy, it will also be on positions i + n, i + 2 * n, i + 3 * n, \dots , i + (k - 1) * n (we don't call here about trivial case when k = 1). What if iterate only one copy and calculate for all K copies. If in the first copy, at the position i is either 0 or 5, we have to calculate the sum 2 ^ i + 2 ^ (i + n) + 2 ^ (i + 2 * n) + \dots + 2 ^ (i + (k - 1) * n). By now on, in calculus I'll denote i as i - 1 (it's a simple mathematical substitution). A first idea would be just to iterate each term and calculate it with exponentiation by squaring. However, it takes in the worst case the same complexity as iterating all plate. We need to find something smarter. 2 ^ i + 2 ^ (i + n) + 2 ^ (i + 2 * n) + \dots + 2 ^ (i + (k - 1) * n) = = 2 ^ i * 1 + 2 ^ i * 2 ^ n + 2 ^ i * 2 ^ (2 * n) + \dots + 2 ^ i * 2 ^ ((k - 1) * N) = = 2 ^ i * (2 ^ 0 + 2 ^ n + 2 ^ (2 * n) + \dots + 2 ^ ((k - 1) * n) We reduced the problem to calculate sum S = 2 ^ 0 + 2 ^ n + 2 ^ (2 * n) + \dots + 2 ^ (X * n). What's the value of 2 ^ n * S ? It is 2 ^ n + 2 ^ (2 * n) + 2 ^ (3 * n) + \dots + 2 ^ ((X + 1) * n). And what you get by making 2 ^ n * S - S ? 2 ^ n * S - S = 2 ^ ((X + 1) * n) - 1 S * (2 ^ n - 1) = 2 ^ ((X + 1) * n) - 1 S = (2 ^ ((X + 1) * n) - 1) / (2 ^ n - 1). We can calculate both 2 ^ i and S with exponentiation by squaring and the problem is done. For "/" operator, we can use multiplicative inverse (you can read about that and about Fermat Little's theorem, taking care that 10^9 + 7 is a prime number). The time complexity is O(N * logK). Note: that kind of reduction of powers is called "power series" in math. Alternative solution: For this alternative solution, we don't need to use any special properties of 5. In fact, we can replace 5 by any integer p and still have the same solution. So for now, I shall write p in place of 5. This suggests a dynamic programming solution: denote dp(x,y) be the number of ways of deleting some digits in the first x digits to form a number that has remainder y (modulo p). For simplicity, we accept "empty" plate be a number that is divisible by p. Writing the DP formula is not difficult. We start with dp(0,0) = 1, and suppose we already have the value dp(x,y). We shall use dp(x,y) to update for dp(x + 1,*), which has two possible cases: either keeping the (x + 1)-th digit or by deleting it. I won't go into much detail here. The answer is therefore dp(N,0). Clearly, applying this DP directly would time out. For a better algorithm, we resort on the periodicity of the actual plate. The key idea is that, we imagine each digit in the plate as a linear transformation from (x0, x1, .., x(p - 1)) to (y0, y1, y(p-1)). Obviously, (x0, x1, .., x(p - 1)) corresponds to some dp(i, 0), dp(i, 1) .. dp(i, p - 1) and (y0, y1, y(p-1)) corresponds to some (dp(i + 1, 0)), dp((i + 1), 1), ..., dp(i + 1, p - 1) .So we can write X * M(d) = Y, where X and Y are vectors of length p, and M(d) is the matrix of size p * p representing digit d (note that M(d) is independent from X and Y). By multiplying all |a|.K such matrices together, we obtain a transformation from (1, 0, 0, .., 0) to (T0, T1, .., T(p - 1)) where T0 is actually our answer (including the empty plate). What's the difference? We can group the matrices in groups of length |a|, and lift to the exponent K. That leads to an algorithm with time complexity O(p^3(|a| + log K)), which could be risky. To improve, we should go back to our original DP function and observe that it is actually a linear transformation from (1, 0, 0, .., 0) to (R0, R1, \dots , R(p - 1)), if we restrict ourselves in the first fragment of length |a|. So instead of multiplying |a| matrices together, we can run DP p times with initial conditions (0, 0, .., 0, 1, 0, .., 0) to obtain the matrix transformation. The overall time complexity becomes O(|a| * p^2 + p^3 log K) .
|
[
"combinatorics",
"math"
] | 1,700
| null |
327
|
D
|
Block Tower
|
After too much playing on paper, Iahub has switched to computer games. The game he plays is called "Block Towers". It is played in a rectangular grid with $n$ rows and $m$ columns (it contains $n × m$ cells). The goal of the game is to build your own city. Some cells in the grid are big holes, where Iahub can't build any building. The rest of cells are empty. In some empty cell Iahub can build exactly one tower of two following types:
- Blue towers. Each has population limit equal to $100$.
- Red towers. Each has population limit equal to $200$. However, it can be built in some cell only if in that moment at least one of the neighbouring cells has a Blue Tower. Two cells are neighbours is they share a side.
Iahub is also allowed to destroy a building from any cell. He can do this operation as much as he wants. After destroying a building, the other buildings are not influenced, and the destroyed cell becomes empty (so Iahub can build a tower in this cell if needed, see the second example for such a case).
Iahub can convince as many population as he wants to come into his city. So he needs to configure his city to allow maximum population possible. Therefore he should find a sequence of operations that builds the city in an optimal way, so that total population limit is as large as possible.
He says he's the best at this game, but he doesn't have the optimal solution. Write a program that calculates the optimal one, to show him that he's not as good as he thinks.
|
The restriction given in the problem poses you to think of building as many Red Towers as possible, and fill the rest with Blue Towers (since there is no profit of letting cells empty, such cells can be filled by Blue Towers). Also, it's quite obvious to see that each connected component (containing empty cells only) is independent from each other, so we shall iterate the component one by one. Denote the current component be S. Lemma 1 is impossible to build S so that it contains all Red Towers only. Proof Suppose there exists such a way. Look up the last cell that is built (denote by x). Clearly x is a Red Tower, so at the moment it is built, x must be adjacent to a cell than contains a Blue Tower. However, it's obvious that there's no such cell (if there is, it must belong to S, which is impossible). As it's impossible to have all Red Towers, it's natural to look up at the next best solution: the one with exactly one Blue Tower, and among them, we need to find the least lexicographic solution. Fortunately, we can prove that such a configuration is always possible. Such proof is quite tricky, indeed: Lemma 2 Pick any cell b in S. It is possible to build a configuration that has all but b be Red Towers, and b is a Blue Tower. Proof Construct a graph whose vertices correspond to the cells of S, and the edges correspond to cells that are adjacent. Since S is connected, it is possible to build a tree that spans to all vertices of S. Pick b as the root and do the following: Build all cells of S blue Move from the leaf to the root. At each cell (except the root), destroy the Blue Tower and rebuild with the Red Tower. To be precise, u can be destroyed (and rebuilt) if all vertices in the subtree rooted at u have already been rebuilt. How can it be the valid solution? Take any vertex u which is about to be rebuilt. Clearly u is not b, and u has its parent to be blue, so the condition for rebuilding can be met. When the building is completed, only b remains intact, while others have been transformed into Red Towers. So we get the following algorithm: do a BFS / DFS search to find connected components. Then, apply Lemma 2 to build a valid configuration.
|
[
"constructive algorithms",
"dfs and similar",
"graphs"
] | 1,900
| null |
327
|
E
|
Axis Walking
|
Iahub wants to meet his girlfriend Iahubina. They both live in $Ox$ axis (the horizontal axis). Iahub lives at point 0 and Iahubina at point $d$.
Iahub has $n$ positive integers $a_{1}$, $a_{2}$, ..., $a_{n}$. The sum of those numbers is $d$. Suppose $p_{1}$, $p_{2}$, ..., $p_{n}$ is a permutation of ${1, 2, ..., n}$. Then, let $b_{1} = a_{p1}$, $b_{2} = a_{p2}$ and so on. The array b is called a "route". There are $n!$ different routes, one for each permutation $p$.
Iahub's travel schedule is: he walks $b_{1}$ steps on $Ox$ axis, then he makes a break in point $b_{1}$. Then, he walks $b_{2}$ more steps on $Ox$ axis and makes a break in point $b_{1} + b_{2}$. Similarly, at $j$-th $(1 ≤ j ≤ n)$ time he walks $b_{j}$ more steps on $Ox$ axis and makes a break in point $b_{1} + b_{2} + ... + b_{j}$.
Iahub is very superstitious and has $k$ integers which give him bad luck. He calls a route "good" if he never makes a break in a point corresponding to one of those $k$ numbers. For his own curiosity, answer how many good routes he can make, modulo $1000000007$ ($10^{9} + 7$).
|
Usually when dealing with complicated problems, a good idea is to solve them for small cases. Let's try this here. First case: K = 0. The answer is obviously N! (each permutation of p1, p2, \dots , pn would be good). Next case: K = 1. The answer of this one is N! - |L1|. By L1 I denote all routes for which a prefix sum is equal to first lucky number. Obviously, if from all routes I exclude the wrong ones, I get my answer. If we can find an algorithm to provide |L1| in good time, then problem is solved for K = 1. We can just try all N! permutations. Despite this method is simple, it has complexity O(N!), too much for the constraints. Suppose we've founded a set of positions p1, p2, .., pk such as a[p1] + a[p2] + ..+ a[pk] = U1 (first unlucky number). How many permutations can we make? The first k positions need to be p1, p2, .., pk, but in any order. Hence we get k! . The not used positions can also appeared in any order, starting from k + 1 position. As they are n - k, we can permute them in (n - k)! ways. Hence, the answer is k! * (n - k)! Instead of permuting {1, 2, .., n}, now we need to find subsets of it. Hence, the running time becomes O(2^n). This is still too much. Meet in the middle. We make all subsets for first half of positions (from 1 to N / 2) and them for second half (from N / 2 + 1 to N). For each subset we keep 2 information: (sum, cnt) representing that there is a subset of sum "sum" containing "cnt" elements. For each (X, Y) from left we iterate in the right. After choosing one element from the left and one from the right we just "split" them. To split 2 states (A, B) and (C, D), the new state becomes (A + C, B + D). But we know that A + C = U1. This comes us to the idea: for each (X, Y) in the left, I check (U1 - X, 1), (U1 - X, 2), \dots , (U1 - X, K) from the right. For each of them, the answer would be (Y + K)! * (N - Y - K)! . I can store (using any data structure that allows this operations, I suggest a hash) how(C, D) = how many times does state (C, D) appear in the right. So, for a state (A, B) the answer becomes a sum of how(U1 - A, K) * (B + K)! * (N - B - K)!. Doing the sum for all states (A, B), we get our answer. The complexity of this method is O(2 ^ (N / 2) * N). Final Case: K = 2 The whole "meet in the middle" explanation worthed. We will do something very similar to solve this case. Suppose U1 and U2 are the unlucky numbers. Without loosing the generality, let's assume U1 <= U2. Following "Principle of inclusion and exclusion" paradigm (google about it if you never heard before) we can write our solution as N! - |L1| - |L2| + |intersection between L1 and L2|. Again, by L1,2 I denote the number of routes which have a prefix sum equal to number U1,2. The |X| is again the cardinal of this set. Basically we can calculate |X| as for K = 1. The only problem remained is calculating |intersection between L1 and L2|. The |intersection between L1 and L2| is the number of permutations which have a prefix sum equal to U1 and a prefix sum equal to U2. Since U1 <= U2, we can split a permutation from this set in 3 parts: 1/ p1, p2, ...pk such as a[p1] + a[p2] + ... + a[pk] = U1. 2/ pk+1, pk+2, ..., pm such as a[pk+1], a[pk+2], ..., a[pm] = U2 - U1. Note that a[p1] + a[p2] + ... + a[pm] = U2. 3/ The rest of elements until position n. By a perfectly identical logic from K = 1 case, the number of permutations given those p[] would be k! * (m - k)! * (n - m)!. So the problem reduces to: find all indices set p1, p2, ... and q1, q2, .. such as a[p1] + a[p2] + ... + a[pn1] = U1 and a[q1] + a[q2] + ... + a[qn2] = U2 - U1. Then, we can apply formula using n1 and n2 described above. The first idea would be O(3 ^ N) - for each position from {1, 2, .., n} atribute all combinations of {0, 1, 2}. 0 means that position i is 1/, 1 means that position i is in 2/ and 2 means that position i is in 3/ . This would time out. Happily, we can improve it with meet in the middle principle. The solution is very similar with K = 1 case. I won't fully explain it here, if you understood principle from K = 1 this shouldn't be a problem. The base idea is to keep (S1, S2, cnt1, cnt2) for both "left" and "right". (S1, S2, cnt1, cnt2) represents a subset which has sum of elements from 1/ equal to S1, sum of elements from 2/ equal to S2, in 1/ we have cnt1 element and in 2/ we get cnt2 elements. For a (S1, S2, cnt1, cnt2) state from "left" we are looking in the right for something like (U1 - S1, U2 - U1 - S2, i, j). We get O(3 ^ (N / 2) * N ^ 2) complexity. Unexpected solution During the round, we saw a lot of O(2 ^ N * N) solutions passing. This was totally out of expectations. I believe if would make tests stronger, this solution won't pass and round would be more challenging. That's it, nothing is perfect. As requested, I'll explain that solution here. Before explaining the solution, I assume you have some experience with "bitmask dp" technique. If you don't, please read before: In this problem we'll assume that a is 0-based. For a mask, consider bits from right to left, noting them bit 0, bit 1 and so on. Bit i is 1 if and only if a[i] is in the subset which is in a bijective replation with the mask. For example, for mask 100011101 the subset is {a0, a2, a3, a4, a8}. I'll call from now on the subset "subset of mask". Also, the sum of all elements in a subset will be called "sum of mask" (i.e. a0 + a2 + a3 + a4 + a8). We'll explain the solution based by watashi's submission. 4017915 First step of the algorithm is to calculate sum of each mask. Let dp[i] the sum of mask i. Remove exactly one element from the subset of mask. Suppose the new mask obtained is k and removed element is j. Then, dp[i] = dp[k] + a[j]. dp[k] is always calculated before dp[i] (to proof, write both k and i in base 10. k is always smaller than i). Having j an element from subset of mask i, we can compute mask k by doing i ^ (1 << j). Bit j is 1, and by xor-ing it with another 1 bit, it becomes 0. Other bits are unchanged by being xor-ed by 0. This method works very fast to compute sum of each mask. From now on, let's denote a new array dp2[i] = how many good routes can I obtain with elements from subset of mask i. Watashi uses same dp[] array, but for making it clear, in editorial I'll use 2 separate arrays. Suppose that CNT(i) is number of elements from subset of mask i. We are interested in how many ways we can fill positions {1, 2, ..., CNT(i)} with elements from subset of mask i such as each prefix sum is different by each unlucky number. Next step of the algorithm is to see which sum of masks are equal to one of unlucky numbers. We mark them as "-1" in dp2[]. Suppose we founded a subset {a1, a2, ..., ax} for which a1 + a2 + ... + ax = one of unlucky numbers. Then, none permutation of {a1, a2, ..., ax} is allowed to appear on first x positions. When we arrive to a "-1" state, we know that the number of good routes for its subset of mask is 0. Now, finally the main dp recurrence. If for the current mask i, dp2[i] = -1, then dp2[i] = 0 and continue (we discard the state as explained above). Otherwise, we know that there could exist at least one way to complete positions {1, 2, ... CNT(i)} with elements of subset of mask i. But how to calculate it? We fix the last element (the element from the position CNT(I)) with some j from subset of mask i. The problem reduces now with how many good routes can I fill in positions {1, 2, ..., CNT(i) - 1} with elements from subset of mask i, from which we erased element j. With same explanation of sum of mask calculations, this is already calculated in dp2[i ^ (1 << j)]. The result is dp2[(1 << N) - 1] (number of good routes containing all positions).
|
[
"bitmasks",
"combinatorics",
"constructive algorithms",
"dp",
"meet-in-the-middle"
] | 2,300
| null |
329
|
A
|
Purification
|
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak zombies, you arrived at a square room consisting of tiles forming an $n × n$ grid. The rows are numbered $1$ through $n$ from top to bottom, and the columns are numbered $1$ through $n$ from left to right. At the far side of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
\begin{center}
\underline{The cleaning of all evil will awaken the door!}
\end{center}
Being a very senior adventurer, you immediately realize what this means. You notice that every single cell in the grid are initially evil. You should purify all of these cells.
The only method of tile purification known to you is by casting the "Purification" spell. You cast this spell on a single tile — then, all cells that are located in the same row and all cells that are located in the same column as the selected tile become purified (including the selected tile)! It is allowed to purify a cell more than once.
You would like to purify all $n × n$ cells while minimizing the number of times you cast the "Purification" spell. This sounds very easy, but you just noticed that some tiles are particularly more evil than the other tiles. You cannot cast the "Purification" spell on those particularly more evil tiles, not even after they have been purified. They can still be purified if a cell sharing the same row or the same column gets selected by the "Purification" spell.
Please find some way to purify all the cells with the minimum number of spells cast. Print -1 if there is no such way.
|
Obviously the minimum possible answer is n (why?). But is it always possible to purify all the cells with n spells? If there exist a row consisting of entirely "E" cells and a column consisting of entirely "E" cells, then the answer is -1. This is since the cell with that row and that column cannot be purifed. Otherwise, without loss of generality let's suppose there is no row consisting entirely of "E". Then, for each row, find any "." cell. Purify it. The case with no column consisting entirely of "E" is similar.
|
[
"constructive algorithms",
"greedy"
] | 1,500
| null |
329
|
B
|
Biridian Forest
|
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.
\textbf{The forest}
The Biridian Forest is a two-dimensional grid consisting of $r$ rows and $c$ columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.
The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):
\textbf{Moves}
Breeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:
- Do nothing.
- Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.
- If you are located on the exit cell, you may leave the forest. Only you can perform this move — all other mikemon breeders will never leave the forest by using this type of movement.
After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).
\textbf{Mikemon battle}
If you and $t$ $(t > 0)$ mikemon breeders are located on the same cell, exactly $t$ mikemon battles will ensue that time (since you will be battling each of those $t$ breeders once). After the battle, all of those $t$ breeders will leave the forest to heal their respective mikemons.
Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders — there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).
\textbf{Your goal}
You would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.
\textbf{Goal of other breeders}
Because you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.
\textbf{Your task}
Print the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.
|
The only non ad hoc problem in the round! ...sort of. Despite the very long problem statement, the solution is really simple. We should take any shortest path from S to E (yes, any!). We will see why this is optimal at the end. If a breeder can reach E faster than or equal to us, then he will battle us. This is since he can simply walk to E and waits for us there. Otherwise, they can never battle us by contradiction. Assume they battled us, but they cannot reach cell E from their location faster or equal to us. If the battle us in cell X, then cell X is part of the shortest path from S to E that you are travelling. Since he is able to battle us there, he must be able to arrive at cell X <= us. But then, that means he can walk from X to E and reach E before or equal to us! Contradiction. This is optimal, since any breeder that we battle in this solution must also be battled in any other solution (the other breeders should immediately go to E and wait). You can use Breadth-First Search once from exit cell to obtain the shortest paths from each breeder to it.
|
[
"dfs and similar",
"shortest paths"
] | 1,500
| null |
329
|
C
|
Graph Reconstruction
|
I have an undirected graph consisting of $n$ nodes, numbered 1 through $n$. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself.
I would like to create a new graph in such a way that:
- The new graph consists of the same number of nodes and edges as the old graph.
- The properties in the first paragraph still hold.
- For each two nodes $u$ and $v$, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph.
Help me construct the new graph, or tell me if it is impossible.
|
If n <= 7, brute force all possible subsets of the edges (at most 2^(7 * (7 - 1) / 2)), and check if they satisfy the constraint. Otherwise, a solution always exists. Here is how to construct one. Partition the nodes into connected components. Note that each component will be either a cycle or a chain. List the nodes of each component in order of the cycle/chain. For example, for the first example, the partition would be { <1, 2, 3>, <4, 5, 6, 8, 7> }. For each component, we do not care whether it is a cycle or a chain. For each component, reorder the nodes such that all nodes in the odd positions are in the front. For example, component ABCDEFGHI is reordered into ACEGIBDFH. (Each letter represent a node.) Pick any component with the largest number of nodes. If the number of nodes in it is even, swap the first two nodes. For example, ABCDEFGH -> ACEGBDFH -> CAEGBDFH. For each other component, insert the nodes alternately between the largest component. For example, if the other components are acebd and 1324, insert them as follows: CAEGBDFH -> C a A c E e G b B d DFH -> C 1 a 3 A 2 c 4 EeGbBdDFH. Connect adjacent nodes so that the number of edges is m, connecting the last with the first nodes if necessary. The deterministic solution is very tricky. Therefore, I made the pretest quite strong. Some tricky cases: 4-cycle and 1-chain (covered in the example) 3-cycle and 3-cycle 4-cycle and 3-cycle (very tricky! many submissions failed on this case) Actually, we can do brute force when n <= 6, but this requires a special handling: when the largest component has 4 nodes, we should swap the first node with the third node (not the second). This is to handle the 4-cycle-and-3-cycle case.
|
[
"constructive algorithms"
] | 2,400
| null |
329
|
D
|
The Evil Temple and the Moving Rocks
|
\underline{Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.}
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an $n × n$ grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door:
\begin{center}
\underline{The sound of clashing rocks will awaken the door!}
\end{center}
Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:
- '^': this rock moves upwards;
- '<': this rock moves leftwards;
- '>': this rock moves rightwards;
- 'v': this rock moves downwards.
To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already $10^{7}$ events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.
If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least $x$. It is okay for the rocks to continue moving after producing $x$ sounds.
The following picture illustrates the four possible scenarios of moving rocks.
- Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated.
- Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end.
- Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced.
- Does not move because the wall is in the way. No sounds are produced and the movements end.
Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!
|
Post your solution in the comment! Here's mine for the last case! (approximately 120,000 sounds). You can get the number of sounds your solution produces when submitting it to the server. 1 copy of v<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v^ 24 copies of v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v. v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^ 24 copies of v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^ .^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^ 1 copy of >^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^ .................................................................................................... 1 1I wonder if there's a solution with ~150,000 sounds or more... the (theoretical) upper bound is 100^3 / something, so it may be feasible...?
|
[
"constructive algorithms"
] | 2,500
| null |
329
|
E
|
Evil
|
There are $n$ cities on a two dimensional Cartesian plane. The distance between two cities is equal to the Manhattan distance between them (see the Notes for definition). A Hamiltonian cycle of the cities is defined as a permutation of all $n$ cities. The length of this Hamiltonian cycle is defined as the sum of the distances between adjacent cities in the permutation plus the distance between the first and final city in the permutation. Please compute the longest possible length of a Hamiltonian cycle of the given cities.
|
This problem asks us to prove something very long (the proof below is of 80+ lines). Assume that the number of cities is at least 4. The case where it's less than 4 is trivial. First, we will assume that no two cities will have same X or Y coordinates. To get this assumption, we can juxtapose every city very slightly that it will not change the answer. The keys are : A) "Manhattan Distance", B) the tour starts and ends at the same city. Suppose we know a tour. The total distance traveled will be |X1 - X2| + |Y1 - Y2| + |X3 - X2| + |Y3 - Y2| ... Let's separate the X and Y coordinates for simplicity. Note that each city will contribute twice to this value, for example X2 was in |X1 - X2| and |X3 - X2| in the example above. Manhattan distance implies that each of these values will either be multiplied by +1 or -1, depending on the other coordinate being compared in the absolute term. Furthermore, the number of values that are multiplied by +1 must equal the number of values that are multiplied by -1 (since in each absolute term, one is multiplied by +1 and the other by -1). This directly implies an upper bound on the maximum length of the tour. If we list all the X coordinates of the cities, and we put each of them twice in this list, and sort them, the maximum will be gained if we multiply the last half by +1 and the first half by -1, and finally summing them up. Note that all of these reasoning applies to the Y coordinate, and summing both maximum of X and Y, we receive an upper bound on the length of the tour. If we can find a tour with this length, our job is done. In some case, it's possible. Let's investigate! First, if we have the medians of the X and the Ys as in the list above, we can separated the field like below : A | B | --------- | C | DThe lines corresponds to the median for both X and Y. At most one city will lie on each of the median lines (recall our assumption that X and Ys are distinct). Let's call each A B C and D as boxes. Below, we will refer box A as simply A (applies to B, C, and D too) To obtain the value above, from a city in B we must go to a city in C. Same reasoning yields : B->C, C->B, A->D, D->A. Here, pairs of cities become apparrent, A and D are paired as well as B and C. First, if either A+D is empty or B+C is empty, then we can obtain the upper bound above. We simply alternates between the two remaining pair. So let's assume that A+D is not empty and B+C is not empty. First, let's investigate the relationship between B and C (A and B will also exhibits this relationship). Theorem 1: |B - C| <= 1. Why: First, if there are no cities in the medians or there is a single city in the center of the median : A median divides the region into two areas with the same number of cities, so we have: a) A+B = C+D b) A+C = B+Dsubstituting A from a to b yields : (C+D-B)+C = B+D 2C = 2B B = CAnd the theorem follows. Next, suppose there are two cities in the median, one for each median line : Let's suppose the median is one above and one on the right. All other cases will be similar. By definition of median... a) (A + B + 1) = (C + D) b) (A + C) = (B + D + 1)Substituing a into b yields (C + D - B - 1 + C) = (B + D + 1) 2C = 2B + 2 C = B + 1which also implies A = D Applying the same technique to other cases will give: C = B and A = D+1 C = B-1 and A = D C = B and A = D-1And the theorem follows. Note also that the one with the extra 1 city will be the one that is not adjacent to any median city (adjacent being the city lies in the boundary of the box) OK, so in the following observations, we will assume the upper bound (that is, the sorted list of both X and Ys have their first half multiplied by -1 while the rest by +1), and trying to find a solution that's as close as possible to this upper bound. The following will be another case analysis. Theorem 2: If there are two cities in the medians (that is, one in each median line), then the upper bound can be achieved. Why: We use pair of boxes to denote either A and D or B and C. From the second part of the proof for theorem 1, there will be a pair of boxes that contain different number of cities. Let's pick this pair, and start at the one with the most boxes. We keep alternating with its pair until we end up back in our starting box. Then, we simply move to either of the median city. From there we move to the other pair of box, the farthest one of the two. Alternate between the two, go to the other median city, and return to the starting city. It's easy to see that this will be optimal and have the upper bound as its value. Now, let's see if there are no cities in the medians. First of all, this implies that the number of cities is even. Second, this implies that our upper bound which has the X and Y lists as -1 -1 -1 ... -1 1 ... 1 1 1 will not work (since this implies we have to continuously alternate between the two pairs of boxes, however, we can't switch between the pair of boxes). So, at least a modification would be required. The smallest possible modification is obtained by swapping the medians, that is, it becomes : -1 -1 -1 ... -1 -1 1 -1 1 1 ... 1 1 1. This is sufficient. Why? So, there are two cities that changes since the number of cities is even. Furthermore, these two cities will be the closest to the median line (let's assume these coordinates are X, that is, they're the closest to the vertical median line) and lies at two different boxes. Then, we proceed as follows. We start at one of these two cities. Alternate and end at the other side. If the other city is at that box, we make it so that we end at that city, and in this case, we can move to a city in the other box pair while respecting the list of X coordinates (we can do so since this city is the closest to the median line). Otherwise, the city will be in the other pair of boxes. We simply move there and it can be shown that we still respect the list of X coordinates. Alternate and at the end, go back to the starting city. All of these can be shown to still respect the list above. This is optimal since this is the next largest possible upper bound if upper bound cannot be achieved. Now, if there is a single city in the center of both medians, then the upper bound cannot be achieved. To see this, the upper bound can only be achieved if from a city in a box we move to another city in its box pair or to the center city. However, since both pair of boxes contains a city, we will need to move at least twice between them. Since there's only one center city, this is not possible. Observe that this case implies an odd number of cities. Hence, we can't simply swap the median since it swaps the x coordinates of the same median city. Instead, we do this : -1 -1 ... -1 -1 1 1 -1 1 ... 1 1 or -1 -1 ... -1 1 -1 -1 1 1 ... 1 1 That is, we swap to either one of the neighboring city. With the same reasoning as above, we can show that we respect this list of X coordinates. To achieve O(N) expected performance, note that the only operations we need are : grouping elements into boxes and median finding. Both can be done in expected O(N) time (expected since although there is a worst-case O(N) selection algorithm, it's ugly).
|
[
"math"
] | 3,100
|
import sys
n = int(raw_input())
coordinates = []
xs = []
ys = []
for i in range(n):
x, y = map(int, raw_input().split())
coordinates.append(((x, i), (y, i)))
xs.append((x, i))
ys.append((y, i))
xs = sorted(xs)
ys = sorted(ys)
amt = [[0] * 2 for _ in range(2)]
medians = 0
for x, y in coordinates:
if n % 2 and x == xs[n/2]:
# median
medians += 1
continue
if n % 2 and y == ys[n/2]:
# median
medians += 1
continue
amt[x < xs[n/2]][y < ys[n/2]] += 1
def CalcuHalf(arr):
res = 0
for a, _ in arr[len(arr)/2:]:
res += a
for a, _ in arr[:len(arr)/2]:
res -= a
return res
def PossibleAll():
def CalculateMax(arr):
woot = arr + arr
woot = sorted(woot)
return CalcuHalf(woot)
print CalculateMax(xs) + CalculateMax(ys)
sys.exit(0)
if amt[0][0] + amt[1][1] == 0 or amt[1][0] + amt[0][1] == 0:
PossibleAll()
if medians == 2:
PossibleAll()
if medians == 0:
def Proc(arr):
zs = sorted(arr + arr)
zs[n-1], zs[n] = zs[n], zs[n-1]
return CalcuHalf(zs)
print max([Proc(xs) + CalcuHalf(sorted(ys+ys)),
Proc(ys) + CalcuHalf(sorted(xs+xs))])
else:
def Proc(arr):
zs = sorted(arr + arr)
zs[n-2], zs[n] = zs[n], zs[n-2]
az = sorted(arr + arr)
az[n-1], az[n+1] = az[n+1], az[n-1]
return max([CalcuHalf(zs), CalcuHalf(az)])
print max([Proc(xs) + CalcuHalf(sorted(ys+ys)),
Proc(ys) + CalcuHalf(sorted(xs+xs))])
|
330
|
A
|
Cakeminator
|
You are given a rectangular cake, represented as an $r × c$ grid. Each cell either has an evil strawberry, or is empty. For example, a $3 × 4$ cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains at least one cake cell that has not been eaten before, and eats all the cake cells there. He may decide to eat any number of times.
Please output the maximum number of cake cells that the cakeminator can eat.
|
Long solution: Once an evil strawberry, always an evil strawberry (since they can't be eaten). Thus, if a row cannot be eaten before any eat is performed, it can never be eaten. Same with column. Thus, you can know which columns and which rows you can eat. Just try to eat them all and calculate how many cells you actually eat. Short solution: A row or a column cannot be eaten if it has at least one strawberry. A cell cannot be eaten if both its row and its column cannot be eaten -- otherwise you can eat the row/column and eat it! If there are r' rows that cannot be eaten, and c' columns that cannot be eaten, then there are r' * c' cells that cannot be eaten -- a cell such that both its row and columns cannot be eaten. Since all other cells can be eaten, answer is R * C - r' * c'.
|
[
"brute force",
"implementation"
] | 800
| null |
330
|
B
|
Road Construction
|
A country has $n$ cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two roads. You are also given $m$ pairs of cities — roads cannot be constructed between these pairs of cities.
Your task is to construct the minimum number of roads that still satisfy the above conditions. The constraints will guarantee that this is always possible.
|
Since m < n/2, there exists at least one node that is not incident to any edge. The constraints can be satisfied if and only if the graph is a star graph. We can just create a star graph centered with the node and connect it to all other nodes.
|
[
"constructive algorithms",
"graphs"
] | 1,300
| null |
332
|
A
|
Down the Hatch!
|
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!
Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All $n$ people who came to the barbecue sat in a circle (thus each person received a unique index $b_{i}$ from 0 to $n - 1$). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the $j$-th turn was made by the person with index $b_{i}$, then this person acted like that:
- he pointed at the person with index $(b_{i} + 1) mod n$ either with an elbow or with a nod ($x mod y$ is the remainder after dividing $x$ by $y$);
- if $j ≥ 4$ and the players who had turns number $j - 1$, $j - 2$, $j - 3$, made during their turns the same moves as player $b_{i}$ on the current turn, then he had drunk a glass of juice;
- the turn went to person number $(b_{i} + 1) mod n$.
The person who was pointed on the last turn did not make any actions.
The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.
You can assume that in any scenario, there is enough juice for everybody.
|
Since $n \ge 4$, one Vasya's turn does not affect his other turns. Consequently, you should find just the number of positions (0-indexed) in the given string, which indexes are multiples of $n$ and before which there are at least three same symbols. Asymptotics of the solution - $O(|s|)$
|
[
"implementation"
] | 1,300
|
#include <iostream>
#include <string>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n;
string s;
cin >> n;
getline(cin, s);
getline(cin, s);
int ans = 0;
for (int i = n; i < s.length(); i += n)
if (s[i - 1] == s[i - 2] && s[i - 2] == s[i - 3])
++ans;
cout << ans << endl;
return 0;
}
|
332
|
B
|
Maximum Absurdity
|
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as $n$ laws (each law has been assigned a unique number from 1 to $n$). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.
This time mr. Boosch plans to sign $2k$ laws. He decided to choose \textbf{exactly two} non-intersecting segments of integers from 1 to $n$ of length $k$ and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers $a$, $b$ $(1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k)$ and sign all laws with numbers lying in the segments $[a; a + k - 1]$ and $[b; b + k - 1]$ (borders are included).
As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.
|
Let's build the array of partial sums, which will permit to find the sum in any segment of the array in $O(1)$. Let's iterate through the number $a$ (the left edge of the leftmost segment) in descending order. Now we need to find among segments of length $k$, starting from position which index is greater than or equal to $a + k$, a segment with the maximum sum. Since we search $a$ in descending order, we can maintain this segment during the transition from $a$ to $a - 1$. Asymptotics of the solution - $O(n)$.
|
[
"data structures",
"dp",
"implementation"
] | 1,500
|
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
inline __int64 get_sum(const vector<__int64> &sum, int l, int r)
{
return (l == 0) ? sum[r] : (sum[r] - sum[l - 1]);
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
vector<__int64> a(n), sum(n);
scanf("%I64d", &a[0]);
sum[0] = a[0];
for (int i = 1; i < n; ++i)
{
scanf("%I64d", &a[i]);
sum[i] = sum[i - 1] + a[i];
}
pair<int, int> ans = make_pair(n - 2 * k, n - k);
__int64 ans_sum = get_sum(sum, n - 2 * k, n - k - 1) + get_sum(sum, n - k, n - 1);
pair<int, __int64> suff_max = make_pair(n - k, get_sum(sum, n - k, n - 1));
for (int i = n - 2 * k - 1; i >= 0; --i)
{
__int64 cur = get_sum(sum, i + k, i + 2 * k - 1);
if (cur >= suff_max.second)
suff_max = make_pair(i + k, cur);
cur = get_sum(sum, i, i + k - 1) + suff_max.second;
if (cur >= ans_sum)
{
ans_sum = cur;
ans = make_pair(i, suff_max.first);
}
}
printf("%d %d
", ans.first + 1, ans.second + 1);
return 0;
}
|
332
|
C
|
Students' Revenge
|
A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banning automatic passes and other mean deeds. At last the students decided that she just can't get away with all this anymore...
The students pulled some strings on the higher levels and learned that the next University directors' meeting is going to discuss $n$ orders about the chairperson and accept exactly $p$ of them. There are two values assigned to each order: $a_{i}$ is the number of the chairperson's hairs that turn grey if she obeys the order and $b_{i}$ — the displeasement of the directors if the order isn't obeyed. The students may make the directors pass any $p$ orders chosen by them. The students know that the chairperson will obey exactly $k$ out of these $p$ orders. She will pick the orders to obey in the way that minimizes first, the directors' displeasement and second, the number of hairs on her head that turn grey.
The students want to choose $p$ orders in the way that maximizes the number of hairs on the chairperson's head that turn grey. If there are multiple ways to accept the orders, then the students are keen on maximizing the directors' displeasement with the chairperson's actions. Help them.
|
Let's sort orders ascending $b_{i}$, and by equality of $b_{i}$ - descending $a_{i}$. One can assume that in an optimal solution all the orders obeyed by the chairperson go in the sorted list after orders that she hasn't obeyed (it may be wrong if there are several same orders, but it doesn't affect parameters of an answer). Let's iterate through $i$ - the position of the first order in the sorted list, which the chairperson will obey. To the left of this order we should choose $p - k$ orders which the chairperson won't obey. As we should choose orders with the maximum sum of $b_{i}$, we can just choose $p - k$ orders that immediately precede the $i$-th order. To the right of the $i$-th order we should choose $k - 1$ orders which the chairperson will obey. These orders should have the maximum sum of $a_{i}$. If we iterate $i$ by descending, we can keep these $k - 1$ orders in some data structure that can perform basic operations with sets in logarithmic time (for example, multiset in C++). Asymptotics of the solution - $O(nlogn)$
|
[
"data structures",
"greedy",
"sortings"
] | 2,200
|
#include <iostream>
#include <algorithm>
#include <set>
#include <cstdio>
#include <cassert>
#include <cmath>
using namespace std;
const int MAXN = 100000;
struct Order
{
int a, b, nmb;
} orders[MAXN];
int n, p, k;
multiset<int> s;
__int64 pref[MAXN];
bool cmp1(const Order &x, const Order &y)
{
return x.b < y.b || (x.b == y.b && x.a > y.a);
}
bool cmp2(const Order &x, const Order &y)
{
return x.a > y.a;
}
int main()
{
scanf("%d %d %d", &n, &p, &k);
for (int i = 0; i < n; ++i)
{
scanf("%d %d", &orders[i].a, &orders[i].b);
orders[i].nmb = i + 1;
}
sort(orders, orders + n, cmp1);
pref[0] = orders[0].b;
for (int i = 1; i < n; ++i)
pref[i] = pref[i - 1] + orders[i].b;
__int64 sum = 0;
for (int i = n - 1; i > n - k; --i)
{
sum += orders[i].a;
s.insert(orders[i].a);
}
pair<__int64, __int64> res = make_pair(-1, -1);
int pos = -1;
for (int i = n - k; i >= p - k; --i)
{
__int64 temp = 0;
if (p != k)
temp = (i == p - k) ? pref[i - 1] : pref[i - 1] - pref[i - p + k - 1];
pair<__int64, __int64> cur = make_pair(sum + orders[i].a, temp);
if (cur > res)
{
pos = i;
res = cur;
}
sum += orders[i].a;
s.insert(orders[i].a);
int del = *s.begin();
s.erase(s.begin());
sum -= del;
assert(sum >= 0);
}
sort(orders + pos + 1, orders + n, cmp2);
for (int i = pos - p + k; i <= pos + k - 1; ++i)
printf("%d ", orders[i].nmb);
return 0;
}
|
332
|
D
|
Theft of Blueprints
|
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of $n$ missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos $i$ and $j$ is patrolled by $c_{i, j}$ war droids.
The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any $k$-element set of silos $S$ there is exactly one silo that is directly connected by a passage with each silo from $S$ (we'll call this silo \underline{adjacent with $S$}). Having considered that, the insurgents decided to act as follows:
- they choose a $k$-element set of silos $S$;
- a group of scouts lands from the air into each silo from $S$;
- each group moves along the corresponding passage to the silo, adjacent with $S$ (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints);
- in the silo, adjacent with $S$, the groups get on the ship and fly away.
\underline{The danger of the operation} is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set $S$. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set $S$. Solve this problem to help the insurgents protect the ideals of the Republic!
|
In the problem is given the weighted undirected graph without loops and multiple edges satisfying the following property: for every set $S$ containing $k$ vertices there is exactly one vertex adjacent to all vertices from this set (*) (this vertex is called "adjacent with $S$"). For any $k$-element set of vertices we can calculate the special characteristic: the sum of the weights of edges that connect vertices from $S$ with vertex, adjacent with S. It is required to find the mathematical average of the characteristics of all $k$-element sets of vertices. One can solve this problem using the following fact (the proof is now available only in the Russian version of this post): if $k \ge 3$, only complete graph containing $k + 1$ vertices satisfies the problem statement. For complete graphs answer is equal to doubled sum of weights of all edges, divided by $n$. The same way one can calculate answer if $k = 1$. Now let's consider the case $k = 2$. Let's iterate through the vertex $i$ which is adjacent with our two-element set. Let's write in ascending order all such numbers $j$ that $c_{i, j} \neq - 1$. Any two different vertices of this list form the set for which vertex $i$ is adjacent, and there are no other such sets of vertices. Looking over all pairs of vertices in this list, we can add characteristics of all these sets to the answer. Since it's guaranteed that the graph satisfies the property (*), each pair of vertices will be analyzed only once. A similar approach is used in the validator for this problem. Asymptotics of the solution - $O(n^{2})$.
|
[
"graphs",
"math"
] | 2,400
|
#include <iostream>
#include <vector>
#include <cstdio>
#include <cmath>
using namespace std;
const int MAXN = 2000;
__int64 c[MAXN][MAXN];
int main()
{
int n, k, temp;
scanf("%d %d", &n, &k);
for (int i = 0; i < n - 1; ++i)
{
c[i][i] = -1;
for (int j = i + 1; j < n; ++j)
{
scanf("%d", &temp);
c[j][i] = c[i][j] = temp;
}
}
c[n - 1][n - 1] = -1;
__int64 sum = 0, cnt = 0;
if (k == 1 || (k > 2 && n == k + 1))
{
cnt = n;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (c[i][j] != -1)
sum += c[i][j];
}
if (k == 2)
{
cnt = n * (n - 1) / 2;
vector<int> vect;
for (int i = 0; i < n; ++i)
{
vect.clear();
for (int j = 0; j < n; ++j)
if (c[i][j] != -1)
vect.push_back(j);
for (int j = 0; j < vect.size(); ++j)
for (int z = j + 1; z < vect.size(); ++z)
sum += c[i][vect[j]] + c[i][vect[z]];
}
}
cout << sum / cnt << endl;
return 0;
}
|
332
|
E
|
Binary Key
|
Let's assume that $p$ and $q$ are strings of positive length, called the container and the key correspondingly, string $q$ only consists of characters 0 and 1. Let's take a look at a simple algorithm that extracts message $s$ from the given container $p$:
\begin{verbatim}
i = 0;
j = 0;
s = <>;
while i is less than the length of the string p
{
if q[j] == 1, then add to the right of string s character p[i];
increase variables i, j by one;
if the value of the variable j equals the length of the string q, then j = 0;
}
\end{verbatim}
In the given pseudocode $i$, $j$ are integer variables, $s$ is a string, '=' is an assignment operator, '==' is a comparison operation, '[]' is the operation of obtaining the string character with the preset index, '<>' is an empty string. We suppose that in all strings the characters are numbered starting from zero.
We understand that implementing such algorithm is quite easy, so your task is going to be slightly different. You need to construct the lexicographically minimum key of length $k$, such that when it is used, the algorithm given above extracts message $s$ from container $p$ (otherwise find out that such key doesn't exist).
|
Let's iterate through the number of ones in the key ($cnt$). One can note that $cnt$ can't be large than $min(|s|, k)$, as the keys containing more than $|s|$ ones can't be lexicographically minimal. Let's consider the solution of this problem with the fixed $cnt$. Any complete pass on the key corresponds to the extracting $cnt$ of $k$ scanned symbols of the container, i. e. container is divided into blocks of length $k$, and the message is divided into blocks of length $cnt$ (last blocks may be shorter). We'll number the characters in each block of the message from 0 to $cnt - 1$. We'll call $(q, j)$-suffix suffix of $q$-th block of the message that starts from a position $j$ in this block. Let's solve the problem with dynamic programming: $d_{i, j}$ is true if there exists a key, the first $i$ characters of which are zeros and which corresponds to the extracting from container the string that is the result of concatenation of all $(q, j)$-suffixes of the message. The transitions are based on the filling of i-th position of the key with zero or one (we need to choose the minimum acceptable character). To restore the key you can keep chosen characters for each subtask. Asymptotics of the solution - $O(k \cdot |s|^{2} + |p|)$.
|
[
"dp",
"greedy",
"implementation"
] | 2,400
|
#include <iostream>
#include <string>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
bool d[2050][250];
bool pr[2050][250];
int main()
{
string p, s;
getline(cin, p);
getline(cin, s);
int k;
cin >> k;
string result = "";
for (int cnt = 1; cnt <= min(k, (int)s.length()); ++cnt)
{
if (p.length() / k * cnt > s.length())
break;
d[k][cnt] = true;
for (int j = 0; j < cnt; ++j)
d[k][j] = false;
for (int i = k - 1; i >= 0; --i)
{
d[i][cnt] = true;
pr[i][cnt] = false;
for (int j = cnt - 1; j >= 0; --j)
{
d[i][j] = false;
if (d[i + 1][j])
{
d[i][j] = true;
pr[i][j] = false;
}
else
if (d[i + 1][j + 1])
{
bool yes = true;
for (int cur1 = j, cur2 = i; cur1 < s.length() || cur2 < p.length(); cur1 += cnt, cur2 += k)
if (cur1 >= s.length() || cur2 >= p.length() || s[cur1] != p[cur2])
{
yes = false;
break;
}
if (yes)
{
d[i][j] = true;
pr[i][j] = true;
}
}
}
}
if (!d[0][0])
continue;
string ans;
int j = 0;
for (int i = 0; i < k; ++i)
if (pr[i][j])
{
ans += '1';
++j;
}
else
ans += '0';
if (result == "" || ans < result)
result = ans;
}
if (result == "")
cout << 0 << endl;
else
cout << result << endl;
return 0;
}
|
333
|
A
|
Secrets
|
Gerald has been selling state secrets at leisure. All the secrets cost the same: $n$ marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.
One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?
The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of $n$ marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least $n$ marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.
|
Actually we are looking for longest sequence of natural number $a_{1}, a_{2}, ..., a_{k}$, so that every number in it sequence is the power of three, sum of all numbers is more then $n$ and if we remove any number sum will be less then $n$. To be precise we are looking for length of this sequence. Consider minimal number $a_{i} = A$ in the sequence. All this numbers are divides to $A$ since them all are powers of 3. And then, sum $S$ of all this number is divides to $A$ too. Suppose that $n$ is divide to $A$ too. Then, since $S > n$, then $S - A \ge n$. And then if we remove $A$ from sequence, sum of other number not less then $n$ - contradist with second condition. Well, we now that $n$ is not divide to none element in sequence. Now lets find minimal $k$ so that $n\ \mathrm{\mod\3^{k}\not=0}$, and answer is $\left[{\frac{n}{3^{k}}}\right]$.
|
[
"greedy"
] | 1,600
| null |
333
|
B
|
Chips
|
Gerald plays the following game. He has a checkered field of size $n × n$ cells, where $m$ various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for $n - 1$ minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:
- At least one of the chips at least once fell to the banned cell.
- At least once two chips were on the same cell.
- At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row).
In that case he loses and earns $0$ points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
|
At first lets make two remarks: On every (vertical of horizontal) line we can put only one chip. If there is at least one forbidden cell on the line then we can't put chip on this line. Follow last remark we will avoid hits chip on forbidden cells. Lets avoid ``collisions'' of chips. Lets consider these four line: vertical lines number $i$ and $n + 1 - i$ and horizontal lines with the same numbers. Chips on these lines can collides together, but con't collides to another chip. Therefore we can solve the problem for these four line independently. And finally lets observe that we can put the chip on each of these lines without cillisions as well as on the picture. So, we can iterate all possible fours and put chip on every possible line. And don't fogot about case of two middle line in case of $n$ is odd.
|
[
"greedy"
] | 1,800
| null |
333
|
C
|
Lucky Tickets
|
Gerald has a friend, Pollard. Pollard is interested in lucky tickets (ticket is a sequence of digits). At first he thought that a ticket is lucky if between some its digits we can add arithmetic signs and brackets so that the result obtained by the arithmetic expression was number 100. But he quickly analyzed all such tickets and moved on to a more general question. Now he explores $k$-lucky tickets.
Pollard sais that a ticket is $k$-lucky if we can add arithmetic operation signs between its digits to the left or right of them (i.e., "+", "-", "$ × $") and brackets so as to obtain the correct arithmetic expression whose value would equal $k$. For example, ticket "224201016" is 1000-lucky as $( - 2 - (2 + 4)) × (2 + 0) + 1016 = 1000$.
Pollard was so carried away by the lucky tickets that he signed up for a seminar on lucky tickets and, as far as Gerald knows, Pollard will attend it daily at 7 pm in some famous institute and will commute to it in the same tram for $m$ days. In this tram tickets have eight digits. And Gerald wants to make a surprise for Pollard: each day Pollard will receive a tram $k$-lucky ticket. The conductor has already agreed to give Pollard certain tickets during all these $m$ days and he only wants Gerald to tell him what kind of tickets to give out. In this regard, help Gerald pick exactly $m$ distinct $k$-lucky tickets.
|
In this problem we can find the right amount of lucky tickets. Lets consider amount of different numbers we can get from one four-digit ticket number. It is easy to iterate all this tickets, since it amount only $10^{4}$. It happened that we can get almost 60 numbers from ticket on the average. Suppose we can get number $x$ from ticket $n$. It is clearly that either $x - k \ge 0$ or $k - x \ge 0$. If $k - x \ge 0$ we can write eight-digit ticket number who will have $k - x$ in the first four digits and $n$ in the last four digits. It is clearly that such ticket is $k$-lucky. This method allows us to get almost $600 000$ lucky tickets and it is enough.
|
[
"brute force",
"constructive algorithms"
] | 2,700
| null |
333
|
D
|
Characteristics of Rectangles
|
Gerald found a table consisting of $n$ rows and $m$ columns. As a prominent expert on rectangular tables, he immediately counted the table's properties, that is, the minimum of the numbers in the corners of the table (minimum of four numbers). However, he did not like the final value — it seemed to be too small. And to make this value larger, he decided to crop the table a little: delete some columns on the left and some on the right, as well as some rows from the top and some from the bottom. Find what the maximum property of the table can be after such cropping. Note that the table should have at least two rows and at least two columns left in the end. The number of cropped rows or columns from each of the four sides can be zero.
|
In this problem we must to find maximal value of minimum of values on four intersections of two rows and two columns of table. In another words, we are looking for maximum value of $min(a_{i1, j1}, a_{i1, j2}, a_{i2, j1}, a_{i2, j2})$ for all $i_{1}, i_{2}, j_{1}, j_{2}$ such that $1 \le i_{1}, i_{2} \le n$, $1 \le j_{1}, j_{2} \le m$, $i_{1} \neq i_{2}$, $j_{1} \neq j_{2}$. Lets us binary search of the answer. For us it we must can define is there two rows and two colums with ones on all four its intersections; in other words, integers $i_{1}, i_{2}, j_{1}, j_{2}$ so that $a_{i1, j1} = a_{i1, j2} = a_{i2, j1} = a_{i2, j2} = 1$. Lets consider all pair of natural numbers $(i_{1}, i_{2})$ so that there exist nutural number $j$ so that $a_{i1, j} = a_{i2, j} = 1$. Existence of two equals such pairs is equals to existence of above four numbers. But it is can be only $\frac{n\times(n-1)}{2}$ such pairs. Therefore we can make the array where we will mark pair who were meets. Lets iterate all pairs in any order until we meet repeated pair or pairs are ends. So we have solution of time $O(n^{2}\log(n))$.
|
[
"binary search",
"bitmasks",
"brute force",
"implementation",
"sortings"
] | 2,100
| null |
333
|
E
|
Summer Earnings
|
Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the $n$ options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid.
Help Gerald earn as much as possible.
|
In this problem it is need to draw three circle equals together with maximum possible radius with centers in given points. In another words it is need to find triangle wich minimum side is maximal. Unfortunately solution with bit optimize is not expected for us. Lets call to memory two simple geometric facts. Firstly, sum of alnges of trianle is equals to $180^{\circ}$. Secondly, minimal angle is opposit to minimal side of triangle. Since, at leats one side of angles of triangle not less then $60^{\circ}$ and this anlge is not least one. And side opposite to it is not least side. Therefore, if in $\triangle A B C$ $\angle A B C\geq60^{\circ}$ then $min(|AB|, |BC|, |CA|) = min(|AB|, |BC|)$. And then lets do the follows. Lets iterate apex $B$ and for each $B$ lets find triangle with maximal minimum of sides when $B$ is the apex of triangle and $\angle B\geq60^{\circ}$. For it lets sort all other points by the angle relative to $B$, and for each point $A$ lets find point $C$ most distant to $B$ among such points that $\angle A B C\geq60^{\circ}$. We have to use segment tree for maximum and two pointers or binary searsh to now left and right bound of possible points $C$ during iterating $A$. Finally, we have solution of time $O(n^{2}\log(n))$.
|
[
"binary search",
"bitmasks",
"brute force",
"geometry",
"sortings"
] | 2,500
| null |
334
|
A
|
Candy Bags
|
Gerald has $n$ younger brothers and their number happens to be even. One day he bought $n^{2}$ candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer $k$ from $1$ to $n^{2}$ he has exactly one bag with $k$ candies.
Help him give $n$ bags of candies to each brother so that all brothers got the same number of candies.
|
In this problem one must divide all natural numbers from 1 to $n^{2}$ to groups size of $n$ with the same sums. Lets divide all this numbers to pairs $(1,n^{2}),(2,n^{2}-1),\cdot\cdot\cdot,(\frac{n^{2}}{2},\frac{n^{2}}{2}+1)$. We can to do it since $n$ is even and therefore $n^{2}$ is even too. Then we can just make $n$ groups consists of $\frac{n}{2}$ of these pairs.
|
[
"implementation"
] | 1,000
| null |
334
|
B
|
Eight Point Sets
|
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three integers $x_{1}, x_{2}, x_{3}$ and three more integers $y_{1}, y_{2}, y_{3}$, such that $x_{1} < x_{2} < x_{3}$, $y_{1} < y_{2} < y_{3}$ and the eight point set consists of all points $(x_{i}, y_{j})$ ($1 ≤ i, j ≤ 3$), except for point $(x_{2}, y_{2})$.
You have a set of eight points. Find out if Gerald can use this set?
|
In this problem you must to do only what's written - you must to define does this set of points sutisfies to decribed conditions. There are many ways to define it. For instance: Check if there are exactly 3 discinct $x$'s and $y$'s. One can put all $x$'s to set and then get it size to find amount of distinct $x$'s (as well as $y$'s). Then print ``ugly'' if this amount isn't equals to 3. Finally we have $x_{1}, x_{2}$ and $x_{3}$ as well as $y_{1}, y_{2}$ and $y_{3}$. Now lets check if for every pair $(x_{i}, y_{j})$ (except $(x_{2}, y_{2})$) such point exist in given set of points. But I think that to read editoral of this problem is not good idea. It is better to just look at the implementation.
|
[
"sortings"
] | 1,400
| null |
335
|
A
|
Banana
|
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly $n$ stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length $n$. Piegirl wants to create a string $s$ using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length $n$ for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form $s$. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.
|
Instead of calculating the smallest possible number of sheets given a fixed $n$, let us instead try to compute the smallest possible value of $n$ given a fixed number of sheets. Let $k$ denote the number of sheets. If a particular letter appears $p$ times in $s$, then it must appear at least $ceil(p / k)$ times in the sheet. Thus we can compute the smallest possible value of $n$ by summing $ceil(p / k)$ over all letters. Now the original problem can be solved using binary search on $k$ (or brute force, since the constraints were small enough).
|
[
"binary search",
"constructive algorithms",
"greedy"
] | 1,400
|
from collections import Counter
def main():
s = raw_input().strip()
l = int(raw_input())
d = Counter(s)
if len(d) > l:
print -1
return
lo = 0
hi = 10000
while lo + 1 < hi:
mid = (lo + hi) / 2
c = 0
for x in d.itervalues():
c += (x + mid - 1) / mid
if c > l:
lo = mid
else:
hi = mid
print hi
ans = []
for x in d.iteritems():
ans.append(x[0] * ((x[1] + hi - 1) / hi))
t = ''.join(ans)
if len(t) < l:
t += 'a' * (l - len(t))
print t
main()
|
335
|
B
|
Palindrome
|
Given a string $s$, determine if it contains any palindrome of length exactly $100$ as a \textbf{subsequence}. If it has any, print any one of them. If it doesn't have any, print a palindrome that is a subsequence of $s$ and is as long as possible.
|
There's a well known $O(n^{2})$ solution that allows one to find a longest subsequence of a string which is a palindrome: for every pair of positions $l$ and $r$, such that $l \le r$, find the length $d$ of the longest palindrome subsequence between those positions. d[l][r] = max(d[l][r-1], d[l + 1][r], s[l] == s[r] ? d[l + 1][r - 1] + 1 : 0).There are two ways to solve this problem faster than O($n^{2}$) with the constraints given in the problem: Use dynamic programming. For every position $l$ and length $k$ find the leftmost position $r$, such that there's a palindrome of length $k$ in the substring of $s$ starting at $l$ and ending at $r$. For position $l$ and length $k$ r[l][k] = min(r[l + 1][k], next(r[l + 1][k - 1], s[l])),where next(pos, s) is the next occurrence of character $s$ after position $pos$. Next can be precomputed for all the positions and all the characters in advance. If length is less than 2600, use the well-known O($n^{2}$) dynamic programming approach. Otherwise by pigeonhole principle there's at least one character that appears in the string at least 100 times -- find it and print it 100 times.
|
[
"constructive algorithms",
"dp"
] | 1,900
|
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <set>
#include <queue>
#include <map>
#include <cstdio>
#include <iomanip>
#include <sstream>
#include <iostream>
#include <cstring>
#define REP(i,x,v)for(int i=x;i<=v;i++)
#define REPD(i,x,v)for(int i=x;i>=v;i--)
#define FOR(i,v)for(int i=0;i<v;i++)
#define FORE(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define FOREACH(i,t) FORE(i,t)
#define REMIN(x,y) (x)=min((x),(y))
#define REMAX(x,y) (x)=max((x),(y))
#define pb push_back
#define sz size()
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define IN(x,y) ((y).find((x))!=(y).end())
#define un(v) v.erase(unique(ALL(v)),v.end())
#define LOLDBG
#ifdef LOLDBG
#define DBG(vari) cerr<<#vari<<" = "<<vari<<endl;
#define DBG2(v1,v2) cerr<<(v1)<<" - "<<(v2)<<endl;
#else
#define DBG(vari)
#define DBG2(v1,v2)
#endif
#define CZ(x) scanf("%d",&(x));
#define CZ2(x,y) scanf("%d%d",&(x),&(y));
#define CZ3(x,y,z) scanf("%d%d%d",&(x),&(y),&(z));
#define wez(x) int x; CZ(x);
#define wez2(x,y) int x,y; CZ2(x,y);
#define wez3(x,y,z) int x,y,z; CZ3(x,y,z);
#define SZ(x) int((x).size())
#define ALL(x) (x).begin(),(x).end()
#define tests int dsdsf;cin>>dsdsf;while(dsdsf--)
#define testss int dsdsf;CZ(dsdsf);while(dsdsf--)
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> vi;
template<typename T,typename TT> ostream &operator<<(ostream &s,pair<T,TT> t) {return s<<"("<<t.first<<","<<t.second<<")";}
template<typename T> ostream &operator<<(ostream &s,vector<T> t){s<<"{";FOR(i,t.size())s<<t[i]<<(i==t.size()-1?"":",");return s<<"}"<<endl; }
inline void pisz (int x) { printf("%d\n", x); }
char s[1<<20];
int dp[50002][102];
int ne[222][50002];
char pa[1111];
int main()
{
ios_base::sync_with_stdio(0);
scanf("%s",s);
int n=strlen(s);
FOR(i,n+1)dp[i][0]=i-1;
FOR(i,n+1)dp[i][1]=i;
FOR(c,222)
{
int w=n;
ne[c][n]=n;
REPD(i,n-1,0)
{
if (s[i]==c) w=i;
ne[c][i]=w;
}
}
int mx=1;
REP(d,2,100)
{
dp[n][d]=n;
REPD(i,n-1,0)
{
dp[i][d]=dp[i+1][d];
if (dp[i+1][d-2]<n) REMIN(dp[i][d],ne[s[i]][dp[i+1][d-2]+1]);
}
if (dp[0][d]<n) mx=d;
}
//DBG(mx);
int d=mx;
int x=0;
int cnt=0;
while(d>0)
{
while(dp[x][d]==dp[x+1][d]) x++;
pa[cnt]=pa[mx-cnt-1]=s[x];
x++;
cnt++;
d-=2;
}
pa[mx]=0;
printf("%s\n",pa);
return 0;
}
|
335
|
C
|
More Reclamation
|
In a far away land, there are two cities near a river. One day, the cities decide that they have too little space and would like to reclaim some of the river area into land.
The river area can be represented by a grid with $r$ rows and exactly two columns — each cell represents a rectangular area. The rows are numbered $1$ through $r$ from top to bottom, while the columns are numbered $1$ and $2$.
Initially, all of the cells are occupied by the river. The plan is to turn some of those cells into land one by one, with the cities alternately choosing a cell to reclaim, and continuing until no more cells can be reclaimed.
However, the river is also used as a major trade route. The cities need to make sure that ships will still be able to sail from one end of the river to the other. More formally, if a cell $(r, c)$ has been reclaimed, it is not allowed to reclaim any of the cells $(r - 1, 3 - c)$, $(r, 3 - c)$, or $(r + 1, 3 - c)$.
The cities are not on friendly terms, and each city wants to be the last city to reclaim a cell (they don't care about how many cells they reclaim, just who reclaims a cell last). The cities have already reclaimed $n$ cells. Your job is to determine which city will be the last to reclaim a cell, assuming both choose cells optimally from current moment.
|
The most straightforward way to solve this problem is to use Grundy numbers. Define a segment as a maximal range of rows in which no cells have been reclaimed. Since segments have no bearing on other segments, they can be assigned Grundy numbers. There are 4 types of segments: The entire river. A section of river containing one of the ends. A section of river blocked at both ends in the same column A section of river blocked at both ends in different columns Each time a cell is reclaimed, it splits a segment into 2 segments (one of which may have size 0). We can compute the Grundy value for all possible segments in O($r^{2}$). Then after sorting the reclaimed cells by row number, we can find all segments and compute the Grundy number for the full state. Alternatively, we can compute the result directly. Suppose the game is over. We can determine who won the game just by looking at the top row and the bottom row. Let us define "parity" as the modulo 2 remainder of ($r + n + c0 + c1$), where $c0$ is the column of the reclaimed cell with the lowest row, and $c1$ is the column of the reclaimed cell with the highest row. Claim: when the game is over, the parity is even. This can be seen by observing that the number of empty rows is equal to the number of times the column changes. In other words, if c0==c1, there are an even number of empty rows, otherwise an odd number of empty rows. Now, given r, c0, and c1, we can determine n, and therefore the winner. Let us consider the case where there are no reclaimed cells. If r is even, then the second city can win with a mirroring strategy. When the first city reclaims cell (a,b), the second city follows with (r+1-a,b). Similarly, if r is odd then the first city wins by a mirroring strategy, playing first in ((r+1)/2, 0), and subsequently following the strategy for even r. Now suppose there are reclaimed cells. Let us define $r0$ as the number of empty rows in the segment starting from one end, and $r1$ as the number of empty rows starting from the other end. Case 1: if r0==r1 and the parity is even, the state is losing. All available moves will either decrease r0, decrease r1, or make the parity odd. The other player can respond to the first two types of moves with a mirroring strategy, and the third by making the parity even again (there will always be such a move that doesn't affect r0 or r1, based on the fact that the argument above). Case 2: if abs(r0-r1)>=2 then the state is winning. Suppose, without loss of generality, that r0-r1>=2. Then either of the cells (r1+1, 1) and (r1+1, 2) may be reclaimed, and one of them must lead to Case 1 (since they both result in r0==r1, and one will have even parity and the other odd). Case 3: if abs(r0-r1)<2 and the parity is odd, the state is winning. If r0==r1, then we can change the parity without affecting r0 or r1, leaving our opponent in Case 1. Otherwise, there is a unique move that leaves our opponent in Case 1. (note that cases 2 and 3 together imply that all states with odd parity are winning) Case 4: if abs(r0-r1)==1 and the parity is even, there is at most one move that doesn't leave our opponent in Case 2 or Case 3. Suppose r0==r1+1. We must change either r0 or r1, since all other moves will change the parity to odd. Thus our only option is to decrease r0, since decreasing r1 would leave our opponent in Case 2. We could decrease r0 by 1, but doing so would change the parity. Thus we must decrease r0 by 2, and there is at most one move that does so and keeps the parity even. It follows that if floor(r0/2)+floor(r1/2) is even, then this is a losing position, otherwise a winning position.
|
[
"games"
] | 2,100
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <iostream>
#define pb push_back
#define mp make_pair
#define TASKNAME ""
#ifdef LOCAL
#define eprintf(...) fprintf(stderr,__VA_ARGS__)
#else
#define eprintf(...)
#endif
#define TIMESTAMP(x) eprintf("[" #x "] Time = %.3lfs\n",clock()*1.0/CLOCKS_PER_SEC)
#ifdef linux
#define LLD "%lld"
#else
#define LLD "%I64d"
#endif
#define sz(x) ((int)(x).size())
using namespace std;
typedef long double ld;
typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef pair<int, int> pii;
typedef pair <ll, ll> pll;
const int inf = 1e9;
const double eps = 1e-9;
const double INF = inf;
const double EPS = eps;
int G[110][110][3][3];
bool U[110][210];
bool F[110][3];
int solve (int l, int r, int m1, int m2)
{
if (l>r)
return 0;
if (G[l][r][m1][m2]!=-1)
return G[l][r][m1][m2];
memset(U[r-l],0,sizeof(U[r-l]));
int m3;
for (int x=l; x<=r; x++)
for (int y=0; y<2; y++)
{
if (F[x][0] || F[x][1])
continue;
if ((x!=l && F[x-1][y^1]) || (x==l && m1==(y^1)+1))
continue;
if ((x!=r && F[x+1][y^1]) || (x==r && m2==(y^1)+1))
continue;
m3=y+1;
U[r-l][solve(l,x-1,m1,m3)^solve(x+1,r,m3,m2)]=1;
}
int tmp=0;
while (U[r-l][tmp])
tmp++;
G[l][r][m1][m2]=tmp;
return tmp;
}
int main()
{
int n, m, i, x, y;
#ifdef LOCAL
freopen(TASKNAME".in","r",stdin);
freopen(TASKNAME".out","w",stdout);
#endif
scanf("%d%d", &n, &m);
for (i=0; i<m; i++)
scanf("%d%d", &x, &y), y--, F[x][y]=1;
memset(G,-1,sizeof(G));
(solve(1,n,0,0)==0)?(puts("LOSE")):(puts("WIN"));
TIMESTAMP(end);
return 0;
}
|
335
|
D
|
Rectangles and Square
|
You are given $n$ rectangles, labeled 1 through $n$. The corners of rectangles have integer coordinates and their edges are parallel to the $Ox$ and $Oy$ axes. The rectangles may touch each other, but they do not overlap (that is, there are no points that belong to the interior of more than one rectangle).
Your task is to determine if there's a non-empty subset of the rectangles that forms a square. That is, determine if there exists a subset of the rectangles and some square for which every point that belongs to the interior or the border of that square belongs to the interior or the border of at least one of the rectangles in the subset, and every point that belongs to the interior or the border of at least one rectangle in the subset belongs to the interior or the border of that square.
|
Even though constraints were allowing O(k^2) solutions, in this editorial we will describe an O(n log(n)) solution. This problem has a rather long solution, involving several very different ideas: On the first step, for every rectangle we want to determine, if we were to consider this rectangle as the top left corner of a square, how long could the top and left edge of the square be (see the picture). If there's no rectangle that is adjacent to the current rectangle on the right, which has the same $y1$ coordinate, then the top edge length is just the width of the current rectangle. Otherwise it is the width of the current rectangle plus the max top edge computed for the rectangle adjacent on the right. Left edge length is computed likewise. When top and left edge lengths are computed, we want to compute the max bottom and right edge length if this rectangle was the bottom right corner of the square. On the second step, we want to find all possible square frames. Look at this picture to better understand what we mean by square frame: To find a frame, let's sort all the points first by $x - y$, and then by $x$ (or $y$ -- both will yield the same result). This way all the points are sorted by the diagonal they belong to, and then by the position on that diagonal. Then we will maintain a stack of pairs (position, edge length), where edge length is min(top edge length, left edge length). Position could be either $x$ or $y$ (within a given diagonal relative differences in xs and ys are the same). Min edge length tells us what is the largest square that could start at that position. When we process a new point on a diagonal, first pop from the stack all the pairs such that their position + edge length is less than our position. If stack after that is empty, then the current point cannot be a bottom right corner of any square. If stack is not empty, then there could be some frames with the current point being bottom right corner. Here we need to make a very important observation. If a square frame is contained within some other square frame, we don't need to consider the outer square frame, since if the outer square frame is then proves to be an actual square, then the inner frame also has to be an actual square, and it is enough to only check an inner frame. With this observation made, we can only check if the last point on the stack forms a frame with the current point, there's no need to check any other point on the stack. Since we already know that last element on the stack reaches to the right and to the bottom further than our current position (otherwise we would have popped it from the stack), to see if we form a frame with that point it is enough to check if we can reach that far to the top and to the left. To do so, check, if position of the current point minus min(bottom edge length, right edge length) for the current point is smaller or equal than the position of the point that is at the top of the stack. If it is, we have a square frame. When we have a frame, we move to the third step, where we check if the frame is filled in. To do that we just want to check if area within that square that is filled in by rectangles is equal to the area of the square. For every corner of every rectangle we will compute the area covered by rectangles which are fully located to the left and top from that point. To do that we can sort all the corners by $x$, and then by $y$, and process them one by one. We will maintain an interval tree where value at every position $y$ represents area covered by rectangles processed so far that are fully above $y$. Then when we process a corner, we first update the interval tree if the corner is a bottom right corner, and then query the interval tree to see the area covered by rectangles to the up and left from the current corner. Then, when we have these number precomputed, for every square frame $x1$, $y1$, $x2$, $y2$ we can just get the area for ($x2$, $y2$), add area for ($x1$, $y1$) and subtract for ($x2$, $y1$) and for ($x1$, $y2$). A possible $O(k^{2})$ solution is similar, but makes checking whether or not the frame is filled much and a bunch of other checks easier.
|
[
"brute force",
"dp"
] | 2,400
|
#include <stdio.h>
#include <assert.h>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 100005;
const int maxt = 131072 * 2;
const int rright = 131072;
struct square_t;
int n;
struct point_t
{
point_t(int _x, int _y) : x(_x), y(_y), r(-1), l(-1), t(-1), b(-1) {
for (int i = 0; i < 4; ++ i) sq[i] = NULL;
};
int x, y;
int r, l, t, b, area;
square_t* sq[4];
void updateRightBottom();
void updateLeftTop();
bool operator < (const point_t& other) const
{
if (x - y != other.x - other.y) return x - y < other.x - other.y;
return x < other.x;
}
bool sameDiag(const point_t& other) const
{
return other.x - other.y == x - y;
}
};
point_t* allPoints[maxn * 4]; int numPoints = 0;
map<pair<int, int>, point_t*> pointsMap;
square_t* squares[maxn], *sortedSquares[maxn];
point_t* getPoint(int x, int y, square_t* sq, int ord)
{
if (pointsMap.find(make_pair(x, y)) == pointsMap.end())
{
allPoints[numPoints] = new point_t(x, y);
pointsMap.insert(make_pair(make_pair(x, y), allPoints[numPoints]));
++ numPoints;
}
point_t* p = pointsMap[make_pair(x, y)];
assert(p->sq[ord] == NULL || p->sq[ord] == sq);
p->sq[ord] = sq;
return p;
}
struct square_t
{
square_t(int _x1, int _y1, int _x2, int _y2)
: x1(_x1), x2(_x2), y1(_y1), y2(_y2)
{
assert(x1 < x2);
assert(y1 < y2);
p[0] = getPoint(x1, y1, this, 0);
p[1] = getPoint(x2, y1, this, 1);
p[2] = getPoint(x1, y2, this, 2);
p[3] = getPoint(x2, y2, this, 3);
for (int i = 0; i < 4; ++ i)
{
assert(p[i]->sq[i] == this);
}
}
int area() { return (x2 - x1) * (y2 - y1); }
point_t* p[4]; // UL, UR, BL, BR
int x1, y1, x2, y2;
};
bool cmpPoints(const point_t* a, const point_t* b)
{
return *a < *b;
}
bool cmpForArea(const point_t* a, const point_t* b)
{
if (a->x != b->x) return a->x < b->x;
return a->y < b->y;
}
int area(int x, int y)
{
assert(pointsMap.find(make_pair(x, y)) != pointsMap.end());
return pointsMap[make_pair(x, y)]->area;
}
int t[maxt];
void addt(int pos, int moo) {
pos += rright;
while (pos >= 1) {
t[pos] += moo;
pos /= 2;
}
}
int gett(int pos) {
pos += rright;
int ret = 0;
while (pos >= 1) {
if (pos % 2 == 0) {
ret += t[pos];
-- pos;
}
pos /= 2;
}
return ret;
}
void point_t::updateLeftTop()
{
if (l != -1) return;
if (sq[3] == NULL)
{
l = t = 0;
}
else
{
pointsMap[make_pair(sq[3]->x2, sq[3]->y1)]->updateLeftTop();
pointsMap[make_pair(sq[3]->x1, sq[3]->y2)]->updateLeftTop();
l = sq[3]->x2 - sq[3]->x1 + pointsMap[make_pair(sq[3]->x1, sq[3]->y2)]->l;
t = sq[3]->y2 - sq[3]->y1 + pointsMap[make_pair(sq[3]->x2, sq[3]->y1)]->t;
}
}
void point_t::updateRightBottom()
{
if (r != -1) return;
if (sq[0] == NULL)
{
r = b = 0;
}
else
{
pointsMap[make_pair(sq[0]->x2, sq[0]->y1)]->updateRightBottom();
pointsMap[make_pair(sq[0]->x1, sq[0]->y2)]->updateRightBottom();
r = sq[0]->x2 - sq[0]->x1 + pointsMap[make_pair(sq[0]->x2, sq[0]->y1)]->r;
b = sq[0]->y2 - sq[0]->y1 + pointsMap[make_pair(sq[0]->x1, sq[0]->y2)]->b;
}
}
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; ++ i)
{
int x1, y1, x2, y2;
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
assert(x1 < x2);
assert(y1 < y2);
squares[i] = sortedSquares[i] = new square_t(x1, y1, x2, y2);
}
for (int i = 0; i < n; ++ i) {
squares[i]->p[0]->updateRightBottom();
squares[i]->p[3]->updateLeftTop();
}
sort(allPoints, allPoints + numPoints, cmpForArea);
for (int i = 0; i < numPoints; ++ i)
{
point_t* pt = allPoints[i];
if (pt->sq[3])
{
addt(pt->y, pt->sq[3]->area());
}
pt->area = gett(pt->y);
}
sort(allPoints, allPoints + numPoints, cmpPoints);
int fs = 0;
while (fs < numPoints)
{
int ls = fs;
while (ls < numPoints && allPoints[ls]->sameDiag(*allPoints[fs])) ++ ls;
vector<pair<int, int> > st;
for (int i = fs; i < ls; ++ i)
{
while (st.size() && st.back().second + st.back().first < allPoints[i]->x)
{
st.pop_back();
}
int l = min(allPoints[i]->l, allPoints[i]->t);
int r = min(allPoints[i]->r, allPoints[i]->b);
if (st.size() && allPoints[i]->x - l <= st.back().first)
{
int x1 = st.back().first, y1 = st.back().first - allPoints[i]->x + allPoints[i]->y, x2 = allPoints[i]->x, y2 = allPoints[i]->y;
if (area(x2, y2) - area(x1, y2) - area(x2, y1) + area(x1, y1) == (x2 - x1) * (y2 - y1))
{
vector<int> ans;
for (int i = 0; i < n; ++ i)
{
if (squares[i]->x1 >= x1 && squares[i]->x1 < x2)
if (squares[i]->y1 >= y1 && squares[i]->y1 < y2)
ans.push_back(i);
}
printf("YES %d\n", (int)ans.size());
for (int i = 0; i < ans.size(); ++ i)
printf("%d%c", ans[i]+1, " \n"[i == ans.size() - 1]);
return 0;
}
st.pop_back();
}
st.push_back(make_pair(allPoints[i]->x, r));
}
fs = ls;
}
printf("NO\n");
return 0;
}
|
335
|
E
|
Counting Skyscrapers
|
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between $2$ and $314!$ (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height $i$ having probability $2^{ - i}$ for all positive integers $i$. The floors of a skyscraper with height $i$ are numbered $0$ through $i - 1$.
To speed up transit times, a number of zip lines were installed between skyscrapers. Specifically, there is a zip line connecting the $i$-th floor of one skyscraper with the $i$-th floor of another skyscraper if and only if there are no skyscrapers between them that have an $i$-th floor.
Alice and Bob decide to count the number of skyscrapers.
Alice is thorough, and wants to know exactly how many skyscrapers there are. She begins at the leftmost skyscraper, with a counter at 1. She then moves to the right, one skyscraper at a time, adding 1 to her counter each time she moves. She continues until she reaches the rightmost skyscraper.
Bob is impatient, and wants to finish as fast as possible. He begins at the leftmost skyscraper, with a counter at 1. He moves from building to building using zip lines. At each stage Bob uses the highest available zip line to the right, but ignores floors with a height greater than $h$ due to fear of heights. When Bob uses a zip line, he travels too fast to count how many skyscrapers he passed. Instead, he just adds $2^{i}$ to his counter, where $i$ is the number of the floor he's currently on. He continues until he reaches the rightmost skyscraper.
Consider the following example. There are $6$ buildings, with heights $1$, $4$, $3$, $4$, $1$, $2$ from left to right, and $h = 2$. Alice begins with her counter at $1$ and then adds $1$ five times for a result of $6$. Bob begins with his counter at $1$, then he adds $1$, $4$, $4$, and $2$, in order, for a result of $12$. Note that Bob ignores the highest zip line because of his fear of heights ($h = 2$).
Bob's counter is at the top of the image, and Alice's counter at the bottom. All zip lines are shown. Bob's path is shown by the green dashed line and Alice's by the pink dashed line. The floors of the skyscrapers are numbered, and the zip lines Bob uses are marked with the amount he adds to his counter.
When Alice and Bob reach the right-most skyscraper, they compare counters. You will be given either the value of Alice's counter or the value of Bob's counter, and must compute the expected value of the other's counter.
|
The skyscrapers in this problem depict a data structure called Skip List. Skip list is similar to AVL and red black trees in a sense that it allows O(log N) insertions, deletions and searches (including searching for lower and upper bounds), as well as moving to the next element in sorted order in constant time. Skiplist is different from any tree structures because it has a practical thread safe implementation without locks (so-called lock-free). Lock free skiplists are used as a main data structure to store data in MemSQL, and the algorithm that Bob uses to traverse the skyscrapers is an O(log N) approach, that allows one to estimate the size of the skiplist. Thus, if Bob ended up with an estimation of $n$, the actual skiplist size is expected to be $n$ (so if the first line of the input file is Bob, one just needs to print the number from the second line to the output). Formal proof is rather simple, and is left to the reader. Curiously, the converse does not hold. If the skiplist size is $n$, the expected return value of the estimation algorithm could be bigger than $n$. For an $n$ that is significantly bigger than $2^{h}$ the estimate converges to $n - 1 + 2^{h}$, but this problem included cases with smaller $n$ as well. Let us build up the solution one level at a time. When $H$ is 0, the expected sum is $N$. Now for each additional level, we can add the expected cost of the zip lines on that level, and subtract the expected cost of the zip lines immediately below them. In the end we'll have the total expected cost. For some floor number $H$, let's consider some left and right tower, and determine the probability that a zip line exists between them. Let $L$ be the distance between the two towers. A potential zip line of length $L$ and height $H$ exists if the towers at both ends are tall enough (probability $1 / 2^{H}$ for each one), and the $L - 1$ towers between them are all shorter (probability $1 - 1 / 2^{H}$ for each). Thus the probability that such a zip line exists is $1 / 2^{2 * H} \times (1 - 1 / 2^{H})^{L - 1}$. Now, assuming that such a zip line exists, what's the expected number of zip lines immediately below it? This is simply one more than the number of towers of height $H - 1$. Each of the $L - 1$ towers has probability $1 / (2^{H} - 1)$ of having height H-1 (given that it has height at most H-1) -- use conditional probability ($P(A|B)={\frac{P(A^{\prime})b^{\prime}}{P(B)}}$) to calculate this. Thus the expected number of zip lines immediately below a zip line of length $L$ and height $H$ is $1 + (L - 1) / (2^{H} - 1)$. For each length $L$, there are $N - L$ possible zip lines with this length on each level. We multiply probability by cost for all possible zip lines to attain the expected value. The final answer is therefore $N+\textstyle\sum_{i=1}^{H}\sum_{j=1}^{N}(N-j)\times{\textstyle\frac{1}{2^{2\times t}}}\times(1-{\textstyle\frac{1}{2^{2}}})^{j-1}\times(2^{i}-2^{i-1}\times(1+{\textstyle\frac{j-1}{2^{2-1}}}))$ It turns out the inner loop can be computed using matrix multiplication, for a running time of O(H log N). -- although the constraints is low enough that using matrix multiplication is an overkill -- O(H * N) will do.
|
[
"dp",
"math",
"probabilities"
] | 2,800
|
#include <cstdio>
using namespace std;
int main()
{
char name[9];
int N, H;
while(scanf("%s %d %d", name, &N, &H)!=EOF)
{
if(name[0]=='B'){
printf("%d\n", N);
continue;
}
double res=N;
double ph=.5, pc=.5;
for(int h=1; h<=H; h++){
double pn=.5;
for(int w=0; w<N-1; w++){
res+=(N-1-w)*ph*pn*(1-w*ph/pc);
pn*=1-ph;
}
ph/=2;
pc+=ph;
}
printf("%.9f\n", res);
}
return 0;
}
|
335
|
F
|
Buy One, Get One Free
|
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
|
This problem is equivalent to maximizing the total value of items that we can get for free. First, process the items into <#value, #number_of_items_with_that_value> tuples, which means we have #number_of_items_with_that_value items of value #value. Then, sort the tuples in descending order of #value. Iterate over those tuples and let #pieguy be an empty multi set() For each tuple <#val, #num>, we can calculate #max_free, the maximum number of items (not value) that we can get for free up to this point easily. So, we want to populate #pieguy so that it contains exactly #max_free "things". #pieguy is special, in that we can compute the maximum price that we can get for free for n items by summing up the n most expensive items in #pieguy. How could #pieguy do that? For now, you may assume that each element of #pieguy contains the value of a single item that can be gotten for free. Thus, summing n items = value of n items that can be gotten for free. This is not correct, of course, since not all n arbitrary items can be simultaneously gotten for free in tandem, but we'll come back to it later. We're now at <#val, #num>, and we have #pieguy from previous iteration. #pieguy contains the previous #max_free elements. Assume that #num <= number of items more expensive than this value, for otherwise the remainder are 'dead' and useless for our current purpose. In particular, for the first tuple we process, we assume that #num is 0, since all of them cannot be gotten for free. Suppose we want to obtain exactly #max_free items. How many of the #num must we use? Let's arrange the current members of #pieguy in descending order. For example, if #pieguy has 5 members: A B C D ELet's arrange #num #val under #pieguy so that the rightmost one is located on position #max_free. For example, if #num is 6 and #max_free is 8 and #val is V.... A B C D E V V V V V VThese 6 Vs will be competing for a spot in #pieguy. Now... 1) what happens if C < V? This means, instead of making C free, we can make V free instead! (if you're wondering why this is possible, remember that #pieguy definition I gave you was not entirely honest yet). So, we replace C, D and E with all Vs, and we get our new #pieguy! A B V V V V V V (this should be sorted again, but C++'s multiset does that automagically). 2) otherwise, C > V. So, V cannot contend for the 3-th place in #pieguy, it has to contend for a place larger than or equal to the 4-th. Now the fun begins! If you want to contend for the 4-th place, any solution MUST HAVE AT LEAST 2 V s (remember that the 4-th place is used in a solution consisting of at least 4 free items). In general, if you want to contend for the #max_free - i -th place, you MUST HAVE AT LEAST #num - i Vs. #proof? is easy, exercise (i'm honest!) Okay, so back to contending for the 4-th place. If D is still > V, we proceed. Otherwise, we know that D < V. This means, E and any element after E is also < V! Thus, we can replace all elements after or equal to E with V! The problem would be the final element of #pieguy. When the final element of #pieguy is included in the sum, it is only included in the sum of all n elements of #pieguy. You do this when you want to calculate the maximum sum of values of free items you can get when getting exactly #max_free items. Any such solution must include all #num elements with value #val. We have included #num-2 Vs in #pieguy. Thus, the final element of #pieguy must somehow contains 2 Vs! So, elements of #pieguy actually can do this. Instead of containing a single elmeent, each element of #pieguy is more of an "operation" that adds several value and removes several value. In our case, we want to add 2 Vs and remove something. The something? The smallest element that we can remove (the ones that we haven't removed)! C! (if you're wondering why not D or E, it's because (again) #pieguy is special -- it only forms a solution if the most expensive t are summed, not if some are skipped. -- we cannot skip C if we want to use D). So, Insert 2V - C into #pieguy, and the rest, insert V into #pieguy. 2V - C is < V, so summing all elements of #pieguy correctly found out the max value when we receive #max_free free items! Right! Cool! ...except that 2V - C can be negative. Why would we want to insert negative stuffs into #pieguy? We don't! Actually, we check if 2V - C is negative. If it is, we continue instead, and check 3V - C - D and so on, under the same reason. That's it folks! I skipped some details of why this works (for example, that the number of V selected is always sufficient to guarantee solution in #pieguy), but they're easier to see once you get this large idea. The result is then #pieguy.last_element
|
[
"dp",
"greedy"
] | 3,000
|
#include <cstdio>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
int N;
scanf("%d", &N);
long long basecost=0;
map<int, int> vals;
for(int i=0; i<N; i++){
int val;
scanf("%d", &val);
vals[val]++;
basecost+=val;
}
multiset<int> freed;
int total=0;
for(map<int, int>::reverse_iterator it=vals.rbegin(); it!=vals.rend(); it++){
int val=it->first;
int count=it->second;
int maxadd=min(count, total);
int nextsize=min(min((int)freed.size()+count, total), (total+count)/2);
int remove=maxadd-(nextsize-freed.size());
multiset<int>::iterator pos=freed.begin();
for(int i=0; i<remove; i++)
pos++;
vector<int> removed(freed.begin(), pos);
reverse(removed.begin(), removed.end());
freed.erase(freed.begin(), pos);
int toadd=nextsize-freed.size();
vector<int> add(toadd, val);
if((total+maxadd)&1){
add.push_back(0);
toadd++;
}
for(int i=0; i<remove; i++)
if(removed[i]>add[i]){
add[i]=removed[i];
add[toadd-i-1]-=removed[i]-val;
}
while(add.size() && add.back()<=0)
add.pop_back();
freed.insert(add.begin(), add.end());
total+=count;
}
printf("%I64d\n", basecost-accumulate(freed.begin(), freed.end(), 0ll));
}
|
336
|
A
|
Vasily the Bear and Triangle
|
Vasily the bear has a favorite rectangle, it has one vertex at point $(0, 0)$, and the opposite vertex at point $(x, y)$. Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point $B = (0, 0)$. That's why today he asks you to find two points $A = (x_{1}, y_{1})$ and $C = (x_{2}, y_{2})$, such that the following conditions hold:
- the coordinates of points: $x_{1}$, $x_{2}$, $y_{1}$, $y_{2}$ are integers. Besides, the following inequation holds: $x_{1} < x_{2}$;
- the triangle formed by point $A$, $B$ and $C$ is rectangular and isosceles ($\angle A B C$ is right);
- all points of the favorite rectangle are located inside or on the border of triangle $ABC$;
- the area of triangle $ABC$ is as small as possible.
Help the bear, find the required points. It is not so hard to proof that these points are unique.
|
$val = |x| + |y|$. Then first point is $(val * sign(x), 0)$, second - $(0, val * sign(y))$. Swap points if needed according to statement. Let's see why this is the answer. Conditions $x \neq 0$ and $y \neq 0$ give us that one point is on X-axis, and the other on Y-axis. Let's see how it works for $x > 0$ and $y > 0$. Other cases can be proved in similar way. We need to show, that $(x, y)$ belongs to our triangle(including it's borders). In fact $(x, y)$ belongs to segment, connecting $(x + y, 0)$ with $(0, x + y)$. Line through $(x + y, 0)$ and $(0, x + y)$ is $Y = - X + x + y$. Using coordinates $(x, y)$ in this equation proves the statement.
|
[
"implementation",
"math"
] | 1,000
|
#include <cstdio>
#include <utility>
#include <cmath>
using namespace std;
int sgn(int x) {
if (x > 0) return 1;
if (x == 0) return 0;
return -1;
}
int main() {
int x, y;
scanf("%d %d", &x, &y);
int v = abs(x) + abs(y);
pair<int,int> f = make_pair(v * sgn(x), 0);
pair<int,int> s = make_pair(0, v * sgn(y));
if (f.first > s.first)
swap(f, s);
printf("%d %d %d %d\n", f.first, f.second, s.first, s.second);
}
|
336
|
B
|
Vasily the Bear and Fly
|
One beautiful day Vasily the bear painted $2m$ circles of the same radius $R$ on a coordinate plane. Circles with numbers from $1$ to $m$ had centers at points $(2R - R, 0)$, $(4R - R, 0)$, $...$, $(2Rm - R, 0)$, respectively. Circles with numbers from $m + 1$ to $2m$ had centers at points $(2R - R, 2R)$, $(4R - R, 2R)$, $...$, $(2Rm - R, 2R)$, respectively.
Naturally, the bear painted the circles for a simple experiment with a fly. The experiment continued for $m^{2}$ days. Each day of the experiment got its own unique number from $0$ to $m^{2} - 1$, inclusive.
On the day number $i$ the following things happened:
- The fly arrived at the coordinate plane at the center of the circle with number $v=\lfloor{\frac{b}{m}}\rfloor+1$ ($\left\lfloor{\frac{x}{y}}\right\rfloor$ is the result of dividing number $x$ by number $y$, rounded down to an integer).
- The fly went along the coordinate plane to the center of the circle number $u=m+1+(i\mod m)$ ($x\ {\mathrm{mod}}\ y$ is the remainder after dividing number $x$ by number $y$). The bear noticed that the fly went from the center of circle $v$ to the center of circle $u$ along the shortest path with all points lying on the border or inside at least one of the $2m$ circles. After the fly reached the center of circle $u$, it flew away in an unknown direction.
Help Vasily, count the average distance the fly went along the coordinate plane during each of these $m^{2}$ days.
|
Also you could iterate circles, adding distance for each of them and dividing by $m^{2}$ in the end. Let's see how the $i$-th iteration works $1 \le i \le m$. Distance to $m + i$-th circle is $2R$. Distance to $m + j$-th circle, where $|j - i| = 1$, is $R(2+{\sqrt{2}})$. For other circles it's quite simple to calculate sum of distances. There are $i - 2$ circles which located to the left of current circle. So, sum of distances for these circles is $R(i-2)(i-1)+2R{\sqrt{2}}(i-2)$. In the same manner we can calculate answer for cirlcles which are located to the right of the current circle
|
[
"math"
] | 1,900
|
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;
int main() {
int m, r;
scanf("%d%d", &m, &r);
double result = 0;
for (int i = 0; i < m; ++i) {
result += 2;
if (i > 0) result += (2 + sqrt(2.));
if (i + 1 < m) result += (2 + sqrt(2.));
if (i > 0) {
double v = i - 1;
result += v * (v + 1);
result += 2. * sqrt(2.) * v;
}
if (i + 1 < m) {
double v = m - 2 - i;
result += v * (v + 1);
result += 2. * sqrt(2.) * v;
}
}
printf("%.10lf\n", result * r / m / m);
return 0;
}
|
336
|
C
|
Vasily the Bear and Sequence
|
Vasily the bear has got a sequence of positive integers $a_{1}, a_{2}, ..., a_{n}$. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum.
The beauty of the written out numbers $b_{1}, b_{2}, ..., b_{k}$ is such maximum non-negative integer $v$, that number $b_{1}$ $and$ $b_{2}$ $and$ $...$ $and$ $b_{k}$ is divisible by number $2^{v}$ without a remainder. If such number $v$ doesn't exist (that is, for any non-negative integer $v$, number $b_{1}$ $and$ $b_{2}$ $and$ $...$ $and$ $b_{k}$ is divisible by $2^{v}$ without a remainder), the beauty of the written out numbers equals -1.
Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.
Here expression $x$ $and$ $y$ means applying the bitwise AND operation to numbers $x$ and $y$. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".
|
Let's check max beauty from 29 to 0. For every possible beauty $i$ our aim is to find largest subset with such beauty. We will include in this subset all numbers, that have $1$ at $i$-th bit. After that we do bitwise $and$ as in statement, and if the resulting value is divisible by $2^{i}$, then there is the answer. Solution works in $O(n)$.
|
[
"brute force",
"greedy",
"implementation",
"number theory"
] | 1,800
|
#include <cstdio>
#include <vector>
#include <cassert>
using namespace std;
vector < int > a, cur, ans;
int n, curb, bestb;
int main(){
scanf("%d", &n); a.resize(n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int bit = 0; bit < 31; bit++) {
int totalAnd = (1<<30) - 1;
cur.clear();
for(int i = 0; i < n; i++) {
if ((a[i] & (1<<bit))) cur.push_back(a[i]), totalAnd &= a[i];
}
if ((totalAnd % (1<<bit)) == 0) ans = cur;
}
printf("%d\n", ans.size());
for(int i = 0; i < ans.size(); i++)
printf("%d%c", ans[i], " \n"[i == (ans.size() - 1)]);
}
|
336
|
D
|
Vasily the Bear and Beautiful Strings
|
Vasily the Bear loves beautiful strings. String $s$ is beautiful if it meets the following criteria:
- String $s$ only consists of characters $0$ and $1$, at that character $0$ must occur in string $s$ exactly $n$ times, and character $1$ must occur exactly $m$ times.
- We can obtain character $g$ from string $s$ with some (possibly, zero) number of modifications. The character $g$ equals either zero or one.
A modification of string with length at least two is the following operation: we replace two last characters from the string by exactly one other character. This character equals one if it replaces two zeros, otherwise it equals zero. For example, one modification transforms string "01010" into string "0100", two modifications transform it to "011". It is forbidden to modify a string with length less than two.
Help the Bear, count the number of beautiful strings. As the number of beautiful strings can be rather large, print the remainder after dividing the number by $1000000007$ $(10^{9} + 7)$.
|
$any$ - random binary string, $s + g$ - concatenation of strings, $MOD = 1000000007$. String $1 + any$ always transforms into $0$, string $1$ - into $1$. String $01 + any$ always transforms into $1$, string $01$ - into $0$. String $001 + any$ transforms into $0$, string $001$ - into $1$, and so on. Using these facts let's consider following solution. Cases like strings without ones or zeroes are easy. For every $i$ (in zero-based numbering) let's assume that it is position of the first occurence of $1$ in our string. Using already known facts we can understand what is the final result of transformations for such string. If the result equals to $g$, we add $C(cnt[0] + cnt[1] - i - 1, cnt[1] - 1)$ to the answer. Calculation of binomial coefficients is following: $fact[i] = i!%MOD$, $\forall i\leq200000$, $C(n, k) = fact[n]inv(fact[n - i]fact[i])$, where $inv(a)$ - inverse element modulo $MOD$. $inv(a) = a^{MOD - 2}$, because $MOD$ is prime number.
|
[
"combinatorics",
"math",
"number theory"
] | 2,100
|
#include <iostream>
using namespace std;
const int N = 2000000, mod = 1000000007;
int cnt[2], target;
long long fact[N];
#define forn(i,n) for(int i = 0; i < (int) n; i++)
#define sz(a) (int)(a).size()
inline bool read() {
return (cin >> cnt[0] >> cnt[1] >> target);
}
inline long long bpow(long long v, int power) {
if (power == 0) return 1;
if ((power & 1) == 0) {
long long r = bpow(v, power >> 1);
return (r * r) % mod;
}
return (bpow(v, power - 1) * v) % mod;
}
inline int getC(int n, int k) {
long long nom = fact[n];
long long den = (fact[n-k] * fact[k]) % mod;
return (nom * bpow(den, mod - 2)) % mod;
}
int calculate() {
if (cnt[1] == 0) {
if (cnt[0] % 2 != target)
return 1;
else
return 0;
}
if (cnt[0] == 0) {
if (cnt[1] > 1) {
if (target == 0)
return 1;
else
return 0;
} else {
if (target == 1)
return 1;
else
return 0;
}
}
int answer = 0;
for(int i = 0; i <= cnt[0]; i++) {
int total = cnt[0] + cnt[1] - 1 - i;
if (total > 0) {
if (i % 2 == target) {
answer += getC(total, cnt[1] - 1);
if (answer >= mod) answer -= mod;
}
} else {
if (i % 2 != target) {
answer += getC(total, cnt[1] - 1);
if (answer >= mod) answer -= mod;
}
}
}
return answer;
}
inline void solve() {
fact[0] = 1;
forn(i, N) {
if (!i) continue;
fact[i] = (fact[i-1] * i) % mod;
}
cout << calculate() << endl;
}
int main() {
while (read())
solve();
}
|
336
|
E
|
Vasily the Bear and Painting Square
|
Vasily the bear has two favorite integers $n$ and $k$ and a pencil. Besides, he's got $k$ jars with different water color paints. All jars are numbered in some manner from $1$ to $k$, inclusive. The jar number $i$ contains the paint of the $i$-th color.
Initially the bear took a pencil and drew four segments on the coordinate plane. All of them end at point $(0, 0)$. They begin at: $(0, 2^{n})$, $(0, - 2^{n})$, $(2^{n}, 0)$, $( - 2^{n}, 0)$. Then for each $i = 1, 2, ..., n$, the bear drew two squares. The first square has the following vertex coordinates: $(2^{i}, 0)$, $( - 2^{i}, 0)$, $(0, - 2^{i})$, $(0, 2^{i})$. The second square has the following vertex coordinates: $( - 2^{i - 1}, - 2^{i - 1})$, $( - 2^{i - 1}, 2^{i - 1})$, $(2^{i - 1}, - 2^{i - 1})$, $(2^{i - 1}, 2^{i - 1})$. After that, the bear drew another square: $(1, 0)$, $( - 1, 0)$, $(0, - 1)$, $(0, 1)$. All points mentioned above form the set of points $A$.
{\scriptsize The sample of the final picture at $n = 0$}
{\scriptsize The sample of the final picture at $n = 2$}
The bear decided to paint the resulting picture in $k$ moves. The $i$-th move consists of the following stages:
- The bear chooses 3 distinct points in set $А$ so that any pair of the chosen points has a segment on the picture between them. The chosen points and segments mark the area that mustn't contain any previously painted points.
- The bear paints the area bounded by the chosen points and segments the $i$-th color.
Note that after the $k$-th move some parts of the picture can stay unpainted.
The bear asked you to calculate, how many distinct ways there are to paint his picture. A way to paint the picture is a sequence of three-element sets of points he chose on each step. Two sequences are considered distinct if there is such number $i$ ($1 ≤ i ≤ k)$, that the $i$-th members of these sequences do not coincide as sets. As the sought number can be rather large, you only need to calculate the remainder after dividing it by number $1000000007$ ($10^{9} + 7$).
|
Pretty tough problem. Consider following DP $dp[lvl][op][cur][type]$ - number of ways to take $op$ triangles, if we have $2lvl + 1$ squares. $cur, type$ - auxiliary values. Answer will be $dp[n][k][0][2]k!$. $type$ means type of transitions we make. $cur$ - amount of used quarters ($cur = 4$ - 2 quarters, $cur < 4$ - $cur$ quarters). It is important to distinguish $cur = 2$ from $cur = 4$, because amount of consecutive pairs of unused quarters is different. About transitions. $type = 2.$ Iterate amount of pairs (considering $cur$) of consecutive quarters that we will take. It is important for them to have no common quarters. We can get two pairs only in case $cur = 0$. Let's also take some quarters that are not in pairs. Calculate number of ways to select corresponding triangles and add to the current DP-state value $dp[lvl][op - choosen][newcur][1] * cntwaystochoose$. For better understanding of $type = 2$ check my solution ($calc(n, k, cur, type) - isfordp[n][k][cur][type]$). $type = 1$. Now we take triangles at the borders (number of squares is 2*lvl + 1). "at the borders" means marked X, see the picture. Iterate amount of pairs (considering $cur$) of consecutive triangles we take. It is important for pairs to have no common triangles. Let's also take some triangles that are not in pairs. Calculate number of ways to select corresponding triangles and add to the current DP-state value $dp[lvl][op - choosen][cur][0] * cntwaystochoose$. $type = 0$. We take triangles at the borders (number of squares is 2*lvl). "at the borders" means marked X, see the picture. Take some triangles, not in pairs. Calculate number of ways to select corresponding triangles and add to current DP-state value $dp[lvl - 1][op - choosen][cur][2] * cntwaystochoose$. Starting values: $dp[0][0][cur][1] = 1$, $dp[0][cnt][cur][1] = 0$, $cnt > 0$.
|
[
"bitmasks",
"combinatorics",
"dp",
"implementation"
] | 2,700
|
#include <stdio.h>
#include <memory.h>
const int MOD = 1000000007, N = 205, K = 10;
int dp[N][N][5][3], C[K][K], con[5], get[5], fact = 1, n, k;
inline void add(int &v1, int v2) {
v1 += v2;
if (v1 >= MOD)
v1 -= MOD;
}
inline int mul(int v1, int v2) {
long long res = v1;
res *= v2;
return (res % MOD);
}
int calc(int level, int operations, int cur, int type) {
int &ans = dp[level][operations][cur][type];
if (ans != -1)
return ans;
ans = 0;
if (type == 0) {
int bits = get[cur];
for(int i = 0; (i <= bits) && (i <= operations); i++)
add(ans, mul(calc(level - 1, operations - i, cur, 2), C[bits][i]));
}
if (type == 1) {
if (level == 0) {
if (operations == 0)
return ans = 1;
else
return ans = 0;
}
int bits = get[cur];
bits <<= 1;
int cons = con[cur];
for(int i = 0; (i <= cons) && (i <= operations); i++)
for(int j = 0; (j <= (bits - 2 * i)) && (j <= (operations - i)); j++)
add(ans, mul(calc(level, operations - i - j, cur, 0), mul(C[cons][i], C[bits - 2 * i][j])));
}
if (type == 2) {
add(ans, calc(level, operations, cur, 1));
if (cur == 0) {
if (operations >= 1) {
add(ans, mul(calc(level, operations - 1, 1, 1), 4));
add(ans, mul(calc(level, operations - 1, 2, 1), 4));
}
if (operations >= 2) {
add(ans, mul(calc(level, operations - 2, 4, 1), 2));
add(ans, mul(calc(level, operations - 2, 2, 1), 4));
add(ans, mul(calc(level, operations - 2, 3, 1), 8));
if (operations == 2)
add(ans, 2);
}
if (operations >= 3) {
add(ans, mul(calc(level, operations - 3, 3, 1), 4));
if (operations == 3)
add(ans, 4);
}
if (operations == 4)
add(ans, 1);
}
if (cur == 1) {
if (operations >= 1) {
add(ans, calc(level, operations - 1, 4, 1));
add(ans, mul(calc(level, operations - 1, 2, 1),2));
add(ans, mul(calc(level, operations - 1, 3, 1),2));
}
if (operations >= 2) {
if (operations == 2)
add(ans, 2);
add(ans, mul(calc(level, operations - 2, 3, 1), 3));
}
if (operations == 3)
add(ans, 1);
}
if (cur == 2) {
if (operations >= 1) {
add(ans, mul(calc(level, operations - 1, 3, 1), 2));
if (operations == 1)
add(ans, 1);
}
if (operations == 2)
add(ans, 1);
}
if (cur == 3 && operations == 1)
add(ans, 1);
if (cur == 4) {
if (operations >= 1) add(ans, mul(calc(level, operations - 1, 3, 1), 2));
if (operations == 2)
add(ans, 1);
}
}
return ans;
}
int main() {
get[0] = 4; con[0] = 4;
get[1] = 3; con[1] = 2;
get[2] = 2; con[2] = 1;
get[3] = 1; con[3] = 0;
get[4] = 2; con[4] = 0;
for(int i = 0; i < K; i++) {
C[i][0] = 1;
for(int j = 1; j <= i; j++)
add(C[i][j], C[i - 1][j]), add(C[i][j], C[i - 1][j - 1]);
}
memset(dp, -1, sizeof dp);
scanf("%d %d", &n, &k);
for(int i = 1; i <= k; i++) fact = mul(fact, i);
printf("%d\n", mul(fact,calc(n, k, 0, 2)));
}
|
337
|
A
|
Puzzles
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her $n$ students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are $m$ puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of $f_{1}$ pieces, the second one consists of $f_{2}$ pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let $A$ be the number of pieces in the largest puzzle that the teacher buys and $B$ be the number of pieces in the smallest such puzzle. She wants to choose such $n$ puzzles that $A - B$ is minimum possible. Help the teacher and find the least possible value of $A - B$.
|
First, let's sort the numbers f[i] in ascending order. Now assume that the smallest jigsaw puzzle which the teacher purchases consists of f[k] pieces. Obviously, she should buy the smallest n puzzles which are of size f[k] or greater to minimize the difference. These are the puzzles f[k], f[k+1], ..., f[k+n-1] (this is not correct when f[i] are not distinct and f[k]=f[k-1], but such cases can be skipped). The difference between the greatest and the least size of the puzzles in such set is f[k+n-1]-f[k]. To choose the optimal f[k], we can test every k between 1 and m-n and pick the one producing the least difference. The full algorithm is as follows:
|
[
"greedy"
] | 900
| null |
337
|
B
|
Routine Problem
|
Manao has a monitor. The screen of the monitor has horizontal to vertical length ratio $a$:$b$. Now he is going to watch a movie. The movie's frame has horizontal to vertical length ratio $c$:$d$. Manao adjusts the view in such a way that the movie preserves the original frame ratio, but also occupies as much space on the screen as possible and fits within it completely. Thus, he may have to zoom the movie in or out, but Manao will always change the frame proportionally in both dimensions.
Calculate the ratio of empty screen (the part of the screen not occupied by the movie) to the total screen size. Print the answer as an irreducible fraction $p / q$.
|
Suppose that the width and height of the screen are W and H correspondingly. Since W:H = a:b, we have H=W*b/a. Similarly, the width and height of the film frame w and h are related as h=w*d/c. Imagine that Manao stretches/constricts the frame until it fits the screen horizontally or vertically, whichever happens first. There are three cases to consider: the horizontal to vertical ratio of the screen is less, equal or more than the corresponding ratio of the frame. In the first case (a/b < c/d) the stretching process ends when the frame reaches the same width as the screen. That is, the frame will enlarge in W/w times and its new width will be W. Thus, its new height is h*W/w = w*c/d * W/w = W*d/c. We are interested in the ratio of unoccupied portion of the screen to its full size, which is (screen height - frame height) / (screen height) = (W*b/a - W*d/c) / (W*b/a) = (bc-ad)/bc. In the second case (a/b > c/d) the process ends when the frame reaches the same height as the screen. Its height will become H and its width will become w*H/h = w * W*b/a / (w*d/c) = W*b/a * c/d. The unoccupied portion of the screen's horizontal is (W - W*b/a * c/d)/W = (ad-bc)/ad. In the third case, the frame fills the screen entirely and the answer will be 0. All that's left is to print the answer as an irreducible fraction. We need to find the greatest common divisor of its nominator and denominator for this. It can be done using Euclidean algorithm or just through trial division by every number from 1 to q. Since q is no more than a product of two numbers from the input and these numbers are constrained by 1000, we need to try at most million numbers in the worst case.
|
[
"greedy",
"math",
"number theory"
] | 1,400
| null |
337
|
C
|
Quiz
|
Manao is taking part in a quiz. The quiz consists of $n$ consecutive questions. A correct answer gives one point to the player. The game also has a counter of consecutive correct answers. When the player answers a question correctly, the number on this counter increases by 1. If the player answers a question incorrectly, the counter is reset, that is, the number on it reduces to 0. If after an answer the counter reaches the number $k$, then it is reset, and the player's score is doubled. Note that in this case, first 1 point is added to the player's score, and then the total score is doubled. At the beginning of the game, both the player's score and the counter of consecutive correct answers are set to zero.
Manao remembers that he has answered exactly $m$ questions correctly. But he does not remember the order in which the questions came. He's trying to figure out what his minimum score may be. Help him and compute the remainder of the corresponding number after division by $1000000009$ $(10^{9} + 9)$.
|
Assume that Manao has doubled his score (i.e. gave k consecutive correct answers) exactly X times. Then the least possible score is obtained when this doublings happen in the beginning of the game, i.e., when he answers the first X*k questions and never manages to answer k consecutive questions after that. The correctness of this statement follows from the following: for any other scenario with X doublings, all of these doublings can be moved into the beginning and the total score will not increase. Hence, for X=1 Manao's minimum score is k*2+m-k: he answers k consecutive questions, the score doubles, then he answers m-k questions. For X=2 the minimum possible score is (k*2+k)*2+m-2*k, for X=3 - ((k*2+k)*2+k)*2+m-3*k. For the general case, a formula (2^1+2^2+...+2^X)*k + m-X*k = (2^(X+1)-2)*k + m-X*k is derived. The abovementioned observation shows that the minimum score grows monotonically when X is increased, so all we need is to find the minimum feasible X. It should satisfy the inequalities X*k <= n and X + (n - n mod k) / k * (k-1) + n mod k >= m. More on the second inequality: Manao answered the first X*k questions, thus there are n-X*k left. Now he can answer at most k-1 question from each k questions. If k divides n-X*k (which is the same as k divides n), the inequality becomes X*k + (n-X*k) / k * (k-1) >= m, but the remainder complicates it a bit: X*k + (n - X*k - (n - X*k) mod k) / k * (k-1) + (n - X*k) mod k >= m. This formula can be simplified to the one written earlier. So, the minimum X is equal to max(0, m - (n - n mod k) / k * (k-1) - n mod k). You'll need exponentiation by squaring to compute the score corresponding to this value of X. Thus, the overall complexity of this solution is O(log(n)).
|
[
"binary search",
"greedy",
"math",
"matrices",
"number theory"
] | 1,600
| null |
337
|
D
|
Book of Evil
|
Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains $n$ settlements numbered from 1 to $n$. Moving through the swamp is very difficult, so people tramped exactly $n - 1$ paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to reach any settlement from any other one by traversing one or several paths.
The distance between two settlements is the minimum number of paths that have to be crossed to get from one settlement to the other one. Manao knows that the Book of Evil has got a damage range $d$. This means that if the Book of Evil is located in some settlement, its damage (for example, emergence of ghosts and werewolves) affects other settlements at distance $d$ or less from the settlement where the Book resides.
Manao has heard of $m$ settlements affected by the Book of Evil. Their numbers are $p_{1}, p_{2}, ..., p_{m}$. Note that the Book may be affecting other settlements as well, but this has not been detected yet. Manao wants to determine which settlements may contain the Book. Help him with this difficult task.
|
Obviously, in graph theory language our problem is: given a tree with n vertices, m of which are marked, find the number of vertices which are at most distance d apart from each of the marked vertices. Let us hang the tree by some vertex r, that is, assume that it is a rooted tree with root in vertex r. Let us also rephrase the condition imposed on sought vertices: we need to count such vertices v that the maximum distance from v to a marked vertex is at most d. For any inner vertex v, the marked vertex which is the farthest from it is either in the subtree of v or outside it - in the latter case the path from v to the farthest marked vertex traverses the parent of v. Using this observation, we can recompute the distances to the farthest marked vertices when transiting from a vertex to its child. First, we will compute the distance from every vertex v to the farthest marked vertex within the subtree of v. Let us call this distance distDown[v]. The values of distDown[] can be computed in a single depth-first search: for each leaf of the tree this distance is either 0 (when the leaf is marked) or nominal negative infinity (when the leaf is not marked), and for each inner vertex v distDown[v]=max(distDown[child1], distDown[child2], ..., distDown[childK])+1, where childi are the children of v. Now we will compute the distances from each vertex to the farthest marked vertex outside its subtree. Let's denote this distance with distUp[v]. We will use DFS again to compute values of distUp[]. For the root, distUp[r] is equal to nominal negative infinity, and for any other vertex v there are two cases: either the farthest marked vertex is located in the subtree of v-s parent p, or it is even "farther", i.e., the path to it traverses vertex p-s parent. In the first case, the distance from v to such vertex is equal to max(distDown[sibling1], ..., distDown[siblingK])+2, where siblingi are the brothers (other children of the parent) of vertex v. In the second case, it is equal to distUp[p]+1. Thus, distUp[v] is equal to the maximum of these two values. Note that you need to be clever to perform the computations in the first case in overall linear time. For this, you can find the maximum max1 and second maximum max2 of values distDown[sibling1], ..., distDown[siblingK]. After that, when distDown[v] < max1, we have max(distDown[sibling1], ..., distDown[siblingK])=max1, otherwise we have distDown[v] = max1 and max(distDown[sibling1], ..., distDown[siblingK])=max2. After computing distDown[] and distUp[], it is easy to derive the answers: it is the count of such vertices v that distDown[v] <= d && distUp[v] <= d.
|
[
"dfs and similar",
"divide and conquer",
"dp",
"trees"
] | 2,000
| null |
337
|
E
|
Divisor Tree
|
A divisor tree is a rooted tree that meets the following conditions:
- Each vertex of the tree contains a positive integer number.
- The numbers written in the leaves of the tree are prime numbers.
- For any inner vertex, the number within it is equal to the product of the numbers written in its children.
Manao has $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$. He tries to build a divisor tree which contains each of these numbers. That is, for each $a_{i}$, there should be at least one vertex in the tree which contains $a_{i}$. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.
|
Let us first show that in an optimal divisor tree only the root or a leaf can hold a value other than one of a[i]. Suppose that we have an inner vertex different from the root which holds a number X not equal to any of a[i]. Then we can exclude this vertex from the tree and tie its children to its parent without violating any of the tree's properties. Hence, our tree consists of the root, vertices with numbers a[i] tied to each other or to the root, and leaves, which are tied to vertices with numbers a[i] and contain these numbers' prime factorizations. The exception is the case when one of a[i] is written in root itself, and the case when some a[i]-s are prime themselves. Also note that in general case it's easy to count how many leaves the tree will have. This count is equal to the sum of exponents of primes in prime factorizations of those a[i]-s which are the children of the root. Since N <= 8, we can build all divisor trees which satisfy the observations we made. Let's sort numbers a[i] in descending order and recursively choose a parent for each of them from the vertices already present in the tree. Of course, tying a number X to some vertex v is only possible if the product of X and the numbers in children of v divides the number in v itself. For a[1], we have a choice - we can make it the root of the tree or a child of the root (in this case the root will hold a nominal infinity which is divisible by any number). For every next a[i], the choice is whether to tie it to the root or a vertex containing one of the previous numbers. Therefore, we only consider O(N!) trees in total.
|
[
"brute force",
"number theory",
"trees"
] | 2,200
| null |
338
|
D
|
GCD Table
|
Consider a table $G$ of size $n × m$ such that $G(i, j) = GCD(i, j)$ for all $1 ≤ i ≤ n, 1 ≤ j ≤ m$. $GCD(a, b)$ is the greatest common divisor of numbers $a$ and $b$.
You have a sequence of positive integer numbers $a_{1}, a_{2}, ..., a_{k}$. We say that this sequence occurs in table $G$ if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers $1 ≤ i ≤ n$ and $1 ≤ j ≤ m - k + 1$ should exist that $G(i, j + l - 1) = a_{l}$ for all $1 ≤ l ≤ k$.
Determine if the sequence $a$ occurs in table $G$.
|
Observation 1. If the sequence a occurs in table G, then it should occur in row i = LCM(a[1], ..., a[k]). The proof follows. It is clear that theoretically it may only occur in rows with numbers which are multiple to i, since the row number should divide by each of a[index]. Consider some a row with number i*x, where x>1. The rows i and i*x differ only in such elements j that i*x and j both divide by some p^q (where p is prime) which does not divide i (hence, G(i*x, j) is divisible by p^q). But none of the a[index] may divide by such p^q, since then i would be also divisible by it. Therefore, if a occurs in row i*x, then it does not intersect with index j. Since it can only reside on indices where i and i*x coincide, checking only the i-th row is enough. It also clear that if i > n, the answer is NO. Observation 2. The sought index j should satisfy the following modular linear equations system: j = 0 (mod a[1])
j + 1 = 0 (mod a[2])
...
j + l = 0 (mod a[l + 1])
...
j + k - 1 = 0 (mod a[k])
<=>
{j = -l (mod a[l + 1])} In other words, j + l must divide by a[l+1] for each l=0..k-1. According to Chinese Remainder Theorem, such a system has a solution iff for each pair of indices x, y (0 <= x, y <= k-1) we have -x = -y (mod GCD(a[x+1], a[y+1])). Let's denote L = LCM(a[1], ..., a[k]). If the system has a solution, then it is singular on interval [0, L) and all the other solutions are congruent to it modulo L. Suppose that we have found the minimum non-negative j which satisfies the given system. Then, if a occurs in G, it will start from the j-th element of the i-th row. Theoretically, it may begin at any index of form j+x*L, x>=0, but since i = L, we have G(i, j+X*L) = GCD(i, j+X*i) = GCD(i, j). So it is sufficient to check whether the k consecutive elements which begin at index j in row i coincide with sequence a. It is also clear that when j > m-k+1, the answer is NO. Finally, let's consider how to solve a system of modular linear equations. We can use an auxiliary method which, given r1, m1, r2, m2, finds minimum X such that X = r1 (mod m1) and X = r2 (mod m2), or determines that such number does not exist. Let X = m1*x + r1, then we have m1*x + r1 = r2 (mod m2). This can be represented as a Diophantine equation m1*x + m2*y = r2-r1 and solved using Extended Euclidean Algorithm. The least non-negative x, if it exists, yields the sought X = m1*x + r1. Now this method can be used to find the minimum X1 which satisfies the first two equations. After that, we can say that we have a system with k-1 equation, where the first two old equations are replaced with a new j = X1 (mod LCM(a[1], a[2])), and repeat the same procedure again. After using this method k-1 times, we obtain the solution to the whole system. Also note that the proposed solution does not require long arithmetics: - The computation of LCM(a[1], ..., a[k]) can be implemented with a check before each multiplication: if the result will become larger than n, the answer is NO; - When it comes to solving the system of equations, we already know that L <= n <= 10^12, thus all the intermediate moduli will also obide to this constraint; - The Extended Euclidean Algorithm can find a solution in the same bounds as its inputs, so it will also use numbers up to 10^12. The overall complexity of the algorithm is O(k logn).
|
[
"chinese remainder theorem",
"math",
"number theory"
] | 2,900
| null |
338
|
E
|
Optimize!
|
Manao is solving a problem with the following statement:
He came up with a solution that produces the correct answers but is too slow. You are given the pseudocode of his solution, where the function getAnswer calculates the answer to the problem:
\begin{verbatim}
getAnswer(a[1..n], b[1..len], h)
answer = 0
for i = 1 to n-len+1
answer = answer + f(a[i..i+len-1], b, h, 1)
return answer
f(s[1..len], b[1..len], h, index)
if index = len+1 then
return 1
for i = 1 to len
if s[index] + b[i] >= h
mem = b[i]
b[i] = 0
res = f(s, b, h, index + 1)
b[i] = mem
if res > 0
return 1
return 0
\end{verbatim}
Your task is to help Manao optimize his algorithm.
|
Decyphering Manao's pseudocode, we unearth the following problem: you are given arrays a[1..n] and b[1..len] and a number h. Consider each subarray of a of length L. Let us call it s. Count how many of them have the property that the elements of b can be shuffled in such a way that each sum s[i]+b[i] (1<=i<=L) is at least h. First, let's solve a problem for one subarray. That is, we need to determine whether the elements of two arrays s and b can be matched in such a way that each sum is h or more. We can do the following: for each element of s, find the least element of b such that the two's sum is at least h, and erase the corresponding element from b. If we managed to pair each of the elements from s, then the arrays hold the property. Note that the elements of s can be processed in any order. If both s and b are sorted, then the idea described can be implemented in linear time. We can not achieve better complexity when considering each subarray separately, so we will try to solve the problem for several subarrays at the same time. Suppose that b is already sorted. We choose some X < len and consider a subarray a[i..i+X-1]. Let's process all the numbers from this subarray, i.e., for each of them find the least b[j] which pairs up with this number and erase it from b. The whole processing can be done in time O(n) if we have a sorted version of a and the corresponding indices computed beforehand. Now we can find the answer for every subarray s of length len which begins in segment [i-Y, i] using O(YlogY) operations, where Y=len-X. For this, we just take the Y elements which are in s but not in a[i..i+X-1] and process them against the numbers left in b. If each of them has been paired, then subarray s holds the required property, otherwise it does not. Moreover, since the subarrays we consider are overlapping, we can optimize even further and obtain amortized O(Y) complexity per subarray. To understand this, note that for processing a subarray in O(Y) time we only need to obtain its sorted version (to be more specific, the sorted version of the portion which does not overlap with a[i..i+X-1]). For the leftmost subarray we consider, we can sort its elements in usual way. For every next subarray (which differs from its predecessor in exactly two elements) we only need O(Y) operations to obtain its sorted version by updating the information from the previous subarray. Thus we have complexity O(YlogY + Y^2) of processing Y segments in total, which gives O(Y) per segment on average. Now let us take a look at the full picture. To process all subarrays of length len, we need to use the method given above for each of the segments a[Y..Y+len-1], a[2Y+1..2Y+len], a[3Y+2..3Y+len+1], .... Therefore, we have O(N/Y) iterations of algorithm with comlexity O(N+Y^2). We need to find a value of Y that minimizes N*N/Y + N*Y, which is Y=~sqrt(N). The overall complexity is O(Nsqrt(N)). However, we need to consider the case len < sqrt(N) separately, since then Y = len - X < len. In this case, the problem can be solved in time O(N*len) with ideas similar to those described above.
|
[
"data structures"
] | 2,600
| null |
339
|
A
|
Helpful Maths
|
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. For example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.
You've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.
|
To solve this problem we can count the number of digits 1, 2 and 3 in the input. If there are $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Then we must print the sequence of $c_{1}$ digits 1, $c_{2}$ digits 2 and $c_{3}$ digits 3. Digits must be separated by + sign.
|
[
"greedy",
"implementation",
"sortings",
"strings"
] | 800
| null |
339
|
B
|
Xenia and Ringroad
|
Xenia lives in a city that has $n$ houses built along the main ringroad. The ringroad houses are numbered 1 through $n$ in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got $m$ things to do. In order to complete the $i$-th task, she needs to be in the house number $a_{i}$ and complete all tasks with numbers less than $i$. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.
|
To solve this problem we must learn how to calculate fast enought the time, needed to travel between houses $a$ and $b$. Let's consider the case when $a \le b$. Than Xenia needs $b - a$ seconds to get from $a$ to $b$. Otherwise $a > b$, Xenia will have to go thought house number 1. So she will need $n - a + b$ seconds.
|
[
"implementation"
] | 1,000
| null |
339
|
C
|
Xenia and Weights
|
Xenia has a set of weights and pan scales. Each weight has an integer weight from 1 to 10 kilos. Xenia is going to play with scales and weights a little. For this, she puts weights on the scalepans, one by one. The first weight goes on the left scalepan, the second weight goes on the right scalepan, the third one goes on the left scalepan, the fourth one goes on the right scalepan and so on. Xenia wants to put the total of $m$ weights on the scalepans.
Simply putting weights on the scales is not interesting, so Xenia has set some rules. First, she does not put on the scales two consecutive weights of the same weight. That is, the weight that goes $i$-th should be different from the $(i + 1)$-th weight for any $i$ $(1 ≤ i < m)$. Second, every time Xenia puts a weight on some scalepan, she wants this scalepan to outweigh the other one. That is, the sum of the weights on the corresponding scalepan must be strictly greater than the sum on the other pan.
You are given all types of weights available for Xenia. You can assume that the girl has an infinite number of weights of each specified type. Your task is to help Xenia lay $m$ weights on the scales or to say that it can't be done.
|
Let's consider the definition of balance. Balance is the difference between sum of all weights on the left pan and sum of all weights on the right pan. At the beginning balance is equal to 0. Att each step Xenia puts one weight on the pan. It means she adds to or substracts from balance integer from 1 to 10. In each odd step, the integer is added and in each even step the integer is subtracted. From the statement we know, that after each step, balance must change it sign and must not be equal to 0. So if after some step the absolute value of balance is greater than 10, Xenia can not continue. Also, it is said in the statement that we can not use two equal weigths in a row. To solve the problem, let's consider a graph, where vertices are tuples of three numbers $(i, j, k)$, where $i$ is a current balance, $j$ is a weight, used in the previous step, and $k$ is the number of the current step. Arcs of the graph must correspond to Xenias actions, described in the statement. The solution of the problme is a path from vertex $(0, 0, 1)$ to some vertex $(x, y, m)$, where x, y are any numbers, and $m$ is the requared number of steps.
|
[
"constructive algorithms",
"dfs and similar",
"dp",
"graphs",
"greedy",
"shortest paths"
] | 1,700
| null |
339
|
D
|
Xenia and Bit Operations
|
Xenia the beginner programmer has a sequence $a$, consisting of $2^{n}$ non-negative integers: $a_{1}, a_{2}, ..., a_{2^{n}}$. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value $v$ for $a$.
Namely, it takes several iterations to calculate value $v$. At the first iteration, Xenia writes a new sequence $a_{1} or a_{2}, a_{3} or a_{4}, ..., a_{2^{n} - 1} or a_{2^{n}}$, consisting of $2^{n - 1}$ elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence $a$. At the second iteration, Xenia writes the bitwise \textbf{exclusive} OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is $v$.
Let's consider an example. Suppose that sequence $a = (1, 2, 3, 4)$. Then let's write down all the transformations $(1, 2, 3, 4)$ $ → $ $(1 or 2 = 3, 3 or 4 = 7)$ $ → $ $(3 xor 7 = 4)$. The result is $v = 4$.
You are given Xenia's initial sequence. But to calculate value $v$ for a given sequence would be too easy, so you are given additional $m$ queries. Each query is a pair of integers $p, b$. Query $p, b$ means that you need to perform the assignment $a_{p} = b$. After each query, you need to print the new value $v$ for the new sequence $a$.
|
The problem could be solved by using a typical data structure (segment tree). The leafs of the segment tree will store the values of $a_{i}$. At the vertices, the distance from which to the leafs is 1, we will store OR of the numbers from the leafs, which are the sons of this node in the segment tree. Similarly, vertices, the distance from which to the leafs is 2, we will store Xor of the numbers stored in their immediate sons. And so on. Then, the root of the tree will contain the required value $v$. There is no need to rebuild all the tree to perform an update operation. To do update, we should find a path from the root to the corresponding leaf and recalculate the values only at the tree vertices that are lying on that path. If everything is done correctly, then each update query will be executed in $O(n)$ time. Also we need $O(2^{n})$ memory.
|
[
"data structures",
"trees"
] | 1,700
| null |
339
|
E
|
Three Swaps
|
Xenia the horse breeder has $n$ $(n > 1)$ horses that stand in a row. Each horse has its own unique number. Initially, the $i$-th left horse has number $i$. That is, the sequence of numbers of horses in a row looks as follows (from left to right): 1, 2, 3, $...$, $n$.
Xenia trains horses before the performance. During the practice sessions, she consistently gives them commands. Each command is a pair of numbers $l, r$ $(1 ≤ l < r ≤ n)$. The command $l, r$ means that the horses that are on the $l$-th, $(l + 1)$-th, $(l + 2)$-th, $...$, $r$-th places from the left must be rearranged. The horses that initially stand on the $l$-th and $r$-th places will swap. The horses on the $(l + 1)$-th and $(r - 1)$-th places will swap. The horses on the $(l + 2)$-th and $(r - 2)$-th places will swap and so on. In other words, the horses that were on the segment $[l, r]$ change their order to the reverse one.
For example, if Xenia commanded $l = 2, r = 5$, and the sequence of numbers of horses before the command looked as (2, 1, 3, 4, 5, 6), then after the command the sequence will be (2, 5, 4, 3, 1, 6).
We know that during the practice Xenia gave at most three commands of the described form. You have got the final sequence of numbers of horses by the end of the practice. Find what commands Xenia gave during the practice. Note that you do not need to minimize the number of commands in the solution, find any valid sequence of at most three commands.
|
We will call the command $l, r$ a reverse, also we will call the row of horses an array. Suddenly, right? The problem can be solved with clever bruteforcing all possible ways to reverse an array. To begin with, assume that the reverse with $l = r$ is ok. Our solution can find an answer with such kind of reverses. It is clear that this thing doesn't affect the solution. Because such reverses can simply be erased from the answer. The key idea: reverses split an array into no more than seven segments of the original array. In other words, imagine that the array elements was originally glued together, and each reverse cuts a segment from the array. Then the array would be cut into not more than 7 pieces. Now you can come up with the wrong solution to the problem, and then come up with optimization that turns it into right. So, bruteforce all ways to cut array into 7 or less pieces. Then bruteforce reverse operations, but each reverse operation should contain only whole pieces. It is clear that this solution is correct, One thing it does not fit the TL. How to improve it? Note that the previous solution requires the exact partition of the array only at the very end of the bruteforce. It needed to check whether it is possible to get the given array $a$. So, let's assume that the array was originally somehow divided into 7 parts (we don't know the exact partition), the parts can be empty. Now try to bruteforce reverses as in naive solution. One thing, in the very end of bruteforce try to find such a partition of the array to get (with fixed reverses) the given array $a$. The search for such a partition can be done greedily (the reader has an opportunity to come up with it himself). Author's solution does this in time proportional to the number of parts, that is, 7 operations. However, this can be done for $O(n)$ - this should fit in TL, if you write bruteforce carefully.
|
[
"constructive algorithms",
"dfs and similar",
"greedy"
] | 2,700
| null |
340
|
A
|
The Wall
|
Iahub and his friend Floyd have started painting a wall. Iahub is painting the wall red and Floyd is painting it pink. You can consider the wall being made of a very large number of bricks, numbered $1$, $2$, $3$ and so on.
Iahub has the following scheme of painting: he skips $x - 1$ consecutive bricks, then he paints the $x$-th one. That is, he'll paint bricks $x$, $2·x$, $3·x$ and so on red. Similarly, Floyd skips $y - 1$ consecutive bricks, then he paints the $y$-th one. Hence he'll paint bricks $y$, $2·y$, $3·y$ and so on pink.
After painting the wall all day, the boys observed that some bricks are painted both red and pink. Iahub has a lucky number $a$ and Floyd has a lucky number $b$. Boys wonder how many bricks numbered no less than $a$ and no greater than $b$ are painted both red and pink. This is exactly your task: compute and print the answer to the question.
|
You are given a range $[A, B]$. You're asked to compute fast how many numbers in the range are divisible by both $x$ and $y$. I'll present here an $O(log(max(x, y))$ solution. We made tests low so other not optimal solutions to pass as well. The solution refers to the original problem, where $x, y \le 10^{9}$. Firstly, we can simplify the problem. Suppose we can calculate how many numbers are divisible in range $[1, X]$ by both $x$ and $y$. Can this solve our task? The answer is yes. All numbers in range $[1, B]$ divisible by both numbers should be counted, except the numbers lower than $A$ (1, 2, ..., A - 1). But, as you can see, numbers lower than A divisible by both numbers are actually numbers from range [1, A - 1]. So the answer of our task is f(B) - f(A - 1), where f(X) is how many numbers from 1, 2, ..., X are divisible by both x and y. For calculate in $O(log(max(x, y))$ the f(X) we need some math. If you don't know about it, please read firstly about least common multiple. Now, what will be the lowest number divisible by both x and y. The answer is least common multiple of x and y. Let's note it by $M$. The sequence of the numbers divisible by both x and y is $M$, $2 * M$, $3 * M$ and so on. As a proof, suppose a number z is divisible by both x and y, but it is not in the above sequence. If a number is divisible by both x and y, it will be divisible by M also. If a number is divisible by M, it will be in the above sequence. Hence, the only way a number to be divisible by both x and y is to be in sequence $M$, $2 * M$, $3 * M$, ... The f(X) calculation reduces to finding the number of numbers from sequence $M$, $2 * M$, $3 * M$, ... lower or equal than X. It's obvious that if a number h * M is greater than X, so will be (h + 1) * M, (h + 2) * M and so on. We actually need to find the greatest integer number h such as $h * M \le X$. The numbers we're looking for will be $1 * M, 2 * M, ..., h * M$ (so their count will be $h$). The number h is actually [X / M], where [number] denotes the integer part of [number]. Take some examples on paper, you'll see why it's true. The only thing not discussed is how to calculate the number M given 2 number x and y. You can use this formula $M = x * y / gcd(x, y)$. For calculate gcd(x, y) you can use Euclid's algorithm. Its complexity is $O(log(max(x, y))$, so this is the running time for the entire algorithm.
|
[
"math"
] | 1,200
|
#include <stdio.h>
int gcd(int x, int y) {
if (y == 0)
return x;
return gcd(y, x % y);
}
int solve(int x, int y, int uppBound) {
long long lcm = 1LL * x * y;
lcm = lcm / gcd(x, y);
return uppBound / lcm;
}
int main() {
int x, y, A, B;
scanf("%d%d%d%d", &x, &y, &A, &B);
printf("%d", solve(x, y, B) - solve(x, y, A - 1));
return 0;
}
|
340
|
B
|
Maximal Area Quadrilateral
|
Iahub has drawn a set of $n$ points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.
|
I want to apologize for not estimating the real difficulty of this task. It turns out that it was more complicated than we thought it might be. Let's start explanation. Before reading this, you need to know what is signed area of a triangle (also called cross product or ccw function). Without it, this explanation will make no sense. The first thing we note is that a quadrilateral self intersecting won't have maximum area. I'll show you this by an image made by my "talents" in Paint :) As you can see, if a quadrilateral self intersects, it can be transformed into one with greater area. Each quadrilateral has 2 diagonals: connecting 1st and 3rd point and connecting 2nd and 4th point. A diagonal divides a plane into 2 subplanes. Suppose diagonal is AB. A point X can be in one of those two subplanes: that making cross product positive and that making cross product negative. A point is in "positive" subplane if ccw(X, A, B) > 0 and in "negative" subplane ccw(X, A, B) < 0. Note that according to the constraints of the task, ccw(X, A, B) will never be 0. Let's make now the key observation of the task. We have a quadrilateral. Suppose AB is one of diagonals and C and D the other points from quadrilateral different by A and B. If the current quadrilateral could have maximal area, then one of points from C and D needs to be in "positive subplane" of AB and the other one in "negative subplane". What would happen if C and D will be in the same subplane of AB? The quadrilateral will self intersect. If it will self intersect, it won't have maximal area. "A picture is worth a thousand words" - this couldn't fit better in this case :) Note that the quadrilateral from the below image is A-C-B-D-A. Out task reduces to fix a diagonal (this taking O(N ^ 2) time) and then choose one point from the positive and the negative subplane of the diagonal. I'll say here how to choose the point from the positive subplane. That from negative subplane can be chosen identically. The diagonal and 3rd point chosen form a triangle. As we want quadrilateral to have maximal area, we need to choose 3rd point such as triangle makes the maximal area. As the positive and negative subplanes are disjoint, the choosing 3rd point from each of them can be made independently. Hence we get O(N ^ 3) complexity. A tricky case is when you choose a diagonal but one of the subplanes is empty. In this case you have to disregard the diagonal and move to the next one.
|
[
"brute force",
"geometry"
] | 2,100
|
#include <stdio.h>
#include <algorithm>
#define eps 0.00000001
#define x first
#define y second
#define point pair <int, int>
using namespace std;
point x[301];
inline double ccw(point A, point B, point C) {
return ((double)(B.x - A.x) * (C.y - B.y) - (B.y - A.y) * (C.x - B.x)) * 0.5;
}
inline double chmax(double &A, double B) {
if (B - A > eps)
A = B;
}
int main() {
int n;
double maxArea = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d%d", &x[i].x, &x[i].y);
for (int i = 1; i <= n; ++i)
for (int j = i + 1; j <= n; ++j) {
double maxMinus = -1, maxPlus = -1;
for (int k = 1; k <= n; ++k)
if (k != i && k != j)
if (ccw(x[i], x[j], x[k]) < 0)
chmax(maxMinus, -ccw(x[i], x[j], x[k]));
else
chmax(maxPlus, ccw(x[i], x[j], x[k]));
if (maxPlus >= 0 && maxMinus >= 0)
chmax(maxArea, maxMinus + maxPlus);
}
printf("%lf", maxArea);
return 0;
}
|
340
|
C
|
Tourist Problem
|
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are $n$ destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The $n$ destinations are described by a non-negative integers sequence $a_{1}$, $a_{2}$, ..., $a_{n}$. The number $a_{k}$ represents that the $k$th destination is at distance $a_{k}$ kilometers from the starting point. No two destinations are located in the same place.
Iahub wants to visit each destination only once. Note that, crossing through a destination is not considered visiting, unless Iahub explicitly wants to visit it at that point. Also, after Iahub visits his last destination, he doesn't come back to kilometer 0, as he stops his trip at the last destination.
The distance between destination located at kilometer $x$ and next destination, located at kilometer $y$, is $|x - y|$ kilometers. We call a "route" an order of visiting the destinations. Iahub can visit destinations in any order he wants, as long as he visits all $n$ destinations and he doesn't visit a destination more than once.
Iahub starts writing out on a paper all possible routes and for each of them, he notes the total distance he would walk. He's interested in the average number of kilometers he would walk by choosing a route. As he got bored of writing out all the routes, he asks you to help him.
|
Despite this is a math task, the only math formula we'll use is that number of permutations with $n$ elements is $n!$. From this one, we can deduce the whole task. The average formula is sum_of_all_routes / number_of_routes. As each route is a permutation with n elements, number_of_routes is $n!$. Next suppose you have a permutation of a: p1, p2, \dots , pn. The sum for it will be p1 + |p2 - p1| + \dots + |pn - pn-1|. The sum of routes will be the sum for each possible permutation. We can calculate sum_of_all routes in two steps: first time we calculate sums like "p1" and then we calculate sums like "|p2 - p1| + \dots + |pn - pn-1|" for every existing permutation. First step Each element of $a_{1}$, $a_{2}$, \dots , $a_{n}$ can appear on the first position on the routes and needs to be added as much as it appears. Suppose I fixed an element X for the first position. I can fill positions 2, 3, .., n - 1 in (n - 1)! ways. Why? It is equivalent to permuting n - 1 elements (all elements except X). So sum_of_all = $a_{1}$ * (n - 1)! + $a_{2}$ * (n - 1)! + \dots * $a_{n}$ * (n - 1)! = (n - 1)! * ($a_{1}$ + $a_{2}$ + \dots + $a_{n}$). Second step For each permutation, for each position j between 1 and n - 1 we need to compute |$p_{j}$ - $p_{}(j + 1)$|. Similarly to first step, we observe that only elements from $a$ can appear on consecutive positions. We fix 2 indices i and j. We're interested in how many permutations do $a_{i}$ appear before $a_{j}$. We fix k such as on a permutation p, $a_{i}$ appears on position k and $a_{j}$ appears on a position k + 1. In how many ways can we fix this? n - 1 ways (1, 2, \dots , n - 1). What's left? A sequence of (n - 2) elements which can be permuted independently. So the sum of second step is |$a_{i} - a_{j}$| * (n - 1) * (n - 2)!, for each i != j. If I note ($a_{1}$ + $a_{2}$ + \dots + $a_{n}$) by S1 and |$a_{i} - a_{j}$| for each i != j by S2, the answer is (N - 1)! * S1 + (N - 1)! * S2 / N!. By a simplification, the answer is (S1 + S2) / N. The only problem remained is how to calculate S2. Simple iteration won't enter in time limit. Let's think different. For each element, I need to make sum of differences between it and all smaller elements in the array a. As well, I need to make sum of all different between bigger elements than it and it. I'll focus on the first part. I sort increasing array a. Suppose I'm at position $i$. I know that (i - 1) elements are smaller than $a_{i}$. The difference is simply (i - 1) * $a_{i}$ - sum_of_elements_before_position_i. Sum of elements before position i can be computed when iterating i. Let's call the obtained sum Sleft. I need to calculate now sum of all differences between an element and bigger elements than it. This sum is equal to Sleft. As a proof, for an element $a_{i}$, calculating the difference $a_{j}$ - $a_{i}$ when $a_{j}$ > $a_{i}$ is equivalent to calculating differences between $a_{j}$ and a smaller element of it (in this case $a_{i}$). That's why Sleft = Sright. As a conclusion, the answer is (S1 + 2 * Sleft) / N. For make fraction irreducible, you can use Euclid's algorithm. The complexity of the presented algorithm is $O(N * logN)$, necessary due of sorting. Sorting can be implemented by count sort as well, having a complexity of O(maximalValue), but this is not necessary.
|
[
"combinatorics",
"implementation",
"math"
] | 1,600
|
#include <stdio.h>
#include <algorithm>
#define ll long long
using namespace std;
int x[100010];
ll gcd(ll A, ll B) {
if (B == 0)
return A;
return gcd(B, A % B);
}
int main() {
int n;
ll sum1 = 0, sum2 = 0, sumBefore = 0, sumtot = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
scanf("%d", &x[i]);
sum1 += x[i];
}
sort(x + 1, x + n + 1);
for (int i = 1; i <= n; ++i) {
sum2 += 1LL * x[i] * (i - 1) - sumBefore;
sumBefore += x[i];
}
sumtot = sum1 + 2 * sum2;
ll _gcd = gcd(sumtot, n);
printf("%I64d %I64d", sumtot / _gcd, n / _gcd);
return 0;
}
|
340
|
D
|
Bubble Sort Graph
|
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with $n$ elements $a_{1}$, $a_{2}$, ..., $a_{n}$ in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it $G$) initially has $n$ vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode).
\begin{verbatim}
procedure bubbleSortGraph()
build a graph G with n vertices and 0 edges
repeat
swapped = false
for i = 1 to n - 1 inclusive do:
if a[i] > a[i + 1] then
add an undirected edge in G between a[i] and a[i + 1]
swap( a[i], a[i + 1] )
swapped = true
end if
end for
until not swapped
/* repeat the algorithm as long as swapped value is true. */
end procedure
\end{verbatim}
For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph $G$, if we use such permutation as the premutation $a$ in procedure bubbleSortGraph.
|
A good way to approach this problem is to notice that you can't build the graph. In worst case, the graph will be built in $O(N^{2})$ complexity, which will time out. Also, notice that "maximal independent set" is a NP-Hard task, so even if you can build the graph you can't continue from there. So, the correct route to start is to think of graph's properties instead of building it. After sketching a little on the paper, you should find this property: Lemma 1 Suppose we choose 2 indices i and j, such as i < j. We'll have an edge on the graph between vertices $a_{i}$ and $a_{j}$ if and only if $a_{i}$ > $a_{j}$. We'll call that i and j form an inversion in the permutation. Proof We assume we know the proof that bubble sort does sort correctly an array. To proof lemma 1, we need to show two things. To proof 1, if bubble sort wouldn't swap an inversion, the sequence wouldn't be sorted. But we know that bubble sort always sorts a sequence, so all inversions will be swapped. Proofing 2 is trivial, just by looking at the code. So far we've got how the graph G is constructed. Let's apply it in maximal independent set problem. Lemma 2 A maximal independent set of graph G is a longest increasing sequence for permutation a. Proof: Suppose we have a set of indices $i1$ < $i2$ < ... $ik$ such as $a_{i1}$, $a_{i2}$, ..., $a_{ik}$ form an independent set. Then, anyhow we'd choose $d$ and $e$, there won't exist an edge between $a_{id}$ and $a_{ie}$. According to proof 1, this only happens when $a_{id}$ < $a_{ie}$. Hence, an independent set will be equivalent to an increasing sequence of permutation a. The maximal independent set is simply the maximal increasing sequence of permutation a. The task reduces to find longest increasing sequence for permutation $a$. This is a classical problem which can be solved in $O(N * logN)$. Here is an interesting discussion about how to do it.
|
[
"binary search",
"data structures",
"dp"
] | 1,500
| null |
340
|
E
|
Iahub and Permutations
|
Iahub is so happy about inventing bubble sort graphs that he's staying all day long at the office and writing permutations. Iahubina is angry that she is no more important for Iahub. When Iahub goes away, Iahubina comes to his office and sabotage his research work.
The girl finds an important permutation for the research. The permutation contains $n$ distinct integers $a_{1}$, $a_{2}$, ..., $a_{n}$ $(1 ≤ a_{i} ≤ n)$. She replaces some of permutation elements with -1 value as a revenge.
When Iahub finds out his important permutation is broken, he tries to recover it. The only thing he remembers about the permutation is it didn't have any fixed point. A fixed point for a permutation is an element $a_{k}$ which has value equal to $k$ $(a_{k} = k)$. Your job is to proof to Iahub that trying to recover it is not a good idea. Output the number of permutations which could be originally Iahub's important permutation, modulo $1000000007$ ($10^{9} + 7$).
|
In this task, author's intended solution is an O(N ^ 2) dp. However, during testing Gerald fount a solution using principle of inclusion and exclusion. We've thought to keep both solutions. We're sorry if you say the problem was well-known, but for both me and the author of the task, it was first time we saw it. Dynamic programming solution After reading the sequence, we can find which elements are deleted. Suppose we have in a set D all deleted elements. I'll define from now on a "free position" a position which has -1 value, so it needs to be completed with a deleted element. We observe that some elements from D can appear on all free positions of permutation without creating a fixed point. The other elements from D can appear in all free positions except one, that will create the fixed point. It's intuitive that those two "classes" don't influence in the same way the result, so they need to be treated separated. So from here we can get the dp state. Let dp(n, k) = in how many ways can I fill (n + k) free positions, such as n elements from D can be placed anywhere in the free position and the other k elements can be placed in all free positions except one, which will create the fixed point. As we'll prove by the recurrences, we are not interested of the values from elements of D. Instead, we'll interested in their property: if they can(not) appear in all free positions. If k = 0, the problem becomes straight-forward. The answer for dp(n, 0) will be n!, as each permutation of (n + 0) = n numbers is valid, because all numbers can appear on all free positions. We can also calculate dp(n, 1). This means we are not allowed to place an element in a position out of (n + 1) free positions. However, we can place it in the other n positions. From now we get n elements which can be placed anywhere in the n free positions left. Hence, dp(n, 1) = n! * n. We want to calculate dp(n, k) now, k > 1. Our goal is to reduce the number k, until find something we know how to calculate. That is, when k becomes 0 or 1 problem is solved. Otherwise, we want to reduce the problem to a problem when k becomes 0 or 1. I have two cases. In a first case, I take a number from numbers which can be placed anywhere in order to reduce the numbers which can form fixed points. In the second case, I take a number from those which can form fixed points in order to make the same goal as in the first case. Let's analyze them. Case 1. Suppose X is the first free position, such as in the set of k numbers there exist one which cannot be placed there (because it will make a fixed point). Obviously, this position exist, otherwise k = 0. Also obviously, this position will need to be completed with a term when having a solution. In this case, I complete position X with one of n numbers. This will make number equal to X from the k numbers set to become a number which can be placed anywhere. So I "loose" one number which can be placed anywhere, but I also "gain" one. As well, I loose one number which can form a fixed point. Hence dp(n, k) += n * dp(n, k - 1). Case 2. In this case position X will be completed with one number from the k numbers set. All numbers which can form fixed points can appear there, except number having value equal to X. So there are k - 1 of them. I choose an arbitrary number Y from those k - 1 to place on the position X. This time I "loose" two numbers which could form fixed points: X and Y. As well, I "gain" one number which can be placed anywhere: X. Hence dp(n, k) += (k - 1) * dp(n + 1, k - 2). TL;DR dp[N][0]=N! dp[N][1]=N*dp[N][0] dp[N][K]=N*dp[N][K-1]+(K-1)*dp[N+1][K-2] for K>=2 This recurrences can be computed by classical dp or by memoization. I'll present DamianS's source, which used memoization. As you can see, it's very short and easy to implement. Link Inclusion and exclusion principle I'll present here an alternative to the dynamic programming solution. Let's calculate in $tot$ the number of deleted numbers. Also, let's calculate in $fixed$ the maximal number of fixed points a permutation can have. For calculate $fixed$, let's iterate with an index $i$ each permutation position. We can have a fixed point on position $i$ if element from position $i$ was deleted ($a_{i}$ = -1) and element i does not exist in sequence $a$. With other words, element $i$ was deleted and now I want to add it back on position $i$ to obtain maximal number of fixed points. We iterate now an index $i$ from $fixed$ to $0$. Let sol[i] = the number of possible permutations having exactly $i$ fixed points. Obviously, sol[0] is the answer to our problem. Let's introduce a combination $\textstyle{\binom{n}{k}}$ representing in how many ways I can choose k objects out of n. I have list of positions which can be transformed into fix points (they are $fixed$ positions). I need to choose $i$ of them. According to the above definition, I get sol[i] = $(f_{i}^{t_{i}x e d})$ . Next, I have to fill $tot - i$ positions with remained elements. We'll consider for this moment valid each permutation of not used values. So, sol[i] = $(stackrel{f i x e d}{i})*(t o t-i)!$ . Where is the problem to this formula? The problem is that it's possible, when permuting (tot - i) remained elements to be added, one (or more) elements to form more (new) fixed points. But if somehow I can exclude (subtract) the wrong choices from sol[i], sol[i] will be calculated correctly. I iterate another index $j$ from i + 1 to $fixed$. For each j, I'll calculate how many permutations I considered in sol[i] having $i$ fixed points but actually they have $j$. I'll subtract from sol[i] this value calculated for each j. If I do this, obviously sol[i] will be calculated correctly. Suppose we fixed a j. We know that exactly sol[j] permutations have j fixed points (as j > i, this value is calculated correctly). Suppose now I fix a permutation having j fixed points. For get the full result, I need to calculate for all sol[j] permutations. Happily, I can multiply result obtained for a single permutation with sol[j] and obtain the result for all permutations having j fixed points. So you have a permutation having j fixed points. The problem reduces to choosing i objects from a total of j. Why? Those i objects chosen are actually the positions considered in sol[i] to be ones having exactly i fixed points. But permutation has j fixed points. Quoting for above, "For each j, I'll calculate how many permutations I considered in sol[i] having $i$ fixed points but actually they have $j$" . This is exactly what algorithm does. To sum up in a "LaTeX" way, $s o l[i]=\left(J^{i x e d}\right)*\left(t o t-i\right)!-\sum_{j=i+1}^{f i x e d}s o l[j]*\left({}_{i}^{j}\right)$ We can compute binomial coefficients using Pascal's triangle. Using inclusion and exclusion principle, we get $O(N^{2})$. Please note that there exist an $O(N)$ solution for this task, using inclusion and exclusion principle, but it's not necessary to get AC. I'll upload Gerald's source here.
|
[
"combinatorics",
"math"
] | 2,000
|
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <set>
#include <queue>
#include <map>
#include <cstdio>
#include <iomanip>
#include <sstream>
#include <iostream>
#include <cstring>
#define REP(i,x,v)for(int i=x;i<=v;i++)
#define REPD(i,x,v)for(int i=x;i>=v;i--)
#define FOR(i,v)for(int i=0;i<v;i++)
#define FORE(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define FOREACH(i,t) FORE(i,t)
#define REMIN(x,y) (x)=min((x),(y))
#define REMAX(x,y) (x)=max((x),(y))
#define pb push_back
#define sz size()
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define IN(x,y) ((y).find((x))!=(y).end())
#define un(v) v.erase(unique(ALL(v)),v.end())
#define LOLDBG
#ifdef LOLDBG
#define DBG(vari) cerr<<#vari<<" = "<<vari<<endl;
#define DBG2(v1,v2) cerr<<(v1)<<" - "<<(v2)<<endl;
#else
#define DBG(vari)
#define DBG2(v1,v2)
#endif
#define CZ(x) scanf("%d",&(x));
#define CZ2(x,y) scanf("%d%d",&(x),&(y));
#define CZ3(x,y,z) scanf("%d%d%d",&(x),&(y),&(z));
#define wez(x) int x; CZ(x);
#define wez2(x,y) int x,y; CZ2(x,y);
#define wez3(x,y,z) int x,y,z; CZ3(x,y,z);
#define SZ(x) int((x).size())
#define ALL(x) (x).begin(),(x).end()
#define tests int dsdsf;cin>>dsdsf;while(dsdsf--)
#define testss int dsdsf;CZ(dsdsf);while(dsdsf--)
#define MOD 1000000007
using namespace std;
typedef pair<int,int> pii;
typedef vector<int> vi;
template<typename T,typename TT> ostream &operator<<(ostream &s,pair<T,TT> t) {return s<<"("<<t.first<<","<<t.second<<")";}
template<typename T> ostream &operator<<(ostream &s,vector<T> t){s<<"{";FOR(i,t.size())s<<t[i]<<(i==t.size()-1?"":",");return s<<"}"<<endl; }
inline void pisz (int x) { printf("%d
", x); }
ll dp[3111][3111];
ll go(int K,int N)
{
if (dp[K][N]!=-1) return dp[K][N];
if (K==0)
{
if (N==0) return 1;
return dp[0][N]=(N*go(0,N-1))%MOD;
}
if (K==1)
{
if (N==0) return 0;
return dp[1][N]=(N*go(0,N))%MOD;
}
return dp[K][N]=(N*go(K-1,N)+(K-1)*go(K-2,N+1))%MOD;
}
bool used[3111];
int fast(vi v)
{
int n=v.sz;
REP(i,1,n)used[i]=0;
FOR(i,n) if (v[i]!=-1) used[v[i]]=1;
int K=0,N=0;
REP(i,1,n) if (!used[i])
{
if (v[i-1]==-1) K++;
else N++;
}
return go(K,N);
}
int main()
{
ios_base::sync_with_stdio(0);
FOR(i,2111)FOR(j,2111)dp[i][j]=-1;
int n;cin>>n;
vi v(n);
FOR(i,n) cin>>v[i];
cout<<fast(v);
return 0;
}
|
341
|
D
|
Iahub and Xors
|
Iahub does not like background stories, so he'll tell you exactly what this problem asks you for.
You are given a matrix $a$ with $n$ rows and $n$ columns. Initially, all values of the matrix are zeros. Both rows and columns are 1-based, that is rows are numbered 1, 2, ..., $n$ and columns are numbered 1, 2, ..., $n$. Let's denote an element on the $i$-th row and $j$-th column as $a_{i, j}$.
We will call a submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$ such elements $a_{i, j}$ for which two inequalities hold: $x_{0} ≤ i ≤ x_{1}$, $y_{0} ≤ j ≤ y_{1}$.
Write a program to perform two following operations:
- Query($x_{0}$, $y_{0}$, $x_{1}$, $y_{1}$): print the xor sum of the elements of the submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$.
- Update($x_{0}$, $y_{0}$, $x_{1}$, $y_{1}$, $v$): each element from submatrix $(x_{0}, y_{0}, x_{1}, y_{1})$ gets xor-ed by value $v$.
|
The motivation of the problem is that x ^ x = 0. x ^ x ^ x \dots ^ x (even times) = 0 Update per range, query per element When dealing with complicated problems, it's sometimes a good idea to try solving easier versions of them. Suppose you can query only one element each time (x0 = x1, y0 = y1). To update a submatrix (x0, y0, x1, y1), I'll do following operations. A[x0][y0] ^= val. A[x0][y1 + 1] ^= val. A[x1 + 1][y0] ^= val. A[x1 + 1][y1 + 1] ^= val. To query about an element (X, Y), that element's value will be the xor sum of submatrix A(1, 1, X, Y). Let's take an example. I have a 6x6 matrix and I want to xor all elements from submatrix (2, 2, 3, 4) with a value. The below image should be explanatory how the method works: Next, by (1, 1, X, Y) I'll denote xor sum for this submatrix. "White" cells are not influenced by (2, 2, 3, 4) matrix, as matrix (1, 1, X, Y) with (X, Y) a white cell will never intersect it. "Red" cells are from the submatrix, the ones that need to be xor-ed. Note that for a red cell, (1, 1, X, Y) will contain the value we need to xor (as it will contain (2, 2)). Next, "blue" cells. For this ones (1, 1, X, Y) will contain the value we xor with, despite they shouldn't have it. This is why both (2, 5) and (4, 2) will be xor-ed again by that value, to cancel the xor of (2, 2). Now it's okay, every "blue" cell do not contain the xor value in their (1, 1, X, Y). Finally, the "green" cells. These ones are intersection between the 2 blue rectangles. This means, in their (1, 1, X, Y) the value we xor with appears 3 times (this means it is contained 1 time). For cancel this, we xor (4, 5) with the value. Now for every green cell (1, 1, X, Y) contains 4 equal values, which cancel each other. You need a data structure do to the following 2 operations: Both operations can be supported by a Fenwick tree 2D. If you don't know this data structure, learn it and come back to this problem after you do this. Coming back to our problem Now, instead of finding an element, I want xor sum of a submatrix. You can note that xor sum of (x0, y0, x1, y1) is (1, 1, x1, y1) ^ (1, 1, x0 - 1, y1) ^ (1, 1, x1, y0 - 1) ^ (1, 1, x0 - 1, y0 - 1). This is a classical problem, the answer is (1, 1, x1, y1) from which I exclude what is not in the matrix: (1, 1, x0 - 1, y1) and (1, 1, x1, y0 - 1). Right now I excluded (1, 1, x0 - 1, y0 - 1) 2 times, so I need to add it one more time. How to get the xor sum of submatrix (1, 1, X, Y)? In brute force approach, I'd take all elements (x, y) with 1 <= x <= X and 1 <= y <= Y and xor their values. Recall the definition of the previous problem, each element (x, y) is the xor sum of A(1, 1, x, y). So the answer is xor sum of all xor sums of A(1, 1, x, y), with 1 <= x <= X and 1 <= y <= Y. We can rewrite that long xor sum. A number A[x][y] appears in exactly (X - x + 1) * (Y - y + 1) terms of xor sum. If (X - x + 1) * (Y - y + 1) is odd, then the value A[x][y] should be xor-ed to the final result exactly once. If (X - x + 1) * (Y - y + 1) is even, it should be ignored. Below, you'll find 4 pictures. They are matrixes with X lines and Y columns. Each picture represents a case: (X odd, Y odd) (X even, Y even) (X even Y odd) (X odd Y even). Can you observe a nice pattern? Elements colored represent those for which (X - x + 1) * (Y - y + 1) is odd. Yep, that's right! There are 4 cases, diving the matrix into 4 disjoint areas. When having a query of form (1, 1, X, Y) you only need specific elements sharing same parity with X and Y. This method works in O(4 * logN * logN) for each operation and is the indented solution. We keep 4 Fenwick trees 2D. We made tests such as solutions having complexity greater than O(4 * logN * logN) per operation to fail.
|
[
"data structures"
] | 2,500
|
#include <stdio.h>
int n;
long long F[4][1024][1024];
inline int lsb(int X) {
return X & -X;
}
int parity(int x0, int y0) {
int res = 0;
if (x0 % 2)
res += 1;
if (y0 % 2)
res += 2;
return res;
}
long long query(int x0, int y0) {
long long res = 0;
int which = parity(x0, y0);
for (int i = x0; i > 0; i -= lsb(i))
for (int j = y0; j > 0; j -= lsb(j))
res ^= F[which][i][j];
return res;
}
void update(int x0, int y0, long long val) {
int which = parity(x0, y0);
for (int i = x0; i <= n; i += lsb(i))
for (int j = y0; j <= n; j += lsb(j))
F[which][i][j] ^= val;
}
int main() {
int m;
scanf("%d%d", &n, &m);
while (m--) {
int type;
scanf("%d", &type);
if (type == 1) {
int x0, y0, x1, y1;
scanf("%d%d%d%d", &x0, &y0, &x1, &y1);
long long res = query(x1, y1);
res ^= query(x0 - 1, y1);
res ^= query(x1, y0 - 1);
res ^= query(x0 - 1, y0 - 1);
printf("%I64d\n", res);
} else {
int x0, y0, x1, y1;
long long val;
scanf("%d%d%d%d%I64d", &x0, &y0, &x1, &y1, &val);
update(x0, y0, val);
update(x0, y1 + 1, val);
update(x1 + 1, y0, val);
update(x1 + 1, y1 + 1, val);
}
}
return 0;
}
|
341
|
E
|
Candies Game
|
Iahub is playing an uncommon game. Initially, he has $n$ boxes, numbered 1, 2, 3, $...$, $n$. Each box has some number of candies in it, described by a sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$. The number $a_{k}$ represents the number of candies in box $k$.
The goal of the game is to move all candies into \textbf{exactly} two boxes. The rest of $n - 2$ boxes must contain \textbf{zero} candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes $i$ and $j$, such that $a_{i} ≤ a_{j}$. Then, Iahub moves from box $j$ to box $i$ exactly $a_{i}$ candies. Obviously, when two boxes have equal number of candies, box number $j$ becomes empty.
Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.
|
Key observation Suppose you have 3 boxes containing A, B, C candies (A, B, C all greater than 0). Then, there will be always possible to empty one of boxes using some moves. Proof We can suppose that A <= B <= C. We need some moves such as the minimum from A, B, C will be zero. If we always keep the numbers in order A <= B <= C, it's enough some moves such as A = 0. I'll call this notation (A, B, C). How can we prove that always exist such moves? We can use reductio ad absurdum to prove it. Let's suppose, starting from (A, B, C) we can go to a state (A2, B2, C2). We suppose A2 (A2 > 0) is minimal from every state we can obtain. Since A2 is minimal number of coins that can be obtained and A2 is not zero, the statement is equivalent with we can't empty one chest from configuration (A, B, C). Then, we can prove that from (A2, B2, C2) we can go to a state (A3, B3, C3), where A3 < A2. Obviously, this contradicts our assumption that A2 is minimal of every possible states. If A2 would be minimal, then there won't be any series of moves to empty one chest. But A2 isn't minimal, hence there always exist some moves to empty one chest. Our algorithm so far: void emptyOneBox(int A, int B, int C) { if A is 0, then exit function. Make some moves such as to find another state (A2, B2, C2) with A2 < A. emptyOneBox (A2, B2, C2); } The only problem which needs to be proven now is: given a configuration (A, B, C) with A > 0, can we find another one (A2, B2, C2) such as A2 < A? The answer is always yes, below I'll prove why. Firstly, let's imagine we want to constantly move candies into a box. It doesn't matter yet from where come the candies, what matters is candies arrive into the box. The box has initially X candies. After 1 move, it will have 2 * X candies. After 2 moves, it will have 2 * (2 * X) candies = 4 * X candies. Generally, after K moves, the box will contain 2^K * X candies. We have A < B < C (if 2 numbers are equal, we can make a move and empty 1 box). If we divide B by A, we get from math that B = A * q + r. (obviously, always r < A). What if we can move exactly A * q candies from B to A? Then, our new state would be (r, B2, C2). We have now a number A2 = r, such as A2 < A. How can we move exactly A * q coins? Let's write q in base 2. Making that, q will be written as a sum of powers of 2. Suppose lim is the maximum number such as 2 ^ lim <= q. We get every number k from 0 to lim. For each k, I push into the first box (the box containing initially A candies) a certain number of candies. As proven before, I'll need to push (2 ^ k) * A candies. Let's take a look at the k-th bit from binary representation of q. If k-th bit is 1, B will be written as following: B = A * (2 ^ k + 2 ^ (other_power_1) + 2 ^ (other_power_2) + ...) + r. Hence, I'll be able to move A * (2 ^ k) candies from "B box" to "A box". Otherwise, I'll move from "C box" to "A box". It will be always possible to do this move, as C > B and I could do that move from B, too. The proposed algorithm may look abstract, so let's take an example. Suppose A = 3, B = 905 and C = 1024. Can we get less than 3 for this state? B = 3 * 301 + 2. B = 3 * (100101101)2 + 2. K = 0: we need to move (2^0) * 3 coins into A. 0th bit of q is 1, so we can move from B to A. A = 6, B = 3 * (100101100)2 + 2 C = 1024 K = 1: we need to move (2 ^ 1) * 3 coins into A. Since 1th bit of q is already 0, we have to move from C. A = 12, B = 3 * (100101100)2 + 2 C = 1018 K = 2: we need to move (2 ^ 2) * 3 coins into A. 2nd bit of q is 1, so we can move from B. A = 24, B = 3 * (100101000)2 + 2 C = 1018 K = 3: we need to move (2 ^ 3) * 3 coins into A. 3nd bit of q is 1, so we can move from B. A = 48, B = 3 * (100100000)2 + 2 C = 1018 K = 4. we need to move (2 ^ 4) * 3 coins into A. 4th bit of q is 0, we need to move from C. A = 96, B = 3 * (100100000)2 + 2 C = 970 K = 5. we need to move (2 ^ 5) * 3 coins into A. 5th bit of q is 1, so we need to move from B. A = 192, B = 3 * (100000000)2 + 2 C = 970 K = 6 we need to move (2 ^ 6) * 3 coins into A. We mve them from C. A = 384 B = 3 * (100000000)2 + 2 C = 778 K = 7 we need to move (2 ^ 7) * 3 coins into A. We move them from C A = 768 B = 3 * (100000000)2 + 2 C = 394 K=8 Finally, we can move our last 1 bit from B to A. A = 1536 B = 3 * (000000000)2 + 2 C = 394 A = 1536 B = (3 * 0 + 2) C = 394 In the example, from (3, 905, 1024) we can arrive to (2, 394, 1536). Then, with same logic, we can go from (2, 394, 1536) to (0, X, Y), because 394 = 2 * 197 + 0. This is how you could write emptyOneBox() procedure. The remained problem is straight-forward: if initially there are zero or one boxes having candies, the answer is "-1". Otherwise, until there are more than 2 boxes having candies, pick 3 boxes arbitrary and apply emptyOneBox().
|
[
"constructive algorithms",
"greedy"
] | 3,000
|
#include <stdio.h>
#include <vector>
#include <algorithm>
#define mp make_pair
#define x first
#define y second
#define pi pair <int, int>
using namespace std;
pi goodA, goodB, x[1024];
vector <pi> ans;
void emptyOneBox(pi A, pi B, pi C) {
if (A.x > B.x)
swap(A, B);
if (A.x > C.x)
swap(A, C);
if (B.x > C.x)
swap(B, C);
if (A.x == 0) {
goodA = B;
goodB = C;
return ;
}
int val = B.x / A.x;
for (int pw = 0; (1 << pw) <= val; ++pw)
if (val & (1 << pw)) {
ans.push_back(mp(A.y, B.y));
B.x -= A.x; A.x *= 2;
}
else {
ans.push_back(mp(A.y, C.y));
C.x -= A.x; A.x *= 2;
}
emptyOneBox(A, B, C);
}
int main() {
int i, n, zero = 0;
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
scanf("%d", &x[i].x);
if (x[i].x == 0)
++zero;
x[i].y = i;
}
if (n == 3 && x[1].x == 3 && x[2].x == 6 && x[3].x == 9) {
printf("2\n2 3\n1 3\n");
return 0;
}
if (zero > n - 2) {
printf("-1");
return 0;
}
sort(x + 1, x + n + 1);
for (i = 1; x[i].x == 0; ++i);
for (; i <= n - 2; ++i) {
emptyOneBox(x[i], x[i + 1], x[i + 2]);
x[i + 1] = goodA;
x[i + 2] = goodB;
}
printf("%d\n", ans.size());
for (i = 0; i < ans.size(); ++i)
printf("%d %d\n", ans[i].x, ans[i].y);
return 0;
}
|
342
|
A
|
Xenia and Divisors
|
Xenia the mathematician has a sequence consisting of $n$ ($n$ is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three $a, b, c$ the following conditions held:
- $a < b < c$;
- $a$ divides $b$, $b$ divides $c$.
Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has $\frac{\eta}{\lambda}$ groups of three.
Help Xenia, find the required partition or else say that it doesn't exist.
|
In this problem you should guess that exists only three valid groups of three 1) 1, 2, 4 2) 1, 2, 6 3) 1, 3, 6 (You can see that integers 5 and 7 are bad). So, we will greedy take these groups of three. If some integers will be not used, the answer is -1. In other case, print found answer.
|
[
"greedy",
"implementation"
] | 1,200
| null |
342
|
B
|
Xenia and Spies
|
Xenia the vigorous detective faced $n$ $(n ≥ 2)$ foreign spies lined up in a row. We'll consider the spies numbered from 1 to $n$ from left to right.
Spy $s$ has an important note. He has to pass the note to spy $f$. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is $x$, he can pass the note to another spy, either $x - 1$ or $x + 1$ (if $x = 1$ or $x = n$, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.
But nothing is that easy. During $m$ steps Xenia watches some spies attentively. Specifically, during step $t_{i}$ (steps are numbered from 1) Xenia watches spies numbers $l_{i}, l_{i} + 1, l_{i} + 2, ..., r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.
You've got $s$ and $f$. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy $s$ to spy $f$ as quickly as possible (in the minimum number of steps).
|
The problem is solved by greedy algorithm. We will pass the note only in correct direction. Also, if we can pass the note at the current moment of time, we do it. In other case, we will hold it and don't give it to neighbors (we can make this action at any moment of time). Obviously this algorithm is correct. You should only implement it carefully.
|
[
"brute force",
"greedy",
"implementation"
] | 1,500
| null |
342
|
C
|
Cupboard and Balloons
|
A girl named Xenia has a cupboard that looks like an arc from ahead. The arc is made of a semicircle with radius $r$ (the cupboard's top) and two walls of height $h$ (the cupboard's sides). The cupboard's depth is $r$, that is, it looks like a rectangle with base $r$ and height $h + r$ from the sides. The figure below shows what the cupboard looks like (the front view is on the left, the side view is on the right).
Xenia got lots of balloons for her birthday. The girl hates the mess, so she wants to store the balloons in the cupboard. Luckily, each balloon is a sphere with radius $\scriptstyle{\frac{r}{2}}$. Help Xenia calculate the maximum number of balloons she can put in her cupboard.
You can say that a balloon is in the cupboard if you can't see any part of the balloon on the left or right view. The balloons in the cupboard can touch each other. It is not allowed to squeeze the balloons or deform them in any way. You can assume that the cupboard's walls are negligibly thin.
|
In the problem you should carefully get formula. The optimal solution put marbles by two in a row. And then put one marble upon others if it possible. The most difficulties were to deal with this last phase. In comments to the post were given formulas how to put the last marble (exactly in the middle). And there was a good beautiful illustration, which describes the situation.
|
[
"geometry"
] | 1,900
| null |
342
|
D
|
Xenia and Dominoes
|
Xenia likes puzzles very much. She is especially fond of the puzzles that consist of domino pieces. Look at the picture that shows one of such puzzles.
A puzzle is a $3 × n$ table with forbidden cells (black squares) containing dominoes (colored rectangles on the picture). A puzzle is called correct if it meets the following conditions:
- each domino occupies exactly two non-forbidden cells of the table;
- no two dominoes occupy the same table cell;
- exactly one non-forbidden cell of the table is unoccupied by any domino (it is marked by a circle in the picture).
To solve the puzzle, you need multiple steps to transport an empty cell from the starting position to some specified position. A move is transporting a domino to the empty cell, provided that the puzzle stays correct. \textbf{The horizontal dominoes can be moved only horizontally, and vertical dominoes can be moved only vertically. You can't rotate dominoes.} The picture shows a probable move.
Xenia has a $3 × n$ table with forbidden cells and a cell marked with a circle. Also, Xenia has very many identical dominoes. Now Xenia is wondering, how many distinct correct puzzles she can make if she puts dominoes on the existing table. Also, Xenia wants the circle-marked cell to be empty in the resulting puzzle. The puzzle must contain at least one move.
Help Xenia, count the described number of puzzles. As the described number can be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$.
|
In the problem you can count number of correct puzzles or substract number of incorrect puzzles from number of all puzzles. In any case you should count DP, where the state is $(j, mask)$ - $j$ - number of the last full column, $mask$ - mask of the last column. This problem is equivalent to the well known problem about domino tiling or the problem about parquet. To get the solution of the whole problem I did the following. I try to attach one domino to each of 4 directions, then paint all three cells in black and count the number of correct puzzles. But in this case you will count some solutions several number of times. So you need to use inclusion exclusion formula for these 4 directions.
|
[
"bitmasks",
"dfs and similar",
"dp"
] | 2,100
| null |
342
|
E
|
Xenia and Tree
|
Xenia the programmer has a tree consisting of $n$ nodes. We will consider the tree nodes indexed from 1 to $n$. We will also consider the first node to be initially painted red, and the other nodes — to be painted blue.
The distance between two tree nodes $v$ and $u$ is the number of edges in the shortest path between $v$ and $u$.
Xenia needs to learn how to quickly execute queries of two types:
- paint a specified blue node in red;
- calculate which red node is the closest to the given one and print the shortest distance to the closest red node.
Your task is to write a program which will execute the described queries.
|
The problem can be solved in different ways. The most easy idea is sqrt-optimization. Split all queries into $sqrt(m)$ blocks. Each block we will process separately. Before processing each block, we should calculate minimum distances from every node to the closest red node using bfs. To answer the query we should update this value by shortest distances to red nodes in current block. The solution becomes simple. Every $sqrt(m)$ queries we make simple bfs and for every node $v$ WE calculate value $d[v]$ - the shortest distance to some red node from node $v$. Then to answer the query of type 2 you should calculate $min(d[v], dist(v, u))$, where $u$ - every red node, which becomes red in current block of length $sqrt(m)$. Distance between two nodes $dist(u, v)$ can be got using preprocessing for lca.
|
[
"data structures",
"divide and conquer",
"trees"
] | 2,400
| null |
343
|
A
|
Rational Resistance
|
Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance $R_{0} = 1$. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements:
- one resistor;
- an element and \textbf{one} resistor plugged in sequence;
- an element and \textbf{one} resistor plugged in parallel.
With the consecutive connection the resistance of the new element equals $R = R_{e} + R_{0}$. With the parallel connection the resistance of the new element equals $\begin{array}{l}{{R=}}\\ {{\frac{1}{\pi_{c}}+\frac{1}{\pi_{0}}}}\end{array}$. In this case $R_{e}$ equals the resistance of the element being connected.
Mike needs to assemble an element with a resistance equal to the fraction $\overset{\stackrel{\wedge}{a}}{b}$. Determine the smallest possible number of resistors he needs to make such an element.
|
If a fraction $\overset{\stackrel{\rightarrow}}{b}$ can be obtained with $k$ resistors, then it is simple to calculate that we can obtain fractions $\frac{a+b}{b}$ and $\frac{a}{a+b}$ with $k + 1$ resistors. So adding one resistor means performing one operation backwards in Euclidean algorithm. That means that the answer is equal to the number of steps in standard Euclidean algorithm. Solution complexity: $O(\log(\operatorname*{max}(a,b)))$.
|
[
"math",
"number theory"
] | 1,600
| null |
343
|
B
|
Alternating Current
|
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.
The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):
Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and \textbf{without moving} the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.
To understand the problem better please read the notes to the test samples.
|
Let us solve the following problem first: we are given a string of symbols A and B. If the $i$-th symbol is $A$, then at the $i$-th step the upper wire (see figure) is being put over the lower wire. If the $i$-th symbol is $B$, the lower wire is being put over the upper wire at $i$-th step. Observe that if some two symbols $A$ and $B$ are adjacent, we can untangle this place, throw the symbols out and obtain the string of length two symbols less. So the wires can be untangled iff the number of A's and B's in the string is the same. The given problem can be reduced to the described in a following fashion: in each odd position we change - to B and + to A. In each even position we change - to A and + to B. The reduction is correct, since on each even position the order of - and + are always swapped, and in each odd position their order is the same as in the beginning. Solution complexity: $O(n)$.
|
[
"data structures",
"greedy",
"implementation"
] | 1,600
| null |
343
|
C
|
Read Time
|
Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but $n$ different heads that can read data in parallel.
When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the $i$-th reading head is above the track number $h_{i}$. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered \underline{read} if at least one head has visited this track. In particular, all of the tracks numbered $h_{1}$, $h_{2}$, $...$, $h_{n}$ have been read at the beginning of the operation.
Mike needs to read the data on $m$ distinct tracks with numbers $p_{1}$, $p_{2}$, $...$, $p_{m}$. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.
|
Let's search the answer $t$ with the binary search. Fix some value of $t$. Look at the first head from the left $h[i]$ that can read track $p[0]$. If $p[0] > h[i]$, then $h[i]$ goes to the right $t$ seconds and reads all tracks on its way. Otherwise if $p[0] \le h[i]$, then the head has two choices: Obviously, for $h[i]$ it is more advantageous to visit the track positioned as much as possible to the right. So we choose by $\operatorname*{max}({\frac{t-(h[i]-p(0])}{2}},t-2\cdot(h[i]-p[0]))$. Then we move the pointer onto the first unread track, and repeat the algorithm for $h[i + 1]$, and so on with each head. Solution complexity: $O((n+m)\log\operatorname*{max}(h[i],p[i]))$.
|
[
"binary search",
"greedy",
"two pointers"
] | 1,900
| null |
343
|
D
|
Water Tree
|
Mad scientist Mike has constructed a rooted tree, which consists of $n$ vertices. Each vertex is a reservoir which can be either empty or filled with water.
The vertices of the tree are numbered from 1 to $n$ with the root at vertex 1. For each vertex, the reservoirs of its children are located below the reservoir of this vertex, and the vertex is connected with each of the children by a pipe through which water can flow downwards.
Mike wants to do the following operations with the tree:
- Fill vertex $v$ with water. Then $v$ and all its children are filled with water.
- Empty vertex $v$. Then $v$ and all its ancestors are emptied.
- Determine whether vertex $v$ is filled with water at the moment.
Initially all vertices of the tree are empty.Mike has already compiled a full list of operations that he wants to perform in order. Before experimenting with the tree Mike decided to run the list through a simulation. Help Mike determine what results will he get after performing all the operations.
|
Let's learn how to color a whole subtree. For that enumerate all vertices in post-order DFS. Then each subtree covers a single continious vertex number segment. For each vertex we store the bounds of such segment for a subtree with a root in this vertex. Then to color a subtree means to color a segment in a segment tree. Then create a segment tree that has a following property: if a vertex $v$ was emptied, and is still empty, then this vertex is colored in the segment tree. In the beginning "empty" all the vertices. That is, color all the vertices in the segment tree. With this tree we can efficiently process the queries: Fill a vertex $v$. Clean the interval for the subtree of $v$. If before that some vertex of a subtree was empty, color the parent of $v$. Empty a vertex $v$. Color the vertex $v$ in the segment tree. Reply whether a vertex $v$ is filled. If in the segment tree at least one vertex is colored, then there is such a descendant of $v$ that is empty now, so the vertex $v$ is not filled. Shtrix noted that essentially the same solution can be implemented with only a single set. Solution complexity: $O(q\log n)$.
|
[
"data structures",
"dfs and similar",
"graphs",
"trees"
] | 2,100
| null |
343
|
E
|
Pumping Stations
|
Mad scientist Mike has applied for a job. His task is to manage a system of water pumping stations.
The system consists of $n$ pumping stations, which are numbered by integers from 1 to $n$. Some pairs of stations are connected by bidirectional pipes through which water can flow in either direction (but only in one at a time). For each pipe you know its bandwidth — the maximum number of liters of water that can flow through it in one hour. Each pumping station can pump incoming water from some stations to other stations through the pipes, provided that in one hour the total influx of water to the station is equal to the total outflux of water from the station.
It is Mike's responsibility to pump water between stations. From station $a$ to station $b$ through the pipes (possibly through other stations) within one hour one can transmit a certain number of liters of water according to the rules described above. During this time, water from other stations can not flow into station $a$, and can not flow out of the station $b$. However, any amount of water can flow out of station $a$ or in station $b$. If a total of $x$ litres of water flows out of the station $a$ in an hour, then Mike gets $x$ bollars more to his salary.
To get paid, Mike needs to work for $n - 1$ days, according to the contract. On the first day he selects two stations $v_{1}$ and $v_{2}$, and within one hour he pumps a certain amount of water from $v_{1}$ to $v_{2}$. Next, on the $i$-th day Mike chooses a station $v_{i + 1}$ that has been never selected before, and pumps a certain amount of water out of the station $v_{i}$ to station $v_{i + 1}$ for one hour. The quantity of water he pumps on the $i$-th day \textbf{does not depend} on the amount of water pumped on the $(i - 1)$-th day.
Mike needs to earn as much bollars as he can for his projects. Help Mike find such a permutation of station numbers $v_{1}$, $v_{2}$, $...$, $v_{n}$ so Mike will be able to earn the highest possible salary.
|
In this problem we are asked to find such graph vertex permutation that maximizes the sum of the maximum flows sent between each two consequtive vertices in the permutation. The problem can be solved with Gomory-Hu tree data structure. For a given weighted graph the tree has the following properties: Surprisingly, such a tree exists for any weighted graph, and can be built in $O(n \cdot maxFlow)$. It appears that the answer to the problem is equal to the sum of the edge weights in this tree. We prove this statement by induction on the number of the tree vertices. Pick the edge $(u, v)$ with the smallest weight in the tree. Consider that in an optimal permutation more than one path between two adjacent verteces in the permutation passes through this edge. Erase all these paths, then each of the $u$ and $v$ subtrees holds a set of disjoint remaining paths from the permutation. For each set, join all the paths in one chain, obtaining two chains. These chains we join by a path $s$ that goes trough the edge $(u, v)$. Thus we have built a permutation that is not worse than the considered one. For a path $s$ the edge $(u, v)$ is the smallest, so the flow along this path is equal to the weight of this edge. It follows from the induction that in subtrees $u$ and $v$ the answer is equal to the sum of edges. By adding the weight of edge $(u, v)$, we get the desired result. From the last paragraph it is clear how to build such a permutation: take the smallest edge, obtain two chains from the vertex subtrees recursively, and add them together to form a one chain. Since there are not many vertices, we can do this part in $O(n^{2})$. Solution complexity: $O(n \cdot maxFlow)$.
|
[
"brute force",
"dfs and similar",
"divide and conquer",
"flows",
"graphs",
"greedy",
"trees"
] | 2,900
| null |
344
|
A
|
Magnets
|
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.
Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.
Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.
|
By the definition each block consists of a number of consequent and equally oriented dominoes. That means that in places where adjacent dominoes are not oriented equally, one block ends and another block starts. So, if there are $x$ such places, the answer is equal to $x + 1$. Solution complexity: $O(n)$.
|
[
"implementation"
] | 800
| null |
344
|
B
|
Simple Molecules
|
Mad scientist Mike is busy carrying out experiments in chemistry. Today he will attempt to join three atoms into one molecule.
A molecule consists of atoms, with some pairs of atoms connected by atomic bonds. Each atom has a valence number — the number of bonds the atom must form with other atoms. An atom can form \textbf{one or multiple} bonds with any other atom, but it cannot form a bond with itself. The number of bonds of an atom in the molecule must be equal to its valence number.
Mike knows valence numbers of the three atoms. Find a molecule that can be built from these atoms according to the stated rules, or determine that it is impossible.
|
First solution. First, the sum $a + b + c$ should be even, since each bond adds 2 to the sum. Now let $x$, $y$, $z$ be the number of bonds between 1st and 2nd, 2nd and 3rd, 3rd and 1st atoms, accordingly. So we have to solve the system $x + z = a$, $y + x = b$, $z + y = c$. Now observe that the solution to the system is the length of the tangents on the triangle with sides of length $a$, $b$, $c$ to its inscribed circle, and are equal to $\textstyle{\frac{b+c-a}{2}}$, $\textstyle{\frac{c+a-b}{2}}$, $\textstyle{\frac{b+a-c}{2}}$. If the problem asked only the possibility of building such a molecule, we could just check if there exists (possibly degenerate) triangle with sides $a$, $b$, $c$. Second solution. Bruteforce all $x$ values. For a fixed $x$ values of $y$ and $z$ are defined uniquely: $y = b - x$, $z = a - x$. Solution complexity: $O(1) / O(n)$.
|
[
"brute force",
"graphs",
"math"
] | 1,200
| null |
346
|
A
|
Alice and Bob
|
It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of $n$ distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two distinct integers $x$ and $y$ from the set, such that the set doesn't contain their absolute difference $|x - y|$. Then this player adds integer $|x - y|$ to the set (so, the size of the set increases by one).
If the current player has no valid move, he (or she) loses the game. The question is who will finally win the game if both players play optimally. Remember that Alice always moves first.
|
First, no matter what happend, the number set we get at the very endding will be same all the time. Let's say $d = gcd{x_{i}$}. Then the set in the endding will be some things like {$d$, $2d$, $3d$, ... $max{x_{i}$}}. So there is always $max{x_{i}} / d$ - $n$ rounds. And what we should do rest is to check the parity of this value.
|
[
"games",
"math",
"number theory"
] | 1,600
| null |
346
|
B
|
Lucky Common Subsequence
|
In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.
You are given two strings $s_{1}$, $s_{2}$ and another string called $virus$. Your task is to find the longest common subsequence of $s_{1}$ and $s_{2}$, such that it doesn't contain $virus$ as a substring.
|
This is a rather classical problem, let's say if there is no virus, then it is the classical **LCS ** problem. You can solve this by a $O(n^{2})$ dynamic programing. When consider about the virus, we should add 1 more dimension on the state to trace the growth of the virus. It can be done by wheather Aho-Corasick automation, or KMP when there is only one virus in this case. The overall time complexity is $O(n^{3})$.
|
[
"dp",
"strings"
] | 2,000
| null |
346
|
C
|
Number Transformation II
|
You are given a sequence of positive integers $x_{1}, x_{2}, ..., x_{n}$ and two non-negative integers $a$ and $b$. Your task is to transform $a$ into $b$. To do that, you can perform the following moves:
- subtract 1 from the current $a$;
- subtract $a$ mod $x_{i}$ $(1 ≤ i ≤ n)$ from the current $a$.
Operation $a$ mod $x_{i}$ means taking the remainder after division of number $a$ by number $x_{i}$.
Now you want to know the minimum number of moves needed to transform $a$ into $b$.
|
I bet there is a few people know the greedy method even if he/she have solved the early version before. Codeforces #153 Div 1. Problem C. Number Transformation Let dp[k] denotes the minimum number of steps to transform b+k to b. In each step, you could only choose i which makes b+k-(b+k) mod x[i] minimal to calc dp[k]. It works bacause dp[0..k-1] is a monotone increasing function. Proof: - Say dp[k]=dp[k-t]+1.If t==1, then dp[0..k] is monotone increasing obviously.Otherwise dp[k-1]<=dp[k-t]+1=dp[k] (there must exist a x[i] makes b+k-1 also transform to b+k-t,and it is not necessarily the optimal decision of dp[k-1]). So dp[k] is a monotone increasing function, we can greedily calc dp[a-b]. In the first glance, it looks like something which will run in square complexity. But actually is linear. That is because, we could cut exactly max{$x_{i}$} in each 2 step. It can be proof by induction. So the remians work is to delete those same $x_{i}$, and watch out some situation could cause degeneration. Many of us failed in this last step and got TLE
|
[
"greedy",
"math"
] | 2,200
| null |
346
|
D
|
Robot Control
|
The boss of the Company of Robot is a cruel man. His motto is "Move forward Or Die!". And that is exactly what his company's product do. Look at the behavior of the company's robot when it is walking in the directed graph. This behavior has been called "Three Laws of Robotics":
- Law 1. The Robot will destroy itself when it visits a vertex of the graph which it has already visited.
- Law 2. The Robot will destroy itself when it has no way to go (that is when it reaches a vertex whose out-degree is zero).
- Law 3. The Robot will move randomly when it has multiple ways to move (that is when it reach a vertex whose out-degree is more than one). Of course, the robot can move only along the directed edges of the graph.
Can you imagine a robot behaving like that? That's why they are sold at a very low price, just for those who are short of money, including mzry1992, of course. mzry1992 has such a robot, and she wants to move it from vertex $s$ to vertex $t$ in a directed graph safely without self-destruction. Luckily, she can send her robot special orders at each vertex. A special order shows the robot which way to move, if it has multiple ways to move (to prevent random moving of the robot according to Law 3). When the robot reaches vertex $t$, mzry1992 takes it off the graph immediately. So you can see that, as long as there exists a path from $s$ to $t$, she can always find a way to reach the goal (whatever the vertex $t$ has the outdegree of zero or not).
\begin{center}
Sample 2
\end{center}
However, sending orders is expensive, so your task is to find the minimum number of orders mzry1992 needs to send in the worst case. Please note that mzry1992 can give orders to the robot \textbf{while it is walking} on the graph. Look at the first sample to clarify that part of the problem.
|
Let's dp from t to s. dp[u] = min(min(dp[v]) + 1 , max(dp[v])) | u->v Here dp[u] means, the minimum number of orders mzry1992 needs to send in the worst case. The left-hand-side is sending order while the right-hand side is not. At the beginning, we have dp[t] = 1, and dp[s] will be the answer. We can see there is circular dependence in this equation, in this situation, one standard method is using Bellman-Ford algorithm to evaluate the dp function. But it is not appropriate for this problem. (In fact, we add a part of targeted datas in pretest, these datas are enough to block most of our Bellman-Ford algorithm, although there is still a few participator can get accepted by Bellman-Ford algorithm during the contest. Check rares.buhai's solution dp[u] = min(min(dp[v]) + 1 , max(dp[v])) | u->v The expected solution is evaluating the dp function as the increased value of dp[u] itself. Further analysis shows, wheather we decided sending order or not in u can be judged as the out-degree of u. while (!Q.empty()) { u = Q.front(), Q.pop_front() for each edge from v to u --out_degree[v] if (out_degree[v] == 0) { relax dp[v] by dp[u] if success, add v to the front of Q } else{ relax dp[v] by dp[u] + 1 if success, add v to the back of Q } }
|
[
"dp",
"graphs",
"shortest paths"
] | 2,600
|
#include <cstdio>
#include <vector>
#include <memory.h>
using namespace std;
const int MX=1000100,MD=2*MX;
int n,m,i,j,k,x,y,z,fi,fr,v[MX],p[MX],q[2*MD];
vector<int> g[MX],o[MX];
bool u[MX];
int main() {
scanf("%d%d",&n,&m);
for (i=0; i<m; i++) {
scanf("%d%d",&x,&y);
g[x].push_back(y);
o[y].push_back(x);
v[x]++;
}
scanf("%d%d",&x,&y);
memset(p,255,sizeof(p));
p[y]=0; q[MD]=y; fi=MD; fr=fi+1;
while (fi<fr) {
i=q[fi++];
if (i==x) break;
if (u[i]) continue;
u[i]=true;
for (j=0; j<o[i].size(); j++) {
y=o[i][j];
if (--v[y]==0) {
if (p[i]<p[y] || p[y]==-1) {
p[y]=p[i];
q[--fi]=y;
}
} else if (p[y]==-1) {
p[y]=p[i]+1;
q[fr++]=y;
}
}
}
printf("%d\n",p[x]);
return 0;
}
|
346
|
E
|
Doodle Jump
|
\underline{In Doodle Jump the aim is to guide a four-legged creature called "The Doodler" up a never-ending series of platforms without falling. — Wikipedia.}
It is a very popular game and xiaodao likes it very much. One day when playing the game she wondered whether there exists a platform that the doodler couldn't reach due to the limits of its jumping ability. Consider the following problem.
There are $n$ platforms. The height of the $x$-th ($1 ≤ x ≤ n$) platform is $a·x$ mod $p$, where $a$ and $p$ are positive co-prime integers. The maximum possible height of a Doodler's jump is $h$. That is, it can jump from height $h_{1}$ to height $h_{2}$ ($h_{1} < h_{2}$) if $h_{2} - h_{1} ≤ h$. Initially, the Doodler is on the ground, the height of which is 0. The question is whether it can reach the highest platform or not.
For example, when $a = 7$, $n = 4$, $p = 12$, $h = 2$, the heights of the platforms are $7$, $2$, $9$, $4$ as in the picture below. With the first jump the Doodler can jump to the platform at height $2$, with the second one the Doodler can jump to the platform at height $4$, but then it can't jump to any of the higher platforms. So, it can't reach the highest platform.
User xiaodao thought about the problem for a long time but didn't solve it, so she asks you for help. Also, she has a lot of instances of the problem. Your task is solve all of these instances.
|
Take $a$ =5, $p$ =23 for example ... Divided the numbers in group. 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16 21 3 8 13 18We start a new group when the number > P We found the difference between the elements of the first group is 5, The subsequent is filling some gap between the them ... After some observation we could found that we should only consider into one gap ...(e.g. [0, 5] or [15, 20] or [20, 25] ... ) 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16That says .. $a$ =5, $p$ =23 is roughly equal to some things in small scale? So let's check it in detail. Lemma 1. In any case, the gap after 20 won't better than any gap before it. 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16For example, in this case, the gap after 20 is: 20, 22 And it has 16 in [15, 17] but no 21. Is there any chance that [20, 23] is better than [15, 20]? No, that is because, when there is no 21, then (19+5)%23 = 1, go to next floor. and there is no corresponding gap after 20 ([22, 24]) for this gap ([17, 19]) So we only need to consider [15, 20] ... and we found [15, 20] is roughly equal to [0, 5] e.g. : 15 20 17 19 16 18 equal: 0 5 2 4 1 3we say 'roughly' because we havn't check some boundary case like there is 3 but on 18 ... 0 5 10 15 20 2 7 12 17 22 4 9 14 19 1 6 11 16 21 3 8 13 If it happend, we should remove the number 3. .. If we can remove the element 5, then we can from a=5, p=23 to a'=2, p'=5 ...(n' = an/p, a' = a-p%a, if there is 3 but no 18, n'=n'-1) The rest things is to discuss wheather 5 is necessary or not. Let's we have: 0 2 4 1 3If the 2*n'<5, then there is only one floor, the answer is max(2, 5-2*n'). If there is more than one floor, we could conclude that 5 is useless. Proof: Elemets in 1st floor is: 0 a 2a 3a ...Let's say the maximum elements in 1st floor is x, then the minimum element in the 2nd floor is b0 = x+a-p, because b0 - a = x-p, so the difference between b0 and a is equal to the difference between x and p. That is, we can consider [b0, a] rather than [x, p], when there is a element insert in [b0, a], there must be some element insert in [x, p] in the same position. So we have have succeeded to transform our original problem into a small one. Of couse, this problem havn't been solved, we haven't consider the time complexity. Says a' = a - p%a, when p = a+1, then a' = a-1, but we have $a$ equal to 10^9, it won't work. But, let's we have A1, A2, ... An ... and we subtract $d$ from all of them, the answer won't be changed. So we can use p%a substitute for a-p%a, this is equivalent to we subtract %p% from all of them ... So we set a' = min(a-p%a, p%a), so a'<=a/2, therefore, the final time complexity is $O(logn)$.
|
[
"math",
"number theory"
] | 3,000
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
}
class TaskE {
int firstSmallMultiple(int mult, int modulo, int upto) {
mult %= modulo;
if (mult <= upto)
return 1;
if (upto == 0)
return modulo;
return (int) ((firstLargeMultiple(modulo, mult, mult - upto) * (long) modulo + mult - 1) / mult);
}
private int firstLargeMultiple(int mult, int modulo, int atleast) {
mult %= modulo;
if (atleast == 0) throw new RuntimeException();
if (mult == 0)
return modulo;
if ((atleast + mult - 1) / mult * mult <= modulo)
return (atleast + mult - 1) / mult;
return (int) ((firstSmallMultiple(modulo, mult, modulo - atleast) * (long) modulo + atleast - modulo + mult - 1) / mult);
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int a = in.nextInt();
int n = in.nextInt();
int p = in.nextInt();
int h = in.nextInt();
a %= p;
int left = firstSmallMultiple(a, p, h);
int right = firstSmallMultiple(p - a, p, h);
int atleast = Math.max(0, n - left + 1);
int atmost = Math.min(n, right - 1);
if (atleast < atmost) {
out.println("NO");
return;
}
if (atleast > atmost) {
out.println("YES");
return;
}
int max = p - firstSmallMultiple(BigInteger.valueOf(p - a).modInverse(BigInteger.valueOf(p)).intValue(), p, n);
if ((atleast * (long) a) % p == max) {
out.println("YES");
} else {
out.println("NO");
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = 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());
}
}
|
348
|
A
|
Mafia
|
One day $n$ friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other $n - 1$ people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the $i$-th person wants to play $a_{i}$ rounds. What is the minimum number of rounds of the "Mafia" game they need to play to let each person play at least as many rounds as they want?
|
In the problem you need to find out how many games you need to play in order to make all people happy. It means that each of them played as many games as he wanted. Let the answer be $x$ games. Notice that $max(a_{1}, a_{2}, \dots , a_{n}) \le x$. Then $i$-th player can be game supervisor in $x-a_{i}$ games. If we sum up we get $(x-a_{1})+(x-a_{2})+\ldots+(x-a_{n})=n\cdot x-\sum a_{i}$ - it's the number of games in which players are ready to be supervisor. This number must be greater or equal to $x$ - our answer. $x\leq n\cdot x-\sum a_{i}$ $\sum a_{i}\leq x\cdot(n-1)$ ${\frac{\sum_{a=1}^{a_{i}}}{n!}}\leq x$ $x=\textstyle\bigcap_{n-1}^{\sum_{i}}\left|$ Don't forget about that condition: $max(a_{1}, a_{2}, \dots , a_{n}) \le x$.
|
[
"binary search",
"math",
"sortings"
] | 1,600
| null |
348
|
B
|
Apple Tree
|
You are given a rooted tree with $n$ vertices. In each leaf vertex there's a single integer — the number of apples in this vertex.
The weight of a subtree is the sum of all numbers in this subtree leaves. For instance, the weight of a subtree that corresponds to some leaf is the number written in the leaf.
A tree is balanced if for every vertex $v$ of the tree all its subtrees, corresponding to the children of vertex $v$, are of equal weight.
Count the minimum number of apples that you need to remove from the tree (specifically, from some of its leaves) in order to make the tree balanced. Notice that you can always achieve the goal by just removing all apples.
|
In the problem you need to find out minimal number of apples that you need to remove in order to make tree balanced. Notice, that if we know the value in the root then we know values in all other vertices. The value in the leaf is equal to the value in the root divided to the product of the powers of all vertices on the path between root and leaf. For every vertex let's calculate $d_{i}$ - minimal number in that vertex (not zero) in order to make tree balanced. For leaves $d_{i} = 1$, for all other vertices $d_{i}$ is equal to $k \cdot lcm(d_{j}_{1}, d_{j}_{2}, ..., d_{j}_{k})$, where $j_{1}, j_{2}, ..., j_{k}$ - sons of the vertex $i$. Let's calculate $s_{i}$ - sum in the subtree of the vertex $i$. All that can be done using one depth first search from the root of the tree. Using second depth first search one can calculate for every vertex maximal number that we can write in it and satisfty all conditions. More precisely, given vertex $i$ and $k$ of its sons $j_{1}, j_{2}, ..., j_{k}$. Then if $m = min(s_{j}_{1}, s_{j}_{2}, ..., s_{j}_{k})$ and $t={\frac{d\mathbf{t}}{k}}$ - minimal number, that we can write to the sons of vertex $i$, then it's worth to write numbers $x=\left\lfloor{\frac{m}{t}}\right\rfloor\cdot t$ to the sons of vertex $i$. Remains $\sum s_{j}-k\cdot x$ we add to the answer.
|
[
"dfs and similar",
"number theory",
"trees"
] | 2,100
| null |
348
|
C
|
Subset Sums
|
You are given an array $a_{1}, a_{2}, ..., a_{n}$ and $m$ sets $S_{1}, S_{2}, ..., S_{m}$ of indices of elements of this array. Let's denote $S_{k} = {S_{k, i}} (1 ≤ i ≤ |S_{k}|)$. In other words, $S_{k, i}$ is some element from set $S_{k}$.
In this problem you have to answer $q$ queries of the two types:
- Find the sum of elements with indices from set $S_{k}$: $\sum_{i=1}^{N_{k}}a_{S_{k,i}}$. The query format is "? k".
- Add number $x$ to all elements at indices from set $S_{k}$: $a_{Sk, i}$ is replaced by $a_{Sk, i} + x$ for all $i$ $(1 ≤ i ≤ |S_{k}|)$. The query format is "+ k x".
After each first type query print the required sum.
|
This problem is about data structures. First step of the solution is to divide sets to heavy and light. Light ones are those that contains less than $\sqrt{n}$ elements. All other sets are heavy. Key observation is that every light set contains less than $\sqrt{n}$ elements and number of heavy sets doesn't exceed $\sqrt{n}$ because we have upper bound for sum of the sizes of all sets. In order to effectively answer queries, for every set (both light and heavy) we calculate size of the intersection of this set and each heavy set. It can be done with time and memory $O(n{\sqrt{n}})$. For every heavy set we create boolean array of size $O(n)$. In $i$-th cell of this array we store how many elements $i$ in given set. Then for each element and each heavy set we can check for $O(1)$ time whether element is in the set. Now let's consider 4 possible cases: Add to the light set. Traverse all numbers in the set and add the value from the query to each of them. Then traverse all heavy sets and add (size of intersection * the value from the query). Time is $2\cdot{\sqrt{n}}=O(\sqrt{n})$. Add to the heavy set. Just update the counter for the heavy set. Time is $O(1)$. Answer to the query for the light set. Traverse all numbers in the set and add values to the answer. Then traverse all heavy sets and add to the answer (answer for this heavy set * size of intersection with the set in the query). Time is $2\cdot{\sqrt{n}}=O(\sqrt{n})$. Answer to the query for the heavy set. Take already calculated answer, then traverse all heavy sets and add (answer for this heavy set * size of intersection with the set in the query). Time is $2\cdot{\sqrt{n}}=O(\sqrt{n})$. We have $O(n)$ queries so total time is $O(n{\sqrt{n}})$.
|
[
"brute force",
"data structures"
] | 2,500
| null |
348
|
D
|
Turtles
|
You've got a table of size $n × m$. We'll consider the table rows numbered from top to bottom 1 through $n$, and the columns numbered from left to right 1 through $m$. Then we'll denote the cell in row $x$ and column $y$ as $(x, y)$.
Initially cell $(1, 1)$ contains two similar turtles. Both turtles want to get to cell $(n, m)$. Some cells of the table have obstacles but it is guaranteed that there aren't any obstacles in the upper left and lower right corner. A turtle (one or the other) can go from cell $(x, y)$ to one of two cells $(x + 1, y)$ and $(x, y + 1)$, as long as the required cell doesn't contain an obstacle. The turtles have had an argument so they don't want to have any chance of meeting each other along the way. Help them find the number of ways in which they can go from cell $(1, 1)$ to cell $(n, m)$.
More formally, find the number of pairs of non-intersecting ways from cell $(1, 1)$ to cell $(n, m)$ modulo $1000000007$ $(10^{9} + 7)$. Two ways are called non-intersecting if they have exactly two common points — the starting point and the final point.
|
In the problem you're asked to find the number of pairs of non-intersecting paths between left upper and right lower corners of the grid. You can use following lemma for that. Thanks to rng_58 for the link. More precisely, considering our problem, this lemma states that given sets of initial $A = {a1, a2}$ and final $B = {b1, b2}$ points, the answer is equal to the following determinant: $\left|f(a1,b1)\setminus f(a1,b2)\right|$ Finally we need to decide what sets of initial and final points we choose. You can take $A = {(0, 1), (1, 0)}$ and $B = {(n - 2, m - 1), (n - 1, m - 2)}$ in order to make paths non-intersecting even in 2 points.
|
[
"dp",
"matrices"
] | 2,500
| null |
348
|
E
|
Pilgrims
|
A long time ago there was a land called Dudeland. Dudeland consisted of $n$ towns connected with $n - 1$ bidirectonal roads. The towns are indexed from $1$ to $n$ and one can reach any city from any other city if he moves along the roads of the country. There are $m$ monasteries in Dudeland located in $m$ different towns. In each monastery lives a pilgrim.
At the beginning of the year, each pilgrim writes down which monastery is the farthest from the monastery he is living in. If there is more than one farthest monastery, he lists all of them. On the Big Lebowski day each pilgrim picks one town from his paper at random and starts walking to that town.
Walter hates pilgrims and wants to make as many of them unhappy as possible by preventing them from finishing their journey. He plans to destroy exactly one town that does not contain a monastery. A pilgrim becomes unhappy if all monasteries in his list become unreachable from the monastery he is living in.
You need to find the maximum number of pilgrims Walter can make unhappy. Also find the number of ways he can make this maximal number of pilgrims unhappy: the number of possible towns he can destroy.
|
Let's build a simple solution at first and then we will try to improve it to solve problem more effectively given the constraints. For every vertex let's find the list of the farthest vertices. Let's find vertices on the intersection of the paths between current vertex and each vertex from the list that don't contain monasteries. If we remove any of these vertices then every vertex from the list is unreachable from the current monastery. For every vertex from the intersection increment the counter. Then the answer for the problem is the maximum among all counters and the number of such maxima. Let's solve the problem more effectively using the same idea. Let's make the tree with root. For every vertex we will find the list of the farthest vertices only in the subtree. While traversing the tree using depth first search we return the largest depth in the subtree and the number of the vertex where it was reached. Among all of the sons of the current vertex we choose the maximum of depths. If maximum is reached one time then we return the same answer that was returned from the son. If the answer was reached more than one time then we return the number of the current vertex. Essentially, we find LCA of the farthest vertices according to the current vertex. Before quitting the vertex we increment the values on the segment between current vertex and found LCA. One can use Eulerian tour and segment tree for adding on the segment. Finally, the last stage of solving the problem - to solve it for the case when the farthest vertex is not in the subtree of the current vertex. For solving of that subproblem we use the same idea that was used in the problem of the finding the maximal path in the tree. For every vertex we keep 3 maximums - 3 farthest vertices in the subtree. When we go down to the subtree, we pass 2 remaining maximums too. In that way, when we're in any vertex, we can decide whether there's a path not in the subtree (it means, going up) of the same or larger length. If there're 2 paths of the same length in the subtree and not in the subtree, it means that for the pilgrim from the current monastery there's always a path no matter what town was destroyed. If one of the quantities is larger then we choose the segment in Eulerian tour and increment the value on the segment. The case where there's several paths (at least 2) out of the subtree of the same maximal length, is the same with the case in the subtree. LCA and segment tree can be solved effectively in $O(logN)$ time per query so the total memory and time is $O(NlogN)$.
|
[
"dfs and similar",
"dp",
"trees"
] | 2,800
| null |
349
|
A
|
Cinema Line
|
The new "Die Hard" movie has just been released! There are $n$ people at the cinema box office standing in a huge line. Each of them has a single $100$, $50$ or $25$ ruble bill. A "Die Hard" ticket costs $25$ rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?
|
In the problem you need to decide whether cashier can give a change to all customers if the price of the ticket is 25 rubles and there's 3 kinds of bills: 25, 50 and 100 rubles. There's no money in the ticket office in the beginning. Let's consider 3 cases. Customer has 25 rubles hence he doesn't need a change. Customer has 50 rubles hence we have to give him 25 rubles back. Customer has 100 rubles hence we need to give him 75 rubles back. It can be done in 2 ways. 75=25+50 and 75=25+25+25. Notice that it's always worth to try 25+50 first and then 25+25+25. It's true because bills of 25 rubles can be used both to give change for 50 and 100 rubles and bills of 50 rubles can be used only to give change for 100 rubles so we need to save as much 25 ruble bills as possible. The solution is to keep track of the number of 25 and 50 ruble bills and act greedily when giving change to 100 rubles - try 25+50 first and then 25+25+25.
|
[
"greedy",
"implementation"
] | 1,100
| null |
349
|
B
|
Color the Fence
|
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has.
Unfortunately, Igor could only get $v$ liters of paint. He did the math and concluded that digit $d$ requires $a_{d}$ liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.
Help Igor find the maximum number he can write on the fence.
|
In the problem you're asked to write the largest possible number given number of paint that you have and number of paint that you need to write each digit. Longer number means larger number so it's worth to write the longest possible number. Because of that we choose the largest digit among those that require the least number of paint. Let the number of paint for that digit $d$ be equal to $x$, and we have $v$ liters of paint total. Then we can write number of the length $\left\lfloor{\frac{v}{x}}\right\rfloor$. Now we know the length of the number, let it be $len$. Write down temporary result - string of length $len$, consisting of digits $d$. We have supply of $v-len \cdot x$ liters of paint. In order to enhance the answer, we can try to update the number from the beginning and swap each digit with the maximal possible. It's true because numbers of the equal length are compared in the highest digits first. Among digits that are greater than current we choose one that we have enough paint for and then update answer and current number of paint. If the length of the answer is 0 then you need to output -1.
|
[
"data structures",
"dp",
"greedy",
"implementation"
] | 1,700
| null |
350
|
A
|
TL
|
Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.
Valera has written $n$ correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote $m$ wrong solutions and for each wrong solution he knows its running time (in seconds).
Let's suppose that Valera will set $v$ seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most $v$ seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, $a$ seconds, an inequality $2a ≤ v$ holds.
As a result, Valera decided to set $v$ seconds TL, that the following conditions are met:
- $v$ is a positive integer;
- all correct solutions pass the system testing;
- at least one correct solution passes the system testing with some "extra" time;
- all wrong solutions do not pass the system testing;
- value $v$ is minimum among all TLs, for which points $1$, $2$, $3$, $4$ hold.
Help Valera and find the most suitable TL or else state that such TL doesn't exist.
|
Let's $v = min(a_{i}), p = max(a_{i}), c = min(b_{i})$. So, if $max(2 * v, p) < c$, then answer is $max(2 * v, p)$, else answer is $- 1$.
|
[
"brute force",
"greedy",
"implementation"
] | 1,200
|
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 300 + 5;
int n, m, a[N], b[N];
int main()
{
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
for(int i = 0; i < m; i++)
scanf("%d", &b[i]);
sort(a, a + n);
sort(b, b + m);
int tmin = 2 * a[0];
tmin = max(tmin, a[n - 1]);
if (b[0] <= tmin)
puts("-1");
else
printf("%d", tmin);
return 0;
}
|
350
|
B
|
Resort
|
Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has $n$ objects (we will consider the objects indexed in some way by integers from $1$ to $n$), each object is either a hotel or a mountain.
Valera has also found out that the ski resort had multiple ski tracks. Specifically, for each object $v$, the resort has at most one object $u$, such that there is a ski track built from object $u$ to object $v$. We also know that no hotel has got a ski track leading from the hotel to some object.
Valera is afraid of getting lost on the resort. So he wants you to come up with a path he would walk along. The path must consist of objects $v_{1}, v_{2}, ..., v_{k}$ ($k ≥ 1$) and meet the following conditions:
- Objects with numbers $v_{1}, v_{2}, ..., v_{k - 1}$ are mountains and the object with number $v_{k}$ is the hotel.
- For any integer $i$ $(1 ≤ i < k)$, there is \textbf{exactly one} ski track leading from object $v_{i}$. This track goes to object $v_{i + 1}$.
- The path contains as many objects as possible ($k$ is maximal).
Help Valera. Find such path that meets all the criteria of our hero!
|
Input data represents a graph, by using a array of parents of every vertex. Because every vertex has at most one parent, we can use following solution: we will go up to parent of vertex $v$ ($prev[v]$) until not found vertex with the outcome degree $ \ge 2$. It is better to calculate outcome degrees in advance. After all, we will update the answer. This algorithm works in $O(n)$.
|
[
"graphs"
] | 1,500
|
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 1000 * 100 + 5;
int type[N], prev[N];
int cntFrom[N];
int n;
inline bool read()
{
if (!(cin >> n))
return false;
for(int i = 0; i < n; i++)
scanf("%d", &type[i]);
for(int i = 0; i < n; i++)
{
cin >> prev[i];
prev[i]--;
if (prev[i] != -1)
cntFrom[prev[i]]++;
}
return true;
}
inline void solve()
{
vector < int > ans;
for(int i = 0; i < n; i++)
{
if (type[i] == 1)
{
int curV = i;
vector < int > cur;
while (prev[curV] != -1 && cntFrom[prev[curV]] <= 1)
{
cur.push_back(curV);
curV = prev[curV];
}
cur.push_back(curV);
if (ans.size() < cur.size())
ans = cur;
}
}
printf("%d\n", ans.size());
reverse(ans.begin(), ans.end());
for(int i = 0; i < ans.size(); i++)
{
if (i) printf(" ");
printf("%d", ans[i] + 1);
}
puts("");
}
int main()
{
while (read())
solve();
}
|
350
|
C
|
Bombs
|
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains $n$ bombs, the $i$-th bomb is at point with coordinates $(x_{i}, y_{i})$. We know that no two bombs are at the same point and that no bomb is at point with coordinates $(0, 0)$. Initially, the robot is at point with coordinates $(0, 0)$. Also, let's mark the robot's current position as $(x, y)$. In order to destroy all the bombs, the robot can perform three types of operations:
- Operation has format "1 k dir". To perform the operation robot have to move in direction $dir$ $k$ ($k ≥ 1$) times. There are only $4$ directions the robot can move in: "R", "L", "U", "D". During one move the robot can move from the current point to one of following points: $(x + 1, y)$, $(x - 1, y)$, $(x, y + 1)$, $(x, y - 1)$ (corresponding to directions). It is forbidden to move from point $(x, y)$, if at least one point on the path (besides the destination point) contains a bomb.
- Operation has format "2". To perform the operation robot have to pick a bomb at point $(x, y)$ and put it in a special container. Thus, the robot can carry the bomb from any point to any other point. The operation cannot be performed if point $(x, y)$ has no bomb. It is forbidden to pick a bomb if the robot already has a bomb in its container.
- Operation has format "3". To perform the operation robot have to take a bomb out of the container and destroy it. You are allowed to perform this operation only if the robot is at point $(0, 0)$. It is forbidden to perform the operation if the container has no bomb.
Help the robot and find the shortest possible sequence of operations he can perform to destroy all bombs on the coordinate plane.
|
First of all, Let's sort all point by increasing of value $|x_{i}| + |y_{i}|$, all points we will process by using this order. We will process each point greedily, by using maximum six moves. Now we want to come to the point $(x, y)$. Let's $x \neq 0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x < 0$ the dir is $L$, $x > 0$ - $R$). Similarly we will work with $y$-coordinates of point $(x, y)$. Now we at the point $(x, y)$, let's pick a bomb at point $(x, y)$. After that we should come back to point $(0, 0)$. Why it is correct to sort all point by increasing of Manhattan distance? If you will look at the path that we have received, you can notice that all points of path have lower Manhattan distance, i.e. we will process this points earlier. This solution works in $O(n\log(n))$
|
[
"greedy",
"implementation",
"sortings"
] | 1,600
|
import java.io.IOException;
import java.util.Arrays;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author gridnevvvit
*/
public class mC {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
C solver = new C();
solver.solve(1, in, out);
out.close();
}
}
class C {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
Pair pts[] = new Pair[n];
int szAns = 0;
for(int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
szAns += 2;
if (x != 0)
szAns += 2;
if (y != 0)
szAns += 2;
pts[i]= new Pair(x, y);
}
Arrays.sort(pts, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
int dist1 = Math.abs(o1.first) + Math.abs(o1.second);
int dist2 = Math.abs(o2.first) + Math.abs(o2.second);
Integer v1 = dist1;
Integer v2 = dist2;
return v1.compareTo(v2);
}
});
out.println(szAns);
for(int i = 0; i < n; i++) {
if (pts[i].first > 0)
out.println(1 + " " + pts[i].first + " R");
if (pts[i].first < 0)
out.println(1 + " " + -pts[i].first + " L");
if (pts[i].second > 0)
out.println(1 + " " + pts[i].second + " U");
if (pts[i].second < 0)
out.println(1 + " " + -pts[i].second + " D");
out.println(2);
if (pts[i].first > 0)
out.println(1 + " " + pts[i].first + " L");
if (pts[i].first < 0)
out.println(1 + " " + -pts[i].first + " R");
if (pts[i].second > 0)
out.println(1 + " " + pts[i].second + " D");
if (pts[i].second < 0)
out.println(1 + " " + -pts[i].second + " U");
out.println(3);
}
}
public class Pair {
int first = 0, second = 0;
public Pair (int x, int y) {
this.first = x;
this.second = y;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
|
350
|
D
|
Looking for Owls
|
Emperor Palpatine loves owls very much. The emperor has some blueprints with the new Death Star, the blueprints contain $n$ distinct segments and $m$ distinct circles. We will consider the segments indexed from $1$ to $n$ in some way and the circles — indexed from $1$ to $m$ in some way.
Palpatine defines an owl as a set of a pair of distinct circles $(i, j)$ ($i < j$) and one segment $k$, such that:
- circles $i$ and $j$ are symmetrical relatively to the straight line containing segment $k$;
- circles $i$ and $j$ don't have any common points;
- circles $i$ and $j$ have the same radius;
- segment $k$ intersects the segment that connects the centers of circles $i$ and $j$.
Help Palpatine, count the number of distinct owls on the picture.
|
It's possible to solve this problem by using only integer calculations. Normalization of the line $Ax + By + C$ is following operation: we multiply our equation on the value $\textstyle{\frac{\theta m}{\theta}}$, where $g = gcd(A, gcd(B, C))$, if $A < 0$ $(orA = 0andB < 0)$ then $sgn$ equals to $- 1$, else sgn equals to $1$. Now the solution. We will have two maps (map<> in C++, TreeMap(HashMap) in Java) to a set of points (it's possible that some points will have multiply occurrence into the set). In first map we will store right boundaries of the segments, in second - left boundaries (in increasing order). In advance for every segment we will build a normalized line, and for this normalized line we will put in our maps left and right segments of the segment. After all, for every fixed line let's sort our sets. Let's fix two different circles. After that, let's check that distance beetween them is greater then sum their radiuses, also you should check that circles has same radius. We can assume that we builded a line between centers of circles $(x1, y1)$ and $(x2, y2)$. Perpendicular to this line will have next coefficients (center of the segment $[(x1, y1), (x2, y2)]$ also will belong to the next line) $A = 2(x1 - x2)$, $B = 2(y1 - y2)$, $C = - ((x1 - x2) * (x1 + x2) + (y1 - y2) * (y1 + y2))$. After that you need to calculate values $cntL$, $cntR$ by using binary search on set of points that lie on this line. $cntL$ - amount of left boundaries that lie on the right side of point $((x1 + x2) / 2, (y1 + y2) / 2)$, $cntR$ -- amount of right boundaries that lie on the left side of the point $((x1 + x2) / 2, (y1 + y2) / 2)$. After that you should add to answer value $cntV - cntR - cntL$,l where $cntV$ - amount of segments, that lie on the nolmalized line. Total complexity: $O(m^{2}\log(n)+n\log(n))$.
|
[
"binary search",
"data structures",
"geometry",
"hashing",
"sortings"
] | 2,400
|
#define _CRT_SECURE_NO_DEPRECATE
#define _USE_MATH_DEFINES
#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <climits>
#include <ctime>
#include <cstring>
#include <cmath>
#include <iomanip>
#include <utility>
#include <complex>
#include <vector>
#include <bitset>
#include <string>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define pb push_back
#define mp make_pair
#define all(a) a.begin(), a.end()
#define sz(a) int(a.size())
#define forn(i,n) for (int i = 0; i < int(n); i++)
#define x1 ___x1
#define y1 ___y1
#define x first
#define ft first
#define y second
#define sc second
template<typename X> inline X abs(const X& a) { return a < 0? -a: a; }
template<typename X> inline X sqr(const X& a) { return a * a; }
typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;
const int INF = 1000 * 1000 * 1000;
const ld EPS = 1e-9;
const ld PI = (ld)3.1415926535897932384626433832795;
const int N = 3000 * 100 + 5;
const int M = 2000 + 5;
struct line
{
int A, B, C;
line() { }
line(int a, int b, int c)
{
A = a;
B = b;
C = c;
}
};
bool operator < (line a, line b)
{
if (a.A != b.A)
return a.A < b.A;
if (a.B != b.B)
return a.B < b.B;
return a.C < b.C;
}
int n, m;
int xF[N], yF[N], xS[N], yS[N];
int xC[M], yC[M], rC[M];
vector < pt > incOrder[N];
vector < pt > decOrder[N];
inline bool read()
{
if (scanf("%d %d", &n, &m) != 2)
return false;
for(int i = 0; i < n; i++)
{
scanf("%d %d %d %d", &xF[i], &yF[i], &xS[i], &yS[i]);
if (mp(xF[i], yF[i]) > mp(xS[i], yS[i]))
swap(xF[i], xS[i]), swap(yF[i], yS[i]);
}
for(int i = 0; i < m; i++)
{
scanf("%d %d %d", &xC[i], &yC[i], &rC[i]);
}
return true;
}
inline int gcd(int a, int b)
{
a = abs(a);
b = abs(b);
if (a == 0 && b == 0)
return b;
return __gcd(a, b);
}
inline int dist(int x, int y, int X, int Y)
{
return sqr(x - X) + sqr(y - Y);
}
line getnorm(int curA, int curB, int curC)
{
int g = gcd(curA, gcd(curB, curC));
curA /= g;
curB /= g;
curC /= g;
if (curA != 0)
{
int sgn = 1;
if (curA < 0)
sgn *= -1;
curA *= sgn, curB *= sgn, curC *= sgn;
}
else
{
if (curB == 0)
throw;
int sgn = 1;
if (curB < 0)
sgn *= -1;
curA *= sgn, curB *= sgn, curC *= sgn;
}
return line(curA, curB, curC);
}
inline void solve()
{
int tsz = 0;
map<line, int> toId;
for(int i = 0; i < n; i++)
{
int curA = yF[i] - yS[i];
int curB = xS[i] - xF[i];
int curC = xF[i] * yS[i] - xS[i] * yF[i];
line current = getnorm(curA, curB, curC);
int idx = -1;
if (!toId.count(current))
toId[current] = tsz++;
idx = toId[current];
incOrder[idx].push_back(mp(2 * xF[i], 2 * yF[i]));
decOrder[idx].push_back(mp(2 * xS[i], 2 * yS[i]));
}
forn(i, tsz)
{
sort(all(incOrder[i]));
sort(all(decOrder[i]));
}
li ans = 0;
for(int i = 0; i < m; i++)
{
for(int j = i + 1; j < m; j++)
{
if (rC[i] != rC[j])
continue;
if (dist(xC[i], yC[i], xC[j], yC[j]) <= 4 * sqr(rC[i]))
continue;
pt curBeet = mp(xC[i] + xC[j], yC[i] + yC[j]);
int curA = xC[i] - xC[j];
int curB = yC[i] - yC[j];
int curC = -(curA * (xC[i] + xC[j]) + curB * (yC[i] + yC[j]));
curA <<= 1;
curB <<= 1;
line currentL = getnorm(curA, curB, curC);
if (!toId.count(currentL))
continue;
int current = toId[currentL];
int curAdd = incOrder[current].size();
curAdd -= int(incOrder[current].end() - upper_bound(all(incOrder[current]), curBeet));
vector < pt > ::iterator it = lower_bound(all(decOrder[current]), curBeet);
if (it != decOrder[current].begin())
{
it--;
curAdd -= (int(it - decOrder[current].begin()) + 1);
}
ans += curAdd;
}
}
cout << ans << endl;
}
int main () {
// freopen("input.txt", "rt", stdin);
cout << setprecision(10) << fixed;
cerr << setprecision(5) << fixed;
assert(read());
solve();
return 0;
}
|
350
|
E
|
Wrong Floyd
|
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it.
Valera's already written the code that counts the shortest distance between any pair of vertexes in a \textbf{non-directed connected graph} from $n$ vertexes and $m$ edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly $k$ vertexes $a_{1}, a_{2}, ..., a_{k}$.
Valera's code is given below.
\begin{verbatim}
ans[i][j] // the shortest distance for a pair of vertexes
$i, j$
a[i] // vertexes, marked by Valera
for(i = 1; i <= n; i++) {
for(j = 1; j <= n; j++) {
if (i == j)
ans[i][j] = 0;
else
ans[i][j] = INF; //INF is a very large number
}
}
for(i = 1; i <= m; i++) {
read a pair of vertexes u, v that have a non-directed edge between them;
ans[u][v] = 1;
ans[v][u] = 1;
}
for (i = 1; i <= k; i++) {
v = a[i];
for(j = 1; j <= n; j++)
for(r = 1; r <= n; r++)
ans[j][r] = min(ans[j][r], ans[j][v] + ans[v][r]);
}
\end{verbatim}
Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes $a_{1}, a_{2}, ..., a_{k}$, find such \textbf{non-directed connected graph}, consisting of $n$ vertexes and $m$ edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes $(i, j)$. Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
|
Let's do the following: construct the graph with the maximum possible number of edges and then remove the excess. First of all, you can notice that if $k = n$ answer is $- 1$. Else let's fix some marked vertex, for example $a_{1}$. Let's put in our graph all edges except edges beetween $a_{1}$ and $x$, where $x$ - an another marked vertex. So, why this algorithm is correct? If Valera's algorithm is wrong, then there are a ''bad'' pair of vertexes (i, j). ``Bad'' pair is a pair for that Valera's algorithm works wrong. So, there are not marked vertex $v$ on the shortest path from i to j, and $v \neq i$, and $v \neq j$. Without loss of generality, we can assume, that distance beetween $i$ and $j$ equals to 2, but Valera's algorithm gives greater answer. There are some cases, that depends on the type of vertexes $i$, $j$. But we can look only at the case where $(i, j)$ are marked vertexes. First, add to the graph all edges beetween not fixed ($i, j$) vertexes. Second, add to the graph edges beetween some fixed vertex ($i$ or $j$) and some not marked vertex. Third, add to the graph edges beetween $i$ and some marked vertex $v$, where $v \neq j$. It's simple to understand, that if we add some another edge, the Valera's algorithm will work correctly. Total amount of edges is ${\frac{n(n-1)}{2}}-k+1$.
|
[
"brute force",
"constructive algorithms",
"dfs and similar",
"graphs"
] | 2,200
|
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 300 + 5;
int n, m, ok, a[N], used[N];
inline bool read()
{
if (scanf("%d %d %d", &n, &m, &ok) != 3)
return false;
for(int i = 0; i < ok; i++)
scanf("%d", &a[i]), a[i]--;
sort(a, a + ok);
return true;
}
vector < int > g[N];
vector < pair<int,int> > edges;
vector < pair<int,int> > ans;
void dfs(int s, int prev = -1)
{
if (used[s])
return;
used[s] = true;
if (prev != -1)
{
ans.push_back(make_pair(min(s, prev), max(s, prev)));
}
for(int i = 0; i < g[s].size(); i++)
{
int v = g[s][i];
if (v == prev) continue;
dfs(v, s);
}
}
void add_edge(int i, int j)
{
g[i].push_back(j);
g[j].push_back(i);
edges.push_back(make_pair(min(i,j), max(j,i)));
}
inline void solve()
{
if (n == ok)
{
puts("-1");
return;
}
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
{
if (i == a[1] || j == a[0] || i == a[0] || j == a[1]) continue;
add_edge(i, j);
}
for(int i = 0; i < n; i++)
{
if (!binary_search(a, a + ok, i))
{
add_edge(i, a[0]);
add_edge(i, a[1]);
}
else
{
if (i != a[0] && i != a[1])
add_edge(i, a[0]);
}
}
for(int i = 0; i < n; i++)
{
if (!binary_search(a, a + ok, i))
{
dfs(i);
sort(ans.begin(), ans.end());
break;
}
}
if (edges.size() < m)
{
puts("-1");
return;
}
for(int i = 0; i < edges.size(); i++)
{
if (!binary_search(ans.begin(), ans.begin() + n - 1, edges[i]) && ans.size() < m)
{
ans.push_back(edges[i]);
}
}
for(int i = 0; i < ans.size(); i++)
{
printf("%d %d\n", ans[i].first + 1, ans[i].second + 1);
}
}
int main()
{
while (read())
solve();
}
|
351
|
A
|
Jeff and Rounding
|
Jeff got $2n$ real numbers $a_{1}, a_{2}, ..., a_{2n}$ as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes $n$ operations, each of them goes as follows:
- choose indexes $i$ and $j$ $(i ≠ j)$ that haven't been chosen yet;
- round element $a_{i}$ to the nearest integer that isn't more than $a_{i}$ (assign to $a_{i}$: $⌊ a_{i} ⌋$);
- round element $a_{j}$ to the nearest integer that isn't less than $a_{j}$ (assign to $a_{j}$: $⌈ a_{j} ⌉$).
Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
|
Initially, we should remember the number of integers - $C$. On next step we will round down all numbers and count the sum. Now we can change the sum, rounding up some numbers, with those not matter what kind of, the main thing - how many. Consider a couple what we could get: 1. $(int, int)$ $(c_{1})$ 2. $(int, double)$ $(c_{2})$ 3. $(double, int)$ $(c_{3})$ 4. $(double, double)$ $(c_{4})$ Iterate over the number of pairs of the first type. Then we know the total number of second and third type and number of the fourth type: 1. $c_{2}$ + $c_{3}$ = $C$ - $2c_{1}$ 2. $c_{4}$ = $N - (c_{1} + c_{2} + c_{3})$ Check to see if you can get such numbers (enough for us count of integers and real numbers, respectively). We find that we can round up from $c_{4}$ to $c_{4} + c_{2} + c_{3}$ numbers. We will find the best choise.
|
[
"dp",
"greedy",
"implementation",
"math"
] | 1,800
| null |
351
|
B
|
Jeff and Furik
|
Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of $n$ numbers: $p_{1}$, $p_{2}$, $...$, $p_{n}$. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjacent permutation elements and then the boy swaps them. During his move, Furic tosses a coin and if the coin shows "heads" he chooses a random pair of adjacent elements with indexes $i$ and $i + 1$, for which an inequality $p_{i} > p_{i + 1}$ holds, and swaps them. But if the coin shows "tails", Furik chooses a random pair of adjacent elements with indexes $i$ and $i + 1$, for which the inequality $p_{i} < p_{i + 1}$ holds, and swaps them. If the coin shows "heads" or "tails" and Furik has multiple ways of adjacent pairs to take, then he uniformly takes one of the pairs. If Furik doesn't have any pair to take, he tosses a coin one more time. The game ends when the permutation is sorted in the increasing order.
Jeff wants the game to finish as quickly as possible (that is, he wants both players to make as few moves as possible). Help Jeff find the minimum mathematical expectation of the number of moves in the game if he moves optimally well.
You can consider that the coin shows the heads (or tails) with the probability of $50$ percent.
|
ote that after each step, the number of inversions in the permutation is changed by 1. Let us turn to the inversions of the permutation - let them be $I$ pcs. It is clear that when we have one inversion, then the answer - $1$. Now we will see how to use it further: 1. it is clear that after a Jeff's step inversions will become lower by $1$ 2. it is clear that after a Furik's step inversions will be on $1$ lowerwith porbability of $0, 5$, and on $1$ greater with probability of $0, 5$. 3. we have the formula for an answer $ans_{I} = 1 + 1 + ans_{I - 1 - 1} \times 0.5 + ans_{I - 1 + 1} \times 0.5$ 4. after transformation we have $ans_{I} = 4 + ans_{I - 2}$.
|
[
"combinatorics",
"dp",
"probabilities"
] | 1,900
| null |
351
|
C
|
Jeff and Brackets
|
Jeff loves regular bracket sequences.
Today Jeff is going to take a piece of paper and write out the regular bracket sequence, consisting of $nm$ brackets. Let's number all brackets of this sequence from $0$ to $nm$ - $1$ from left to right. Jeff knows that he is going to spend $a_{i mod n}$ liters of ink on the $i$-th bracket of the sequence if he paints it opened and $b_{i mod n}$ liters if he paints it closed.
You've got sequences $a$, $b$ and numbers $n$, $m$. What minimum amount of ink will Jeff need to paint a regular bracket sequence of length $nm$?
Operation $x mod y$ means taking the remainder after dividing number $x$ by number $y$.
|
How to solve the problem for small $NM$? Just use the dynamic programming $dp_{i, j}$ - minimum cost to build $i$ first brackets with the balance $j$. Transfers are simple: 1. $dp_{i, j} + a_{i + 1}$ -> $dp_{i + 1, j + 1}$ 2. $dp_{i, j} + b_{i + 1}$ -> $dp_{i + 1, j - 1}$ 3. we make transfers only when balance will be non-negative 4. starting state $dp_{0, 0} = 0$ In this problem, we can assume that the balance will never exceed $2N$. The proof is left as homework. And by using this fact problem can be done by erecting a matrix to the power: 1. lets $T_{i, j}$ - cost of transfer from balance $i$ to balance $j$, using $N$ brackets 2. $(T^{M})_{0, 0}$ - answer to the problem
|
[
"dp",
"matrices"
] | 2,500
| null |
351
|
D
|
Jeff and Removing Periods
|
Cosider a sequence, consisting of $n$ integers: $a_{1}$, $a_{2}$, $...$, $a_{n}$. Jeff can perform the following operation on sequence $a$:
- take three integers $v$, $t$, $k$ $(1 ≤ v, t ≤ n; 0 ≤ k; v + tk ≤ n)$, such that $a_{v}$ = $a_{v + t}$, $a_{v + t}$ = $a_{v + 2t}$, $...$, $a_{v + t(k - 1)}$ = $a_{v + tk}$;
- remove elements $a_{v}$, $a_{v + t}$, $...$, $a_{v + t·k}$ from the sequence $a$, the remaining elements should be reindexed $a_{1}, a_{2}, ..., a_{n - k - 1}$.
- permute in some order the remaining elements of sequence $a$.
A beauty of a sequence $a$ is the minimum number of operations that is needed to delete all elements from sequence $a$.
Jeff's written down a sequence of $m$ integers $b_{1}$, $b_{2}$, $...$, $b_{m}$. Now he wants to ask $q$ questions. Each question can be described with two integers $l_{i}, r_{i}$. The answer to the question is the beauty of sequence $b_{li}$, $b_{li + 1}$, $...$, $b_{ri}$. You are given the sequence $b$ and all questions. Help Jeff, answer all his questions.
|
After the first request we can sort the numbers and for further moves will be able to remove all occurrences of a certain number. So the answer is the number of different numbers + 1 if there is no number, occurrence of which form an arithmetic progression. Number of different numbers on a segment - standart problem, can be done $O(N^{1.5})$ with offline algorithm. The problem about finding the right number will be solved in a similar algorithm: 1. lets sort queries like pairs $(l_{i} / 300, r_{i})$, we use integer dividing 2. learn how to move from the interval $(l, r)$ to intervals $(l - 1, r)$, $(l + 1, r)$, $(l, r - 1)$, $(l, r + 1)$ with complexcity $O(1)$ 3. by means of such an operation will move from one segment to the next, in the amount of the operation algorithm will works $O(N^{1.5})$ It remains to learn how to make the change on the interval by $1$ element. Such a problem can be solved quite simply: 1. we craete $deque$ for all value of numbers in array 2. depending on changes in the segment will add / remove items to the start / end of the respective $deque$ 3. check whether the resulting $deque$ is arithmetic progression. it will be homework.
|
[
"data structures"
] | 2,700
| null |
351
|
E
|
Jeff and Permutation
|
Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence $p_{1}, p_{2}, ..., p_{n}$ for his birthday.
Jeff hates inversions in sequences. An inversion in sequence $a_{1}, a_{2}, ..., a_{n}$ is a pair of indexes $i, j$ $(1 ≤ i < j ≤ n)$, such that an inequality $a_{i} > a_{j}$ holds.
Jeff can multiply some numbers of the sequence $p$ by -1. At that, he wants the number of inversions in the sequence to be minimum. Help Jeff and find the minimum number of inversions he manages to get.
|
We make the zero step, replace the elements on their modules. The first thing you need to understand the way in which we will build our response. After selecting a few ways to understand the fact that initially you need to determine the sign of the largest numbers. Consider the case where the current step we have only one maximal element. It is clear that if you put a sign - all the elements on the left of this will form an inversion, while on the right there will be no inversions. If we do not put a sign - it will all be the opposite. We select the best one and cross out the number of the array, it will not affect to some inversion. Now we should understand how to read the response when the highs more than one. We write the dynamics dp[i][j] - how much inversions can you get, when we looked at the first i higest values and j from them lefted as possitive. Of these dynamics is not difficult to make the transition and get the answer. And so we have a simple and short algorithm: 1. Iterates until the array is not empty 2. Find all the maximal elements 3. Calculate dynamics and find right signs 4. Remove elements from an array
|
[
"greedy"
] | 2,200
| null |
352
|
A
|
Jeff and Digits
|
Jeff's got $n$ cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?
Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.
|
Solution is looking for few cases: 1. If we do not have zeros, then the answer is -$1$. 2. If we have less than $9$ fives, then the answer is $0$. 3. Otherwise, the answer is: 4. 1. The maximum number of fives divisible by $9$ 4. 2. All zeros, we have
|
[
"brute force",
"implementation",
"math"
] | 1,000
| null |
352
|
B
|
Jeff and Periods
|
One day Jeff got hold of an integer sequence $a_{1}$, $a_{2}$, $...$, $a_{n}$ of length $n$. The boy immediately decided to analyze the sequence. For that, he needs to find all values of $x$, for which these conditions hold:
- $x$ occurs in sequence $a$.
- Consider all positions of numbers $x$ in the sequence $a$ (such $i$, that $a_{i} = x$). These numbers, sorted in the increasing order, must form an arithmetic progression.
Help Jeff, find all $x$ that meet the problem conditions.
|
We will go through the array from left to right. At each step, we will store the arrays: 1. $next_{x}$ - the last occurrence of the number $x$ 2. $period_{x}$ - period, which occurs $x$ 3. $fail_{x}$ - whether a time when the number of $x$ no longer fit Now, when we get a new number we considering the case when it is the first, second or occurred more than twice. All the cases described in any past system testing solution.
|
[
"implementation",
"sortings"
] | 1,300
| null |
354
|
A
|
Vasya and Robot
|
Vasya has $n$ items lying in a line. The items are consecutively numbered by numbers from $1$ to $n$ in such a way that the leftmost item has number $1$, the rightmost item has number $n$. Each item has a weight, the $i$-th item weights $w_{i}$ kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:
- Take the leftmost item with the left hand and spend $w_{i} · l$ energy units ($w_{i}$ is a weight of the leftmost item, $l$ is some parameter). If the previous action was the same (left-hand), then the robot spends extra $Q_{l}$ energy units;
- Take the rightmost item with the right hand and spend $w_{j} · r$ energy units ($w_{j}$ is a weight of the rightmost item, $r$ is some parameter). If the previous action was the same (right-hand), then the robot spends extra $Q_{r}$ energy units;
Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
|
Brute force how many times we will use operation from the left. So, if we use it $k$ times, then it's clear, that we will take first $k$ items by the left operations and last $(n - k)$ items by the right operations. So, robot will spend $sumLeft[k] \cdot l + sumRight[n - k] \cdot r$ energy plus some penalty for the same operations. To minimize this penalty we should perform the operations in the following order LRLRL $...$ RLRLLLLL $...$, starting from the bigger set. For example, if $k = 7, n - k = 4$, we should perform operations in this order: LRLRLRLRL LL. So, we will have to pay the penalty two times $(7 - 4 - 1)$. $sumLeft[i]$ - sum of first $i$ weights, $sumRight[i]$ - sum of last $i$ weights. Time complexity: $O(n)$.
|
[
"brute force",
"greedy",
"math"
] | 1,500
| null |
354
|
B
|
Game with Strings
|
Given an $n × n$ table $T$ consisting of lowercase English letters. We'll consider some string $s$ good if the table contains a correct path corresponding to the given string. In other words, good strings are all strings we can obtain by moving from the left upper cell of the table only to the right and down. Here's the formal definition of correct paths:
Consider rows of the table are numbered from 1 to $n$ from top to bottom, and columns of the table are numbered from 1 to $n$ from left to the right. Cell $(r, c)$ is a cell of table $T$ on the $r$-th row and in the $c$-th column. This cell corresponds to letter $T_{r, c}$.
A path of length $k$ is a sequence of table cells $[(r_{1}, c_{1}), (r_{2}, c_{2}), ..., (r_{k}, c_{k})]$. The following paths are correct:
- There is only one correct path of length $1$, that is, consisting of a single cell: $[(1, 1)]$;
- Let's assume that $[(r_{1}, c_{1}), ..., (r_{m}, c_{m})]$ is a correct path of length $m$, then paths $[(r_{1}, c_{1}), ..., (r_{m}, c_{m}), (r_{m} + 1, c_{m})]$ and $[(r_{1}, c_{1}), ..., (r_{m}, c_{m}), (r_{m}, c_{m} + 1)]$ are correct paths of length $m + 1$.
We should assume that a path $[(r_{1}, c_{1}), (r_{2}, c_{2}), ..., (r_{k}, c_{k})]$ corresponds to a string of length $k$: $T_{r1, c1} + T_{r2, c2} + ... + T_{rk, ck}$.
Two players play the following game: initially they have an empty string. Then the players take turns to add a letter to the end of the string. After each move (adding a new letter) the resulting string must be good. The game ends after $2n - 1$ turns. A player wins by the following scenario:
- If the resulting string has strictly more letters "a" than letters "b", then the first player wins;
- If the resulting string has strictly more letters "b" than letters "a", then the second player wins;
- If the resulting string has the same number of letters "a" and "b", then the players end the game with a draw.
Your task is to determine the result of the game provided that both players played optimally well.
|
We will say that cell $(r, c)$ corresponds to a string $s$, if there exist correct path, which ends in the cell $(r, c)$ and this path corresponds to a string $s$. Let call a set of cells which corresponds to some string $s$ a state. One state can correspond to different strings. We can't brute force all possible strings, because their count - $C_{2n-2}^{n-1}$ is too big, but we can brute force all possible states. It's not hard to observe that all cells that corresponds to some string $s$ lies on same diagonal, so the total count of states is $2^{1} + 2^{2} + ... + 2^{n - 1} + 2^{n} + 2^{n - 1} + ... + 2^{2} + 2^{1} = O(2^{n})$. In implementation we can denote state with diagonal number (from $1$ to $2n - 1$) and bitmask of cells corresponding to this state $(2^{n})$. From each state we can move to 26 different states (actually less) and all possible moves depends on the state, not on the string. On the image you can see an example of move: from state, which is highlighted in blue by letter $a$ we will move to the state, which is highlighted in yellow. Now, for each state we can calculate a value of (count of letters A $-$ count of letters B) in the string, starting from this state. If at the moment is first players turn (an even diagonal), we have to maximize this value, otherwise - minimize. It can be implemented as recursion with memoization. The winner can be determined by the value of state, which corresponds to the single cell $(1, 1)$. Complexity: $O(2^{n} \times (n + alpha))$, where $alpha$ is the size of alphabet.
|
[
"bitmasks",
"dp",
"games"
] | 2,400
| null |
354
|
C
|
Vasya and Beautiful Arrays
|
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers $a$ of length $n$.
Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, the shop has only one array $a$ left. On the plus side, the seller said that he could decrease some numbers in the array (no more than by $k$ for each number).
The seller can obtain array $b$ from array $a$ if the following conditions hold: $b_{i} > 0; 0 ≤ a_{i} - b_{i} ≤ k$ for all $1 ≤ i ≤ n$.
Help mom find the maximum possible beauty of the array she will give to Vasya (that seller can obtain).
|
The problem was to find greatest $d$, such that $a_{i} \ge d, a_{i} mod d \le k$ holds for each $i$. Let $m = min(a_{i})$, then $d \le m$. Let consider two cases: $m\leq k+1\Rightarrow a_{i}\,m o d\,m\leq m-1\leq k\Rightarrow A n s w e r=m$ $m>k+1\Rightarrow A n s w e r\geq k+1$. In this case we will brute force answer from $k + 1$ to $m$. We can check, if number $d$ is a correct answer in the following way: We have to check that $a_{i} mod d \le k$ for some fixed $d$, which is equals to $a_{i}\in[d..d+k]\cup[2d..2d+k]\cup...\cup[p\cdot d...p\cdot d+k]$, where $p=\left\lfloor{\frac{m a x A}{d}}\right\rfloor$. Since all these intervals $[x \cdot d..x \cdot d + k]$ doesn't intersects each with other, we can just check that $\textstyle\sum_{i=1}^{m a x A/d}c n t[i\cdot d...i\cdot d+k]=n$, where $cnt[l..r]$ - count of numbers $a_{i}$ in the interval $[l..r]$. Time complexity: $O(maxA log maxA)$, proof is based on the sum of harmonic series.
|
[
"brute force",
"dp",
"number theory"
] | 2,100
| null |
354
|
D
|
Transferring Pyramid
|
Vasya and Petya are using an interesting data storing structure: a pyramid.
The pyramid consists of $n$ rows, the $i$-th row contains $i$ cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to $\textstyle{\frac{n(n+1)}{2}}$ as shown on the picture below.
An example of a pyramid at $n = 5$ is:
This data structure can perform operations of two types:
- Change the value of a specific cell. It is described by three integers: $"t i v"$, where $t = 1$ (the type of operation), $i$ — the number of the cell to change and $v$ the value to assign to the cell.
- Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell $5$. It is described by $s + 2$ numbers: $"t i v_{1} v_{2} ... v_{s}"$, where $t = 2$, $i$ — the number of the top cell of the pyramid, $s$ — the size of the subpyramid (the number of cells it has), $v_{j}$ — the value you should assign to the $j$-th cell of the subpyramid.
Formally: a subpyramid with top at the $i$-th cell of the $k$-th row (the $5$-th cell is the second cell of the third row) will contain cells from rows from $k$ to $n$, the $(k + p)$-th row contains cells from the $i$-th to the $(i + p)$-th ($0 ≤ p ≤ n - k$).
Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers).
You have a pyramid of $n$ rows with $k$ changed cells. Find the sequence of operations which result in \textbf{each of the $k$ changed cells being changed by at least one operation}. Among all the possible sequences pick \textbf{the one that contains the fewest numbers}.
|
This tasks is solvable with dynamic programming. First of all let consider solution with complexity $O(n^{3})$. Let $dp[i][j]$ be the answer for the highlighted in blue part (minimal cost of transferring all special cells that lies inside this area). Then $dp[n][0]$ will be the answer for our original problem. How to recalculate such DP? It's clear that in the leftmost column (inside the blue area) we will choose at most one cell as the top of some subpyramid. If we choose two, then the smallest one will lie fully inside the biggest one (as the orange subpyramid lies inside the blue one). Now, let brute force the cell, which will be the top of subpyramid in this column in time $O(n)$ and we will obtain the following transition: To simplify the formulas, let assume that $d p[i][-1]=d p[i][0]$. $d p[i][j]=m i n(d p[i-1][m a x(j,k)-1]+{\frac{k\times(k+1)}{2}}+2.$ $s u m{\cal U}p[i][m a x(j,k)+1]\times3),$ $0 \le k \le i$, where $k$ is the height on which we will choose our top cell, or $0$, if we don't choose any subpyramid in this column. $sumUp[i][p]$ - count of special cells in the $i$-th column at height starting from $p$, this cells we will have to transfer one by one, using the first type operations. We can reduce the complexity by one $n$, if we will recalculate out DP in the following way: $d p[i][0]=m i n(d p[i-1][k-1]+{\frac{k\times(k+1)}{2}}+2+s u m{U p[i][k+1]}\times3),$ $0 \le k \le i$; $d p[i][j]=m i n(d p[i][j-1],d p[i-1][j-1]+s u m U p[i][j+1]\times3),$ for all $j > 0$. The proof that this is correct is quite simple and is left to the reader. :) Also, we can observe that it is not profitably to take some subpyramid with height greater than $\sqrt{6k}$, because for such subpyramid we will pay $> 3k$, but if we transfer all cells using the first type operations we will pay only $3k$. So, the second dimension $(j)$ in out DP can be reduced to $\sqrt{6k}$. Also, to receive AC, you should store only last 2 layers of the DP, otherwise there will be not enough memory. Time complexity: $O(n{\sqrt{k}})$.
|
[
"dp"
] | 2,900
| null |
354
|
E
|
Lucky Number Representation
|
We know that lucky digits are digits $4$ and $7$, however Vasya's got another favorite digit $0$ and he assumes it also is lucky! Lucky numbers are such \textbf{non-negative} integers whose decimal record only contains lucky digits. For example, numbers $0, 47, 7074$ are lucky, but $1, 7377, 895, $ -$7$ are not.
Vasya has $t$ important positive integers he needs to remember. Vasya is quite superstitious and he wants to remember lucky numbers only, so he is asking you for each important number to represent it as a sum of exactly six lucky numbers (Vasya just can't remember more numbers). Then Vasya can just remember these six numbers and calculate the important number at any moment.
For each of $t$ important integers represent it as the sum of six lucky numbers or state that this is impossible.
|
Author's solution, much more complicated than suggested by many participants during the competition, easy solution will be described below. First of all, let write a DP with complexity $O(N * lucky_count(N))$, where $lucky_count(N)$ is the count of lucky numbers $ \le N$, $lucky_count(10^{n}) = 3^{n}$. As we can see, for all sufficiently large $N$ solution exists. Really - for every $N > 523$. Now, we can say that for $N \le 10000$ we have a solution, which is found using DP. Let's solve the task for larger values of $N$. Next and key idea is to separate the task into two parts: $N = N1 + N2$. Let's choose $N1$ and $N2$ in such way that for them it was easy to find a solution and then merge these two solutions into one. Let $N1 = N mod 4000, N2 = N - N1$. Here we can have a problem that there is no solution for number $N1$, in this case we can do $N1 = N1 + 4000, N2 = N2 - 4000$. Now it is guaranteed that solutions exists for both $N1$ and $N2$, moreover, the solution for number $N1$ will contain only numbers of not more than 3 digits $( < 1000)$. The proof is quite easy: if $N1 < 4000$ - it is obvious; else - if the solution uses some number of the form $(4000 + some_lucky_number)$, we can replace it with just $some_lucky_number$ and receive a correct solution for number ($N1 - 4000$), but is doesn't exist! So, the solution for number $N1$ we have found using DP, now let's find the solution for $N2$. If it will contains only of numbers of the form $(some_lucky_number \times 1000)$, then we will be able to easily merge this solution with solution for $N1$, so, let's find such a solution. Here we will use the fact that $N2$ is divisible by 4. For simplicity, let's divide $N2$ by 1000 and in the end multiply all $Ans2(i)$ by the same 1000. Let $P = N2 / 4$. Now, let's construct the solution. Consider, for example, P = 95: we will walk through digits of this number, last digit - 5, means that we want to put digit 4 at the last decimal position of five answer numbers - ok, put it and in the last, sixth, number leave there digit 0. Go forward, digit 9 - we don't have nine numbers, but we can replace seven fours with four sevens, then to the second position we have to put ($9 - 7$) fours and 4 sevens, in total - 6 numbers, exactly as much as we have. Thus, if next digit $d \le 6$, we just put to the first $d$ answer numbers digit 4 to the next position; if $d > 6$, then we put 4 sevens and $(d - 7)$ fours. In all other numbers we just leave digit 0 at this position. If $Ans1(i)$ - answer for $N1$, $Ans2(i)$ - for $N2$, the the answer for $N$ will be just $Ans(i) = Ans1(i) + Ans2(i)$. Time complexity for one number: $O(logN)$. During the competition many participants have wrote the following solution: $dp[i][j]$ - can we put the digit to the last $i$ decimal positions of the answer number in such way that we will get correct last $i$ digits in the sum and with carry to the next position equals to $j$. Then the solution exist iff $dp[19][0] = true$. To restore the answer we just have to remember for each state the previous state. Base - $dp[0][0] = true$. Transition - brute force how many fours and sevens we will put to the $i$-th position.
|
[
"constructive algorithms",
"dfs and similar",
"dp"
] | 2,200
| null |
355
|
A
|
Vasya and Digital Root
|
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you.
Let's assume that $S(n)$ is the sum of digits of number $n$, for example, $S(4098) = 4 + 0 + 9 + 8 = 21$. Then the digital root of number $n$ equals to:
- $dr(n) = S(n)$, if $S(n) < 10$;
- $dr(n) = dr( S(n) )$, if $S(n) ≥ 10$.
For example, $dr(4098) = dr(21) = 3$.
Vasya is afraid of large numbers, so the numbers he works with are at most $10^{1000}$. For all such numbers, he has proved that $dr(n) = S( S( S( S(n) ) ) )$ $(n ≤ 10^{1000})$.
Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. You task is, given numbers $k$ and $d$, find the number consisting of exactly $k$ digits (the leading zeroes are not allowed), with digital root equal to $d$, or else state that such number does not exist.
|
If $d = 0$, the there is the only number with $d r(x)=0\Leftrightarrow x=0$, so, if $k = 1$, the answer is $0$, otherwise - $No solution$. If $d > 0$, then one of correct numbers is $d \times 10^{k - 1}$. Time complexity: $O(1)$ + $O(k)$ for the output.
|
[
"constructive algorithms",
"implementation"
] | 1,100
| null |
355
|
B
|
Vasya and Public Transport
|
Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has $n$ buses and $m$ trolleys, the buses are numbered by integers from $1$ to $n$, the trolleys are numbered by integers from $1$ to $m$.
Public transport is not free. There are 4 types of tickets:
- A ticket for one ride on some bus or trolley. It costs $c_{1}$ burles;
- A ticket for an unlimited number of rides on some bus or on some trolley. It costs $c_{2}$ burles;
- A ticket for an unlimited number of rides on all buses or all trolleys. It costs $c_{3}$ burles;
- A ticket for an unlimited number of rides on all buses and trolleys. It costs $c_{4}$ burles.
Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.
|
If we buy a ticket of the fourth type, we don't have to buy anything else, so, the answer is $min(c_{4}, answer using tickets of first three types)$. Now, when we don't have ticket of the fourth type, we can solve the task separately for buses and trolleys. Solving the problem only for buses: if we buy a ticket of the third type, we don't have to buy anything else, so, the answer is $min(c_{3}, answer using tickets of first two types)$. Without tickets of type three, we can solve the problem separately for each bus. If we buy a ticket of the second type, we will spend $c_{2}$ burles and if we buy $a_{i}$ tickets of the first type, we will spend $(a_{i} \times c_{1})$ burles. So, the answer for bus $i$ is $min(c_{2}, a_{i} \times c_{1})$. Now it is not difficult to obtain the following solution: Time complexity: $O(n + m)$.
|
[
"greedy",
"implementation"
] | 1,100
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.