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
283
C
Coin Troubles
In the Isle of Guernsey there are $n$ different types of coins. For each $i$ $(1 ≤ i ≤ n)$, coin of type $i$ is worth $a_{i}$ cents. It is possible that $a_{i} = a_{j}$ for some $i$ and $j$ $(i ≠ j)$. Bessie has some set of these coins totaling $t$ cents. She tells Jessie $q$ pairs of integers. For each $i$ $(1 ≤ i ≤ q)$, the pair $b_{i}, c_{i}$ tells Jessie that Bessie has a strictly greater number of coins of type $b_{i}$ than coins of type $c_{i}$. It is known that all $b_{i}$ are distinct and all $c_{i}$ are distinct. Help Jessie find the number of possible combinations of coins Bessie could have. Two combinations are considered different if there is some $i$ $(1 ≤ i ≤ n)$, such that the number of coins Bessie has of type $i$ is different in the two combinations. Since the answer can be very large, output it modulo $1000000007$ $(10^{9} + 7)$. If there are no possible combinations of coins totaling $t$ cents that satisfy Bessie's conditions, output 0.
Imagine the problem as a graph where coins are the nodes and Bessie's statements are directed edges between coins. Because of the problem conditions, the graph must be a set of cycles and directed paths. If there are any cycles in the graph, the answer is clearly 0. Then, suppose we have a path $p_{1}, p_{2}, \dots p_{k}$ in the graph, where it is known that we have more coins of type $p_{1}$ than of type $p_{2}$, more of type $p_{2}$ than of type $p_{3},$ and so on. The key observation in this problem is that this is equivalent to having k independent coins of value ${a_{}(p_{1}), a_{}(p_{1}) + a_{}(p_{2}), a_{}(p_{1}) + a_{}(p_{2}) + a_{}(p_{3}), \dots }.$ The first coin in our new list represents how many more coins of type $p_{1}$ than of type $p_{2}$ we have, the second coin in our new list represents how many more coins of type $p_{2}$ than of type $p_{3}$ we have, and so on. However, we must be careful to note that we need at least one of each of the new coins except for the last one, so we can subtract their values from T before doing the DP. After creating our new set of values, we can run the DP the same way we would run a standard knapsack. This algorithm takes $O(nt)$ time total.
[ "dp" ]
2,100
null
283
D
Cows and Cool Sequences
Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help! A pair $(x, y)$ of positive integers is "cool" if $x$ can be expressed as the sum of $y$ consecutive integers (not necessarily positive). A sequence $(a_{1}, a_{2}, ..., a_{n})$ is "cool" if the pairs $(a_{1}, a_{2}), (a_{2}, a_{3}), ..., (a_{n - 1}, a_{n})$ are all cool. The cows have a sequence of $n$ positive integers, $a_{1}, a_{2}, ..., a_{n}$. In one move, they may replace some $a_{i}$ with any other positive integer (there are no other limits on the new value of $a_{i}$). Determine the smallest number of moves needed to make the resulting sequence cool.
Let $v_{2}(n)$ denote the exponent of the largest power of $2$ that divides $n.$ For example $v_{2}(5) = 0, v_{2}(96) = 5.$ Let $f(n)$ denote the largest odd factor of $n.$ We can show that for fixed $a_{i}, a_{j}(i < j),$ we can construct a cool sequence $a_{i} = b_{i}, b_{i + 1}, ... b_{j - 1}, b_{j} = a_{j}$ if and only if $f(a_{j})|f(a_{i})$ and either $v_{2}(a_{i}) + j - i = v_{2}(a_{j})$ or $v_{2}(a_{j}) \le j - i - 1.$ Proof here With this observation, we can use dynamic programming where the $k$th state is the maximum number of $a_{i}$ ($i \le k$) we can keep so that it is possible to make $a_{1}, ... a_{k}$ cool. The transition for this is $O(n),$ and the answer is just $n - max (dp[1], dp[2], ..., dp[n]).$ This algorithm is $O(n^{2}).$
[ "dp", "math", "number theory" ]
2,400
null
283
E
Cow Tennis Tournament
Farmer John is hosting a tennis tournament with his $n$ cows. Each cow has a skill level $s_{i}$, and no two cows having the same skill level. Every cow plays every other cow exactly once in the tournament, and each cow beats every cow with skill level lower than its own. However, Farmer John thinks the tournament will be demoralizing for the weakest cows who lose most or all of their matches, so he wants to flip some of the results. In particular, at $k$ different instances, he will take two integers $a_{i}, b_{i}$ $(a_{i} < b_{i})$ and flip all the results between cows with skill level between $a_{i}$ and $b_{i}$ inclusive. That is, for any pair $x, y$ $(x\neq y;\;s_{x},s_{y}\in[a_{i},b_{i}])$ he will change the result of the match on the final scoreboard (so if $x$ won the match, the scoreboard will now display that $y$ won the match, and vice versa). It is possible that Farmer John will change the result of a match multiple times. It is not guaranteed that $a_{i}$ and $b_{i}$ are equal to some cow's skill level. Farmer John wants to determine how balanced he made the tournament results look. In particular, he wants to count the number of triples of cows $(p, q, r)$ for which the final leaderboard shows that cow $p$ beats cow $q$, cow $q$ beats cow $r$, and cow $r$ beats cow $p$. Help him determine this number. Note that two triples are considered different if they do not contain the same set of cows (i.e. if there is a cow in one triple that is not in the other).
This will go over the basic outline for solution. We can show that the answer is $\textstyle{\binom{n}{3}}-\sum_{i}{\binom{n_{i}}{2}}$ where $w_{i}$ is the number of wins cow $i$ appears to have. Proof here Now sort the skill levels of the cows (the order of the $s_{i}$ doesn't actually matter). $s_{1}$ is lowest skill. Now consider an $n \times n$ grid where the $i$th row and $j$th column of the grid is a 1 if the match between cow $i$ and cow $j$ is flipped. The grid is initially all zeros and Farmer John's query simply flips a rectangle of the form $[a, b] \times [a, b].$ We can process these queries and compute the number of wins for each cow using a vertical sweep line on the grid and updating with a seg tree on the interval [1,n]. The seg tree needs to handle queries of the form \begin{enumerate} \item Flip all numbers (0->1, 1->0) in a range $[a, b].$ \item Query number of 1's in a range $[a, b].$ \end{enumerate} Note that given this seg tree we can compute the number of wins for each cow at every point in the sweep line as (Number of 1's in range [1,i - 1]) + (Number of 0's in range [i + 1, n]). There are $O(m)$ queries so this solution takes $m\log(n)$ time.
[ "combinatorics", "data structures", "math" ]
2,800
null
284
A
Cows and Primitive Roots
The cows have just learned what a primitive root is! Given a prime $p$, a primitive root $\mathrm{mod}\,p$ is an integer $x$ $(1 ≤ x < p)$ such that none of integers $x - 1, x^{2} - 1, ..., x^{p - 2} - 1$ are divisible by $p$, but $x^{p - 1} - 1$ is. Unfortunately, computing primitive roots can be time consuming, so the cows need your help. Given a prime $p$, help the cows find the number of primitive roots $\mathrm{mod}\,p$.
We didn't expect this problem to be so hard :(. This problem can be solved by brute forcing. For any $x,$ you can compute $x^{1},x^{2},\ldots,x^{p-1}\mod p$ in $O(p)$ time (iteratively multiply cur = (cur * i) % p, not use pow in math library!), so overall brute force will be $O(p^{2})$ time. Note: there is actually $O({\sqrt{p}})$ algorithm.
[ "implementation", "math", "number theory" ]
1,400
null
284
B
Cows and Poker Game
There are $n$ cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN". Find the number of cows that can currently show their hands without affecting any betting decisions.
We first note that players who have folded do not affect our desired answer. Then, we can do casework on the number of players who are currently "IN". If no cows are "IN", then all the players who are "ALLIN" can show their hands. If exactly one cow is "IN", she is the only one who can show, so the answer is 1. If two or more cows are "IN", no one can show their hands. Then we simply count the number of cows of each type and check for each case. The total runtime is $O(n).$
[ "brute force", "implementation" ]
1,000
null
285
A
Slightly Decreasing Permutations
{\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.} The decreasing coefficient of permutation $p_{1}, p_{2}, ..., p_{n}$ is the number of such $i (1 ≤ i < n)$, that $p_{i} > p_{i + 1}$. You have numbers $n$ and $k$. Your task is to print the permutation of length $n$ with decreasing coefficient $k$.
As the answer you can print such permutation: $n, n - 1, ..., n - k + 1, 1, 2, ..., n - k$. For example, if $n = 5$, $k = 2$, then the answer is: $5, 4, 1, 2, 3$. If $k = 0$, you should print $1, 2, ..., n$. Such solution can be written in two loops.
[ "greedy", "implementation" ]
1,100
null
285
B
Find Marble
Petya and Vasya are playing a game. Petya's got $n$ non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from $1$ to $n$ from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position $s$. Then he performs some (possibly zero) shuffling operations. One shuffling operation means moving the glass from the first position to position $p_{1}$, the glass from the second position to position $p_{2}$ and so on. That is, a glass goes from position $i$ to position $p_{i}$. Consider all glasses are moving simultaneously during one shuffling operation. When the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in. After all shuffling operations Petya shows Vasya that the ball has moved to position $t$. Vasya's task is to say what minimum number of shuffling operations Petya has performed or determine that Petya has made a mistake and the marble could not have got from position $s$ to position $t$.
It is known that a permutation can be considered as set of cycles. The integer $i$ moves to $p[i]$ for all $i$ $(1 \le i \le n)$. You can start moving from integer $s$ along the cycle. If you find integer $t$, then print the length of the path. If you return to $s$, then print $- 1$.
[ "implementation" ]
1,200
null
285
C
Building Permutation
{\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.} You have a sequence of integers $a_{1}, a_{2}, ..., a_{n}$. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.
The solution of the problem is rather simple. Sort all integers $a$ and then make from integer $a[1]$ integer $1$, from integer $a[2]$ integer $2$ and so on. So, integer $a[i]$ adds to the answer the value $|a[i] - i|$. The answer should be count in 64-bit type. You can simply guess why such solution is correct.
[ "greedy", "implementation", "sortings" ]
1,200
null
285
D
Permutation Sum
{\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.} Petya decided to introduce the sum operation on the set of permutations of length $n$. Let's assume that we are given two permutations of length $n$: $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{n}$. Petya calls the sum of permutations $a$ and $b$ such permutation $c$ of length $n$, where $c_{i} = ((a_{i} - 1 + b_{i} - 1) mod n) + 1$ $(1 ≤ i ≤ n)$. Operation $x\ {\mathrm{mod}}\ y$ means taking the remainder after dividing number $x$ by number $y$. Obviously, not for all permutations $a$ and $b$ exists permutation $c$ that is sum of $a$ and $b$. That's why Petya got sad and asked you to do the following: given $n$, count the number of such pairs of permutations $a$ and $b$ of length $n$, that exists permutation $c$ that is sum of $a$ and $b$. The pair of permutations $x, y$ $(x ≠ y)$ and the pair of permutations $y, x$ are considered distinct pairs. As the answer can be rather large, print the remainder after dividing it by $1000000007$ ($10^{9} + 7$).
For a start, describe bruteforce solution. Firstly, we will always assume, that $a$ is identity permutation, that is $a[i] = i$. In this case, the answer should be multiplied by $n!$. Or in other way your bruteforce will not be counted. Secondly, using our bruteforce we can see, that for even $n$ the answer is $0$. What do you also need to get accepted? First case is to calculate answers for all $n$ on your computer and write them in constant array. In other words you can make precalc. Second case is to make you solution faster. The soltuion using meet-in-the-middle idea works fast for $n \le 15$. If you remember that for even $n$ answer is $0$ then you can get accepted using such solution. But other simple bruteforces and dynamic programmings on maps work slower than $3$ seconds.
[ "bitmasks", "combinatorics", "dp", "implementation", "meet-in-the-middle" ]
1,900
null
285
E
Positions in Permutations
{\textbf{Permutation} $p$ is an ordered set of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. We'll denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size or the length of permutation $p_{1}, p_{2}, ..., p_{n}$.} We'll call position $i$ ($1 ≤ i ≤ n$) in permutation $p_{1}, p_{2}, ..., p_{n}$ good, if $|p[i] - i| = 1$. Count the number of permutations of size $n$ with exactly $k$ good positions. Print the answer modulo $1000000007$ ($10^{9} + 7$).
A common approach for this kind of problem is DP. What we do here is to choose numbers for the good positions first, then fill the others later on. Let f(i, j, k) is the number of ways to choose j good positions in the first i-th position and k is a 2-bit number that represents whether number i and number i + 1 is already used or not. The DP transition is quite simple. Let F(j) is the number of permutations with j good positions, then F(j) = \Sigma (f(n, j, k)) * (n - j)! (because there are n - j numbers left unchosen). However, there are cases we may form some extra good positions when putting these n - j numbers into our permutations, thus F(j) now stores the number of permutations with at least j good positions. But we want F(j) to be the number of permutations with exact j good positions, so we must exclude those permutations with more than j good positions. Let's do it in descending order. First F(n) must be the number of permutations with exact n good positions. Hence, we may calculate F(n - 1) based on F(n), then F(n - 2) based on F(n - 1) and F(n), and so on... The last part is to calculate how many times F(j) is repeatedly counted in F(i) (i < j), it's simply C(j, i) (the number of ways to choose i good positions from j good positions). The overall complexity is O(n^2).
[ "combinatorics", "dp", "math" ]
2,600
#include <iostream> #include <algorithm> using namespace std; const int BASE = int(1e9) + 7; long long f[1010][1010][4], F[1010], c[1010][1010]; void addMod(long long &x, long long y) { x += y; if (x >= BASE) x -= BASE; } int main() { int n, k; cin >> n >> k; for (int i = 0; i <= n; i++) for (int j = 0; j <= i; j++) c[i][j] = j ? (c[i - 1][j] + c[i - 1][j - 1]) % BASE : 1; f[0][0][2] = 1; for (int i = 1; i <= n; i++) for (int j = 0; j < i; j++) for (int z = 0; z < 4; z++) { if (z & 1) addMod(f[i][j + 1][z / 2 + 2], f[i - 1][j][z]); if (i < n) addMod(f[i][j + 1][z / 2], f[i - 1][j][z]); addMod(f[i][j][z / 2 + 2], f[i - 1][j][z]); } for (int j = 0; j <= n; j++) { for (int z = 0; z < 4; z++) addMod(F[j], f[n][j][z]); for (int k = 2; k <= n - j; k++) F[j] = F[j] * k % BASE; } for (int i = n - 1; i >= 0; i--) for (int j = i + 1; j <= n; j++) addMod(F[i], BASE - F[j] * c[j][i] % BASE); cout << F[k] << endl; }
288
A
Polo the Penguin and Strings
Little penguin Polo adores strings. But most of all he adores strings of length $n$. One day he wanted to find a string that meets the following conditions: - The string consists of $n$ lowercase English letters (that is, the string's length equals $n$), exactly $k$ of these letters are distinct. - No two neighbouring letters of a string coincide; that is, if we represent a string as $s = s_{1}s_{2}... s_{n}$, then the following inequality holds, $s_{i} ≠ s_{i + 1}(1 ≤ i < n)$. - Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist. String $x = x_{1}x_{2}... x_{p}$ is lexicographically less than string $y = y_{1}y_{2}... y_{q}$, if either $p < q$ and $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{p} = y_{p}$, or there is such number $r$ $(r < p, r < q)$, that $x_{1} = y_{1}, x_{2} = y_{2}, ... , x_{r} = y_{r}$ and $x_{r + 1} < y_{r + 1}$. The characters of the strings are compared by their ASCII codes.
To solve this problem we need to find out some contruction of resulting string. But first of all, we need find out when there is no result. Obviously, if $k > n$, there is not result - you cannot build string of length $n$ with more than $n$ characters. Another one case is when $k = 1$ and $n > 1$ - there is no answer in that case also. Consider that $k = 2$. It's really easy to see that answer for such case is a string of form $abababab...$. To construct string for $k > 2$ you need to add some extra characters - $c, d, e...$. To make string lexicographically smallest, you need to add that characters as close to the end as we can. And the best bet here is $abbabab...abacdefgh...$. So, we need just to add characters $c, d, e, f...$ (i. e. $k - 2$ characters from $c$) to the end of the string.
[ "greedy" ]
1,300
null
288
B
Polo the Penguin and Houses
Little penguin Polo loves his home village. The village has $n$ houses, indexed by integers from 1 to $n$. Each house has a plaque containing an integer, the $i$-th house has a plaque containing integer $p_{i}$ ($1 ≤ p_{i} ≤ n$). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number $x$. Then he goes to the house whose number is written on the plaque of house $x$ (that is, to house $p_{x}$), then he goes to the house whose number is written on the plaque of house $p_{x}$ (that is, to house $p_{px}$), and so on. We know that: - When the penguin starts walking from any house indexed from 1 to $k$, inclusive, he can walk to house number 1. - When the penguin starts walking from any house indexed from $k + 1$ to $n$, inclusive, he definitely cannot walk to house number 1. - When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house. You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by $1000000007$ $(10^{9} + 7)$.
Since $k \le 8$ you can solve this problem using brute force. This means that you can recursively construct all possible $k^{k}$ possibilities of first $k$ assignments. (For $k = 8$ this is equal to $16 777 216$.) For each of that assignments you need to check whether it is correct or not (by problem statement). Ths can be simply done using loops. When you know the number of assignment for the first $k$ tables (let it be $f(k)$), all you need to do is to count the number of assignment for the rest $n - k$ plaques. Since there should bo no path to $1$, there should be no path to any of first $k$ houses, so at each plaque for houses from $k + 1$ to $n$ there can be any number from $k + 1$ to $n$, inclusive. There are $(n - k)^{n - k}$ such possibilities. And hence the total answer is $f(k)(n - k)^{n - k}$.
[ "combinatorics" ]
1,500
null
288
C
Polo the Penguin and XOR operation
Little penguin Polo likes permutations. But most of all he likes permutations of integers from $0$ to $n$, inclusive. For permutation $p = p_{0}, p_{1}, ..., p_{n}$, Polo has defined its beauty — number $(0\oplus p_{0})+(1\oplus p_{1})+\cdot\cdot\cdot+(n\oplus p_{n})$. Expression $x\oplus y$ means applying the operation of bitwise excluding "OR" to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor". Help him find among all permutations of integers from $0$ to $n$ the permutation with the maximum beauty.
Since we need to maximize the result, we need to find such permutation, for which the least number of bit disappear. (We consider bit disappeared if it was 1 both in $i$ and $p_{i}$, so in $i\oplus p_{i}$ it is 0). It turns out that for each $n$ there is such permutation that no bit disappear. How to build it? We will be solving problem by iterations while $n > 0$. On each iteration, we need to find the biggest (the leftmost in binary representation) bit which is not $0$ in binary representation of $n$ and denote it position (bits are numbered from 0) by $b$. Now we need to find integer $m$ - minimal integer from $0$ to $n$, inclusive, such that $b$-th bit is also $1$ in it. After that you can see (look image below), that at $m\oplus(m-1)$ no bit disappear, at $(m+1)\oplus(m-2)$ no bit disappear, ..., at $n\oplus(m-(m-m+1))$ no bit disappear. So, it is good to assign exactly that integers to our permutation, i. e. $p_{m} = m - 1$ and $p_{m - 1} = m$, $p_{m + 1} = m - 2$ and $p_{m - 2} = m + 1$ and so on. After that assign value $m - (n - m + 1) - 1$ to $n$ and go to next iteration. Now when we know how to build permutation and that no bit disappear, the value of the answer is equal to $0+p_{0}+1+p_{1}+\ldots+n+p_{n}={\frac{n(n+1)}{2}}+{\frac{n(n+1)}{2}}=n(n+1)$.
[ "implementation", "math" ]
1,700
null
288
D
Polo the Penguin and Trees
Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing $n$ nodes and $n - 1$ edges. We will consider the tree nodes numbered by integers from 1 to $n$. Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers $a, b, c$ and $d$ such that: - $1 ≤ a < b ≤ n$; - $1 ≤ c < d ≤ n$; - there's no such node that lies on both the shortest path from node $a$ to node $b$ and from node $c$ to node $d$. The shortest path betweem two nodes is the path that is shortest in the number of edges. Help Polo solve this problem.
As always in such problems, root our tree at some vertex, for example vertex with number 1. We need to find out, what will happen when we have already chosen one path. Obviously, after deleting all vertices and their edges from that path, tree will disintegrate in some set of trees. Denote their sizes by $c_{1}, c_{2}, ..., c_{k}$, where $k$ is the number of trees. Then the number of ways to choose the second path is equal to $\begin{array}{r}{\mathbf{c}_{1}*(c_{1}-1)}\\ {2}\end{array}+\mathbf{c}_{2}^{\ast(c_{2}-1)}+\ldots+{\frac{c_{k}*(c_{k}-1)}{2}}$. This gives us $O(n^{2})$ solution - just to brute force all pathes and count the number of second paths by this formula. We need to do it in $O(n)$. To do so, dfs our graph and fix some vertex during dfs, we will consider this vertex as the last vertex in the first path. Now we need to find the sum of above formula for the rest of the vertex. Here you can separately solve this problem for all vertex inside subtree of current vertex and for the rest of the vertices. For subtree vertices, you can, after finding the answers for all vertices of subtree, find the answer for root of subtree. To do so, you need to iterate all edges from current vertex and sum up results for that vetices. Also you need to add the sum of values $\frac{d|s u(t-1)}{2}$ multiplied by the number of vertices in subtree, where $d_{i}$ are all sizes of subtrees of vertices from current vertex, not including from current edge). You can use some partial sums of something like that to make it linear. For the rest of the vertices (not in subtree) it is actually similar, but a bit harder. Here you need to keep current result as a parameter of dfs and when you entering some vertex you should add some additional counts to the current sum (similarly as in first case).
[ "combinatorics", "dfs and similar", "trees" ]
2,400
null
288
E
Polo the Penguin and Lucky Numbers
\underline{Everybody knows that lucky numbers are positive integers that contain only lucky digits 4 and 7 in their decimal representation. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.} Polo the Penguin have two positive integers $l$ and $r$ $(l < r)$, both of them are lucky numbers. Moreover, their lengths (that is, the number of digits in the decimal representation without the leading zeroes) are equal to each other. Let's assume that $n$ is the number of distinct lucky numbers, each of them cannot be greater than $r$ or less than $l$, and $a_{i}$ is the $i$-th (in increasing order) number of them. Find $a_{1}·a_{2} + a_{2}·a_{3} + ... + a_{n - 1}·a_{n}$. As the answer can be rather large, print the remainder after dividing it by $1000000007$ ($10^{9} + 7$).
In this problem there are a lot of different formulas, most of them are for optimizing solution and making it lenear. Editorial shows just a general idea because it's pretty hard to explain all of them and good for you to derive it by yourself. If you have any questions - write them all in comments. Denote by $a_{1}, a_{2}, ..., a_{n}$ all lucky number from segment. First of all, we need to do reduce the problem a bit. Let we have some fixed digit $(pos, d)$, i. e. position of this digit is $pos$ (from 0 from right to left) and value is $d$ (4 or 7). Then, for all $a_{i}$ $(1 \le i < n$) such that $pos$-th digit of $a_{i}$ is equal to $d$, we need to add $a_{i + 1} \times d \times 10^{pos}$ to the answer. Now we can see that problem can be reduced to the following. For each fixed digit $(pos, d)$ find the sum of all $a_{i}$ such that $a_{i + 1}$ on the $pos$-th position has digit $d$. Obviously, we can solve the problem for $1..l$ and $1..r$ separately and then subtract the first from the second - that will be the answer. How to find such sum among all lucky numbers of some length but less than some lucky number $x$? We will describe the general idea. Any lucky number, less than $x$ has some common prefix with $x$, then one digit is less than the corresponing in $x$ (i. e. it is 7 in $x$ and 4 in another integer) and the rest of the digits are arbitrary. So, by iterating all such positions where is the first digit less than in $x$, we can, using the fact that the rest of the digits are arbitrary and some formulas and precomputations, compute the results for each position and digit.
[ "dp", "implementation", "math" ]
2,800
null
289
A
Polo the Penguin and Segments
Little penguin Polo adores integer segments, that is, pairs of integers $[l; r]$ $(l ≤ r)$. He has a set that consists of $n$ integer segments: $[l_{1}; r_{1}], [l_{2}; r_{2}], ..., [l_{n}; r_{n}]$. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform $[l; r]$ to either segment $[l - 1; r]$, or to segment $[l; r + 1]$. The value of a set of segments that consists of $n$ segments $[l_{1}; r_{1}], [l_{2}; r_{2}], ..., [l_{n}; r_{n}]$ is the number of integers $x$, such that there is integer $j$, for which the following inequality holds, $l_{j} ≤ x ≤ r_{j}$. Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by $k$.
First of all, we need to count, how many integers are inside given segments at the beginning. Since they don't intersect and even touch, no integer point can belong to more than one segment at the same time. This mans that starting value of segments is $p\ {\stackrel{\mathrm{def}}{=}}\left(r_{1}-l_{1}+1\right)+\left(r_{2}-l_{2}+1\right)+\ldots+\left(r_{n}-l_{n}+1\right)$. If $k$ divides $p$, then answer is $0$ - we don't need to do anything, it's already done. But if it's not true, we need to know the minimal number of turns to make $k$ divisor of $p$. Since we can in single turn increase $p$ by 1 (by decreasing the left point of the leftmost segment), this number is equal to $k-(p\ {\mathrm{mod}}\ k)$.
[ "brute force", "implementation" ]
1,100
null
289
B
Polo the Penguin and Matrix
Little penguin Polo has an $n × m$ matrix, consisting of integers. Let's index the matrix rows from 1 to $n$ from top to bottom and let's index the columns from 1 to $m$ from left to right. Let's represent the matrix element on the intersection of row $i$ and column $j$ as $a_{ij}$. In one move the penguin can add or subtract number $d$ from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
First of all, we need to know when the answer is -1. For that you should notice that after any operation on number $z$, value $z\ {\mathrm{mod}}\ d$ doesn't change. Indeed, $z_{\textrm{m o d}}d=(z+d)\;\;\mathrm{mod}\;=(z-d)\;\;\mathrm{mod}\;d$. This means that there is not answer if there are two different points for which $a_{i j}\mod d$ is diffrent. Now we can transform our problem a bit. We can just write down all integers from matrix $n \times m$ to one array $b$ of size $k = n \times m$ and sort them all in non-decreasing order. It is not hard to notice that in some of the optimal solutions, all number are at the end equal to one of the number for starting array. But also, it is optimal to make all number equal to $b[\underline{{k}}_{2}+1]$ (median element). Why to median? Suppose that we make all numbers equal to non-median element with index $x$. Then if $|x - (k - x)| > 1$ (i. e. from one side there are more elements than from another + 1). So, by moving out element more to median, we can make result better. After we know, to which number we should bring all, the answer is just $|b_{1}-b[\frac{k}{2}+1]|+|b_{2}-b[\frac{k}{2}+1]|+...+|b_{k}-b[\frac{k}{2}+1]|$, divided by $d$.
[ "brute force", "dp", "implementation", "sortings", "ternary search" ]
1,400
null
293
A
Weird Game
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of $2·n$ binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves first. During a move, a player must choose an integer from 1 to $2·n$, which hasn't been chosen by anybody up to that moment. Then the player takes a piece of paper and writes out the corresponding character from his string. Let's represent Yaroslav's word as $s = s_{1}s_{2}... s_{2n}$. Similarly, let's represent Andrey's word as $t = t_{1}t_{2}... t_{2n}$. Then, if Yaroslav choose number $k$ during his move, then he is going to write out character $s_{k}$ on the piece of paper. Similarly, if Andrey choose number $r$ during his move, then he is going to write out character $t_{r}$ on the piece of paper. The game finishes when no player can make a move. After the game is over, Yaroslav makes some integer from the characters written on his piece of paper (Yaroslav can arrange these characters as he wants). Andrey does the same. The resulting numbers can contain leading zeroes. The person with the largest number wins. If the numbers are equal, the game ends with a draw. You are given two strings $s$ and $t$. Determine the outcome of the game provided that Yaroslav and Andrey play optimally well.
The first observation - we don't care about the actual strings, all information we need - number of pairs {0,0}, {0,1}, {1,0}, {1,1}. Count that and then just follow the greedy algorithm, for the first player: try to get a index with {1,1} if there are some, than {1,0}, than {0,1} and than {0,0}. For the second player similar strategy: first {1,1}, than {0,1}, than {1,0}, than {0,0}. After that just compare who has more 1.
[ "games", "greedy" ]
1,500
null
293
B
Distinct Paths
You have a rectangular $n × m$-cell board. Some cells are already painted some of $k$ colors. You need to paint each uncolored cell one of the $k$ colors so that any path from the upper left square to the lower right one doesn't contain any two cells of the same color. The path can go only along side-adjacent cells and can only go down or right. Print the number of possible paintings modulo $1000000007$ $(10^{9} + 7)$.
Every path from the topleft cell to the bottomright cell contain exactly $n + m - 1$ cells. And all of the should be of different color. So $n + m - 1 \le k$. Due to the small constraints for k we may assume that bruteforce might work. The only optimization to get the correct solution is some canonization of the colors. So let's go over all of the cells in some order and color them but with following condition. If i > j, than color i appeared later than color j. If we bruteforce in such way we will have about 1 million different patterns for max case. Than just match them with already painted cells and calculate for each pattern how many different permutations of color we can apply to it.
[ "brute force", "combinatorics" ]
2,700
null
293
C
Cube Problem
Yaroslav, Andrey and Roman love playing cubes. Sometimes they get together and play cubes for hours and hours! Today they got together again and they are playing cubes. Yaroslav took unit cubes and composed them into an $a × a × a$ cube, Andrey made a $b × b × b$ cube and Roman made a $c × c × c$ cube. After that the game was finished and the guys left. But later, Vitaly entered the room. He saw the cubes and wanted to make a cube as well. But what size should the cube be? Of course it should be a large cube with the side of length $a + b + c$. Besides, Vitaly decided to decompose the cubes built by Yaroslav, Andrey and Roman and compose his own large cube out of them. However, it turned out that the unit cubes he got from destroying the three cubes just weren't enough to make a large cube. We know that Vitaly was short of exactly $n$ cubes. Vitaly got upset, demolished everything and left. As he was leaving, he met Petya and told him that there had been three cubes in the room and that he needed another $n$ unit cubes to make his own large cube. Petya entered the room and saw the messily scattered cubes. He wanted to make it neat and orderly again. But he only knows that there had been three cubes, made of small unit cubes and that Vitaly needed $n$ more unit cubes to make a large one! Help Petya understand, how many ways of sizes $a$, $b$, $c$ are there to restore Yaroslav's, Andrey's and Roman's cubes.
After reading the problem statement one can understand that all we need is to calculate the number of positive integer solutions of equation: $(a + b + c)^{3} - a^{3} - b^{3} - c^{3} = n$. The key observation is: $3(a + b)(a + c)(b + c) = (a + b + c)^{3} - a^{3} - b^{3} - c^{3}$, after that simply calculate all divisors of $\frac{n}{3}$ and then first go over all $x = a + b$, such that $x^{3}\leq{\frac{n}{3}}$ then go over all $y = (a + c) \ge x$, such that $x y^{2}\leq{\frac{n}{3}}$ and then determine $z = (b + c)$, such that $x y z={\frac{n}{3}}$. After that we need to solve the system $a + b = x, a + c = y, b + c = z$ and find out how many solutions it adds.
[ "brute force", "math", "number theory" ]
2,400
null
293
D
Ksusha and Square
Ksusha is a vigorous mathematician. She is keen on absolutely incredible mathematical riddles. Today Ksusha came across a convex polygon of non-zero area. She is now wondering: if she chooses a pair of distinct points uniformly among all integer points (points with integer coordinates) inside or on the border of the polygon and then draws a square with two opposite vertices lying in the chosen points, what will the expectation of this square's area be? A pair of distinct points is chosen uniformly among all pairs of distinct points, located inside or on the border of the polygon. Pairs of points $p, q$ $(p ≠ q)$ and $q, p$ are considered the same. Help Ksusha! Count the required expectation.
We can see that we asked to calculate $\sum2((x_{i}-x_{j})^{2}+(y_{i}-y_{j})^{2})$ for all integer points inside the polygon or on its border. We can see that we can process Xs and Ys independently. For each $x$ determine $y_{left}$, $y_{right}$, such that all points $(x, y)$ where $y_{left} \le y \le y_{right}$ are inside the polygon and the range $[y_{left}, y_{right}]$ is as maximal as possible. Now let's assume that we have $a_{1}, a_{2}, ..., a_{k}$ different points with fixed x coordinate ($a_{1}$ stands for $x = - 10^{6}$, $a_{2}$ for $x = - 10^{6} + 1$ and so on). Now the required answer is $a_{2}a_{1} + a_{3}(a_{2} + 2^{2}a_{1}) + a_{4}(a_{3} + 2^{2}a_{2} + 3^{2}a_{1}) + ...$ We can see that: $(a_{2} + 2^{2}a_{1}) - a_{1} = a_{2} + 3a_{1}$, $(a_{3} + 2^{2}a_{2} + 3^{2}a_{1}) - (a_{2} + 2^{2}a_{1}) = a_{3} + 3a_{2} + 5a_{1}$, and so on. So we can precalculate partial sums like $a_{2} + 3a_{1}$, $a_{3} + 3a_{2} + 5a_{1}$, $a_{4} + 3a_{3} + 5a_{2} + 7a_{1}$ (the difference between two consecutive sums is $2(a_{i} + ... + a_{1})$, so we can do that in $O(k)$ time). After this precomputation we just need to sum the results.
[ "geometry", "math", "probabilities", "two pointers" ]
2,700
null
293
E
Close Vertices
You've got a weighted tree, consisting of $n$ vertices. Each edge has a non-negative weight. The length of the path between any two vertices of the tree is the number of edges in the path. The weight of the path is the total weight of all edges it contains. Two vertices are close if there exists a path of length at most $l$ between them and a path of weight at most $w$ between them. Count the number of pairs of vertices $v, u$ $(v < u)$, such that vertices $v$ and $u$ are close.
Let's assume that we have a data structure which can perform such operations as: - add point (x,y) to the structure; shift all points in the structure by vector (dx,dy); answer how many point (x,y) are in the structure where $x \le x_{bound}$, $y \le y_{bound}$; get all elements which are now in the structure; For every vertex of the tree we will store the pointer to such structure. How we update the structures. We will proceed all the vertices in dfs order, if we are in a leaf node, than we create structure which contains only one element (0,0). Otherwise we will sort the children structures by it's size in decreasing order and assign the pointer of the biggest structure to the pointer of the current vertex (Don't forget to shift the structure by (1, weight of edge)). After that we will go over all other children one by one and do the following thing: Shift the structure by (1, weight of edge); Get all elements from the structure; For every element (x,y) answer the query $x_{bound} = L - x$, $y_{bound} = W - y$ (we use parent's structure); Add elements one by one into the structure; After that answer the query $x_{bound} = L, y_{bound} = W$ and add element (0,0). The sum of the results of all the queries is our answer. It's easy to see that there will be no more than $O(N\log N)$ queries and add operations. The remaining part is designing the structure. It can be done in many ways. One of the ways: We have small structures with sizes equals to powers of two; Each structure - it's two-dimensional segments tree; We can add one element in a following way: if there is no substructure with size 1, than add it; else get structures with sizes $1, 2, 4, ..., 2^{k}$ and all its' elements and rebuild the structure with size $2^{k + 1}$; Shifting - just remember shifting vector for every substructure; Answering the query - go over all substructures and add the results.
[ "data structures", "divide and conquer", "trees" ]
2,700
null
294
A
Shaass and Oskols
Shaass has decided to hunt some birds. There are $n$ horizontal electricity wires aligned parallel to each other. Wires are numbered $1$ to $n$ from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are $a_{i}$ oskols sitting on the $i$-th wire. Sometimes Shaass shots one of the birds and the bird dies (suppose that this bird sat at the $i$-th wire). Consequently all the birds on the $i$-th wire to the left of the dead bird get scared and jump up on the wire number $i - 1$, if there exists no upper wire they fly away. Also all the birds to the right of the dead bird jump down on wire number $i + 1$, if there exists no such wire they fly away. Shaass has shot $m$ birds. You're given the initial number of birds on each wire, tell him how many birds are sitting on each wire after the shots.
In this problem you just have to now how many birds are there on each wire after each shot. A good trick for the first and the last wire would be to define wires $0$ and $n + 1$. In this way the birds that fly away sit on these wires and you don't need to worry about accessing some element outside the range of your array.
[ "implementation", "math" ]
800
null
294
B
Shaass and Bookshelf
Shaass has $n$ books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the $i$-th book is $t_{i}$ and its pages' width is equal to $w_{i}$. The thickness of each book is either $1$ or $2$. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
As said in the statement, the thickness of each book is either 1 or 2. Think about when we want to arrange $v_{1}$ books of thickness 1 and $v_{2}$ books of thickness $2$ vertically and arrange all other $n - v_{1} - v_{2}$ books horizontally above them to achieve a configuration with total thickness of vertical books equal to $v_{1} + 2v_{2}$. Is it possible to find such arrangement? Because the total thickness of vertical books is fixed it's good to calculate the minimum possible total width of horizontal books. As the width of a book doesn't matter in vertical arrangement it's good to use the books with shorter width horizontally and the ones with longer width vertically. So pick out $v_{1}$ books with longest width among books of thickness 1 and do the same with books of thickness 2. The sum of width of $n - v_{1} - v_{2}$ remaining books should be at most $v_{1} + 2v_{2}$. The solution would be to try the things we explained above for all possible values of $v_{1}$ and $v_{2}$. And print the best answer. :) There exists other ways to solve this problem mostly using dynamic programming but this was the intended solution of the problem.
[ "dp", "greedy" ]
1,700
null
294
C
Shaass and Lights
There are $n$ lights aligned in a row. These lights are numbered $1$ to $n$ from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo $1000000007 (10^{9} + 7)$.
I just want to solve the third sample of this problem for you and you can figure out the rest by yourself. :) The third sample is ...#...#... where # is a switched on lamp and . is a switched off lamp. As you can see we have three different types of lights. The first three lights (Type A), the 5th to 8th lights (Type B) and the last three lights (Type C). We have to switch on the lights three times for each type of lights. Aside from the order of moves for each type there are $\frac{0\}}{3!_{\ast}^{\dagger}{\hat{\jmath}}_{\pm}^{\dagger}{\hat{\jmath}}_{\pm}^{\dagger}}$ possible permutations of the string AAABBBCCC which tells us how to combine the steps of different types. Switching on the lights is done uniquely for types 1 and 3. But for type 2 each time we have to possible options until we're left with one off light. So there are $2^{3 - 1}$ ways to do this. So the answer would be 1680*1*4*1 = 6720. The general solution would be to find all groups off consecutive switched off lamps and calculate the number of ways to combine all these groups. Then for each group you should calculate in how many ways it can be solved.
[ "combinatorics", "number theory" ]
1,900
null
296
A
Yaroslav and Permutations
Yaroslav has an array that consists of $n$ integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav.
Note that after applying the operations of the exchange, we can get any permutation of numbers. Not difficult to understand that the answer is "YES", if you can place a single number that it would not stand in the neighboring cells. Thus, if a some number is meeted C times, it must fulfill the condition C <= (n+1) / 2.
[ "greedy", "math" ]
1,100
null
297
A
Parity Game
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") $a$ and $b$. Then you try to turn $a$ into $b$ using two types of operations: - Write $parity(a)$ to the end of $a$. For example, $1010\to10100$. - Remove the first character of $a$. For example, $1001\rightarrow001$. You cannot perform this operation if $a$ is empty. You can use as many operations as you want. The problem is, is it possible to turn $a$ into $b$? The $parity$ of a 01-string is $1$ if there is an odd number of "1"s in the string, and $0$ otherwise.
Obv 1: If $a$ has odd parity, we can apply operation 1 to increase its number of 1s by $1$. Obv 2: If $a$ has even parity, its number of 1s cannot increase anymore. Claim: If the number of 1s in $a$ is not fewer than those in $b$, we can always turn $a$ to $b$ The idea is to make a copy of $b$ at the right of $a$. Lets assume $a$ starts with even parity. If we need a $0$, simply apply operation 1. If we need a $1$, keep remove from the head until we removed an 1. Notice that we never remove digits from 'new part' of $a$. Now the parity of $a$ will be odd and we can apply operation 1. After that, the parity of $a$ becomes even again, the number of $1$ in the 'old part' of $a$ decrease by $1$ and we handle a $1$ in $b$. Finally, remove the remaining old part of $a$ and we get $b$. Combine all those facts, we can conclude that we can turn $a$ into $b$ if and only if $countOnes(a) + parity(countOnes(a)) \ge countOnes(b)$
[ "constructive algorithms" ]
1,700
null
297
B
Fish Weight
It is known that there are $k$ fish species in the polar ocean, numbered from $1$ to $k$. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the $i$-th type of fish be $w_{i}$, then $0 < w_{1} ≤ w_{2} ≤ ... ≤ w_{k}$ holds. Polar bears Alice and Bob each have caught some fish, and they are guessing who has the larger sum of weight of the fish he/she's caught. Given the type of the fish they've caught, determine whether it is possible that the fish caught by Alice has a \textbf{strictly larger} total weight than Bob's. In other words, does there exist a sequence of weights $w_{i}$ (not necessary integers), such that the fish caught by Alice has a strictly larger total weight?
First we sort $a$ and $b$ in non-increasing order. We claim that the answer is YES if and only if exists $a$ is lexicographically larger than $b$. $(\leftarrow)$ If $a$ is not lexicographcally larger than $b$, that means for every $i$, $a_{i} \le b_{i}$. That implies for every fish Alice has, there is a corresponding fish Bob has and is as heavy as Alice's. $(\Rightarrow)$ Let $i$ be the smallest index such that $a_{i} > b_{i}$. We can amplify the gap between $w_{ai}$ and $w_{bi}$ as large as we want to make Alice wins.
[ "constructive algorithms", "greedy" ]
1,600
null
297
C
Splitting the Uniqueness
Polar bears like unique arrays — that is, arrays without repeated elements. You have got a unique array $s$ with length $n$ containing non-negative integers. Since you are good friends with Alice and Bob, you decide to split the array in two. Precisely, you need to construct two arrays $a$ and $b$ that are also of length $n$, with the following conditions for all $i$ $(1 ≤ i ≤ n)$: - $a_{i}, b_{i}$ are non-negative integers; - $s_{i} = a_{i} + b_{i}$ . Ideally, $a$ and $b$ should also be unique arrays. However, life in the Arctic is hard and this is not always possible. Fortunately, Alice and Bob are still happy if their arrays are almost unique. We define an array of length $n$ to be almost unique, if and only if it can be turned into a unique array by removing no more than $\textstyle\bigcap{\frac{22}{3}}\setminus$ entries. For example, the array $[1, 2, 1, 3, 2]$ is almost unique because after removing the first two entries, it becomes $[1, 3, 2]$. The array $[1, 2, 1, 3, 1, 2]$ is not almost unique because we need to remove at least $3$ entries to turn it into a unique array. So, your task is to split the given unique array $s$ into two almost unique arrays $a$ and $b$.
An equivalent definition for almost unique, is an array with at least $ \lfloor 2n / 3 \rfloor $ different elements. The idea is to split $s$ into three parts: In the first part, we give uniqueness to $a$. In the second part, we give uniqueness to $b$. In the third part, we give uniqueness to both. Lets assume $s$ is sorted. Since $s$ is an unique array, we know $s_{i} \ge i$ for all $i$ (0-based). The image below will give some intuition on how we are going to split it. $a$ is red, $b$ is blue, the length of the bar represent the magnitude of the number. In the first and second part, we do not care about the array that we are not giving uniqueness to. For exampmle, if $n = 30$: $i = 0... 9:$ assign $a_{i} = i$ (do not care values of $b$) $i = 10... 19:$ assign $b_{i} = i$ (do not care values of $a$) $i = 20... 29:$ assign $b_{i} = 29 - i$ and set $a_{i} = s_{i} - b_{i}$. From $i = 20$, $a$ will have strictly increasing values starting from at least $11$.
[ "constructive algorithms" ]
2,400
null
297
D
Color the Carpet
Even polar bears feel cold when lying on the ice. Therefore, a polar bear Alice is going to make a carpet. The carpet can be viewed as a grid with height $h$ and width $w$. Then the grid is divided into $h × w$ squares. Alice is going to assign one of $k$ different colors to each square. The colors are numbered from 1 to $k$. She may choose not to use all of the colors. However, there are some restrictions. For every two adjacent squares (squares that shares an edge) $x$ and $y$, there is a color constraint in one of the forms: - $color(x) = color(y)$, or - $color(x) ≠ color(y)$. Example of the color constraints: Ideally, Alice wants to satisfy all color constraints. But again, life in the Arctic is hard. It is not always possible to satisfy all color constraints. Fortunately, she will still be happy if at least $\textstyle{\frac{3}{4}}$ of the color constraints are satisfied. If she has $4$ colors she can color the carpet in the following way: And she is happy because $\textstyle{\frac{13}{17}}$ of the color constraints are satisfied, and ${\frac{13}{17}}\geq{\frac{3}{4}}$. Your task is to help her color the carpet.
For $k = 1$ there is only one coloring so we just need to check the number of $=$ constraints. When $k \ge 2$, it turns out that using only $2$ colors is always sufficient to satisfy at least $3 / 4$ of the constraints. Lets assume $w \ge h$ (rotate if not). We will call the constraints that involves cells in different row "vertical constraints", and similar for "horizontal constraints". First we color the first row such that all horizontal constraints in row $1$ are satisfied. We will color the remaining rows one by one. To color row $i$, first we color it such that all horizontal constraints in row $i$ are satisfied. Then consider the vertical constraints between row $i$ and row $i - 1$. Count the number of satisfied and unsatisfied vertical constraints. If there are more unsatisfied constraints than satisfied constraints, flip the coloring of row $i$. Flipping a row means turning $2211212 \rightarrow 1122121$, for example. If we flip the coloring of row $i$, all horizontal constraints in row $i$ are still satisfied, but for the vertical constraints between row $i$ and row $i - 1$, satisfied will turn to unsatisfied, unsatisfied will turn to satisfied. Therefore, we can always satisfy at least half the vertical constraints between row $i$ and row $i - 1$. The number of unsatisfied constraints is at most $(h - 1) \times \lfloor w / 2 \rfloor $, which is at most $1 / 4$ of the total number of constraints (recall $w \ge h$).
[ "constructive algorithms" ]
2,500
null
297
E
Mystic Carvings
The polar bears have discovered a gigantic circular piece of floating ice with some mystic carvings on it. There are $n$ lines carved on the ice. Each line connects two points on the boundary of the ice (we call these points endpoints). The endpoints are numbered $1, 2, ..., 2n$ counter-clockwise along the circumference. No two lines share an endpoint. Now a group of 6 polar bears (Alice, Bob, Carol, Dave, Eve, Frank) are going to build caves on the endpoints. Each polar bear would build a cave and live in it. No two polar bears can build a cave on the same endpoints. Alice and Bob is a pair of superstitious lovers. They believe the lines are carved by aliens (or humans, which are pretty much the same thing to polar bears), and have certain spiritual power. Therefore they want to build their caves on two endpoints which are connected by a line. The same for Carol and Dave, Eve and Frank. The distance between two caves X and Y is defined as one plus minimum number of other caves one need to pass through in order to travel from X to Y along the boundary of the ice (endpoints without caves are not counted). To ensure fairness, the distances between the three pairs of lovers have to be the same (that is, the distance between Alice and Bob, the distance between Carol and Dave, and the distance between Eve and Frank are the same). The figures below show two different configurations, where the dots on the circle are the endpoints. The configuration on the left is not valid. Although each pair of lovers (A and B, C and D, E and F) is connected a line, the distance requirement is not satisfied. The distance between A and B is 2 (one can go from A to B in the clockwise direction passing through F). The distance between E and F is also 2. However, the distance between C and D is 1 (one can go from C to D in the counter-clockwise direction without passing through any other caves). The configuration on the right is valid. All three pairs have the same distance 1. Count the number of ways to build the caves under the requirements. Two configurations are considered the same if the same set of 6 endpoints are used.
For any three lines, they can intersect in one of the following 5 ways: The problem is asking for the number of Type 2 or Type 5. Some of these configs are easy to count (e.g. Type 1), some are not. To count the number of Type 1, we can exhaust the middle line with index $i$, and count the number of lines on the right of the middle line (let it be $x_{i}$) and on the left of the middle line (let it be $y_{i}$), then the number of Type 1 with that middle line is given by $x_{i}y_{i}$. There are several methods to calculate $x_{i}$ efficiently. One of them is to process the endpoints in counter clockwise order (let the current endpoint be $k$), and use a segment tree or binary indexed tree to keep track of the number of lines $(a_{i}, b_{i}), a_{i} < b_{i}$ with $l \le a_{i} < b_{i} \le k$ for different $l$. Let $j$ be the line with $b_{j} = k$, then to find the number of lines with $a_{j} < a_{i} < b_{i} < b_{j}$, we just need to query the count at $a_{j}$, then update the binary indexed tree by adding one to the position $a_{j}$. In the actual implementation, we need to consider that the endpoints are wrapped circularly as well. Unfortunately, Type 2 and Type 5 are the difficult ones. But we are only asked to find the total number of Type 2 and Type 5, which is (number of triples of lines) - (number of Type 1, 3 and 4). The problem then reduces to finding the total number of Type 3 and 4 (namely "We cannot give a 囧 without an XD and a HA"). Note that Type 3 and 4 shares a characteristic that two of the lines (the X in Type 3, and the two vertical lines in Type 4) has exactly one intersection with one of the other two lines. Therefore we can find the number of Type 3 and 4 by iterating through the lines, then count the number of lines on the right ($x_{i}$), on the left ($y_{i}$), and intersecting the considered line ($z_{i} = n - 1 - x_{i} - y_{i}$), and give the number of Type 3 and 4 as the sum of $z_{i}(x_{i} + y_{i})$. After removing double counting, we can get the answer.
[ "data structures" ]
3,000
null
298
A
Snow Footprints
There is a straight snowy road, divided into $n$ blocks. The blocks are numbered from 1 to $n$ from left to right. If one moves from the $i$-th block to the $(i + 1)$-th block, he will leave a right footprint on the $i$-th block. Similarly, if one moves from the $i$-th block to the $(i - 1)$-th block, he will leave a left footprint on the $i$-th block. If there already is a footprint on the $i$-th block, the new footprint will cover the old one. At the beginning, there were no footprints. Then polar bear Alice starts from the $s$-th block, makes a sequence of moves and ends in the $t$-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of $s, t$ by looking at the footprints.
The starting position can be anywhere with a footprint. The footprints can be categorized into 3 types. only $L$ s only $R$ s $R$ s followed by $L$ s In case 1, we end in the left of all footprints. In case 2, we end in the right of all footprints. In case 3, we either end in the rightmost $R$ or the leftmost $L$
[ "greedy", "implementation" ]
1,300
null
298
B
Sail
The polar bears are going fishing. They plan to sail from $(s_{x}, s_{y})$ to $(e_{x}, e_{y})$. However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at $(x, y)$. - If the wind blows to the east, the boat will move to $(x + 1, y)$. - If the wind blows to the south, the boat will move to $(x, y - 1)$. - If the wind blows to the west, the boat will move to $(x - 1, y)$. - If the wind blows to the north, the boat will move to $(x, y + 1)$. Alternatively, they can hold the boat by the anchor. In this case, the boat stays at $(x, y)$. Given the wind direction for $t$ seconds, what is the earliest time they sail to $(e_{x}, e_{y})$?
We can simply move by greedy method - only moves when it takes the boat closer to the destination.
[ "brute force", "greedy", "implementation" ]
1,200
null
299
A
Ksusha and Array
Ksusha is a beginner coder. Today she starts studying arrays. She has array $a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ positive integers. Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
If $a_{i}$ divide $a_{j}$ than $a_{i} \le a_{j}$. So the number which will divide every other number should be less than or equal to every other number, so the only possible candidate - it's the minimum in the array. So just check whether all elements are divisible by the minimal one
[ "brute force", "number theory", "sortings" ]
1,000
null
299
B
Ksusha the Squirrel
Ksusha the Squirrel is standing at the beginning of a straight road, divided into $n$ sectors. The sectors are numbered 1 to $n$, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector $n$. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks. Ksusha the squirrel keeps fit. She can jump from sector $i$ to any of the sectors $i + 1, i + 2, ..., i + k$. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?
Easy to see, that Ksusha is unable to complete her journey if there is a sequence of consecutive # with length more than k.
[ "brute force", "implementation" ]
900
null
300
A
Array
Vitaly has an array of $n$ distinct integers. Vitaly wants to divide this array into three \textbf{non-empty} sets so as the following conditions hold: - The product of all numbers in the first set is less than zero $( < 0)$. - The product of all numbers in the second set is greater than zero $( > 0)$. - The product of all numbers in the third set is equal to zero. - Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array.
In this problem you just need to implement following algorithm. Split input data into 3 vectors: first will contain negative numbers, second positive numbers, third zeroes. If size of first vector is even move one number from it to the third vector. If second vector is empty, then move two numbers from first vector to the second vector. This solution works in $O(n)$.
[ "brute force", "constructive algorithms", "implementation" ]
1,100
#include <cstdio> #include <vector> using namespace std; vector <int> first, second, third; int main () { int n; scanf("%d", &n); for(int i = 0; i < n; i++) { int a; scanf("%d", &a); if (a == 0) third.push_back(a); if (a > 0) second.push_back(a); if (a < 0) first.push_back(a); } if (second.size() == 0) { for(int i = 0; i < 2; i++) second.push_back(first.back()), first.pop_back(); } if (first.size() % 2 == 0) { third.push_back(first.back()); first.pop_back(); } printf("%d", first.size()); for(int i = 0; i < first.size(); i++) { printf(" %d",first[i]); } printf(" %d", second.size()); for(int i = 0; i < second.size(); i++) { printf(" %d", second[i]); } printf(" %d", third.size()); for(int i = 0; i < third.size(); i++) { printf(" %d", third[i]); } puts(""); }
300
B
Coach
A programming coach has $n$ students to teach. We know that $n$ is divisible by $3$. Let's assume that all students are numbered from $1$ to $n$, inclusive. Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the $i$-th student wants to be on the same team with the $j$-th one, then the $j$-th student wants to be on the same team with the $i$-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the $i$-th student wants to be on the same team with the $j$-th, then the $i$-th and the $j$-th students must be on the same team. Also, it is obvious that each student must be on exactly one team. Help the coach and divide the teams the way he wants.
Input data represents a graph. If there is a connected component with at least $4$ vertexes, then answer is $- 1$. Every connected component with $3$ vertexes is a complete team. Other teams are made from $1$ or $2$-vertex components. If amount of $2$-vertex components is greater than $1$-vertex answer is $- 1$. Otherwise match $2$-vertex components with $1$-vertex. If there are some $1$-vertex components left then split them into groups of three. This algorithm works in $O(n + m)$. Also you could implement $O(n^{4})$ solution.
[ "brute force", "dfs and similar", "graphs" ]
1,500
#define _CRT_SECURE_NO_DEPRECATE #define _SECURE_SCL 0 #pragma comment(linker, "/STACK:300000000") #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <complex> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <functional> #include <fstream> #include <iostream> #include <iomanip> #include <map> #include <memory.h> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <sstream> #include <vector> #include <utility> #include <cmath> using namespace std; #define pb push_back #define mp make_pair #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define forn(i,n) for (int i=0; i<int(n); ++i) #define fornd(i,n) for (int i=int(n)-1; i>=0; --i) #define forab(i,a,b) for (int i=int(a); i<int(b); ++i) typedef long long ll; typedef long double ld; typedef unsigned long long ull; const int INF = (int) 1e9; const long long INF64 = (long long) 1e18; const long double eps = 1e-9; const long double pi = 3.14159265358979323846; int g[50][50], n, m; bool used[50]; vector <int> cur; vector <vector <int> > c[50]; void dfs(int v){ used[v] = true; cur.pb(v); for (int i=1; i<=n; i++) if (g[v][i] && !used[i]) dfs(i); } int main(){ #ifdef dudkamaster freopen("input.txt","rt",stdin); freopen("output.txt","wt",stdout); #endif memset(g, 0, sizeof(g)); memset(used, 0, sizeof(used)); cin >> n >> m; for (int i=0; i<m; i++){ int a,b; cin >> a >> b; g[a][b] = g[b][a] = 1; } for (int i=1; i<=n; i++){ if (!used[i]){ cur.clear(); dfs(i); c[sz(cur)].pb(cur); } } vector <vector <int> > out = c[3]; for (int i=4; i<50; i++){ if (sz(c[i])!=0){ cout << -1; return 0; } } if (sz(c[2])>sz(c[1])){ cout << -1; return 0; } if ((sz(c[1])-sz(c[2])) % 3 != 0){ cout << -1; return 0; } forn(i,sz(c[2])){ vector <int> tout; tout.pb(c[2][i][0]); tout.pb(c[2][i][1]); tout.pb(c[1][i][0]); out.pb(tout); } for (int i=sz(c[2]); i<sz(c[1]); i += 3){ vector <int> tout; forn(j,3) tout.pb(c[1][i+j][0]); out.pb(tout); } forn(i,n/3){ forn(j,3) cout << out[i][j] << ' '; cout << endl; } return 0; }
300
C
Beautiful Numbers
Vitaly is a very weird man. He's got two favorite digits $a$ and $b$. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits $a$ and $b$. Vitaly calls a good number excellent, if the sum of its digits is a good number. For example, let's say that Vitaly's favourite digits are $1$ and $3$, then number $12$ isn't good and numbers $13$ or $311$ are. Also, number $111$ is excellent and number $11$ isn't. Now Vitaly is wondering, how many excellent numbers of length exactly $n$ are there. As this number can be rather large, he asks you to count the remainder after dividing it by $1000000007$ $(10^{9} + 7)$. A number's length is the number of digits in its decimal representation without leading zeroes.
Let's $MOD = 1000000007$. Let's precalc factorial values modulo $MOD$. $fact[i] = i!%MOD$, $\forall i\leq100000$. Let $i$ be an amount of digits equal to $a$ in current excellent number. In this case we can find sum of digits in this number: $sum = ai + b(n - i)$. If $sum$ is good, then add $C[n][i]$ to answer. In this problem it's impossible to calculate binomial coefficients using Pascal's triangle, because of large $n$. However it can be done this way $C[n][i] = fact[n]inv(fact[n - i]fact[i])$. $inv(a)$ is multiplicative inverse element(modulo $MOD$). $MOD$ is a prime number, so $inv(a) = a^{MOD - 2}$. Calculating this values for each $i$ from $0$ to $n$ will give correct answer in $O(nlog(MOD))$.
[ "brute force", "combinatorics" ]
1,800
#define _CRT_SECURE_NO_DEPRECATE #define _SECURE_SCL 0 #pragma comment(linker, "/STACK:200000000") #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <complex> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <functional> #include <fstream> #include <iostream> #include <map> #include <memory.h> #include <numeric> #include <iomanip> #include <queue> #include <set> #include <stack> #include <list> #include <string> #include <sstream> #include <vector> #include <utility> #include <cmath> using namespace std; #define pb push_back #define mp make_pair #define mset(mas,val) memset(mas,val,sizeof(mas)) #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define forn(i,n) for (int i=0; i<int(n); ++i) #define fornd(i,n) for (int i=int(n)-1; i>=0; --i) #define forab(i,a,b) for (int i=int(a); i<int(b); ++i) typedef long long ll; typedef long double ld; typedef unsigned long long ull; const int INF = (int) 1e9; const long long INF64 = (long long) 1e18; long double eps = 1e-6; const long double pi = 3.14159265358979323846; const int N = 1e6 + 100; long long fact[N], modulo = INF + 7; int n, a, b; bool read() { if (!(cin >> a >> b >> n)) return false; assert(a >= 1 && a <= 9); assert(b >= a + 1 && b <= 9); assert(n >= 1 && n <= (int)1e6); return true; } long long binpow(long long val, long long deg, long long mod) { if (!deg) return 1 % mod; if (deg & 1) return binpow(val, deg - 1, mod) * val % mod; long long res = binpow(val ,deg >> 1, mod); return (res*res) % mod; } bool check(long long val, int a, int b) { while (val > 0) { if (val % 10 == a || val % 10 == b) { val /= 10; } else return false; } return true; } void initfact() { fact[0] = 1; for(int i = 1; i < N; i++) { fact[i] = (fact[i-1] * i); fact[i] %= modulo; } } long long getC(int n, int i) { long long res = fact[n]; long long div = fact[n-i] * fact[i]; div %= modulo; div = binpow(div, modulo - 2, modulo); return (res * div) % modulo; } void solve() { long long ans = 0; for(int i = 0; i <= n; i++) { long long expsum = a * i + b*(n-i); if (check(expsum, a, b)) { ans += getC(n, i); ans %= modulo; } } cout << ans << endl; } int main(){ #ifdef gridnevvvit freopen("input.txt","rt",stdin); freopen("output.txt","wt",stdout); #endif initfact(); assert(read()); solve(); return 0; }
300
D
Painting Square
Vasily the bear has got a large square white table of $n$ rows and $n$ columns. The table has got a black border around this table. \begin{center} {\scriptsize The example of the initial table at $n$ = 5.} \end{center} Vasily the bear wants to paint his square table in exactly $k$ moves. Each move is sequence of actions: - The bear chooses some square inside his table. At that the square must have a black border painted around it. Also, the square shouldn't contain a black cell. The number of cells in the square shouldn't be less than $2$. - The bear chooses some row and some column inside the chosen square. Then he paints each cell of this row and this column inside the chosen square. After that the rectangles, formed by the square's border and the newly painted cells, must be squares of a non-zero area. \begin{center} {\scriptsize An example of correct painting at $n$ = 7 и $k$ = 2.} \end{center} The bear already knows numbers $n$ and $k$. Help him — find the number of ways to paint the square in exactly $k$ moves. Two ways to paint are called distinct if the resulting tables will differ in at least one cell. As the answer can be rather large, print the remainder after dividing it by $7340033$.
This picture is helpful for understanding. Let's consider problem $D$ in graph terms: We have matrix $n \times n$, which represents a graph: It is tree. Every vertex, except leaves, has 4 children. There are $4^{k}$ distinct vertexes, with distance $k$ from root. We need to color $k$ vertexes of this graph. By that we mean also to color all vertexes on path from $i$ to $1$(root). Knowing $height$ of tree we can build it in unique way. Let's find height of tree in this way: int height = 0; while (n > 1 && n % 2 == 1) { n /= 2; height++; }Let's consider following DP: $z[i][j]$ - number of ways to color graph height $i$ in $j$ steps. Naive solution in $O(k^{4}log(n))$: z[0][0] = 1; z[0][i] = 0, i > 0; z[i][0] = 1, i > 0 z[i][j] = 0; for(int k1 = 0; k1 <= j - 1; k1++) for(int k2 = 0; k2 <= j - 1 - k1; k2++) for(int k3 = 0; k3 <= j - 1 - k1 - k2; k3++) { int k4 = j - 1 - k1 - k2 - k3; z[i][j] += z[i-1][k1] * z[i-1][k2] * z[i-1][k3] * z[i-1][k4]; z[i][j] %= mod; }But it is not what we whant in time terms. Let's consider current DP as polynomial coefficients: $z[i][j]$ - coefficient of power $j$ of polynomial $i$. In that case $z[i + 1][j + 1]$ - coefficient of power $j$ of polynomial $i$ to the 4-th power. This approach allows to solve problem in $O(k^{2}log(n))$. However this solution is quite slow, because of modulo operations. As you see, this modulo is not so big ($ \le 10^{7}$), that allows us to reduce number of modulo operations, thus giving huge perfomance boost. Also it is possible to use FFT to solve in $O(klog(k)log(n))$.
[ "dp", "fft" ]
2,300
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <complex> #include <deque> #include <functional> #include <fstream> #include <iostream> #include <map> #include <memory.h> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <sstream> #include <vector> #include <utility> #include <cmath> using namespace std; #define pb push_back #define mp make_pair #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define forn(i,n) for (int i=0; i<int(n); ++i) #define fornd(i,n) for (int i=int(n)-1; i>=0; --i) #define xrange(i,a,b) for (int i=int(a); i<int(b); ++i) typedef long long ll; typedef long double ld; typedef unsigned long long ull; const int INF = (int) 1e9; const long long INF64 = (long long) 1e18; const long double eps = 1e-9; const long double pi = 3.14159265358979323846; const int mod = 7340033; const ll root = 5; const ll root_1 = 4404020; const ll root_pw = 1<<20; int rev_element[7340033]; ll getmod(ll a, ll tmod){ return ((a%tmod)+tmod)%tmod; } void fft (vector<ll> & a, bool invert) { int n = (int) a.size(); for (int i=1, j=0; i<n; ++i) { int bit = n >> 1; for (; j>=bit; bit>>=1) j -= bit; j += bit; if (i < j) swap (a[i], a[j]); } for (int len=2; len<=n; len<<=1) { ll wlen = invert ? root_1 : root; for (int i=len; i<root_pw; i<<=1) wlen = ll (wlen * 1ll * wlen % mod); for (int i=0; i<n; i+=len) { ll w = 1; for (int j=0; j<len/2; ++j) { ll u = a[i+j], v = ll (a[i+j+len/2] * 1ll * w % mod); a[i+j] = getmod(u+v,mod); a[i+j+len/2] = getmod(u-v,mod); w = ll (w * 1ll * wlen % mod); } } } if (invert) { ll nrev = rev_element[n]; for (int i=0; i<n; ++i) a[i] = int (a[i] * 1ll * nrev % mod); } } void precalc(){ rev_element[1] = 1; for (int i=2; i<mod; i++) rev_element[i] = (mod - (mod/i) * rev_element[mod%i] % mod) % mod; } void multiply (const vector<ll> & a, const vector<ll> & b, vector<ll> & res) { vector <ll> fa (a.begin(), a.end()), fb (b.begin(), b.end()); size_t n = 1; while (n < max (a.size(), b.size())) n <<= 1; n <<= 1; fa.resize (n), fb.resize (n); fft (fa, false), fft (fb, false); forn(i,n) fa[i] *= fb[i]; fft (fa, true); res.resize (n); forn(i,n) res[i] = fa[i] % mod; } int MN = 29; int MK = 1001; vector <vector <ll> > dp(MN+2,vector <ll> (MK,0)); vector <ll> d; void init(){ int m; for (int i=0; i<=MN; i++){ dp[i][0] = 1; multiply(dp[i],dp[i],d); d.resize(MK); multiply(d,d,dp[i+1]); dp[i+1].insert(dp[i+1].begin(),0); dp[i+1].resize(MK); } } int main(){ #ifdef dudkamaster freopen("input.txt","rt",stdin); freopen("output.txt","wt",stdout); #endif precalc(); init(); int tc; scanf("%d", &tc); forn(i,tc){ ll n,k; cin >> n >> k; int iter = 0; while (n>1 && n&1) iter++, n>>=1; cout << dp[iter][k] << endl; } return 0; }
300
E
Empire Strikes Back
In a far away galaxy there is war again. The treacherous Republic made $k$ precision strikes of power $a_{i}$ on the Empire possessions. To cope with the republican threat, the Supreme Council decided to deal a decisive blow to the enemy forces. To successfully complete the conflict, the confrontation balance after the blow should be a positive integer. The balance of confrontation is a number that looks like $\overset{p}{q}$, where $p = n!$ ($n$ is the power of the Imperial strike), $q=\prod_{i=1}^{k}a_{i}!$. After many years of war the Empire's resources are low. So to reduce the costs, $n$ should be a minimum positive integer that is approved by the commanders. Help the Empire, find the minimum positive integer $n$, where the described fraction is a positive integer.
Let's $v a l=\sum_{i=1}^{k}a_{i}$. $val$ is upper bound for answer. $val!$ is divisible by $d e n=\prod_{i=1}^{k}a_{i}!$, you can easily prove it using facts about prime powers in factorial and following inequality $\left|{\frac{\eta}{i}}\right|+\left|{\frac{\eta}{i}}\right|\leq\left|{\frac{(\mu+\mu)}{i}}\right|$. By the way, $\frac{\nu a/|}{d\epsilon m}$ is called multinomial coefficient. So answer can't exceed $10^{13}$. If $n!$ divisible by $den$, then $(n + 1)!$ is also divisible by $den$. That means that function of divisibility is monotonic and we can use binary search. For every $i$, $i = 2..., 10^{7}$, let's precalc max prime in $i$ using linear sieve of Eratosthenes. For $i$ it will be $lp[i]$. After that let's create a vector, with all primes less then $10^{7}$. Now let's calculate following values $cnt[i]$ - amount of numbers $a$, $i < = a$. Now me can factorize denominator like this: for(int i = max; i>=2; i--) { if (lp[i] != i) cnt[lp[i]] += cnt[i]; cnt[i / lp[i]] += cnt[i]; }Finally we use binary search from $lf = 1$ to $r g=\textstyle\sum_{i=1}^{k}a_{i}$.
[ "binary search", "math", "number theory" ]
2,300
#include <cstdio> const int N = (int)1e7 + 100; int lp[N], simples[N], simsz; long long cnt[N]; bool ok(long long mid) { bool can = true; for(int i = 0; i < simsz && can; i++) { long long tmp = mid, f = 0; while(tmp) { tmp /= simples[i]; f += tmp; } if (f < cnt[i]) can = false; } return can; } int main() { int n, max = 0; scanf("%d", &n); long long rg = 0, lf = 1; for(int i = 0; i < n; ++i) { int a; scanf("%d", &a); if (a > max) max = a; rg += a; ++cnt[a]; } for(int i = 2; i <= max; ++i) { if (lp[i] == 0) { lp[i] = i; simples[simsz++] = i; } for(int j = 0; j < simsz && simples[j] <= lp[i] && (long long)i*simples[j]<=max; ++j) { lp[i * simples[j]] = simples[j]; } } for(int i = max; i>=2; i--) cnt[i] += cnt[i+1]; for(int i = max; i>=2; i--) { if (lp[i] != i) cnt[lp[i]] += cnt[i]; cnt[i / lp[i]] += cnt[i]; } for(int i = 0; i < simsz; i++) { cnt[i] = cnt[simples[i]]; } while (rg != lf) { long long mid = (rg+lf)>>1; if (ok(mid)) { rg = mid; } else lf = mid + 1; } printf("%I64d", lf); }
301
A
Yaroslav and Sequence
Yaroslav has an array, consisting of $(2·n - 1)$ integers. In a single operation Yaroslav can change the sign of exactly $n$ elements in the array. In other words, in one operation Yaroslav can select exactly $n$ array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements can be obtained if it is allowed to perform any number of described operations? Help Yaroslav.
Using dfs we will find number of numbers that we can set as positive. Note that we can either set all of the numbers as positive or leave one number(any) as negative. If we can obtain all numbers as positive, we just return sum of modules of the numbers, but if we cannot we will count the same sum and will subtract minimal modular value multiple 2 from sum.
[ "constructive algorithms" ]
1,800
null
301
B
Yaroslav and Time
Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has $n$ clock stations, station number $i$ is at point $(x_{i}, y_{i})$ of the plane. As the player visits station number $i$, he increases the current time on his timer by $a_{i}$. The stations are for one-time use only, so if the player visits some station another time, the time on his timer won't grow. A player spends $d·dist$ time units to move between stations, where $dist$ is the distance the player has covered and $d$ is some constant. The distance between stations $i$ and $j$ is determined as $|x_{i} - x_{j}| + |y_{i} - y_{j}|$. Initially, the player is at station number $1$, and the player has strictly more than zero and strictly less than one units of time. At station number $1$ one unit of money can increase the time on the timer by one time unit (you can buy only integer number of time units). Now Yaroslav is wondering, how much money he needs to get to station $n$. Help Yaroslav. Consider the time to buy and to increase the timer value negligibly small.
We will use binary search to find the answer. Further we will use Ford-Bellman algorithm. On each step we will have an array of maximum values on timer, when we stand in some point. On in transfer we will check: will our player stay alive after travelling beetwen points. If we can make transfer, we will update value of the final destination point. Becouse of a_i<=d and integer coordinates we haven't optimal cycles, and solution exists.
[ "binary search", "graphs", "shortest paths" ]
2,100
null
301
C
Yaroslav and Algorithm
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. - The algorithm receives a string as the input. We denote this input string as $a$. - The algorithm consists of some number of command. Сommand number $i$ looks either as $s_{i}$ >> $w_{i}$, or as $s_{i}$ <> $w_{i}$, where $s_{i}$ and $w_{i}$ are some possibly empty strings of length at most $7$, consisting of digits and characters "?". - At each iteration, the algorithm looks for a command with the minimum index $i$, such that $s_{i}$ occurs in $a$ as a substring. If this command is not found the algorithm terminates. - Let's denote the number of the found command as $k$. In string $a$ the first occurrence of the string $s_{k}$ is replaced by string $w_{k}$. If the found command at that had form $s_{k}$ >> $w_{k}$, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. - The value of string $a$ after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of $n$ positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one. Help Yaroslav.
We will use ? as iterator. In the begin we will set ? before the number. Then we will move it to the end of the string. Then we will change ? to ?? and we will move it to the begin, while we have 9 before ??. If we have another digit, we just increase it, and finish the algorithm. If we have ?? at the begin, we change it to 1, and end the algorithm.
[ "constructive algorithms" ]
2,500
null
301
D
Yaroslav and Divisors
Yaroslav has an array $p = p_{1}, p_{2}, ..., p_{n}$ $(1 ≤ p_{i} ≤ n)$, consisting of $n$ distinct integers. Also, he has $m$ queries: - Query number $i$ is represented as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. - The answer to the query $l_{i}, r_{i}$ is the number of pairs of integers $q$, $w$ $(l_{i} ≤ q, w ≤ r_{i})$ such that $p_{q}$ is the divisor of $p_{w}$. Help Yaroslav, answer all his queries.
Lets add all pair: (x,y) ((d[x]%d[y]==0) || (d[y]%d[x]==0)) to some lest. We can count such pairs using Eretosphen algorithm. Here will be O(n*log(n)) sych pairs using fact, that we have permutation. We will sort all this paairs using counting-sort. Also we will sort given in input intervals. For each given interval we should count number of pairs that countained in given them . Such problem we can solve using Fenvik tree. On each step we will add segments(that are sorted by right side). On each step we will update Fenfick-tree that count number of added pairs on some suffix. Using such tree if it easy to count the answer. So we have O(n*log^2(n)) solution.
[ "data structures" ]
2,200
null
301
E
Yaroslav and Arrangements
Yaroslav calls an array of $r$ integers $a_{1}, a_{2}, ..., a_{r}$ good, if it meets the following conditions: $|a_{1} - a_{2}| = 1, |a_{2} - a_{3}| = 1, ..., |a_{r - 1} - a_{r}| = 1, |a_{r} - a_{1}| = 1$, at that $a_{1}=\operatorname*{min}_{i=1}a_{i}$. An array of integers $b_{1}, b_{2}, ..., b_{r}$ is called great, if it meets the following conditions: - The elements in it do not decrease $(b_{i} ≤ b_{i + 1})$. - If the inequalities $1 ≤ r ≤ n$ and $1 ≤ b_{i} ≤ m$ hold. - If we can rearrange its elements and get at least one and at most $k$ distinct good arrays. Yaroslav has three integers $n, m, k$. He needs to count the number of distinct great arrays. Help Yaroslav! As the answer may be rather large, print the remainder after dividing it by $1000000007$ $(10^{9} + 7)$. Two arrays are considered distinct if there is a position in which they have distinct numbers.
We will build the needed arrays sequentially adding numbers. Let's look at what states we need. First, it is obvious that you need to keep the number of ways to build an array of already added numbers, secondly you need to know the total amount of added numbers. Now let's look at what happens when we add a new number (that is greater than all of the previous in a certain amount). It is clear that the added numbers should stand between the numbers 1 to less. In this case, if we put two new numbers in a row, between them should stand more (since we already have placed less). It is obvious that you need to cover all the previous numbers (among which must stand newly added). Thus, we have another state: the number of integers between which we should put the new ones. Thus we have the dynamics of the four parameters: dp [all] [ways] [lastnumber] [counttoadd]. Transfer. It is clear that you need to add at least counttoadd numbers, but how will this affect the number of ways to arrange the numbers? It's simple. Suppose we added number x, then the number of ways to be multiplied by the value of Q (x-counttoadd, counttoadd), where Q (x, y) - the number of ways to assign the same x balls in y different boxes. Q (x, y) = C (x + y-1, y-1) where C (x, y) - binomial coefficient.
[ "dp" ]
2,800
null
302
A
Eugeny and Array
Eugeny has array $a = a_{1}, a_{2}, ..., a_{n}$, consisting of $n$ integers. Each integer $a_{i}$ equals to -1, or to 1. Also, he has $m$ queries: - Query number $i$ is given as a pair of integers $l_{i}$, $r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ n)$. - The response to the query will be integer $1$, if the elements of array $a$ can be rearranged so as the sum $a_{li} + a_{li + 1} + ... + a_{ri} = 0$, otherwise the response to the query will be integer $0$. Help Eugeny, answer all his queries.
If the length of the given segment is even and count of 1 in input is not lower then half of the length of the segment and count of -1 in the input is not lower then half of the length of the segment so we have answer 1, otherwise 0.
[ "implementation" ]
800
null
302
B
Eugeny and Play List
Eugeny loves listening to music. He has $n$ songs in his play list. We know that song number $i$ has the duration of $t_{i}$ minutes. Eugeny listens to each song, perhaps more than once. He listens to song number $i$ $c_{i}$ times. Eugeny's play list is organized as follows: first song number $1$ plays $c_{1}$ times, then song number $2$ plays $c_{2}$ times, $...$, in the end the song number $n$ plays $c_{n}$ times. Eugeny took a piece of paper and wrote out $m$ moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment $x$ means that Eugeny wants to know which song was playing during the $x$-th minute of his listening to the play list. Help Eugeny and calculate the required numbers of songs.
For each song we will count moment of time, when it will be over (some sums on the prefixes, for example). Further, we will use binary search of two itaratos method to solve the problem.
[ "binary search", "implementation", "two pointers" ]
1,200
null
303
A
Lucky Permutation Triple
Bike is interested in permutations. A permutation of length $n$ is an integer sequence such that each integer from 0 to $(n - 1)$ appears exactly once in it. For example, $[0, 2, 1]$ is a permutation of length 3 while both $[0, 2, 2]$ and $[1, 2, 3]$ is not. A permutation triple of permutations of length $n$ $(a, b, c)$ is called a Lucky Permutation Triple if and only if $\forall i(1\leq i\leq n),a_{i}+b_{i}\equiv c_{i}\mod n$. The sign $a_{i}$ denotes the $i$-th element of permutation $a$. The modular equality described above denotes that the remainders after dividing $a_{i} + b_{i}$ by $n$ and dividing $c_{i}$ by $n$ are equal. Now, he has an integer $n$ and wants to find a Lucky Permutation Triple. Could you please help him?
when n is odd, A[i] = B[i] = i when n is even, there is no solution. So why? Because: S = \Sum_{i=0}^{n-1} i = n/2 (mod n) but 2*S = 0 (mod n)
[ "constructive algorithms", "implementation", "math" ]
1,300
null
303
B
Rectangle Puzzle II
You are given a rectangle grid. That grid's size is $n × m$. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers $(x, y)$ $(0 ≤ x ≤ n, 0 ≤ y ≤ m)$. Your task is to find a maximum sub-rectangle on the grid $(x_{1}, y_{1}, x_{2}, y_{2})$ so that it contains the given point $(x, y)$, and its length-width ratio is exactly $(a, b)$. In other words the following conditions must hold: $0 ≤ x_{1} ≤ x ≤ x_{2} ≤ n$, $0 ≤ y_{1} ≤ y ≤ y_{2} ≤ m$, $\textstyle{\frac{a_{2}-a_{1}}{y_{2}-y_{1}}}={\frac{a}{b}}$. The sides of this sub-rectangle should be parallel to the axes. And values $x_{1}, y_{1}, x_{2}, y_{2}$ should be integers. If there are multiple solutions, find the rectangle which is closest to $(x, y)$. Here "closest" means the Euclid distance between $(x, y)$ and the center of the rectangle is as small as possible. If there are still multiple solutions, find the lexicographically minimum one. Here "lexicographically minimum" means that we should consider the sub-rectangle as sequence of integers $(x_{1}, y_{1}, x_{2}, y_{2})$, so we can choose the lexicographically minimum one.
Give you $n$, $m$, $x$, $y$, $a$, $b$. Find a maximum sub-rectangle within (0, 0) - ($n$, $m$), so that it contains the given point($x$, $y$) and its length-width radio is exactly ($a$, $b$). If there are multiple solutions, find the rectangle which is closest to ($x$, $y$). If there are still multiple solutions, find the lexicographically minimum one. Split the problem into $x$-axis and $y$-axis. Then you can solve the sub tasks in $O(1)$. d = gcd(a,b) a /= d b /= d t = min(n/a, m/b) a *= t b *= tBe careful, when the length is outside the original rectangle.
[ "implementation", "math" ]
1,700
null
303
C
Minimum Modular
You have been given $n$ distinct integers $a_{1}, a_{2}, ..., a_{n}$. You can remove at most $k$ of them. Find the minimum modular $m$ $(m > 0)$, so that for every pair of the remaining integers $(a_{i}, a_{j})$, the following unequality holds: $a_{i}\neq a_{j}\;\;\mathrm{mod}\;m$.
It is hard to solve this problem at once, so at first, let us consider on k = 0, this easier case can be solved by enumerate on the $ans$. Let us define a bool array diff[], which diff[x] is weather there are two number, $a_{i}$, $a_{j}$, such that $abs(a_{i} - a_{j}) = x$. So $ans$ is legal <=> diff[ans], diff[2*ans] \dots are false. The time-complexity $O(n^{2} + mlogm)$. Here $m$ is the maximum $a_{i}$. Consider on $k > 0$, we need to know how many pairs which has difference x. Store them in vector<pair <int, int> > diff[x]; Then use a dsu to maintain the how many a_i are congruent when enumerate on the $ans$.
[ "brute force", "graphs", "math", "number theory" ]
2,400
null
304
A
Pythagorean Theorem II
In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states: \underline{In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the squares whose sides are the two legs (the two sides that meet at a right angle).} The theorem can be written as an equation relating the lengths of the sides $a$, $b$ and $c$, often called the Pythagorean equation: \[ a^{2} + b^{2} = c^{2} \] where $c$ represents the length of the hypotenuse, and $a$ and $b$ represent the lengths of the other two sides. Given $n$, your task is to count how many right-angled triangles with side-lengths $a$, $b$ and $c$ that satisfied an inequality $1 ≤ a ≤ b ≤ c ≤ n$.
This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math.
[ "brute force", "math" ]
1,200
null
304
B
Calendar
Calendars in widespread use today include the Gregorian calendar, which is the de facto international standard, and is used almost everywhere in the world for civil purposes. The Gregorian reform modified the Julian calendar's scheme of leap years as follows: \underline{Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 is not a leap year; the year 2000 is a leap year.} In this problem, you have been given two dates and your task is to calculate how many days are between them. Note, that leap years have unusual number of days in February. Look at the sample to understand what borders are included in the aswer.
This problem can be solve by brute-force, but it come up with a nicer solution if we involve some math.
[ "brute force", "implementation" ]
1,300
null
305
A
Strange Addition
Unfortunately, Vasya can only sum pairs of integers ($a$, $b$), such that for any decimal place at least one number has digit $0$ in this place. For example, Vasya can sum numbers $505$ and $50$, but he cannot sum $1$ and $4$. Vasya has a set of $k$ distinct non-negative integers $d_{1}, d_{2}, ..., d_{k}$. Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?
All you have to do is implement following algorithm: If we have numbers $0$ or $100$, we take them to needed subset. If we got number greater than $0$ and less than 10, we take it. If we got number $x\in[10;100)$ divisible by 10 we take it. In case we have no numbers of second and third type, we take a number $x\in[10;100)$ that is not divisible by 10
[ "brute force", "constructive algorithms", "implementation" ]
1,600
#include <cstdio> #include <vector> int n, cnt[5], a; using namespace std; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &a); if (a == 0) { cnt[0] = 1; continue; } if (a == 100) { cnt[1] = 1; continue; } if (a % 10 == 0) { cnt[2] = a; continue; } if (a < 10) { cnt[3] = a; continue; } cnt[4] = a; } vector < int > ans; if (cnt[0]) ans.push_back(0); if (cnt[1]) ans.push_back(100); if (cnt[2]) ans.push_back(cnt[2]); if (cnt[3]) ans.push_back(cnt[3]); if (!cnt[2] && !cnt[3] && cnt[4]) ans.push_back(cnt[4]); printf("%d ", ans.size()); for(int i = 0; i < ans.size(); i++) { if (i) printf(" "); printf("%d", ans[i]); } puts(""); }
305
B
Continued Fractions
A continued fraction of height $n$ is a fraction of form $a_{1}+{\frac{1}{a_{2}+{\frac{1}{\ldots+{\frac{1}{a_{m}}}}}}}$. You are given two rational numbers, one is represented as $\overset{p}{q}$ and the other one is represented as a finite fraction of height $n$. Check if they are equal.
There are at most two ways to represent rational fraction as continued. Using Euclid algorithm you can do that for $\overset{p}{q}$ and then check equality of corresponding $a_{i}$.
[ "brute force", "implementation", "math" ]
1,700
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <complex> #include <ctime> #include <cstdio> #include <cstdlib> #include <cstring> #include <deque> #include <functional> #include <fstream> #include <iostream> #include <iomanip> #include <map> #include <memory.h> #include <numeric> #include <queue> #include <set> #include <stack> #include <string> #include <sstream> #include <vector> #include <utility> #include <cmath> using namespace std; #define pb push_back #define mp make_pair #define sz(a) (int)(a).size() #define all(a) (a).begin(), (a).end() #define rall(a) (a).rbegin(), (a).rend() #define forn(i,n) for (int i=0; i<int(n); ++i) #define fornd(i,n) for (int i=int(n)-1; i>=0; --i) #define forab(i,a,b) for (int i=int(a); i<int(b); ++i) typedef long long ll; typedef long double ld; typedef unsigned long long ull; const int INF = (int) 1e9; const long long INF64 = (long long) 1e18; const long double eps = 1e-9; const long double pi = 3.14159265358979323846; ll p,q,n; vector <ll> a; vector <ll> m; bool read(){ if (!(cin >> p >> q >> n)) return false; a.assign(n,0); forn(i,n) cin >> a[i]; return true; } void calc(ll a, ll b){ if (a == 0 || b == 0) return; ll q = a/b; m.pb(q); a -= b*q; calc(b,a); } void solve(){ if (n > 1 && a[n-1] == 1){ a[n-2]++; a.pop_back(); n--; } m.clear(); calc(p,q); bool ans = true; if (sz(a)!=sz(m)) ans = false; forn(i,min(sz(a),sz(m))) ans = ans && (a[i]==m[i]); if (ans) puts("YES"); else puts("NO"); } int main(){ #ifdef dudkamaster freopen("input.txt","rt",stdin); freopen("output.txt","wt",stdout); #endif while (read()) solve(); return 0; }
305
C
Ivan and Powers of Two
Ivan has got an array of $n$ non-negative integers $a_{1}, a_{2}, ..., a_{n}$. Ivan knows that the array is sorted in the non-decreasing order. Ivan wrote out integers $2^{a1}, 2^{a2}, ..., 2^{an}$ on a piece of paper. Now he wonders, what minimum number of integers of form $2^{b}$ $(b ≥ 0)$ need to be added to the piece of paper so that the sum of all integers written on the paper equalled $2^{v} - 1$ for some integer $v$ $(v ≥ 0)$. Help Ivan, find the required quantity of numbers.
First of all, let's carry over all powers of two in the following way: if we have $a_{i} = a_{j}$, $i \neq j$, carry 1 to $a_{i} + 1$. Now as all of $a_{i}$ are distinct, the answer is $max(a_{i})$ - $cnt(a_{i})$ + 1, where $max(a_{i})$ - maximal value of $a_{i}$,$cnt(a_{i})$ - size of $a$
[ "greedy", "implementation" ]
1,600
#include <cstdio> const int NMAX = 100005; int a[NMAX], n, tmax, tcnt; int main() { scanf("%d", &n); for(int i = 0; i < n; i++) scanf("%d", &a[n - i - 1]); while (n > 0) { int j = n - 1, cnt; while (j > 0 && a[n - 1] == a[j - 1]) --j; cnt = n - j; if (cnt % 2 == 1) { tcnt++, n--; if (a[n] > tmax) tmax = a[n]; } cnt /= 2; n -= cnt; for(int i = 0; i < cnt; i++) a[n - 1 - i]++; } printf("%d ", tmax - tcnt + 1); }
305
D
Olya and Graph
Olya has got a directed non-weighted graph, consisting of $n$ vertexes and $m$ edges. We will consider that the graph vertexes are indexed from 1 to $n$ in some manner. Then for any graph edge that goes from vertex $v$ to vertex $u$ the following inequation holds: $v < u$. Now Olya wonders, how many ways there are to add an arbitrary (possibly zero) number of edges to the graph so as the following conditions were met: - You can reach vertexes number $i + 1, i + 2, ..., n$ from any vertex number $i$ $(i < n)$. - For any graph edge going from vertex $v$ to vertex $u$ the following inequation fulfills: $v < u$. - There is at most one edge between any two vertexes. - The shortest distance between the pair of vertexes $i, j$ $(i < j)$, for which $j - i ≤ k$ holds, equals $j - i$ edges. - The shortest distance between the pair of vertexes $i, j$ $(i < j)$, for which $j - i > k$ holds, equals either $j - i$ or $j - i - k$ edges. We will consider two ways distinct, if there is the pair of vertexes $i, j$ $(i < j)$, such that first resulting graph has an edge from $i$ to $j$ and the second one doesn't have it. Help Olya. As the required number of ways can be rather large, print it modulo $1000000007$ $(10^{9} + 7)$.
First of all let's consider a graph on a number line. It's neccesary to have edges $i - > i + 1$(first type). Also you can edges like $i - > i + k + 1$ (second type). Other edges are forbidden. This allows us to understand whether the answer is 0 or not. Also answer is 0 when all edges of second type doesn't intersect, considering them to be segments of number line, except when $k \ge n - 1$ - in this case answer is 1. Now we know that answer != 0. Frow all edges we have let's use only second type edges. If there aren't any of this edges we can add 1 to the answer, because of possibility of adding 0 edges to graph. For every vertex $i$, that has possibility of adding second type edges, let's add to answer $2^{cnt}$, $cnt$ - amount of vertexes on [i, min(i + k, n - k - 1)] without edges of second type out of them. Also it is necessary for all the second type edges to start in this segment.
[ "combinatorics", "math" ]
2,200
#include <cstdio> #include <algorithm> #include <utility> #include <cassert> #include <vector> using namespace std; const int MOD = 1000000007, N = 1000005; int n, m, k, ans, degs[N]; #define forn(i,n) for(int i = 0; i < (int) n; i++) inline int add(int a, int b) { a += b; if (a >= MOD) a -= MOD; return a;} int main(){ degs[0] = 1; forn(i, N) { if (!i) continue; degs[i] = add(degs[i-1], degs[i-1]); } scanf("%d %d %d ", &n, &m, &k); vector < pair<int,int> > edges; forn(i, m) { int a, b; scanf("%d %d", &a, &b); if (b - a != 1 && b - a != k + 1) { puts("0"); return 0; } if (b - a == k + 1) edges.push_back(make_pair(a, b)); } sort(edges.begin(), edges.end()); m = edges.size(); if (k == 0 || k >= n - 1) { puts("1"); return 0; } forn(i, m) { if (!(edges[i].first >= edges[0].first && edges[i].first < edges[0].second)) { puts("0"); return 0; } } if (edges.size() == 0) ++ans; forn(i, n) { int f = i + 1, s = i + k + 2, cnt = m; if (s > n || (m > 0 && f > edges[0].first)) break; if (m > 0 && !(f <= edges[0].first && edges[m-1].first < s)) continue; if (m > 0 && f == edges[0].first) cnt--; s = min(s, n - k); ans = add(ans,degs[s - f - cnt - 1]); } printf("%d ", ans); }
305
E
Playing with String
Two people play the following string game. Initially the players have got some string $s$. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. \begin{center} {\scriptsize An example of the initial situation at $s$ = "abacaba"} \end{center} A player's move is the sequence of actions: - The player chooses one of the available pieces of paper with some string written on it. Let's denote it is $t$. Note that initially, only one piece of paper is available. - The player chooses in the string $t = t_{1}t_{2}... t_{|t|}$ character in position $i$ $(1 ≤ i ≤ |t|)$ such that for some positive integer $l$ $(0 < i - l; i + l ≤ |t|)$ the following equations hold: $t_{i - 1} = t_{i + 1}$, $t_{i - 2} = t_{i + 2}$, ..., $t_{i - l} = t_{i + l}$. - Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string $t_{1}t_{2}... t_{i - 1}$, the second one will contain a string consisting of a single character $t_{i}$, the third one contains string $t_{i + 1}t_{i + 2}... t_{|t|}$. \begin{center} {\scriptsize An example of making action $(i = 4)$ with string $s$ = «abacaba»} \end{center} Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.
Let's consider substring of $s$ $s[i... j]$, that all characters from $i$ to $j$ are palindrome centers, and $i - 1, j + 1$ are not. Every such substring can be treated independently from the others, and as we don't need to know it'sstructure let's consider only it length $len$. Let's calculate $grundy[len]$ - Grundy function. If we want to cut character at position $i$ $0 \le i < len$ then our game splits in to independent ones: first will have length $i - 1$, second - $len - i - 2$, as $s[i - 1]$ and $s[i + 1]$ are not centers of palindrome any more.
[ "games" ]
2,300
#include <cstdio> #include <memory.h> #include <cstring> inline int max(int a, int b) { if (a >= b) return a; return b; } const int N = 5005; char s[N]; int grundy[N], mex[N], n, totalXor; int main(){ gets(s); for(int i = 1; i < N; i++) { memset(mex, 0, sizeof mex); for(int j = 0; j < i; j++) { int left = max(0, j - 1); int right = max(0, i - j - 2); int tXor = grundy[left] ^ grundy[right]; if (tXor < N) mex[tXor]++; } for(int j = 0; ; j++) { if (!mex[j]) { grundy[i] = j; break; } } } n = strlen(s); for(int i = 1; i < n - 1; i++) { if (s[i-1] == s[i + 1]) { int j = i; while (j + 2 < n && s[j] == s[j + 2]) j++; totalXor ^= grundy[j - i + 1]; i = j + 1; } } if (totalXor != 0) { puts("First"); for(int i = 1; i < n - 1; i++) { if (s[i-1] == s[i+1]) { int j = i; while (j + 2 < n && s[j] == s[j + 2]) j++; int len = j - i + 1; int nowXor = totalXor ^ grundy[len]; for(int k = 0; k < len; k++) { int left = max(0, k - 1); int right = max(0, len - k - 2); int resXor = nowXor ^ grundy[left] ^ grundy[right]; if (resXor == 0) { printf("%d ", i + k + 1); return 0; } } i = j + 1; } } } puts("Second"); }
309
A
Morning run
People like to be fit. That's why many of them are ready to wake up at dawn, go to the stadium and run. In this problem your task is to help a company design a new stadium. The city of N has a shabby old stadium. Many people like it and every morning thousands of people come out to this stadium to run. The stadium can be represented as a circle, its length is exactly $l$ meters with a marked start line. However, there can't be simultaneous start in the morning, so exactly at 7, each runner goes to his favorite spot on the stadium and starts running from there. Note that not everybody runs in the same manner as everybody else. Some people run in the clockwise direction, some of them run in the counter-clockwise direction. It mostly depends on the runner's mood in the morning, so you can assume that each running direction is equiprobable for each runner in any fixed morning. The stadium is tiny and is in need of major repair, for right now there only is one running track! You can't get too playful on a single track, that's why all runners keep the same running speed — exactly 1 meter per a time unit. Nevertheless, the runners that choose different directions bump into each other as they meet. The company wants to design a new stadium, but they first need to know how bad the old one is. For that they need the expectation of the number of bumpings by $t$ time units after the running has begun. Help the company count the required expectation. Note that each runner chooses a direction equiprobably, independently from the others and then all runners start running simultaneously at 7 a.m. Assume that each runner runs for $t$ time units without stopping. Consider the runners to bump at a certain moment if at that moment they found themselves at the same point in the stadium. A pair of runners can bump more than once.
We were asked to find the expected value of meetings between the runners. How to do that? As the first step, expected value is lineal, so we can split the initial problems into the different ones: find the expected value of meetings between the fixed pair of runners. We will solve these problems. To do that we need to make some observations: Let $x$ be the distance between the two runners and they run face to face for infinite amount of time (probability of that obviously equals to $0.5 \cdot 0.5 = 0.25$). Then the first meeting will happen at time $\scriptstyle{\frac{a}{2}}$, the next one - ${\frac{x}{2}}+{\frac{l}{2}}$, the next - $\displaystyle{\frac{x}{2}}+{\frac{l}{2}}+{\frac{l}{2}}+{\frac{l}{2}}$ and so on. Let us assume that every run ran for $l$ time units. Then if two runners meet - they meet exactly two times. The probability of the meeting equals to $0.5$, because in two cases they run in the same direction and in two cases in the different ones. We will build our solution based on these two observations. As the first step let us represent $t$ as $t = k \cdot l + p$, where $0 \le p < l$. Then each runner will run $k$ full laps. What does that mean? Because we have $\textstyle{\frac{n(n-1)}{2}}$ pairs of runners, then in those $k$ laps each pair will have $2k$ meetings with probability equals to $0.5$. So, we need to add $2k\cdot{\frac{n(n-1)}{2}}\cdot0.5={\frac{k n(n-1)}{2}}$ to the answer. Now we need to take into account $p$ seconds of running. Let us assume that the distance between two runners is $x$ and they run towards each other. Then they will meet if ${\underset{^{\sim}}{a}}\leq l$, or $x \le 2t$. They will meet once more if ${\frac{x}{2}}+{\frac{\imath}{2}}\leq l$, ir $x \le 2t - l$. They cannot meet more than twice, because $p < l$. Let us fix one of the runners, then using binary search we can find all other runners at distance no more than $x$ from the fixed one. Let us choose $x$ as $x = 2t$, and then the number of runners at the distance no more than $x$ stands for the number of runners which meet with the fixed one at least once. If $x = 2t - l$, we will find the number of runners which meet with the fixed one exactly two times. Multiplying these numbers by $0.25$ - probability of the meeting, and add it to the answer. The complexity of this solution is $O(n\log n)$. We can reduce it using two pointers method.
[ "binary search", "math", "two pointers" ]
2,000
null
309
B
Context Advertising
Advertising has become part of our routine. And now, in the era of progressive technologies, we need your ideas to make advertising better! In this problem we'll look at a simplified version of context advertising. You've got a text, consisting of exactly $n$ words. A standard advertising banner has exactly $r$ lines, each line can contain at most $c$ characters. The potential customer always likes it when they can see lots of advertising, so you should determine which maximum number of consecutive words from the text can be written on the banner. Single words in one line of the banner should be separated by spaces. You are allowed to insert more than one space at once. Note that you are not allowed to break the words, that is, each word in the text must occupy exactly one line in the banner. Besides, you cannot change the word order, that is, if you read the banner text consecutively, from top to bottom and from left to right, you should get some consecutive part of the advertisement text. More formally, the statement can be written like that. Let's say that all words are indexed from $1$ to $n$ in the order in which they occur in the advertisement text. Then you have to choose all words, starting from some $i$-th one and ending with some $j$-th one $(1 ≤ i ≤ j ≤ n)$, so that all of them could be written on the banner. There must be as many words as possible. See the samples for clarifications.
We were asked to find the maximal number of words we can fit into the block of size $r \times c$. Let's first solve such problem: what is the maximal number of consecutive words which can fit in a row of lenth $c$, if the first word has index $i$. We can solve it using binary search or moving the pointer. Now let us build a graph, where vertices are the words and there is a directional edge between $i$ and $j$, if words from $i$ to $j - 1$ fit in one row of length $c$, but words from $i$ to $j$ don't. The weight of the edge is $j - i$. The we have the following problem: we need to find the path of length $k$, which has the maximal weight. Easy to solve it with complexity $O(n\log n)$ saving weights of all the paths with lengthes equal to the powers of two, or in $O(n)$ time using dfs. The other problems competitors faced - that we were asked to print the whole text, not only the length.
[ "dp", "two pointers" ]
2,100
null
309
C
Memory for Arrays
You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly $n$ memory clusters, the $i$-th cluster consists of $a_{i}$ cells. You need to find memory for $m$ arrays in your program. The $j$-th array takes $2^{bj}$ consecutive memory cells. There possibly isn't enough memory for all $m$ arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.
We were asked to find the maximal number of arrays we can fit into the memory. A small observation first, let the answer be $k$, then one of the optimal solutions fits the $k$ smallest arrays into the memory. We can assume that we have arrays of size 1 and we want to arrange the memory for the maximal arrays as possible. Then if we have parts of memory of odd size, if we fit array of size 1 at this part we will obtain part of even size. From other hand, if we put arrays of bigger size we will not change the parity and if we don't fill it with arrays of size one and initially it's of odd size then in the end we will have at least one empty cell. So it's reasonable to put the arrays of size one into the memory of odd size. Let's do it until we can do it. We have three possible situations: We don't have memory parts of odd size anymore. We don't have arrays of size 1 anymore. We don't have neither arrays of size 1 neither memory parts of size 1. Let us start from the first case. Suppose that there are some arrays of size 1 left, but there are no memory parts of odd size. Easy to see then in such case we need to group arrays of size 1 in pairs and then consider them as the same array. So we can divide every number by two and reduce the problem to the initial one. In the second case if we divide every number by two we will obtain the same problem (and that cannot increase the answer). The third case is similar to the second one. When implementing this we need to remember that first we have to fill the memory with arrays which are build from the maximal numbers of initial arrays. The complexity of the given algorithm is $O(n\log n)$.
[ "binary search", "bitmasks", "greedy" ]
1,900
null
309
D
Tennis Rackets
Professional sport is more than hard work. It also is the equipment, designed by top engineers. As an example, let's take tennis. Not only should you be in great shape, you also need an excellent racket! In this problem your task is to contribute to the development of tennis and to help to design a revolutionary new concept of a racket! The concept is a triangular racket. Ant it should be not just any triangle, but a regular one. As soon as you've chosen the shape, you need to stretch the net. By the time you came the rocket had $n$ holes drilled on each of its sides. The holes divide each side into equal $n + 1$ parts. At that, the $m$ closest to each apex holes on each side are made for better ventilation only and you cannot stretch the net through them. The next revolutionary idea as to stretch the net as obtuse triangles through the holes, so that for each triangle all apexes lay on different sides. Moreover, you need the net to be stretched along every possible obtuse triangle. That's where we need your help — help us to count the number of triangles the net is going to consist of. Two triangles are considered to be different if their pictures on the fixed at some position racket are different.
We were asked to find the number of obtuse triangles which satisfy the problem statement. Author's solution has complexity $O(n^{2})$, but it has some optimizations, so it easily works under the TL. Every triangle has only one obtuse angle. Due to symmetry reasons we can fix one of the sides and assume that obtuse angle is tangent to this side. Then we only need to find the number of such triangles and multiple the answer by 3. Every side is also symmetric, so we can consider only one half of it and then multiple the answer by 2. Let us assume that vertex $A$ of the triangle has coordinates (0,0). Vertex $B$ (0,$\sqrt{3}$) and $C$(2,0). Then we can find the coordinates of every single point at each of the sides and apply cosine theorem. We obtain the inequality which guarantee us that the triangle is obtuse. It can be written in many ways, on of them is following: If $1 \le i, j, k \le n$ - indices of points which are fixed at each of the sides, then triangle is obtuse iff: $f(i, j, k) = 2i^{2} - i(n + 1) + 2j(n + 1) - ij - k(i + j) < 0$. We can see that $g(i,j)=\frac{2i^{2}-i(n+1)+2j(n+1)-i j}{i+j}$ monotonically increases, so we can use moving pointer method applied to variable $k$. Then just go over all $i$ from $m + 1$ to $\textstyle{\frac{n+1}{2}}$, then $j$ from $m + 1$ till upper bound for $k$ is less than or equal to $n - m + 1$ and just sum the results. We should mention that all of the operations have to be done in int type, it significantly increases the speed.
[ "brute force", "geometry" ]
2,700
null
309
E
Sheep
Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming! A large farm has a meadow with grazing sheep. Overall there are $n$ sheep and each of them contains a unique number from 1 to $n$ — because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep $i$ likes regions from $l_{i}$ to $r_{i}$. There are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep. One morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better — Second would have less work in the evening, because sheep won't scatter too much, being tied to each other! In the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two. Help Second find the right arrangement.
Author's supposed greedy algorithm as a solution for this problem. Let us follow this algorithm. Let us create to label for every interval $Position_{v}$ and $MaximalPosition_{v}$. $Position_{v}$ - stands for position of $v$ in the required permutation. $MaximalPosition_{v}$ - stands for maximal possible position of $v$ in the particular moment of the algorithm. Also let's consider $count$ as a counter with initial value of 0 and set of unprocessed vertices $S$. The algorithm is following. Using binary search we find the maximal possible distance between the farthest sheep. And then check whether exists the permutation with maximal distance no more than $K$. Sort all the intervals in the increasing order of $r_{i}$. $Position_{i} = 0$, $1 \le i \le n$, $MaximalPosition_{i} = n$, $1 \le i \le n$, $current = 1$, $count = 0$. Do $count = count + 1$, $Position_{current} = count$, erase $current$ from $S$, if $S$ - is empty, required permutation has been found. Look at every interval connected to $current$, and update $MaximalPosition_{v} = min(MaximalPosition_{v}, Position_{current} + K)$ Build sets $S(count, j) = {v|MaximalPosition_{v} \le count + j}$. If for every $j \ge K - count + 1$ holds $|S(count, j)| \le j$ go to the step 7, otherwise there is no such permutation. Choose the minimal $j$ such that $|S(count, j)| = j$. Choose from it the interval with the smallest $r_{i}$ and consider it as a new value for $current$, go to the step 4. First let us discuss the complexity. Let us fix $K$ (in total there are $\log n$ iterations with fixed $K$). Every step from 4 to 7 will be done at most $n$ times (every time size of $S$ decreases by one). Every step can be implemented in $O(n)$ time. The most difficult one - step 6. But we can see that it's not necessary to actually build the sets, all we need to know - their sizes. This can be done in linear time just counting the number of intervals that $MaximalPosition_{v} = i$. Let if be $C_{i}$ - then size of $S(count, j)$ equals to $C_{1} + C_{2} + ... + C_{count + j}$, which can be easily calculated with partial sums. Now let us discuss why this algorithm works. If we have $Position$ labels for every interval - we obviously have the solution. Now let us assume that we ended up earlier. Then we will show that there is no such permutation. If algorithm ended, it means that for some $count$ (consider the smallest such $count$), exists $j_{0}$, that $|S(count, j_{0})| > j_{0}$ at this step. Then $|S(count, k)| > k$. Let us prove that from contradiction. From the definition of $count$ we have $|S(count - 1, j)| \le j$ for every $j \ge k - count + 2$. Then $|S(count, j)| = |S(count - 1, j + 1)| - 1 \le j$ for every $j \le k - 1$. And $S(count, j) = S(count, k)$ for $k \le j < n - count = |S(count, j)| = |S(count, k)| \le j$. Finally $|S(count, n - count)| = n - count$. Then $|S(count, j)| \le j$ for every $j$, so we obtain contradiction. That means if algorithm stops at step 6 we have $|S(count, k)| > k$. So exist at least $k + 1$ interval, which still don't have assigned label $Position$ and they should be assigned after $count$. So one of the intervals in $S(count, k)$ has to have the value of $Position$ at least $count + k + 1$. But every intervals in $S(count, k)$ connected to at least one interval with $Position \le count$. So, we obtain that there is now such permutation.
[ "binary search", "greedy" ]
2,900
null
311
A
The Closest Pair
Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded. The problem is the follows. Given $n$ points in the plane, find a pair of points between which the distance is minimized. Distance between $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ is $\sqrt{(x_{2}-x_{1})^{2}+(y_{2}-y_{1})^{2}}$. The pseudo code of the unexpected code is as follows: \begin{verbatim} input n for i from 1 to n input the i-th point's coordinates into p[i] sort array p[] by increasing of x coordinate first and increasing of y coordinate second d=INF //here INF is a number big enough tot=0 for i from 1 to n for j from (i+1) to n ++tot if (p[j].x-p[i].x>=d) then break //notice that "break" is only to be //out of the loop "for j" d=min(d,distance(p[i],p[j])) output d \end{verbatim} Here, $tot$ can be regarded as the running time of the code. Due to the fact that a computer can only run a limited number of operations per second, $tot$ should not be more than $k$ in order not to get Time Limit Exceeded. You are a great hacker. Would you please help Tiny generate a test data and let the code get Time Limit Exceeded?
We read the pseudo code carefully. If we ignore "break", $tot$ will be up to $\textstyle{\frac{n(n-1)}{2}}$. Consider whether we can make such inequality $d \le p[j].x - p[i].x$ is always false. The obvious way is to make all points' x coordinates the same. And we can just choose $n$ distinct numbers to be all points' y coordinate. Thus the problem is solved.
[ "constructive algorithms", "implementation" ]
1,300
null
311
B
Cats Transport
Zxr960115 is owner of a large farm. He feeds $m$ cute cats and employs $p$ feeders. There's a straight road across the farm and $n$ hills along the road, numbered from 1 to $n$ from left to right. The distance between hill $i$ and $(i - 1)$ is $d_{i}$ meters. The feeders live in hill 1. One day, the cats went out to play. Cat $i$ went on a trip to hill $h_{i}$, finished its trip at time $t_{i}$, and then waited at hill $h_{i}$ for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to $n$ without waiting at a hill and takes all the \textbf{waiting} cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want. For example, suppose we have two hills $(d_{2} = 1)$ and one cat that finished its trip at time 3 at hill 2 $(h_{1} = 2)$. Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units. Your task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.
Let a[i] be the distance from hill 1 to hill i, s[i]=a[1]+a[2]+ \dots +a[i]. Firstly, we sort the cats by (Ti-a[i]). Then we can divide the cats into P consecutive parts, and plan a feeder for each part. Dynamic Programming can solve this problem. Let f[i,j] indicates the minimum sum of waiting time with i feeders and j cats. f[i,j] = f[i-1,k]+a[j]*(j-k)-s[j]+s[k] = a[j]*j-s[j] + f[i-1,k]+s[k]-a[j]*k That's O(PM^2). It'll get TLE. Let p>q, if p is "better" than q, then: f[i-1,p]+s[p]-a[j]*p>f[i-1,q]+s[q]-a[j]*q (f[i-1,p]+s[p])-(f[i-1,q]+s[q])>a[j]*(p-q) g[p]-g[q]>a[j]*(p-q) So we can use Convex hull trick with a queue. Then we get O(MP), which can pass the problem.
[ "data structures", "dp" ]
2,400
null
311
C
Fetch the Treasure
Rainbow built $h$ cells in a row that are numbered from 1 to $h$ from left to right. There are $n$ cells with treasure. We call each of these $n$ cells "Treasure Cell". The $i$-th "Treasure Cell" is the $a_{i}$-th cell and the value of treasure in it is $c_{i}$ dollars. Then, Freda went in the first cell. For now, she can go just $k$ cells forward, or return to the first cell. That means Freda was able to reach the 1st, ($k + 1$)-th, ($2·k + 1$)-th, ($3·k + 1$)-th cells and so on. Then Rainbow gave Freda $m$ operations. Each operation is one of the following three types: - Add another method $x$: she can also go just $x$ cells forward at any moment. For example, initially she has only one method $k$. If at some moment she has methods $a_{1}, a_{2}, ..., a_{r}$ then she can reach all the cells with number in form $1+\sum_{i=1}^{r}v_{i}\cdot a_{i}$, where $v_{i}$ — some non-negative integer. - Reduce the value of the treasure in the $x$-th "Treasure Cell" by $y$ dollars. In other words, to apply assignment $c_{x} = c_{x} - y$. - Ask the value of the most valuable treasure among the cells Freda can reach. If Freda cannot reach any cell with the treasure then consider the value of the most valuable treasure equal to 0, and do nothing. Otherwise take the most valuable treasure away. If several "Treasure Cells" have the most valuable treasure, take the "Treasure Cell" with the minimum number (not necessarily with the minimum number of cell). After that the total number of cells with a treasure is decreased by one. As a programmer, you are asked by Freda to write a program to answer each query.
Firstly, we solve such a problem: if we can go exactly k,k1,k2 \dots \dots or kp cells forward each step, what cells can we reach? We divide the H cells into k groups: Group 0,1 \dots \dots k-1. The i-th cell should be in Group (i mod k). If we reach Cell x in Group (x mod k), we can also reach Cell (x+kj , 1<=j<=p) in Group ((x+kj)mod k). If we reach Cell x in Group (x mod k), we can also reach Cell (x+k) in the same group. Let D[i] be the minimum cell we can reach in Group i. Then we can reach all the cells which number are bigger then D[i] in Group i. Regard the groups as points. Regard k,k1,k2 \dots \dots kp as edges. And use a Shortest-Path Algorithm to calculate all D[i]. Notice that there are at most 20 operations of type 1, we are able to run such an algorithm after each of these operations. The total time complexity is O(20*k*20*log(k)) with Dijkstra. Secondly, we build a binary-heap to solve operations of type 2 and 3. Type1 - If a D[i] becomes smaller, we put the new cells we can reach into the heap. Type2 - Decrease a value of a node in the heap, or a cell in the "Treasure Cell" array. Type3 - Ask the biggest node in the heap and delete it. These are basic operations of binary-heap. The time complexity is O(NlogN). In C++, you can also use priority_queue from STL and lazy-tags. So we can solve the whole problem in O(400klogk+NlogN).
[ "brute force", "data structures", "graphs", "shortest paths" ]
2,500
null
311
D
Interval Cubing
While learning Computational Geometry, Tiny is simultaneously learning a useful data structure called segment tree or interval tree. He has scarcely grasped it when comes out a strange problem: Given an integer sequence $a_{1}, a_{2}, ..., a_{n}$. You should run $q$ queries of two types: - Given two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$), ask the sum of all elements in the sequence $a_{l}, a_{l + 1}, ..., a_{r}$. - Given two integers $l$ and $r$ ($1 ≤ l ≤ r ≤ n$), let each element $x$ in the sequence $a_{l}, a_{l + 1}, ..., a_{r}$ becomes $x^{3}$. In other words, apply an assignments $a_{l} = a_{l}^{3}, a_{l + 1} = a_{l + 1}^{3}, ..., a_{r} = a_{r}^{3}$. For every query of type 1, output the answer to it. Tiny himself surely cannot work it out, so he asks you for help. In addition, Tiny is a prime lover. He tells you that because the answer may be too huge, you should only output it modulo $95542721$ (this number is a prime number).
Consider a number $x$. If we apply an assignment $x = x^{3}$, $x$ becomes $x^{3}$. If we apply such assignment once more, we will get $(x^{3})^{3} = x^{32}$. If we apply such assignment $k$ times, we will get $x^{3k}$. Thus, we can get such a sequence $a_{0} = x, a_{1} = x^{3}, a_{2} = x^{32}, ..., a_{k} = x^{3k}, ...$. Consider a prime $p$. From Fermat's Little Theorem, we can get $x^{p - 1} = 1(mod$ $p)$. Further more, we can get $x^{y} = x^{ymod(p - 1)}(mod$ $p)$, here $a$ $mod$ $b$ means the remainder of a divided by b. Fortunately, $3^{48} = 1(mod$ $(95542721 - 1))$, thus, $x^{3k} = x^{3kmod48}(mod$ $p)$. In other words, $a_{k} = a_{k + 48}$, which means the cycle of the sequence is $T = 48$. Let's come back to the topic. Each time we run a 1-type query, for every $i$ in the range $[l, r]$, we apply such an assignment $a_{i} = a_{i}^{3}$. At any moment some $i$ has been applied 48 times such assignments, we can consider this $i$ hasn't been applied any assignments before. We can use segment tree to solve this problem. Every node of the segment tree maintains some information: the times that we applied assignments in the node's whole range(it's a lazy tag), current sum of the node's corresponding range and the sum of the node's range after we applied assignments $k(1 \le k < 48)$ times. In such a way, we can solve the problem in $O(n \cdot T + q \cdot T \cdot logn)$ time.
[ "data structures", "math" ]
2,600
null
311
E
Biologist
SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa. She is going to demonstrate this technique. Now SmallR has $n$ dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to $n$. The cost of change for dog $i$ is $v_{i}$ RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once. This experiment has aroused extensive attention from all sectors of society. There are $m$ rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the $i$-th rich folk will pay SmallR $w_{i}$ RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For $i$-th rich folk, in advance, he will appoint certain $k_{i}$ dogs and certain one gender. He will think SmallR succeeds if and only if on some day the $k_{i}$ appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails. If SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay $g$ RMB to him as apologies for her fail. Then, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose.
Obviously, It is about min-cut, which can be solved by max-flow. So, this problem can regarded as the minimum of losing money if we assume SmallR can get all the money and get a total money(sum of wi)at first. Define that, in the min-cut result, the dogs which are connected directly or indirectly to S are 0-gender.otherwise, those to T are 1-gender.We can easily find that the point of a initial-0-gender dog should get a vi weight edge to S.On the other way, initial-1-gender to T. Then, consider the rich men.As to each of rich men, he can appoint only one gender and some dogs.if any one dog he appoint is not the one appointed gender in the result, he can't give SmallR money.How to deal with the rich men in the graph is a difficulty.We can do this, make a new point for a rich man.Then, link the man's point to all points of his dogs by max enough weigh edges(which we can't cut in the min-cut algorithm), and link the man's point to S or T (which depend on that the man's appointed gender is 0 or 1) with a edge of wi weight. lastly run the min-cut(max-flow), we will get the minimum money we will lose. The answer is TotalMoney-LosedMoney. BTW, the issue of g is a piece of cake, we could add it to every special wi but not add it to the total money.
[ "flows" ]
2,300
null
312
A
Whose sentence is it?
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
We only need to find out if "miao." is a prefix of the sentence, and if "lala." is a suffix of the sentence. Pay attention to the situation when both conditions are satisfied.
[ "implementation", "strings" ]
1,100
null
312
B
Archer
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is $\overset{\stackrel{\alpha}{b}}$ for SmallR while $\frac{\epsilon}{d}$ for Zanoes. The one who shoots in the target first should be the winner. Output the probability that SmallR will win the match.
let p=a/b,q=(1-c/d)*(1-a/b). The answer of this problem can be showed as:p*q^0+p*q^1+p*q^2+ \dots \dots \dots \dots That is the sum of a geometric progression which is infinite but 0<q<1.We can get the limit by the formula:p/(1-q)
[ "math", "probabilities" ]
1,300
null
313
A
Ilya and Bank Account
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money. Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance. Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
Ilya and Bank Account This problem is the easiest one. You need to use only div and mod functions. If $n$>0, then answer is $n$, else you need to delete one of two digits.
[ "implementation", "number theory" ]
900
#include <algorithm> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <ctime> #include <iostream> #include <map> #include <set> #include <string> #include <vector> #define max(a, b) (((a) > (b)) ? (a) : (b)) #define min(a, b) (((a) > (b)) ? (b) : (a)) #define abs(a) (((a) > 0) ? (a) : (-(a))) typedef long long ll; using namespace std; int main () { int n; cin >> n; int Max = n; if (n/10 > Max) Max = n/10; if (n%10 + (n/100)*10 > Max) Max = n%10 + (n/100)*10; cout << Max; }
313
B
Ilya and Queries
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string $s = s_{1}s_{2}... s_{n}$ ($n$ is the length of the string), consisting only of characters "." and "#" and $m$ queries. Each query is described by a pair of integers $l_{i}, r_{i}$ $(1 ≤ l_{i} < r_{i} ≤ n)$. The answer to the query $l_{i}, r_{i}$ is the number of such integers $i$ $(l_{i} ≤ i < r_{i})$, that $s_{i} = s_{i + 1}$. Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
Precalculate some array $A_{i}$, that $A_{i} = 1$, if $s_{i} = s_{i + 1}$, else $A_{i} = 0$. Now for any query $(l, r)$, you need to find sum of $A_{i}$, that $(l \le i < r)$. It is standart problem. For solving this problem you can precalcutate some another array Sum, where $Sum_{i} = A_{1} + A_{2} + ... + A_{i}$. Then sum of interval $(l, r)$ is Sum_r - Sum_{l-1}.
[ "dp", "implementation" ]
1,100
Var a,l,r:array[1..1000000] of longint; s:string; i,m,k:longint; begin Readln(s); for i:=2 to length(s) do begin if s[i]=s[i-1] then inc(k); a[i]:=k; end; Readln(m); for i:=1 to m do Readln(l[i],r[i]); for i:=1 to m do Writeln(a[r[i]]-a[l[i]]); end.
313
C
Ilya and Matrix
Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve. He's got a square $2^{n} × 2^{n}$-sized matrix and $4^{n}$ integers. You need to arrange all these numbers in the matrix (put each number in a single individual cell) so that the beauty of the resulting matrix with numbers is maximum. The beauty of a $2^{n} × 2^{n}$-sized matrix is an integer, obtained by the following algorithm: - Find the maximum element in the matrix. Let's denote it as $m$. - If $n = 0$, then the beauty of the matrix equals $m$. Otherwise, a matrix can be split into 4 non-intersecting $2^{n - 1} × 2^{n - 1}$-sized submatrices, then the beauty of the matrix equals the sum of number $m$ and other four beauties of the described submatrices. As you can see, the algorithm is recursive. Help Ilya, solve the problem and print the resulting maximum beauty of the matrix.
At the start sort array. Let $C_{i}$ - number of times of entering the number in $A_{i}$ optimal placement. Answer is sum of $A_{i} * C_{i}$ for all $i$ $(1 \le i \le 4^{n})$. If we look at the array $C$, we can see that for maximal element $C = n + 1$ (for array with size $4^{n}$), then for second, third and fourth maximum elements $C = n$. On this basis we can see, that for array with non-increasing order answer calculate like $Sum(1, 1) + Sum(1, 4) + Sum(1, 16) + ... + Sum(1, 4^{n})$. So, for solve this problem you have to know only sort.
[ "constructive algorithms", "greedy", "implementation", "sortings" ]
1,400
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; int main() { int n; long long s; vector<int> a; scanf("%d", &n); a.resize(n); for (int i = 0; i < n; ++i) { scanf("%d", &a[i]); } sort(a.rbegin(), a.rend()); s = 0; for (int m = 1; m <= n; m *= 4) { s += accumulate(a.begin(), a.begin() + m, 0LL); } cout << s << endl; return 0; }
313
D
Ilya and Roads
Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as $n$ holes in a row. We will consider the holes numbered from 1 to $n$, from left to right. Ilya is really keep on helping his city. So, he wants to fix at least $k$ holes (perharps he can fix more) on a single ZooVille road. The city has $m$ building companies, the $i$-th company needs $c_{i}$ money units to fix a road segment containing holes with numbers of at least $l_{i}$ and at most $r_{i}$. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment. Determine the minimum money Ilya will need to fix at least $k$ holes.
To solve this problem you need to use dynamic programming. Let $Full_{i, j}$ - minimal cost of covering interval $(i, j)$. Fix left border and move right. You can solve this subtask with complexity $O(nm)$ or $O(nmlogn)$. Now we need to solve the standart problem of dynamic programming. Cover $K$ points with intervals that have not intersect. This problem with square dynamic. $dp_{i, j}$ - minimal cost of covering $j$-points, if you look some prefix length $i$. Answer for all problem is minimal integer from $dp_{i, j}$, $(k \le j \le n)$. To solve second part: $1)$ $dp_{i + 1, j} = min(dp_{i + 1, j}, dp_{i, j})$ - skip point with number $i + 1$ $2)$ $dp_{k, j + len} = min(dp_{k, j + len}, dp_{i, j} + Cost)$; $Cost$ - cost of interval with length $len$, that ending at point k. We precalculate $Cost$ at first part of solution.
[ "dp" ]
2,100
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long llint; const int MAXN = 320; const llint INF = 0x0123456789ABCDEFLL; llint d[MAXN][MAXN], dp[MAXN][MAXN]; int main() { int n, m, k, a, b, c; llint ans; scanf("%d%d%d", &n, &m, &k); fill(d[0], d[n + 1], INF); for (int i = 0; i < m; ++i) { scanf("%d%d%d", &a, &b, &c); --a; d[a][b] = min<llint>(d[a][b], c); } for (int i = 0; i <= n; ++i) { for (int j = 1; j <= n; ++j) { d[j][i] = min(d[j][i], d[j - 1][i]); } } fill(dp[0], dp[n + 1], INF); for (int i = 0; i < n; ++i) { dp[i][0] = 0; for (int j = 0; j <= i; ++j) { if (dp[i][j] == INF) { continue; } dp[i + 1][j] = min(dp[i + 1][j], dp[i][j]); for (int k = i + 1; k <= n; ++k) { dp[k][j + (k - i)] = min(dp[k][j + (k - i)], dp[i][j] + d[i][k]); } } } ans = *min_element(dp[n] + k, dp[n + 1]); if (ans == INF) { ans = -1; } cout << ans << endl; return 0; }
313
E
Ilya and Two Numbers
Ilya has recently taken up archaeology. He's recently found two numbers, written in the $m$-based notation. Each of the found numbers consisted of exactly $n$ digits. Ilya immediately started looking for information about those numbers. He learned that the numbers are part of a cyphered code and the one who can decypher it can get the greatest treasure. After considerable research Ilya understood that to decypher the code, he should do the following: - Rearrange digits in the first number in some manner. Similarly, rearrange digits in the second number in some manner. As a result of this operation, the numbers can get leading zeroes. - Add numbers, digit by digit, modulo $m$. In other words, we need to get the third number of length $n$, each digit of the number is the sum of the respective numbers of the found numbers. For example, suppose there are two numbers recorded in the ternary notation, 001210 and 012111, then if you add them to each other digit by digit modulo 3, you will get number 010021. - The key to the code is the maximum possible number that can be obtained in the previous step. Help Ilya, find the key to the code.
1) Get the number of our sequences in sorted by frequencies. Thus from the first sequence (hereinafter - the first type) - in a direct order from the second - to the contrary. 2) These numbers are put on the stack, where if, recording onto the stack of the second type, we find the number at the top of the first type, then this pair of extract and add to the answer. 3) At the end, obviously the stack we can find a number of properties of the second type and the first bottom - on. Then their grouping in response pairs with the start and end.
[ "constructive algorithms", "data structures", "dsu", "greedy" ]
2,300
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> #include <queue> #include <vector> #include <string> #include <cmath> #define Mod (1000000007LL) #define eps (1e-8) #define Pi (acos(-1.0)) using namespace std; int n,m; int f1[100100],f2[100100]; int f[200200],tot; int ans[100100],x,y; int main() { while(~scanf("%d%d",&n,&m)) { memset(f1,0,sizeof(f1)); memset(f2,0,sizeof(f2)); memset(ans,0,sizeof(ans)); tot=0; for(int i=0;i<n;i++) { scanf("%d",&x); x%=m; f1[x]++; } for(int i=0;i<n;i++) { scanf("%d",&x); f2[x]++; } for(int i=0;i<m;i++) { for(int j=0;j<f1[i];j++) f[++tot]=i+1; for(int j=0;j<f2[m-1-i];j++) { if(tot&&f[tot]>0) { x=f[tot]-1; y=m-1-i; tot--; ans[(x+y)%m]++; // printf("%d\n",x+y); } else f[++tot]=-(m-1-i+1); } } for(int i=1;i<=tot/2;i++) { x=-f[i]-1; y=f[1+tot-i]-1; ans[(x+y)%m]++; //printf("%d\n",x+y); } // printf("%d\n",tot); for(int i=m-1;i>=0;i--) { //printf("%d %d\n",i,ans[i]); for(int j=0;j<ans[i];j++) printf("%d ",i); } printf("\n"); } return 0; }
314
A
Sereja and Contest
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that $n$ people took part in the contest. Let's assume that the participant who got the first place has rating $a_{1}$, the second place participant has rating $a_{2}$, $...$, the $n$-th place participant has rating $a_{n}$. Then changing the rating on the Codesecrof site is calculated by the formula $d_{i}=\sum_{i=1}^{i-1}(a_{j}\cdot(j-1)-(n-i)\cdot a_{i})$. After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant $d_{i} < k$, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table. We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who $d_{i} < k$. We also know that the applications for exclusion from rating were submitted by all participants. Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Note that if we remove some of the participants, we never remove the participants with lower numbers as theirs amount will only increase. So just consider the sequence of all the participants, and if the participant does not fit we delete him.
[ "implementation" ]
1,600
null
314
B
Sereja and Periods
Let's introduce the designation $[x,n]=x+x+\cdot\cdot\cdot+x=\sum_{i=1}^{n}x$, where $x$ is a string, $n$ is a positive integer and operation "$ + $" is the string concatenation operation. For example, $[abc, 2] = abcabc$. We'll say that string $s$ can be obtained from string $t$, if we can remove some characters from string $t$ and obtain string $s$. For example, strings $ab$ and $aсba$ can be obtained from string $xacbac$, and strings $bx$ and $aaa$ cannot be obtained from it. Sereja has two strings, $w = [a, b]$ and $q = [c, d]$. He wants to find such maximum integer $p$ $(p > 0)$, that $[q, p]$ can be obtained from string $w$.
It is clear that we can use greedy algorithm to look for the number of occurrences of the 2nd string in the first string, but it works too slow. To speed up the process, you can look at the first line of the string that specifies the second period. And the answer is divided into how many string you need to set the second string. Next, we consider our greedy algorithm. We are going by the first string, till we find the first character of the second string, then the second, third and so on until the last, then again find the first, second, and so the cycle. It is clear that if we stand in the same twice in a state in which the positions in the first string corresponds to one character string that determines the period and the position of the second string are the same, then we obtain the period. When we find this period, we can just repeat it as many times as possible. To better understand, I advise you to read any accepted solution.
[ "binary search", "dfs and similar", "strings" ]
2,000
null
314
C
Sereja and Subsequences
Sereja has a sequence that consists of $n$ positive integers, $a_{1}, a_{2}, ..., a_{n}$. First Sereja took a piece of squared paper and wrote all \textbf{distinct} non-empty non-decreasing subsequences of sequence $a$. Then for each sequence written on the squared paper, Sereja wrote on a piece of lines paper all sequences that do not exceed it. A sequence of positive integers $x = x_{1}, x_{2}, ..., x_{r}$ doesn't exceed a sequence of positive integers $y = y_{1}, y_{2}, ..., y_{r}$, if the following inequation holds: $x_{1} ≤ y_{1}, x_{2} ≤ y_{2}, ..., x_{r} ≤ y_{r}$. Now Sereja wonders, how many sequences are written on the lines piece of paper. Help Sereja, find the required quantity modulo $1000000007$ $(10^{9} + 7)$.
It is clear that we need to calculate the sum of the products of elements of all the different non-decreasing subsequences of given sequence. Let's go through the sequence from left to right and maintain the array q[i]: what means the sum of all relevant sub-sequences, such that their last element is equal to i. Clearly, if the next number is x, then you need to put q[x] = sum (q[1] + q[2] + ... + q[x]) * x + x. The answer to the problem is the sum of q[i]. To find all the amounts you can use Fenwick tree.
[ "data structures", "dp" ]
2,000
null
314
D
Sereja and Straight Lines
Sereja placed $n$ points on a plane. Now Sereja wants to place on the plane two straight lines, intersecting at a right angle, so that one of the straight lines intersect the $Ox$ axis at an angle of $45$ degrees and the maximum distance from the points to the straight lines were minimum. In this problem we consider the distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equal $|x_{1} - x_{2}| + |y_{1} - y_{2}|$. The distance between the point and the straight lines is the minimum distance from the point to some point belonging to one of the lines. Help Sereja, find the maximum distance from the points to the optimally located straight lines.
Roll all at 45 degrees using the transformation: (x, y) -> (x ', y'): x '= x + y, y' = x-y. Next you need to place two lines parallel to the coordinate axes. Sort the points by the first coordinate. Next, we use a binary search for the answer. May we have fixed a number, you now need to check whether it is enough or not. Note that now we need to put two strips of width 2 * fixed amount that they would have to cover all the points. Suppose that some point should be close to the left side of the vertical strip, then for all points that do not belong to the strip we find the minimum and maximum second coordinate. If the difference between the found coordinates no more then 2 * fixed quantity, the strip can be placed, otherwise - no.
[ "binary search", "data structures", "geometry", "sortings", "two pointers" ]
2,500
null
315
A
Sereja and Bottles
Sereja and his friends went to a picnic. The guys had $n$ soda bottles just for it. Sereja forgot the bottle opener as usual, so the guys had to come up with another way to open bottles. Sereja knows that the $i$-th bottle is from brand $a_{i}$, besides, you can use it to open \textbf{other} bottles of brand $b_{i}$. You can use one bottle to open multiple other bottles. Sereja can open bottle with opened bottle or closed bottle. Knowing this, Sereja wants to find out the number of bottles they've got that they won't be able to open in any way. Help him and find this number.
Just check for each bottle, can I open it with another. In this task can pass absolutely any solutions.
[ "brute force" ]
1,400
null
315
B
Sereja and Array
Sereja has got an array, consisting of $n$ integers, $a_{1}, a_{2}, ..., a_{n}$. Sereja is an active boy, so he is now going to complete $m$ operations. Each operation will have one of the three forms: - Make $v_{i}$-th array element equal to $x_{i}$. In other words, perform the assignment $a_{vi} = x_{i}$. - Increase each array element by $y_{i}$. In other words, perform $n$ assignments $a_{i} = a_{i} + y_{i}$ $(1 ≤ i ≤ n)$. - Take a piece of paper and write out the $q_{i}$-th array element. That is, the element $a_{qi}$. Help Sereja, complete all his operations.
We will support all of the elements in the array, but also we will supprt additionally variable add: how much to add to all the elements. Then to add some value to every element we simply increase the add. In the derivation we deduce the value of the array element + add. When you update the item we put to a value, value that you need to put minus the current value of add.
[ "implementation" ]
1,200
null
317
A
Perfect Pair
Let us call a pair of integer numbers $m$-perfect, if at least one number in the pair is greater than or equal to $m$. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers $x$, $y$ are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the numbers, $(x + y)$. What is the minimum number of such operations one has to perform in order to make the given pair of integers $m$-perfect?
This problem were more about accuracy then about ideas or coding. It is important to not forget any cases here. On each step we replace one of the numbers $x$, $y$ by their sum $x + y$ until the pair becomes $m$-perfect (id est one of them becomes not lesser than $m$). It is clear that one sould replace lesser number from the pair $x$, $y$. Indeed lets say the pair $x_{1} \le y_{1}$ dominates the pair $x_{2} \le y_{2}$, if $y_{1} \ge y_{2}$ and $x_{1} \ge y_{2}$. In this case if one can get $m$-perfect pair from $x_{2}$, $y_{2}$ by certain sequence of actions, then one can get $m$-perfect pair from $x_{1}$, $y_{1}$ by the same or shorter sequence of actions. If $x \le y$, then the pair $x + y$, $y$ dominates the pair $x + y$, $x$. Hence path from $x + y$, $y$ to $m$-perfect is not longer than from $x + y$, $x$, and we may assume that we choose exactly this pair. Consider following cases: $x \le 0$, $y \le 0$ In this case our numbers do not increase in the process. Hence either the pair is alredy $m$-perfect or it will never be. $x > 0$ and $y > 0$ In this case for each $m$ pair will after several steps become $m$-perfect. To count precise number of those steps one needs to launch emulation. If $x > 0$ and $y > 0$, then pair "grows exponentionaly>> (more formally: easy to show that starting from secnd step sum $x + y$ grows in at least $3 / 2$ times each step) and emulation works pretty fast. However in the case $x < 0$ and $y > 0$ (or vice versa) pair might change very slowly. Most bright example is $x = - 10^{18}$, $y = 1$. Thus one needs to count number of steps until both numbers becomes positive before launching emulationt. For $x < 0$ and $y > 0$ number of those steps is exactly $\left\lceil{\frac{\lfloor x\rfloor+y-1}{y}}\right\rceil$.
[ "brute force" ]
1,600
null
317
B
Ants
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction ($x$, $y$) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions ($x + 1$, $y$), ($x - 1$, $y$), ($x$, $y + 1$), ($x$, $y - 1$) — one ant in each direction. No other ant movements will happen. Ants never interfere with each other. Scientists have put a colony of $n$ ants into the junction (0, 0) and now they wish to know how many ants will there be at some given junctions, when the movement of the ants stops.
One may reformulate the problem ass follows. Non-negative integers $A(x, y)$ are placed in the vertices of two-dimensional lattice $\mathbb{Z}^{2}$ We may imagine this construction as a function $A\colon\mathbb{Z}^{2}\to\mathbb{N}_{0}$. On each step for each vertex $P = (x, y)$ with $A(x, y) \ge 4$ we perform operation $ \phi _{P}$, which substracts 4 from $A(x, y)$ and adds 1 to $A(x, y - 1)$, $A(x, y + 1)$, $A(x - 1, y)$, $A(x + 1, y)$. We may think that operation $ \phi _{P}$ applies to the whole function $A$. We need to find values of $A$ after the iterations stops. Key idea is that operactions $ \phi _{P}$ and $ \phi _{Q}$ for all points $P$ and $Q$ commutes, that is $ \phi _{P}( \phi _{Q}(A)) = \phi _{Q}( \phi _{P}(A))$. This means that the order of operations is unimportant. In particular, we may assume that from each given vertex run all possible four-groups of ants and not only one. After this observation one may run full emulation of the process. As an exercise contestants may check that ants will never leave square $200 \times 200$ with center in the origin $0$ with given constraints.
[ "brute force", "implementation" ]
2,000
null
317
C
Balance
A system of $n$ vessels with water is given. Several pairs of vessels are connected by tubes with transfusion mechanisms. One may transfer an integer amount of liters of water between two vessels connected by such tube (tube works in both directions). There might be multiple tubes between two vessels. Total number of tubes equals $e$. Volume of each vessel equals $v$ liters. Of course, the amount of the water in any vessel cannot exceed $v$ liters in the process of transfusions. Given the initial amounts $a_{i}$ of water in the vessels and the desired amounts $b_{i}$ find a sequence of transfusions that deals with the task. Total number of transfusions must not exceed $2·n^{2}$.
In this problem we need to find $2n^{2}$ transfusions from initial configuration to the desired one. First of all we propose the following: if in each connected component overall volume of the water in initial configuration is the same as in desired one, then answer exist. We call the vessel ready, if current volume of its water equals desired one. Let us describe solution which is probably easier to code. We will make vessels ready one by one. Consider the pair of non-ready vessels s and t (there is more water in s than desired, and less water in t than desired), such that they are connected by the path P, and if one transfuses d litres from s to t then one of the vessels becomes ready. Now we need to find a way to transfuse d litres by path P from s to t. One may write recursive function pour(s, t, d) for this aim. Let t' stand before t in this path, then function works as follows: transfuses from t' to t as many water as possible (not more than d of course), then calls pour(s, t', d) and on the final step transfuses from t' to t all that left. It is easy to check that all such transfusions are correct. This algorithm makes $2len$ transfusions on the path of length $len$, so total number of transfusions is not greater than $2n^{2}$.
[ "constructive algorithms", "dfs and similar", "graphs", "trees" ]
2,500
null
317
D
Game with Powers
Vasya and Petya wrote down all integers from $1$ to $n$ to play the "powers" game ($n$ can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number $x$ is chosen at the current turn, it is forbidden to choose $x$ or all of its other positive integer powers (that is, $x^{2}$, $x^{3}$, $...$) at the next turns. For instance, if the number $9$ is chosen at the first turn, one cannot choose $9$ or $81$ later, while it is still allowed to choose $3$ or $27$. The one who cannot make a move loses. Who wins if both Vasya and Petya play optimally?
For each numner $x$ denote sequence of its powers within $[1..n]$ as $Pow(x)$: $P o w(x)=\{x,x^{2},x^{3},x^{4},\cdot\cdot\cdot\}\cap[1..n].$ Game proceeds as follows: on each step one player takes still available number $x$ from $1$ to $n$ and prohibits whole set $Pow(x)$. Who can't make his turn loses. This game may be decomposed in the sum of lesser games. Indeed, lets call number $x$ simple (and corresponding sequence $Pow(x)$ simple), if it is not a power of any number $y < x$. Then: 1. for each $k\in[1..n]$ there is simple $x$, such that $k\in P o w(x)$; 2. for each simple distinct $x$ and $y$ sets $Pow(x)$ and $P(y)$ do not intersect. Indeed, for a given $k$ there is exactly one simple $x$ such that $k$ is power of $x$. This may be showed from fundamental theorem of arithmetic: if $k=p_{1}^{\alpha_{1}}p_{2}^{\alpha_{2}}\cdot\cdot\cdot p_{\ell}^{\alpha_{\ell}}$ and $d = gcd( \alpha _{1}, \alpha _{2}, ..., \alpha _{n})$, then $x=p_{1}^{\alpha_{1}/d}p_{2}^{\alpha_{2}/d}\dots p_{\ell}^{\alpha_{\ell}/d}$. Hence set $[1..n]$ decomposes into primitive sets $Pow(x)$, on each of those $Pow(x)$ game proceeds independetly. Now one may use Sprague-Grundy theory to see that mexx of our game is just xor of all mexx of games on simple $Pow(x)$. For fixed $x$, if $Pow(x) = {x, x^{2}, ..., x^{s}}$, then mexx of the game on $Pow(x)$ depends only on $s$, but not on $x$. In our case $s$ runs from $1$ to $29$, mexx for all such $s$ may be directly precalculated. Now it is enough to find numbers $q(s)$ of simple $x$ with a given size of $Pow(x)$ equal to $s$ (actually we are interested in parity of $q(s)$ not in $q(s)$ itself). Our constraints allows to do it directly: run $x$ from $2$ to $\sqrt{n}$, if it is not crossed out, determine the size $Pow(x)$ [increment corresponding $q(s)$], and cross out all numbers from $Pow(x)$. This cycle finds all simple sequences of length at least $2$. Quantity of non-crossed numbers is the number of all simple sequences of length $1$. Now it is enough to look at parities of $q(s)$ and xor coressponding mexx. However one may find all $q(s)$ for $O(\log^{2}n)$. Indeed lets look at the number $1<x\leqslant{\sqrt{n}}$ and sequence ${x, x^{2}, x^{3}, x^{4}, ..., x^{s}}$. This sequence is not simple iff it is containd in some larger simple sequence. But number of subsequenes of size $s$ in a given sequence of size $t > s$ is easy to find: it is just $[t / s]$. Recalling that simple sequences do not intersect one gets the reccurent formula: $q(s)=[\hat{\nabla}\overline{{{n}}}]-1-\sum_{t=s+1}q(t)\cdot\left[\frac{t}{s}\right]$. Now it is easy to find all $q(s)$ from $q(29)$ to $q(1)$. Remark: while coding it is important to remeber simple number $x = 1$.
[ "dp", "games" ]
2,300
null
317
E
Princess and Her Shadow
Princess Vlada enjoys springing in the meadows and walking in the forest. One day — wonderful, sunny day — during her walk Princess found out with astonishment that her shadow was missing! "Blimey!", — she thought and started her search of the shadow in the forest. Normally the Shadow is too lazy and simply sleeps under the Princess. But at this terrifically hot summer day she got bored of such a dull life, so she decided to play with Vlada. The forest, where our characters entertain themselves, may be represented as a set of integer cells in the plane, where the Shadow and the Princess can move only up, down, left and right by $1$. Some cells (as it happens in decent forests) are occupied by trees. The Shadow and the Princess are not allowed to enter a cell occupied by a tree. Unfortunately, these are the hard times for the forest, so there are very few trees growing here... At first the Princess was walking within the cell ($v_{x}$, $v_{y}$), while the Shadow hid from the Princess in the cell ($s_{x}$, $s_{y}$). The Princess, The Shadow and the trees are located in the different cells. The Shadow is playing with the Princess. As soon as the Princess moves by $1$ in some direction, the Shadow simultaneously flies by $1$ in the same direction, if it is possible (if the cell to fly to is not occupied by some tree); otherwise, the Shadow doesn't move. The Shadow is very shadowy, so our characters do not interfere with each other. We say that the Shadow is caught by the Princess if after some move both of them are located in the same cell. Vlada managed to catch her Shadow! Can you?
In this problem princess Vlada should simply catch the Shadow. Here is the idea of a solution. If there is only one tree, then using it as a barrier to the shadow it is not hard to catch the shadow. Similar technique works if Vlada and Shadow are far from the square where all the trees grow. But what can she do in the dark depths of the forest? If there is no path at all between Vlada and Shadow, then there is no way to catch it. Otherwise consider a shortest path from Vlada to the Shadow and make Vlada follow it. This path gives Vlada a queue of the steps that she should perform. Additionaly if shadow moves, then we add her move to the queue (simply speaking Vlada follows the shadow). This is where the algorithmic part ends. Now we state that either Vlada catches the shadow in the desired number of steps, or steps out of the "forest square". To proof this we note that the length of the path between Vlada and Shadow may only decrease. And if it does not decrease long enough, then once in $k$ steps ($k$ is the length of the path) Vlada and Shadow shifts at the same vector over and over, and at some moment leaves the "forest square". Note that if the trees allow our heroes to step out of the "forest square" at the beginning, then we may just get them out from the start. But taking this approach we still need to catch the Shadow in a "labyrinth forest".
[ "constructive algorithms", "shortest paths" ]
3,100
null
318
A
Even Odds
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first $n$. He writes down the following sequence of numbers: firstly all odd integers from $1$ to $n$ (in ascending order), then all even integers from $1$ to $n$ (also in ascending order). Help our hero to find out which number will stand at the position number $k$.
In this problem we need to understand how exactly numbers from $1$ to $n$ rearrange when we write firstly all odd numbers and after them all even numbers. To find out which number stands at position $k$ one needs to find the position where even numbers start and output either the position of the odd number from the first half of the sequence or for the even number from the second half of the sequence.
[ "math" ]
900
null
318
B
Strings of Power
Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style. Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text. For simplicity, let us assume that Volodya's text can be represented as a single string.
In the heavy metal problem one needs to find the number of the substrings in the string S with a given prefix A and given suffix B. If we mark black all the starting positions of the entries of the string A in S, and white all the starting positions of the entries of the string B, then we come to the following problem: count the number of pairs <black position, white position> (in this order). To solve this it is enough to iterate from left to right counting the number of the passed black positions. Meeting black position we increment this number by one, meeting white position we add to the answer the number of pairs with this white position, which is exactly our memorized number of the already passed black positions.
[ "implementation", "strings", "two pointers" ]
1,300
null
319
A
Malek Dance Club
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has $2^{n}$ members and coincidentally Natalia Fan Club also has $2^{n}$ members. Each member of MDC is assigned a unique id $i$ from $0$ to $2^{n} - 1$. The same holds for each member of NFC. One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers $(a, b)$ such that member $a$ from MDC dances with member $b$ from NFC. The complexity of a pairs' assignment is the number of pairs of dancing pairs $(a, b)$ and $(c, d)$ such that $a < c$ and $b > d$. You are given a binary number of length $n$ named $x$. We know that member $i$ from MDC dances with member $i\oplus x$ from NFC. Your task is to calculate the complexity of this assignment modulo $1000000007$ $(10^{9} + 7)$. Expression $x\oplus y$ denotes applying «XOR» to numbers $x$ and $y$. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».
Solving this problem was easy when you modeled the assignment with two sets of points numbered from $0$ to $2^{n} - 1$ (inclusive) paired with $2^{n}$ line segments. Each line segment corresponds to a dance pair. And each pair of intersecting lines increase the complexity by one. Imagine you now the solution for binary string $x$. Now we want to calculate the answer for $1x$ and $0x$ easily. Look at the figure below: The figure shows what happens in a simple case. Whenever you append $0$ before $x$ the same structure appears twice in the result. But whenever you append $1$ before $x$ the same structure appears twice but the first half of points in right column are swapped with the second half. This increases the number of intersections by size of first half times size of the second half. So if $x$ has length $n$ and $f(x)$ is the complexity of the assignment then we have: $f(0x) = 2f(x)$ $f(1x) = 2f(x) + 2^{2n}$ An interesting fact is that $f(x)$ is equal to $x2^{n - 1}$.
[ "combinatorics", "math" ]
1,600
null
319
C
Kalila and Dimna in the Logging Industry
Kalila and Dimna are two jackals living in a huge jungle. One day they decided to join a logging factory in order to make money. The manager of logging factory wants them to go to the jungle and cut $n$ trees with heights $a_{1}, a_{2}, ..., a_{n}$. They bought a chain saw from a shop. Each time they use the chain saw on the tree number $i$, they can decrease the height of this tree by one unit. Each time that Kalila and Dimna use the chain saw, they need to recharge it. Cost of charging depends on the id of the trees which have been cut completely (a tree is cut completely if its height equal to 0). If the maximum id of a tree which has been cut completely is $i$ (the tree that have height $a_{i}$ in the beginning), then the cost of charging the chain saw would be $b_{i}$. If no tree is cut completely, Kalila and Dimna cannot charge the chain saw. The chainsaw is charged in the beginning. We know that for each $i$ < $j$, $a_{i} < a_{j}$ and $b_{i} > b_{j}$ and also $b_{n} = 0$ and $a_{1} = 1$. Kalila and Dimna want to cut all the trees completely, with minimum cost. They want you to help them! Will you?
This problem is equal to finding the minimum cost to cut the last tree completely. Because any cutting operation can be done with no cost afterward. Let $dp_{i}$ be the minimum cost to cut the $i$-th tree completely. It's easy to figure out that we can calculate $dp_{i}$ if we know the index of the last tree which has been cut completely ($j$-th tree). Knowing this $dp_{i}$ would be equal to $dp_{j} + b_{j}a_{i}$. So $dp_{i} = min_{j = 1..i - 1}(dp_{j} + b_{j}a_{i})$. Using the above information the problem has an easy dynamic programming solution in $O(n^{2})$. There's a known method which can be used to improve recursive relations with similar form. It's called Convex Hull Trick. You can read about it here.
[ "dp", "geometry" ]
2,100
null
320
A
Magic Numbers
A magic number is a number formed by concatenation of numbers $1$, $14$ and $144$. We can use each of these numbers any number of times. Therefore $14144$, $141414$ and $1411$ are magic numbers but $1444$, $514$ and $414$ are not. You're given a number. Determine if it is a magic number or not.
Although the input number is very small, solving the problem for arbitrary length numbers using strings is easier. It's easy to prove that a number meeting the following conditions is magical: The number should only consist of digits $1$ and $4$. The number should begin with digit $1$. The number should not contain three consecutive fours (i.e. $444$).
[ "brute force", "greedy" ]
900
#include <iostream> #include <string> using namespace std; bool is_magical(string number) { for (int i = 0; i < (int)number.size(); i++) if (number[i] != '1' && number[i] != '4') return false; if (number[0] == '4') return false; if (number.find("444") != number.npos) return false; return true; } int main() { string number; cin >> number; if (is_magical(number)) cout << "YES" << endl; else cout << "NO" << endl; return 0; }
320
B
Ping-Pong (Easy Version)
In this problem at each moment you have a set of intervals. You can move from interval $(a, b)$ from our set to interval $(c, d)$ from our set if and only if $c < a < d$ \textbf{or} $c < b < d$. Also there is a path from interval $I_{1}$ from our set to interval $I_{2}$ from our set if there is a sequence of successive moves starting from $I_{1}$ so that we can reach $I_{2}$. Your program should handle the queries of the following two types: - "1 x y" $(x < y)$ — add the new interval $(x, y)$ to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. - "2 a b" $(a ≠ b)$ — answer the question: is there a path from $a$-th (one-based) added interval to $b$-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals.
Imagine the intervals as nodes of a graph and draw directed edges between them as defined in the statement. Now answering the second query would be trivial if you are familiar with graph traversal algorithms like DFS or BFS or even Floyd-Warshall!
[ "dfs and similar", "graphs" ]
1,500
#include<iostream> #include<string.h> using namespace std; int a[111],b[111]; bool f[111]; int n = 0; void dfs(int i) { f[i] = true; for(int k = 1; k <= n;k++) { if(f[k]) continue; if(a[i]>a[k] && a[i] < b[k]) dfs(k); else if(b[i] > a[k] && b[i] < b[k]) dfs(k); } } int k; int main() { cin >> k; memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(f,0,sizeof(f)); for(int i = 1; i <= k; i++) { int x,y,m; cin >> m; if(m == 1) { n++; cin >> a[n]; cin >> b[n]; } if(m == 2) { cin >> x; cin >> y; memset(f,0,sizeof(f)); dfs(x); if(f[y]) cout << "YES" << endl; else cout << "NO" << endl; } } return 0; }
321
A
Ciel and Robot
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string $s$. Each character of $s$ is one move operation. There are four move operations at all: - 'U': go up, (x, y) $ → $ (x, y+1); - 'D': go down, (x, y) $ → $ (x, y-1); - 'L': go left, (x, y) $ → $ (x-1, y); - 'R': go right, (x, y) $ → $ (x+1, y). The robot will do the operations in $s$ from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in $(a, b)$.
Note that after Ciel execute string s, it will moves (dx, dy). And for each repeat, it will alway moves (dx, dy). So the total movement will be k * (dx, dy) + (dx[p], dy[p]) which (dx[p], dy[p]) denotes the movement after execute first p characters. We can enumerate p since (0 <= p < |s| <= 100), and check if there are such k exists. Note that there are some tricks: We can divide dx or dy directly because they both can become zero. Another trick is that k must be non-negative. Many people failed on this test case (which no included in the pretest): -1 -1 UR
[ "binary search", "implementation", "math" ]
1,700
null
321
B
Ciel and Duel
Fox Ciel is playing a card game with her friend Jiro. Jiro has $n$ cards, each one has two attributes: $position$ (Attack or Defense) and $strength$. Fox Ciel has $m$ cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack. Now is Ciel's battle phase, Ciel can do the following operation many times: - Choose one of her cards $X$. This card mustn't be chosen before. - If Jiro has no alive cards at that moment, he gets the damage equal to ($X$'s strength). Otherwise, Ciel needs to choose one Jiro's alive card $Y$, then: - If $Y$'s position is Attack, then ($X$'s strength) $ ≥ $ ($Y$'s strength) must hold. After this attack, card $Y$ dies, and Jiro gets the damage equal to ($X$'s strength) - ($Y$'s strength). - If $Y$'s position is Defense, then ($X$'s strength) $ > $ ($Y$'s strength) must hold. After this attack, card $Y$ dies, but Jiro gets no damage. Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.
We have 3 solutions to this problem: = 1. greedy = There are 2 cases: we killed all Jiro's cards, or not. If we are not killed all of Jiro's cards, then: We never attack his DEF cards, it's meaningless. Suppose we make k attacks, then it must be: use Ciel's k cards with highest strength to attack Jiro's k cards with lowest strength, and we can sort the both k cards by strength to make attack one by one. (If there are an invalid attack, then we can't have k attack) If we kill all Jiro's card: Then for all DEF cards, we consider it from lower strength to higher: if its strength is L, then we find a card of Ciel with strength more than L (If there are many, we choose one with lowest strength). Then we can know if we can kill all DEF cards. And then we choose |x| cards with highest strength of Ciel, try to kill Jiro's remain card. Note that if we could kill all ATK cards, the order doesn't matter: the total damage will be (sum of strength of Ciel's remain card) - (sum of strength of Jiro's remain card). = 2. DP = Above solution looks complicated, can we solve it with few observation? Yes we can. The only observation is that: There always exist an optimal solution that: If Ciel's two card X's strength > Y's strength, and X, Y attacks on A and B with the same position, then A's strength > B's strength. We already use this observation in above solution. Then what can we do? Yes, we can sort all Ciel's card, all ATK card of Jiro, all DEF card of Jiro. Let's DP[pCiel][pATK][pJiro][killAll] be the state that next unconsidered card of Ciel, Jiro's ATk, Jiro's DEF are pCiel, pATK, pJiro, and killAll=1 if and only if we assume at the end we can kill all Jiro's card. Then we have 4 choice: Skip, this card don't attack. Attack on the next ATK card. Attack on the next DEF card. Assume Jiro has no cards and make a direct attack. = 3. MinCostMaxFlow = Well, what if we want to solve this problem with no observation? Ok, if you are good at construct flow algorithm, it's an easy thing to solve this by flow. Please see my solution for details. It just considered the matching relationship.
[ "dp", "flows", "greedy" ]
1,900
null
321
C
Ciel the Commander
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has $n$ cities connected by $n - 1$ undirected roads, and for any two cities there always exists a path between them. Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost. There are enough officers of each rank. But there is a special rule must obey: if $x$ and $y$ are two distinct cities and their officers have the same rank, then on the simple path between $x$ and $y$ there must be a city $z$ that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer. Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
This is a problem with construction on trees. And for these kind of problems, we usually use two method: up-down or down-up. So we have 1 solution for each method: = 1. up-down construction = Suppose we assign an officer with rank A at node x. Then for two distinct subtree rooted by x, says T1 and T2: There can't be any invalid path cross T1 and T2, because it is blocked by node x. (It's clear that we can't make 2 rank A officer.) So we can solve these subtree independently: the only different is that we can't use rank A anymore. Then the question is: which node should x be? It could be good if any subtree will has a small size. And if you have the knowledge of "centroid of tree", then you can quickly find that if x be the centroid of this tree, the subtree's size will be no more than half of the original tree. So we only needs about log2(n) nodes and 26 is enough. = 2. down-up construction = The above solution involves the concept of "centroid of tree" but you might not heard about that, don't worry, we have another solution can solve this problem without knowing that, and it's easier to implement. Suppose we choose 1 as the root and consider it as a directed tree, and on some day we have the following problem: We have some subtree rooted at T1, T2, ..., Tk, and they are already assigned an officer, we need to assign an officer to node x and link them to this node. Well, a normal idea is: we choose one with lowest possible rank. The rank of x should satisfy: If there are a node with rank t exposes at Ti and a node with t exposes at Tj (i!=j), then rank of x must be higher than t. (Otherwise the path between them will be invalid.) If there are a node with rank t exposes at Ti, then the rank of x can't be t. So we can use this rule to choose the lowest possible rank. But can it passes? Yes, it can, but the proof is not such easy, I'll introduce the main idea here: We assign each node a potential: p(x) = {2^('Z' - w) | w is exposed}. For example, if 'Y' and 'Z' are exposed, then p(x) = 1 + 2 = 3. We can proof p(x) <= |# of nodes of the subtree rooted by x| by proof this lemma: When we synthesis x with T1, T2, ..., Tk, p(x) <= 1 + p(T1) + ... + p(Tk). It's not hard to proof, but might have some cases to deal with.
[ "constructive algorithms", "dfs and similar", "divide and conquer", "greedy", "trees" ]
2,100
null
321
D
Ciel and Flipboard
Fox Ciel has a board with $n$ rows and $n$ columns, there is one integer in each cell. It's known that $n$ is an odd number, so let's introduce $x={\frac{n+1}{2}}$. Fox Ciel can do the following operation many times: she choose a sub-board with size $x$ rows and $x$ columns, then all numbers in it will be multiplied by -1. Return the maximal sum of numbers in the board that she can get by these operations.
For this problem we need a big "observation": what setup of "flips" are valid? What means set up of "flips", well, for example, after the 1st step operation of example 1, we get: 1 1 0 1 1 0 0 0 0It means the left top 2x2 cells are negatived. Given a 0-1 matrix of a set up of "flips", how can you determine if we can get it by some N x N (I use N instead of x here, it don't make sense to write something like x x x.) flips. To solve this problem, we need the following observation: For any i, any j<=x: setUp[i][j]^setUp[i][x]^setUp[i][j+x] will be 0. For any i, any j<=x: setUp[j][i]^setUp[x][i]^setUp[j+x][i] will be 0. It's quite easy to proof than find that: after each operation, there always be 0 or 2 cells lay in {setUp[i][j], setUp[i][x], setUp[i][j+x]} or {setUp[j][i], setUp[x][i], setUp[j+x][i]}. So what? Well, then there must be no more than 2^(N*N) solutions, since if we determine the left top N x N cells, we can determine others by above equations. And then? Magically we can proof if one set up meets all above equations, we can get it. And the proof only needs one line: think the operation as addition of vectors in GF2, then we have N*N independent vector, so there must be 2^(N*N) different setups we can get. (Yes, I admit it need some knowledge, or feeling in linear algebra) Then the things are easy: we enumerate {setUp[1][N], setUp[2][N], ..., setUp[N][N]}, and determine others by greedy. (More detailed, by columns.)
[ "dp", "greedy", "math" ]
2,900
null
321
E
Ciel and Gondolas
Fox Ciel is in the Amusement Park. And now she is in a queue in front of the Ferris wheel. There are $n$ people (or foxes more precisely) in the queue: we use first people to refer one at the head of the queue, and $n$-th people to refer the last one in the queue. There will be $k$ gondolas, and the way we allocate gondolas looks like this: - When the first gondolas come, the $q_{1}$ people in head of the queue go into the gondolas. - Then when the second gondolas come, the $q_{2}$ people in head of the remain queue go into the gondolas.... - The remain $q_{k}$ people go into the last ($k$-th) gondolas. Note that $q_{1}$, $q_{2}$, ..., $q_{k}$ must be positive. You can get from the statement that $\sum_{i=1}^{k}q_{i}=n$ and $q_{i} > 0$. You know, people don't want to stay with strangers in the gondolas, so your task is to find an optimal allocation way (that is find an optimal sequence $q$) to make people happy. For every pair of people $i$ and $j$, there exists a value $u_{ij}$ denotes a level of unfamiliar. You can assume $u_{ij} = u_{ji}$ for all $i, j$ $(1 ≤ i, j ≤ n)$ and $u_{ii} = 0$ for all $i$ $(1 ≤ i ≤ n)$. Then an unfamiliar value of a gondolas is the sum of the levels of unfamiliar between any pair of people that is into the gondolas. A total unfamiliar value is the sum of unfamiliar values for all gondolas. Help Fox Ciel to find the minimal possible total unfamiliar value for some optimal allocation.
This problem may jog your memory of OI times (if you have been an OIer and now grows up, like me). Maybe some Chinese contestants might think this problem doesn't worth 2500, but DP optimization is an advanced topic in programming contest for many regions. It's quite easy to find an O(N^2 K) DP: dp[i][j] = max{ k | dp[i-1][k] + cost(k+1...j)} (dp[i][j] means the minimal cost if we divide 1...j foxes into i groups) There are many ways to optimize this kind of dp equation, but a large part of them based one the property of cost function. So we need to find some property independent of cost function. Let opt[i][j] = the smallest k such that dp[i][j] = dp[i][k] + cost(k+1...j) Then intuitively we have opt[i][1] <= opt[i][2] <= ... <= opt[i][n]. (I admit some people don't think it's intuitively correct, but it can proof by some high school algebra) Then how to use this stuff? Let n = 200 and suppose we already get dp[i][j] for i<=3 and now we have to compute dp[4][j]: If we first compute dp[4][100], then we can have opt[4][100] at the same time. And when we compute dp[4][1] ... dp[4][99], we know that the k must lay in 1...opt[4][100]. When we compute dp[4][101] ... dp[4][200], we know that k must lay in opt[4][100]...n. Let's formalize this thing: We use compute(d, L, R, optL, optR) to denote we are computing dp[d][L...R], and we know the k must be in range optL...optR. Then we have: compute(d, L, R, optL, optR) = 1. special case: L==R. 2. let M = (L+R) / 2, we solve dp[d][M] as well as opt[d][M]. Uses about (optR-optL+1) operations. 3. compute(d, L, M-1, optL, opt[d][M]) 4. compute(d, M+1, R, opt[d][M], optR)One can show that this solution will run in O(NlogN * K). Note that we don't need opt[d][M] at the center of interval optL...optR. We can proof at each recursive depth, the total cost by line 2 will be no more than 2n. And there are at most O(log(n)) depths.
[ "data structures", "divide and conquer", "dp" ]
2,600
null
322
A
Ciel and Dancing
Fox Ciel and her friends are in a dancing room. There are $n$ boys and $m$ girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule: - either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before); - or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.
Let's define remainNew = # of people haven't danced before. So at beginning remainNew = n+m, and we have: During the 1st song, remainNew must decreased by at least 2. (Because the boy and girl must haven't danced before.) During the k-th (k>1) song, remainNew must decreased by at least 1. (Because one of the boy or girl must haven't danced before.) So the answer must be no more than n+m-1. And it's not hard to construct one schedule get this maximal possible answer: 1 1 1 2 ... 1 m 2 1 3 1 ... n 1
[ "greedy" ]
1,000
null
322
B
Ciel and Flowers
Fox Ciel has some flowers: $r$ red flowers, $g$ green flowers and $b$ blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets: - To make a "red bouquet", it needs 3 red flowers. - To make a "green bouquet", it needs 3 green flowers. - To make a "blue bouquet", it needs 3 blue flowers. - To make a "mixing bouquet", it needs 1 red, 1 green and 1 blue flower. Help Fox Ciel to find the maximal number of bouquets she can make.
If there are no "mixing bouquet" then the answer will be r/3 + g/3 + b/3. One important observation is that: There always exist an optimal solution with less than 3 mixing bouquet. The proof is here: Once we get 3 mixing bouquet, we can change it to (1 red bouquet + 1 green bouquet + 1 blue bouquet) So we can try 0, 1, 2 mixing bouquet and make the remain 3 kind of bouquets use above greedy method. Output one with largest outcome.
[ "combinatorics", "math" ]
1,600
null
325
A
Square and Rectangles
You are given $n$ rectangles. 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 the rectangles form a square. In other words, determine if the set of points inside or on the border of at least one rectangle is precisely equal to the set of points inside or on the border of some square.
What happens if the rectangles form an $N \times N$ square? Then these two conditions are necessary. 1) The area must be exactly $N \times N$. 2) The length of its sides must be $N$. That means, the difference between the right side of the rightmost rectangle - the left side of the leftmost rectangle is $N$. Same for topmost and bottommost rectangles. We claim that, since the rectangles do not intersect, those two conditions are also sufficient. This is since if there are only $N \times N$ space inside the box bounded by the leftmost, rightmost, topmost, and bottommost rectangles. Thus if the sum of the area is exactly $N \times N$, all space must be filled -- which forms a square.
[ "implementation" ]
1,500
null
325
B
Stadium and Games
Daniel is organizing a football tournament. He has come up with the following tournament format: - In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. - Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are $x$ teams, there will be $\textstyle{\frac{x(x-1)}{2}}$ games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for $n$ games. Help him to determine how many teams he should invite so that the tournament needs \textbf{exactly} $n$ games. You should print all possible numbers of teams that will yield exactly $n$ games in ascending order, or -1 if there are no such numbers.
Suppose the "divide-by-two" stage happens exactly $D$ times, and the round robin happens with $M$ people. Then, the number of games held is: ${\frac{M(M-1)}{2}}+M\times(2^{D}-1)$ We would like that ${\frac{M(M-1)}{2}}+M\times(2^{D}-1)=N$ This is an equation with two variables -- to solve it, we can enumerate the value of one of the variables and calculate the value of the other one. We cannot enumerate the possible values of $M$, since $M$ can vary from 1 to 10^9. However, we can enumerate D, since the number scales exponentially with $D$ -- that is, we should only enumerate $0 \le D \le 62$. Thus, the equation is reduced to ${\frac{M(M-1)}{2}}+M\times C=N$ Since this function is increasing, this can be solved via binary search on M.
[ "binary search", "math" ]
1,800
null