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
120
C
Winnie-the-Pooh and honey
As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are $n$ jars of honey lined up in front of Winnie-the-Pooh, jar number $i$ contains $a_{i}$ kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that $k$ kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly $k$ kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.
One of the possible solutions is direct emulation. Winnie won't do more than $3n$ iterations (because he can use each jar more than three times). You can emulate each iteration in $O(n)$ (just find maximum in array). Summary time - $O(n^{2}) \approx 10^{4}$ operations, memory consumption - $O(n)$ There is another shorter solution: let's notice that order of jars doesn't matter. Let's see how much honey from each jar will be eaten by Winnie and how much will be left to Piglet. If $a_{i} \ge 3k$ then Winnie will leave $a_{i} - 3k$ kg of honey to Piglet. If $a_{i} < 3k$ then he'll leave only $a_{i}{\mathrm{~mod~}}k$ kg. Now solution is one loop. Time and memory consumption is $O(n)$.
[ "implementation", "math" ]
1,100
null
120
E
Put Knight!
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard $n × n$ in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square $(r, c)$ can threat squares $(r - 1, c + 2)$, $(r - 1, c - 2)$, $(r + 1, c + 2)$, $(r + 1, c - 2)$, $(r - 2, c + 1)$, $(r - 2, c - 1)$, $(r + 2, c + 1)$ and $(r + 2, c - 1)$ (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Petya wins if $n$ is odd, Gena wins if $n$ is even. It's quite easy to prove - just do symmetrical turns.
[ "games", "math" ]
1,400
null
120
F
Spiders
One day mum asked Petya to sort his toys and get rid of some of them. Petya found a whole box of toy spiders. They were quite dear to him and the boy didn't want to throw them away. Petya conjured a cunning plan: he will glue all the spiders together and attach them to the ceiling. Besides, Petya knows that the lower the spiders will hang, the more mum is going to like it and then she won't throw his favourite toys away. Help Petya carry out the plan. A spider consists of $k$ beads tied together by $k - 1$ threads. Each thread connects two different beads, at that any pair of beads that make up a spider is either directly connected by a thread, or is connected via some chain of threads and beads. Petya may glue spiders together directly gluing their beads. The length of each thread equals 1. The sizes of the beads can be neglected. That's why we can consider that gluing spiders happens by identifying some of the beads (see the picture). Besides, the construction resulting from the gluing process should also represent a spider, that is, it should have the given features. After Petya glues all spiders together, he measures the length of the resulting toy. The distance between a pair of beads is identified as the total length of the threads that connect these two beads. The length of the resulting construction is the largest distance between all pairs of beads. Petya wants to make the spider whose length is as much as possible. The picture two shows two spiders from the second sample. We can glue to the bead number 2 of the first spider the bead number 1 of the second spider. The threads in the spiders that form the sequence of threads of maximum lengths are highlighted on the picture.
Answer is sum of all spiders' lengths. Use depth-first-search (started at all vertexes) to calculate length of each spider.
[ "dp", "greedy", "trees" ]
1,400
null
120
G
Boom
Let's consider the famous game called Boom (aka Hat) with simplified rules. There are $n$ teams playing the game. Each team has two players. The purpose of the game is to explain the words to the teammate without using any words that contain the same root or that sound similarly. Player $j$ from team $i$ $(1 ≤ i ≤ n, 1 ≤ j ≤ 2)$ is characterized by two numbers: $a_{ij}$ and $b_{ij}$. The numbers correspondingly represent the skill of explaining and the skill of understanding this particular player has. Besides, $m$ cards are used for the game. Each card has a word written on it. The card number $k$ $(1 ≤ k ≤ m)$ is characterized by number $c_{k}$ — the complexity of the word it contains. Before the game starts the cards are put in a deck and shuffled. Then the teams play in turns like that: the 1-st player of the 1-st team, the 1-st player of the 2-nd team, ... , the 1-st player of the $n$-th team, the 2-nd player of the 1-st team, ... , the 2-nd player of the $n$-th team, the 1-st player of the 1-st team and so on. Each turn continues for $t$ seconds. It goes like that: Initially the time for each turn is $t$. While the time left to a player is more than 0, a player takes a card from the top of the deck and starts explaining the word it has to his teammate. The time needed for the $j$-th player of the $i$-th team to explain the word from the card $k$ to his teammate (the $q$-th player of the $i$-th team) equals $max(1, c_{k} - (a_{ij} + b_{iq}) - d_{ik})$ (if $j = 1, $ then $q = 2, $ else $q = 1$). The value $d_{ik}$ is the number of seconds the $i$-th team has already spent explaining the word $k$ during the previous turns. Initially, all $d_{ik}$ equal 0. If a team manages to guess the word before the end of the turn, then the time given above is substracted from the duration of the turn, the card containing the guessed word leaves the game, the team wins one point and the game continues. If the team doesn't manage to guess the word, then the card is put at the bottom of the deck, $d_{ik}$ increases on the amount of time of the turn, spent on explaining the word. Thus, when this team gets the very same word, they start explaining it not from the beginning, but from the point where they stopped. The game ends when words from all $m$ cards are guessed correctly. You are given $n$ teams and a deck of $m$ cards. You should determine for each team, how many points it will have by the end of the game and which words the team will have guessed.
It's simple realization problem. All you need is two-dimensional arrays and one queue.
[ "implementation" ]
1,800
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cassert> #include <algorithm> #include <string> #include <vector> #include <deque> using namespace std; #define eprintf(...) fprintf(stderr, __VA_ARGS__) #define pb push_back #define mp make_pair #define sz(x) ((int)(x).size()) typedef long long ll; typedef vector<ll> vll; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<bool> vb; typedef vector<vb> vvb; typedef pair<int, int> pii; int main() { #ifdef DEBUG freopen("std.in", "r", stdin); freopen("std.out", "w", stdout); #else freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n, t; while (scanf("%d%d", &n, &t) >= 2) { vvi as(n, vi(2)), bs(n, vi(2)); for (int i = 0; i < n; i++) for (int i2 = 0; i2 < 2; i2++) scanf("%d%d", &as[i][i2], &bs[i][i2]); int m; scanf("%d", &m); vector<string> ns(m); vi cs(m); for (int i = 0; i < m; i++) { char buf[30]; scanf("%s%d", buf, &cs[i]); ns[i] = buf; } vector<vector<string> > res(n); vvi d(n, vi(m, 0)); deque<int> dq; for (int i = 0; i < m; i++) dq.pb(i); int cur = 0, cpl = 0; while (!dq.empty()) { int curt = t; while (curt > 0 && !dq.empty()) { int card = dq.front(); dq.pop_front(); int need = max(1, cs[card] - (as[cur][cpl] + bs[cur][!cpl]) - d[cur][card]); if (curt >= need) { curt -= need; res[cur].pb(ns[card]); } else { dq.pb(card); d[cur][card] += curt; curt = 0; } } if (++cur >= n) { cur = 0; cpl = !cpl; } } for (int i = 0; i < n; i++) { printf("%d", sz(res[i])); for (int i2 = 0; i2 < sz(res[i]); i2++) printf(" %s", res[i][i2].c_str()); printf(" "); } } return 0; }
120
H
Brevity is Soul of Wit
As we communicate, we learn much new information. However, the process of communication takes too much time. It becomes clear if we look at the words we use in our everyday speech. We can list many simple words consisting of many letters: "information", "technologies", "university", "construction", "conservatoire", "refrigerator", "stopwatch", "windowsill", "electricity", "government" and so on. Of course, we can continue listing those words ad infinitum. Fortunately, the solution for that problem has been found. To make our speech clear and brief, we should replace the initial words with those that resemble them but are much shorter. This idea hasn't been brought into life yet, that's why you are chosen to improve the situation. Let's consider the following formal model of transforming words: we shall assume that one can use $n$ words in a chat. For each words we shall introduce a notion of its shorter variant. We shall define \textbf{shorter variant} of an arbitrary word $s$ as such word $t$, that meets the following conditions: - it occurs in $s$ as a \textbf{subsequence}, - its length ranges from one to four characters. In other words, the word $t$ consists at least of one and at most of four characters that occur in the same order in the word $s$. Note that those characters do not necessarily follow in $s$ immediately one after another. You are allowed not to shorten the initial word if its length does not exceed four characters. You are given a list of $n$ different words. Your task is to find a set of their shortened variants. The shortened variants of all words from the list should be different.
Notice that there are only $\sum_{k=1}^{4}26^{k}=475254$ different strings that have length 4 or less. Then notice that each of input strings you can change to $\sum_{k=1}^{4}C_{|w_{i}|}^{k}=385$ different short words at most ($|w_{i}|$ is length of the $i$th word). Now let's make bipartite graph. One part is all source words, the second part is all short words and there is edge if and only if we can change word from the first part to the short word from the second part. Now our task is just find perfect matching in this graph. It can be done in $O(n_{1} \cdot m) \approx 200 \cdot 200 \cdot 385 = 15.4 \cdot 10^{6}$ operations which is enough.
[ "graph matchings" ]
1,800
null
120
I
Luck is in Numbers
Vasya has been collecting transport tickets for quite a while now. His collection contains several thousands of tram, trolleybus and bus tickets. Vasya is already fed up with the traditional definition of what a lucky ticket is. Thus, he's looking for new perspectives on that. Besides, Vasya cannot understand why all tickets are only divided into lucky and unlucky ones. He thinks that all tickets are lucky but in different degrees. Having given the matter some thought, Vasya worked out the definition of a ticket's degree of luckiness. Let a ticket consist of $2n$ digits. Let's regard each digit as written as is shown on the picture: You have seen such digits on electronic clocks: seven segments are used to show digits. Each segment can either be colored or not. The colored segments form a digit. Vasya regards the digits as written in this very way and takes the right half of the ticket and puts it one the left one, so that the first digit coincides with the $n + 1$-th one, the second digit coincides with the $n + 2$-th one, ..., the $n$-th digit coincides with the $2n$-th one. For each pair of digits, put one on another, he counts the number of segments colored in both digits and summarizes the resulting numbers. The resulting value is called the degree of luckiness of a ticket. For example, the degree of luckiness of ticket 03 equals four and the degree of luckiness of ticket 2345 equals six. You are given the number of a ticket containing $2n$ digits. Your task is to find among the tickets whose number exceeds the number of this ticket but also consists of $2n$ digits such ticket, whose degree of luckiness exceeds the degrees of luckiness of the given ticket. Moreover, if there are several such tickets, you should only choose the one with the smallest number.
Unfortunately, my solution for this problem is rather big. If someone know beautiful one share it please. The main idea is very standard: let's fix some prefix of number, which is strictly greater than such prefix of source number. If we can get known what is maximal happiness for suffix of our number then we can solve the problem by just running down values for each number in suffix and checking that we still can reach necessary value of happiness. Now solution for this subproblem is just to fill suffix with eights and calculate the answer. It's good but takes a lot of time. We need to store old values and recalculate its in $O(1)$. There are very simple formulas to do it.
[ "greedy" ]
2,200
null
120
J
Minimum Sum
You are given a set of $n$ vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector $v_{i} = (x_{i}, y_{i})$ can be transformed into one of the following four vectors: - $v_{i}^{1} = (x_{i}, y_{i})$, - $v_{i}^{2} = ( - x_{i}, y_{i})$, - $v_{i}^{3} = (x_{i}, - y_{i})$, - $v_{i}^{4} = ( - x_{i}, - y_{i})$. You should find two vectors from the set and determine which of their coordinates should be multiplied by -1 so that the absolute value of the sum of the resulting vectors was minimally possible. More formally, you should choose two vectors $v_{i}$, $v_{j}$ ($1 ≤ i, j ≤ n, i ≠ j$) and two numbers $k_{1}$, $k_{2}$ ($1 ≤ k_{1}, k_{2} ≤ 4$), so that the value of the expression $|v_{i}^{k1} + v_{j}^{k2}|$ were minimum.
Firstly you need to notice that you can turn all vectors in such way that all of them have non-negative coordinates and the answer will remain the same. And now we have the following problem: find two nearest points from the given set. It's standard divide-and-conquer problem, it's described in Wikipedia. Also there is simpler solution (added by diogen): let's sort all our points by distance from a random point far-far away. It's oblivious that if some points lie near each other, distance to this far point doesn't vary a lot. And now solution is run down for each point $C$ points near it in the sorted array. $C$ about 200 is enough to got Accepted.
[ "divide and conquer", "geometry", "sortings" ]
1,900
null
121
A
Lucky Sum
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Let $next(x)$ be the minimum lucky number which is larger than or equals $x$. Petya is interested what is the value of the expression $next(l) + next(l + 1) + ... + next(r - 1) + next(r)$. Help him solve this problem.
Let generate all lucky number between $1$ and $10^{10}$. Consider all segment $[1;L0]$, $[L0 + 1;L1]$, $[L1 + 1;L2]$ ... Then the result equals to product of intersection of segments $[1;L0]$ and $[1;n]$ by $L0$ plus size of intersection of $[L0 + 1;L1]$ and $[1;n]$ multiplied by $L1$ and so on.
[ "implementation" ]
1,100
null
121
B
Lucky Transformation
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has a number consisting of $n$ digits without leading zeroes. He represented it as an array of digits without leading zeroes. Let's call it $d$. The numeration starts with $1$, starting from the most significant digit. Petya wants to perform the following \underline{operation} $k$ times: find the minimum $x$ $(1 ≤ x < n)$ such that $d_{x} = 4$ and $d_{x + 1} = 7$, if $x$ is odd, then to assign $d_{x} = d_{x + 1} = 4$, otherwise to assign $d_{x} = d_{x + 1} = 7$. Note that if no $x$ was found, then the operation counts as completed and the array doesn't change at all. You are given the initial number as an array of digits and the number $k$. Help Petya find the result of completing $k$ operations.
Notice, that if there exits such $i$ that $i$ mod $2$ = $0$ and $d_{i} = 4$ and $d_{i + 1} = 7$ and $d_{i - 1} = 4$ then after that operation there will be a loop. So, let we simple do all operation from left ro right, and, when we will win our loop, just return a rusult (which variates by $k$ mod $2$ ($k$ is one that leaves after operation from left side).
[ "strings" ]
1,500
null
121
C
Lucky Permutation
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} One day Petya dreamt of a lexicographically $k$-th permutation of integers from $1$ to $n$. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
If $n \le 14$ let find out, is $k$ more than $n!$ or not? If yes, then return -1. Then, notice, that since $k \le 10^{9}$, then at most $13$ elements from right (suffix) will change. So, element from left of this part (prefix) will not change (then we can just find a number of lucky numbers on than range). To find result for the rest of the permutation (suffix) we need to find $k$-th permutation of number from $1$ to $t$ ($t$ is maximun integer, such that $t! \le k$). After we find that permutation, we can just loop through that permutation and count result.
[ "brute force", "combinatorics", "number theory" ]
1,900
null
121
D
Lucky Segments
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has $n$ number segments $[l_{1}; r_{1}]$, $[l_{2}; r_{2}]$, ..., $[l_{n}; r_{n}]$. During one move Petya can take any segment (let it be segment number $i$) and replace it with segment $[l_{i} + 1; r_{i} + 1]$ or $[l_{i} - 1; r_{i} - 1]$. In other words, during one move Petya can shift any segment to the left or to the right by a unit distance. Petya calls a number \underline{full} if it belongs to each segment. That is, number $x$ is full if for any $i$ $(1 ≤ i ≤ n)$ the condition $l_{i} ≤ x ≤ r_{i}$ is fulfilled. Petya makes no more than $k$ moves. After that he counts the quantity of full lucky numbers. Find the maximal quantity that he can get.
Lei calculate arrays $L$ and $R$. Let for all lucky $i$, $L[i]$ = number of operation needed to move every segment, which's right end is to left from $i$ to $i$. $R[i]$ = number of operation needed to move every segment which left end is to right to $i$. How to calculate such array? Just use a sorting. Let arrange array $A$ of pairs of integers, first - number, second equals to $0$, if that number end of some segment, $1$ if that number is lucky. Then, iterate from left to right, counting number of segment end we counted and $s_{i}$, $s_{i} = s_{i - 1} + (A_{i} - A_{i - 1}) * c_{i}$. The same way you can use to $R$. Now, to find the answer we must find (using method of two pointers of binary search) pair of indexes $x$ and $y$, such that $i \le j$, $L_{j} + R_{i} \le k$, $Lucky_{j} - Lucky_{i} + 1 \le $ min_size_of_input_segment. Also, is this problem you should arrange function $Mul(a, b)$, which return $min(a * b, INF)$. Since simple multiplication overflows, then you can use multipling modulo $2^{64}$ or double or min-long-arithmetic.
[ "binary search", "implementation", "two pointers" ]
2,500
null
121
E
Lucky Array
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has an array consisting of $n$ numbers. He wants to perform $m$ operations of two types: - \underline{add $l$ $r$ $d$} — add an integer $d$ to all elements whose indexes belong to the interval from $l$ to $r$, inclusive $(1 ≤ l ≤ r ≤ n, 1 ≤ d ≤ 10^{4})$; - \underline{count $l$ $r$} — find and print on the screen how many lucky numbers there are among elements with indexes that belong to the interval from $l$ to $r$ inclusive $(1 ≤ l ≤ r ≤ n)$. Each lucky number should be counted as many times as it appears in the interval. Petya has a list of all operations. The operations are such that after all additions the array won't have numbers that would exceed $10^{4}$. Help Petya write a program that would perform these operations.
In this problem you can use many different algorithms, here is one of them. Obviously, number of different lucky number is $30$, because $A_{i}$ always is $ \le 10000$. Let $D_{i}$ - difference between minimum lucky number which is greater than or equal to $A_{i}$ and $A_{i}$. Now, we need to have 5 (but you can use less number) of operation on $D$: Subtract(l, r, d) - subtract number $d$ from all $A_{i}$ $(l \le i \le r)$, Minimum(l, r) - minumum number of all $D_{i}$ $(l \le i \le r)$, Count(l, r) - how many times that minimum occared in that interval, Left(l, r) = leftmost occarence of that minimum, Set(i, d) - assign $d$ to $D_{i}$ ($D_{i} = d$). Now, we can do our operations. If our operation is "count", then we need to find minimum number $d$ ($d =$ Minimum(l, r)), if it is equal to $0$, then answer is Count(l, r, 0), otherwise, answer is $0$. If out operation is "add", then we need to Subtract(l, r, d), but now some $D_{i}$ might be less than $0$. So, while, Minimum(l, r) $ \le 0$, let j = Left(l, r), assign $D_{j}$ new value (use Set(j, $D_{j}$')), which can be calculated with complaxity $O(1)$. Complexity of this algorithm is $O(m * log(n) + n * log(n) * C)$, where $C$ is equal to $30$.
[ "data structures" ]
2,400
null
122
A
Lucky Division
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya calls a number \underline{almost lucky} if it could be evenly divided by some lucky number. Help him find out if the given number $n$ is almost lucky.
In this problem you just need to loop through the integers $i$ from $1$ to $n$ determine, is $i$ lucky, if yes, then try, if $n$ mod $i$ = $0$, then answer is "YES". If there are no such $i$, answer is "NO".
[ "brute force", "number theory" ]
1,000
null
122
B
Lucky Substring
\underline{Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} One day Petya was delivered a string $s$, containing only digits. He needs to find a string that - represents a lucky number without leading zeroes, - is not empty, - is contained in $s$ as a substring the maximum number of times. Among all the strings for which the three conditions given above are fulfilled, Petya only needs the lexicographically minimum one. Find this string for Petya.
Notice, that answer is either one digit or -1. So, if there are no $4$ and $7$ digits, then answer is -1. Else, if there is more or equel number of digits $4$, then answer is $4$, else answer is $7$.
[ "brute force", "implementation" ]
1,000
null
123
A
Prime Permutation
You are given a string $s$, consisting of small Latin letters. Let's denote the length of the string as $|s|$. The characters in the string are numbered starting from $1$. Your task is to find out if it is possible to rearrange characters in string $s$ so that for any prime number $p ≤ |s|$ and for any integer $i$ ranging from $1$ to $|s| / p$ (inclusive) the following condition was fulfilled $s_{p} = s_{p × i}$. If the answer is positive, find one way to rearrange the characters.
All positions except the first and those whose number is a prime greater $|s| / 2$ have to have the same symbol. Remaining positions can have any symbol. Consider positions that should be the same for $p = 2$ is 2,4,6,8 ... Now let's take a position with the number $x \le |s| / 2$, this position should have the same character as the position of $2$ as the symbol $x$ must be equal to the character at position $2 * x$, which is equal to the character at position $2$. Now consider the position whose number is more than $|s| / 2$. If this position is not a prime then there is a prime number $p$ to divide the number at our positions and $p \le |s| / 2$. So character at position $p$ is equal the character at position $2$ and so a symbol at our position is also consistent to the character at position $2$. The remaining positions are not combined with any other positions so it does not matter which symbol is situated here. Let's find the symbol which occurs the most and try to place the symbol on the position in which the characters have to be equal. If this symbol for all positions is not enough then the answer will be "NO", otherwise arrange the remaining characters by any way at other positions.
[ "implementation", "number theory", "strings" ]
1,300
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const int MAXN = 1001; int n; char s[MAXN]; int c[256]; bool f[MAXN]; int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif gets(s); n = strlen(s); for (int i = 0; i < n; i++) c[s[i]]++; int k = 0; for (int i = 0; i < 256; i++) if (c[i] > c[k]) k = i; memset(f, true, sizeof(f)); for (int i = 2; i * i <= n; i++) if (f[i]) for (int j = i * i; j <= n; j += i) f[j] = false; f[1] = true; for (int i = 2; i + i <= n; i++) f[i] = false; for (int i = 1; i <= n; i++) if (!f[i]) { if (c[k] == 0) { puts("NO"); return 0; } c[s[i - 1] = k]--; } k = 0; for (int i = 1; i <= n; i++) if (f[i]) { while (c[k] == 0) k++; c[s[i - 1] = k]--; } puts("YES"); puts(s); return 0; }
123
B
Squares
You are given an infinite checkered field. You should get from a square ($x_{1}$; $y_{1}$) to a square ($x_{2}$; $y_{2}$). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square ($x$; $y$) is considered bad, if at least one of the two conditions is fulfilled: - $|x + y| ≡ 0$ $(mod 2a)$, - $|x - y| ≡ 0$ $(mod 2b)$. Your task is to find the minimum number of bad cells one will have to visit on the way from ($x_{1}$; $y_{1}$) to ($x_{2}$; $y_{2}$).
Let's turn the field on $45^{o}$ transforming cells coordinates $(x, y)$ in $(x + y, x - y)$. Then the cell $(x, y)$ will be bad if one of the conditions occurs $x \equiv 0$ $(mod$ $2a)$ or $y \equiv 0$ $(mod$ $2b)$. So good cells will be divided into sectors by vertical and horizontal lines. For each sector, it is possible to determine the coordinates of a pair of numbers, the first number that will rise during the transition to the next right sector, and the second pair number will increase during the transition to the next upper sector. From the sector with coordinates $(x, y)$ can go to any nearby on the side of the sector, visiting at least one bad cell, ie in $(x - 1, y)$, $(x + 1, y)$, $(x, y - 1)$ and $(x, y + 1)$. Since the numbers $2a$ and $2b$ have the same parity, then from the sector $(x, y)$ can also go to the sector on the diagonal, and visiting a bad cell, ie in $(x - 1, y + 1)$, $(x + 1, y - 1)$, $(x - 1, y - 1)$ and $(x + 1, y + 1)$. Then it turns out that the minimum number of bad cells, which should be visited on the way out of from the sector $(x1, y1)$ to sector of $(x2, y2)$ equals $max(|x1 - x2|, |y1 - y2|)$. Let's transform the coordinates of the initial and final cells as described rule above. Then find sectors which contain our cells and calculate answer with formula above.
[ "math" ]
1,800
#include <cstdio> #include <algorithm> #include <iostream> using namespace std; int a, b, x1, y1, x2, y2; int x, y; int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif cin >> a >> b >> x1 >> y1 >> x2 >> y2; x = x1; y = y1; x1 = x + y; y1 = y - x; x = x2; y = y2; x2 = x + y; y2 = y - x; a *= 2; b *= 2; x1 = x1 / a + (x1 > 0); x2 = x2 / a + (x2 > 0); y1 = y1 / b + (y1 > 0); y2 = y2 / b + (y2 > 0); cout << max(abs(y2 - y1), abs(x2 - x1)) << endl; return 0; }
123
C
Brackets
A two dimensional array is called a \underline{bracket} array if each grid contains one of the two possible brackets — "(" or ")". A path through the two dimensional array cells is called \underline{monotonous} if any two consecutive cells in the path are side-adjacent and each cell of the path is located below or to the right from the previous one. A two dimensional array whose size equals $n × m$ is called a \underline{correct bracket} array, if any string formed by writing out the brackets on some monotonous way from cell $(1, 1)$ to cell $(n, m)$ forms a correct bracket sequence. Let's define the operation of comparing two correct bracket arrays of equal size ($a$ and $b$) like that. Let's consider a given two dimensional array of priorities ($c$) — a two dimensional array of same size, containing different integers from $1$ to $nm$. Let's find such position $(i, j)$ in the two dimensional array, that $a_{i, j} ≠ b_{i, j}$. If there are several such positions, let's choose the one where number $c_{i, j}$ is minimum. If $a_{i, j} = $"(", then $a < b$, otherwise $a > b$. If the position $(i, j)$ is not found, then the arrays are considered equal. Your task is to find a $k$-th two dimensional correct bracket array. It is guaranteed that for the given sizes of $n$ and $m$ there will be no less than $k$ two dimensional correct bracket arrays.
Let's reduce the problem to a one-dimensional matrix. Consider a monotonous path $(1, 1), (1, 2), ..., (1, m - 1), (1, m), (2, m), ..., (n - 1, m), (n, m)$ which has correct bracket sequence. Now, in this way a cell $(1, m)$ can be replaced on $(2, m - 1)$ and still be a monotonous way and will form the correct sequence of the bracket. So in the cells of $(1, m)$ and $(2, m - 1)$ is one type of bracket. Proceeding further (eg to replace $(1, m - 1)$ on $(2, m - 2)$ or $(2, m)$ on $(3, m - 1)$) can be seen that in cells $(i, j)$ and $(i - 1, j + 1)$ is one type of bracket. Then we get not two-dimensional array $n \times m$, a one-dimensional size $n + m - 1$. For each position can be determined what her highest priority, ie for cell $i$ ($1 \le i \le n + m - 1$), the priority will be equal to the minimum value of $p_{x, y}$ where $1 \le x \le n$, $1 \le y \le m$ and $x + y - 1 = i$. Let's iterate through the positions, starting with the highest priority. Let's put in this position the bracket "(" and consider how many ways can complete the remaining brackets to get the correct bracket sequence. If the number of ways of not less than $k$, then leave in this position "(", or reduce the $k$ on the number of ways and put in this positions bracket ")". And so let's iterate through all items. In order to calculate the number of ways each time dynamics is calculated on two parameters $f_{i, j}$, where $i$ is the number of processed positions, and $j$ is the number of opened brackets. If the position of $i + 1$ bracket is not defined yet then you can go to $f_{i + 1, j + 1}$ or $f_{i + 1, j - 1}$, if defined then only $f_{i + 1, j + 1}$ or only $f_{i + 1, j - 1}$, depending on opening or closing bracket respectively.
[ "combinatorics", "dp", "greedy" ]
2,300
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> using namespace std; const int MAXN = 202; int n, m, l; long long k; int a[MAXN]; int d[MAXN]; char s[MAXN]; long long f[MAXN][MAXN]; bool opr_sort(const int &i, const int &j) { return a[i] < a[j]; } int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif cin >> n >> m >> k; l = n + m - 1; for (int i = 0; i < l; i++) { a[i] = n * m; d[i] = i; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int x; scanf("%d", &x); if (x < a[i + j]) a[i + j] = x; } } sort(d, d + l, opr_sort); for (int I = 0; I < l; I++) { s[d[I]] = '('; f[0][0] = 1; for (int i = 0; i < l; i++) for (int j = i & 1; j <= i && j <= l - i; j += 2) if (f[i][j]) { if (f[i][j] > k) f[i][j] = k; if (s[i] != ')') f[i + 1][j + 1] += f[i][j]; if (s[i] != '(' && j) f[i + 1][j - 1] += f[i][j]; f[i][j] = 0; } // printf("%d %lld ", d[I], f[l][0]); if (k > f[l][0]) { k -= f[l][0]; s[d[I]] = ')'; } f[l][0] = 0; } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) printf("%c", s[i + j]); printf(" "); } return 0; }
123
D
String
You are given a string $s$. Each pair of numbers $l$ and $r$ that fulfill the condition $1 ≤ l ≤ r ≤ |s|$, correspond to a substring of the string $s$, starting in the position $l$ and ending in the position $r$ (inclusive). Let's define the function of two strings $F(x, y)$ like this. We'll find a list of such pairs of numbers for which the corresponding substrings of string $x$ are equal to string $y$. Let's sort this list of pairs according to the pair's first number's increasing. The value of function $F(x, y)$ equals the number of non-empty continuous sequences in the list. For example: $F(babbabbababbab, babb) = 6$. The list of pairs is as follows: $(1, 4), (4, 7), (9, 12)$ Its continuous sequences are: - $(1, 4)$ - $(4, 7)$ - $(9, 12)$ - $(1, 4), (4, 7)$ - $(4, 7), (9, 12)$ - $(1, 4), (4, 7), (9, 12)$ Your task is to calculate for the given string $s$ the sum $F(s, x)$ for all $x$, that $x$ belongs to the set of all substrings of a string $s$.
Sort all suffixes of the string (denoted by an array of strings $c_{i}$). Then the answer to the problem is the amount of $1 \le i \le j \le |s|$ and $1 \le k$, that the prefixes of length $k$ in all $c_{i..j}$ are equal. Options when $i = j$, and $1 \le k \le |c_{i}|$ can calculate at once, it is the number of substrings in the string, ie $|s| * (|s| + 1) / 2$. Now let's count the LCP (longest common prefix) for adjacent suffixes, ie $a_{i} = LCP(c_{i}, c_{i + 1})$ for $1 \le i < |s|$. Then let's count the number of $1 \le i \le j < |s|$ and $1 \le k$, that $k \le min(a_{i..j})$. This task is to count the number of rectangles if there is a limit to the height of each column, ie $a_{i}$ the maximum height of the rectangle in the column $i$. Solve by a stack or list.
[ "string suffix structures" ]
2,300
#include <cstdio> #include <cstring> using namespace std; const int MAXN = 100002; const int MAXM = 20; int n, m, k; char s[MAXN]; int cnt[MAXN]; int A[MAXM][MAXN]; int p[MAXN], _p[MAXN], a[MAXN], _a[MAXN]; int h[MAXN], w[MAXN]; long long f[MAXN]; int sorting(int st, int &k) { for (int i = 0; i < n; i++) _p[i] = p[i] - st < 0? p[i] - st + n : p[i] - st; for (int i = 0; i < k; i++) cnt[i] = 0; for (int i = 0; i < n; i++) cnt[a[_p[i]]]++; for (int i = 1; i < k; i++) cnt[i] += cnt[i - 1]; for (int i = n - 1; i >= 0; i--) p[--cnt[a[_p[i]]]] = _p[i]; for (int i = 0; i < n; i++) _p[i] = p[i] + st < n? p[i] + st : p[i] + st - n; _a[p[0]] = 0; k = 1; for (int i = 1; i < n; i++) { if (a[p[i - 1]] != a[p[i]] || a[_p[i - 1]] != a[_p[i]]) k++; _a[p[i]] = k - 1; } for (int i = 0; i < n; i++) a[i] = _a[i]; return 0; } int lcp(int x, int y) { int res = 0; for (int i = m - 1; i >= 0; i--) if (A[i][x] == A[i][y]) { x += 1 << i; y += 1 << i; res += 1 << i; } return res; } int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif gets(s); n = strlen(s); long long ans = (long long)n * (n + 1) / 2; s[n++] = 0; for (int i = 0; i < n; i++) { p[i] = i; a[i] = s[i]; } k = 256; sorting(0, k); for (m = 0; (1 << m) < n; m++) { int st = 1 << m; for (int i = 0; i < n; i++) A[m][i] = a[i]; sorting(st, k); } for (int i = 0; i < n; i++) A[m][i] = a[i]; m++; k = 0; for (int i = 2; i < n; i++) a[k++] = lcp(p[i - 1], p[i]); n = 0; h[n] = -1; w[n] = 0; f[n] = 0; n++; for (int i = 0; i < k; i++) { int l = 1; while (h[n - 1] >= a[i]) l += w[--n]; w[n] = l; h[n] = a[i]; f[n] = f[n - 1] + (long long)l * a[i]; n++; ans += f[n - 1]; } printf("%I64d ", ans); return 0; }
123
E
Maze
A maze is represented by a tree (an undirected graph, where exactly one way exists between each pair of vertices). In the maze the entrance vertex and the exit vertex are chosen with some probability. The exit from the maze is sought by Deep First Search. If there are several possible ways to move, the move is chosen equiprobably. Consider the following pseudo-code: \begin{verbatim} DFS(x) if x == exit vertex then finish search flag[x] <- TRUE random shuffle the vertices' order in V(x) // here all permutations have equal probability to be chosen for i <- 1 to length[V] do if flag[V[i]] = FALSE then count++; DFS(y); count++; \end{verbatim} $V(x)$ is the list vertices adjacent to $x$. The $flag$ array is initially filled as FALSE. $DFS$ initially starts with a parameter of an entrance vertex. When the \underline{search is finished}, variable $count$ will contain the number of moves. Your task is to count the mathematical expectation of the number of moves one has to do to exit the maze.
Consider what is the expected value for a given entrance and exit vertexes. It is clear that there will be only one path from the entrance to the exit, which in any case will be passed. Also, you can still go in the wrong direction. Consider the case when the chosen vertex from which there is $k$ false paths and one right (it is always). Then before going in the right direction it can be $2^{k}$ equiprobable way around false paths. Every false way occurs the $2^{k - 1}$ ways and to increase the number of moves in $2 \times < amount$ $of$ $vertexes$ $in$ $false$ $subtree >$ ie expectation of a false path to increase by $2 \times < amount$ $of$ $vertexes$ $in$ $false$ $subtree > \times 2^{k - 1} / 2^{k} = < amount$ $of$ $vertexes$ $in$ $false$ $subtree >$. Then expectation in vertex is equal to sum of $< amount$ $of$ $vertexes$ $in$ $false$ $subtrees >$ + 1 (a move in the right direction) + expectation of the vertex if to go the right direction. The result is that the expected value equal to the number of edges reachable from the entrance, without passing through the exit. Let's run dfs and consider of the vertex as exit vertex. Then, if in some subtree defined entrance, the expected value equal to the size of the subtree. Calculate how much of each subtree is the number of entrance and calculate the number of moves, if the exit is in the current vertex. It is necessary not to forget to count cases where the current vertex is an exit and entrance is higher in the tree traversal.
[ "dfs and similar", "dp", "probabilities", "trees" ]
2,500
#include <cstdio> #include <cmath> #include <algorithm> #include <ctime> using namespace std; const int MAXN = 100001; const int MAXM = MAXN + MAXN; int last[MAXN]; int next[MAXM], dest[MAXM]; int f[MAXN], g[MAXN], s[MAXN]; int n; long long ans, F, G; int dfs(int x, int p) { s[x] = 1; for (int i = last[x]; i; i = next[i]) { int y = dest[i]; if (y != p) { dfs(y, x); s[x] += s[y]; f[x] += f[y]; if (g[x]) ans += (long long)g[x] * s[y] * f[y]; } } if (g[x]) ans += (long long)g[x] * (F - f[x]) * (n - s[x]); return 0; } int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif scanf("%d", &n); for (int i = 1; i < n; i++) { int x, y; scanf("%d %d", &x, &y); dest[i] = y; next[i] = last[x]; last[x] = i; dest[i + n] = x; next[i + n] = last[y]; last[y] = i + n; } F = G = 0; for (int i = 1; i <= n; i++) { scanf("%d %d", &f[i], &g[i]); F += f[i]; G += g[i]; } dfs(1, 0); printf("%.20lf ", (double)ans / (F * G)); fprintf(stderr, "Time of execution: %.3lf sec. ", (double)clock()/CLOCKS_PER_SEC); return 0; }
124
A
The number of positions
Petr stands in line of $n$ people, but he doesn't know exactly which position he occupies. He can say that there are no less than $a$ people standing in front of him and no more than $b$ people standing behind him. Find the number of different positions Petr can occupy.
Let's iterate through the each item and check whether it is appropriate to the conditions $a \le i - 1$ and $n - i \le b$ (for $i$ from $1$ to $n$). The first condition can be converted into $a + 1 \le i$, and the condition $n - i \le b$ in $n - b \le i$, then the general condition can be written $max(a + 1, n - b) \le i$ and then our answer can be calculated by the formula $n - max(a + 1, n - b) + 1$.
[ "math" ]
1,000
#include <cstdio> #include <algorithm> using namespace std; int n, a, b; int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif scanf("%d %d %d", &n, &a, &b); printf("%d ", n - max(a + 1, n - b) + 1); return 0; }
124
B
Permutations
You are given $n$ $k$-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers.
Let's try all possible ways to rearrange digits in the numbers and check the difference between maximum and minimum number.
[ "brute force", "combinatorics", "implementation" ]
1,400
#include <cstdio> #include <algorithm> using namespace std; const int MAXN = 8; const int INF = (int)1e+9; int a[MAXN][MAXN]; int n, k; int p[MAXN]; int ans; int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); freopen("out", "w", stdout); #endif scanf("%d %d ", &n, &k); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { char c; scanf("%c", &c); a[i][j] = c - '0'; } scanf(" "); } for (int i = 0; i < k; i++) p[i] = i; ans = INF; do { int mi = INF, ma = -INF; for (int i = 0; i < n; i++) { int x = 0; for (int j = 0; j < k; j++) (x *= 10) += a[i][p[j]]; ma = max(ma, x); mi = min(mi, x); } ans = min(ans, ma - mi); } while (next_permutation(p, p + k)); printf("%d ", ans); return 0; }
126
A
Hot Bath
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is $t_{1}$, and the hot water's temperature is $t_{2}$. The cold water tap can transmit any integer number of water units per second from $0$ to $x_{1}$, inclusive. Similarly, the hot water tap can transmit from $0$ to $x_{2}$ water units per second. If $y_{1}$ water units per second flow through the first tap and $y_{2}$ water units per second flow through the second tap, then the resulting bath water temperature will be: \[ t={\frac{t_{1}y_{1}+t_{2}y_{2}}{y_{1}+y_{2}}} \] Bob wants to open both taps so that the bath water temperature was not less than $t_{0}$. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible. Determine how much each tap should be opened so that Bob was pleased with the result in the end.
At the first you should consider cases when $t_{0} = t_{1}$, $t_{0} = t_{2}$ and $t_{1} = t_{2}$. Answers will be $(x_{1}, 0)$, $(0, x_{2})$ and $(x_{1}, x_{2})$. The last 2 of them didn't present in the pretests. Next, for all $1 \le y_{1} \le x_{1}$ you should find minimal $y_{2}$, for that $t(y_{1}, y_{2}) \ge t_{0}$. You can do it using one of three ways: binary search, two pointers or just calculation by formula $[y_{1}(t_{0} - t_{1}) / (t_{2} - t_{0})]$, where $[x]$ is rounding up of $x$. You should iterate over all cases and choose one optimal of them. The last tricky case consists in the fact that for all $1 \le y_{1} \le x_{1}$ and $1 \le y_{2} \le x_{2}$ $t(y_{1}, y_{2}) < t_{0}$. For example, you can see following test 100 110 2 2 109 (it is the 6th pretest). In this case you should output $(0, x_{2})$. All calculations should be done in 64-bit integers (8th pretest checks overflow of 32-bit integers) or very carefully in the real numbers.
[ "binary search", "brute force", "math" ]
1,900
null
126
B
Password
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them. A little later they found a string $s$, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring $t$ of the string $s$. Prefix supposed that the substring $t$ is the beginning of the string $s$; Suffix supposed that the substring $t$ should be the end of the string $s$; and Obelix supposed that $t$ should be located somewhere inside the string $s$, that is, $t$ is neither its beginning, nor its end. Asterix chose the substring $t$ so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring $t$ aloud, the temple doors opened. You know the string $s$. Find the substring $t$ or determine that such substring does not exist and all that's been written above is just a nice legend.
Let us calculate a prefix-function for all prefices of string. Prefix-function $p[i]$ is maximal length of prefix that also is suffix of substring $[1...i]$. More about prefix function you can see in a description of Knuth-Morris-Pratt algorithm (KMP). The first of possible answers is prefix of length $p[n]$. If $p[n] = 0$, there is no solution. For checking the first possible answer you should iterate over $p[i]$. If at least one of them equal to $p[n]$ (but not $n$-th, of course) - you found the answer. The second possible answer is prefix of length $p[p[n]]$. If $p[p[n]] = 0$, you also have no solution. Otherwise you can be sure that the answer already found. This substring is a prefix and a suffix of our string. Also it is suffix of prefix with length $p[n]$ that places inside of all string. This solution works in $O(n)$. Also this problem can be solved using hashing. You can find hash of every substring in O(1) and compare substrings by comparing thier hashes. Well, let's check for every prefix that it is a suffix of our string and store thier lengths into some array in the increasing order. Then, using binary search over the array, you can find maximal length of prefix that lie inside of string. Check of every prefix you can do in $O(n)$. So, you have some $O(n\log n)$ solution. In point of fact, the array of prefix lengths in the previous solution is list { $p[n]$, $p[p[n]],$ ... }, that written if reversed order. From the first solution you know that the answer is prefix of length either $p[n]$, or $p[p[n]] (if it exists, of course)$. Therefore some naive solution without binary search can fits in the limits if you will stupidly check all prefices in the order of decrease thier lengths:) This solution works in $O(n)$. Also this problem can be solved using $z$-function.
[ "binary search", "dp", "hashing", "string suffix structures", "strings" ]
1,700
null
126
C
E-reader Display
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-readers' software to programmers. The display is represented by $n × n$ square of pixels, each of which can be either black or white. The display rows are numbered with integers from $1$ to $n$ upside down, the columns are numbered with integers from $1$ to $n$ from the left to the right. The display can perform commands like "$x, y$". When a traditional display fulfills such command, it simply inverts a color of $(x, y)$, where $x$ is the row number and $y$ is the column number. But in our new display every pixel that belongs to at least one of the segments $(x, x) - (x, y)$ and $(y, y) - (x, y)$ (both ends of both segments are included) inverts a color. For example, if initially a display $5 × 5$ in size is absolutely white, then the sequence of commands $(1, 4)$, $(3, 5)$, $(5, 1)$, $(3, 3)$ leads to the following changes: You are an e-reader software programmer and you should calculate minimal number of commands needed to display the picture. You can regard all display pixels as initially white.
You can see that every command $i, j$ you should do no more than once. Also order of commands doesn't matter. Actually, sequence of command you can represent as boolean matrix $A$ with size $n \times n$, where $a_{ij} = 1$ mean that you do the command $i, j$, and $a_{ij} = 0$ mean that you don't do it. Let us describe one way to construct the matrix. Let the starting image is boolean matrix $G$. A boolean matrix $B$ of size $n \times n$ stores intermediate image that you will recieve during process of doing commands. For the upper half of matrix $G$ without main diagonal you should move line by line from the up to the down. For every line you should move from the right to the left. You can see that for every positions all nonconsidered positions do not affect the current position. So, if you see that values for position $i, j$ in the matrices $G$ and $B$ are different, you should do command $i, j$: set in the matrix $A$ $a_{ij} = 1$, and change segments $(i, i) - (i, j)$ and $(j, j) - (i, j)$ in the matrix $B$. For the lower half of the matrix $G$ without main diagonal you should do it absolutely symmetric. At the end you should iterate over main diagonal. Here it should be clear. Well, for matrix $G$ you always can build matrix $A$ and do it by exactly one way. It mean that this way requires minimum number of commands. So, you can get answer for problem by following way: you can build the matrix $A$ from the matrix $G$ and output number of ones in the matrix $A$. There is only one problem that you should solve. Algorithm that you can see above works in $O(n^{3})$, that doesn't fit into time limits. Let's speed up it to $O(n^{2})$. Consider in the matrix $B$ the upper half without main diagonal. During doing commands all columns of cells that placed below current position will have same values. Values above current position are not matter for us. Therefore instead of the matrix $B$you can use only one array that stores values of columns. It allows you do every command in $O(1)$ instead of $O(n)$. This optimization gives a solution that works in $O(n^{2})$.
[ "constructive algorithms", "greedy" ]
2,000
null
126
D
Fibonacci Sums
Fibonacci numbers have the following form: \[ F_{1} = 1, \] \[ F_{2} = 2, \] \[ F_{i} = F_{i - 1} + F_{i - 2}, i > 2. \] Let's consider some non-empty set $S = {s_{1}, s_{2}, ..., s_{k}}$, consisting of \textbf{different} Fibonacci numbers. Let's find the sum of values of this set's elements: \[ \textstyle\sum_{i=1}^{k}s_{i}=n \] Let's call the set $S$ a number $n$'s decomposition into Fibonacci sum. It's easy to see that several numbers have several decompositions into Fibonacci sum. For example, for $13$ we have $13, 5 + 8, 2 + 3 + 8$ — three decompositions, and for $16$: $3 + 13, 1 + 2 + 13, 3 + 5 + 8, 1 + 2 + 5 + 8$ — four decompositions. By the given number $n$ determine the number of its possible different decompositions into Fibonacci sum.
Let us represent a number in the Fibonacci code. You can imagine Fibonacci coding by following way: $i$-th bit of number corresponds to the $i$-th Fibonacci number. For example, 16=13+3 will be written as 100100. You can represent into this code any positive integer, for that no two neighbouring 1-bit will be present. It is possible to do it by only one way (let's define this way as canonical). In the problem you should calculate a number of ways to represent some number into Fibonacci code in that two ones can be placed in the neighbour positions. You can easily get the canonical representation if you generate several of Fibonacci numbers (about 90) and after that try to substract all of them in the decreasing order. You should store positions of 1-bits of canonical representation into an array $s$ in the increasing order. You can decompose any of them into two ones. It looks like that: 1000000001 // starting number; 0110000001 // there we decompose 0101100001 // the first "one" 0101011001 // using all 0101010111 // possible ways After some number of such operations you will meet next 1-bit (or the end of number). This 1-bit also can be decomposed, but it can be "shifted" by only one bit. Let us $dp1[i]$ is number of ways to represent a number that consists of $i$ last 1-bits of our number in the case that the first of 1-bits are NOT decomposed. Also let us $dp2[i]$ is number of ways to represent a number that consists of $i$ last 1-bits of our number in the case that the first of 1-bits are decomposed. You can easily recaclulate this dp following way $dp1[0] = 1, dp2[0] = 0$ $dp1[i] = dp1[i - 1] + dp2[i - 1]$ $dp2[i] = dp1[i - 1] * [(s[i] - s[i - 1] - 1) / 2] + dp2[i - 1] * [(s[i] - s[i - 1]) / 2]$ where $[x]$ is rounding down. Answer will be $dp1[k] + dp2[k]$, where $k$ is total number of 1-bits in the canonical representation. So, we have $O(\log n)$ solution for one test.
[ "dp", "math" ]
2,300
null
126
E
Pills
Doctor prescribed medicine to his patient. The medicine is represented by pills. Each pill consists of a shell and healing powder. The shell consists of two halves; each half has one of four colors — blue, red, white or yellow. The doctor wants to put $28$ pills in a rectangular box $7 × 8$ in size. Besides, each pill occupies exactly two neighboring cells and any cell contains exactly one half of a pill. Thus, the result is a four colored picture $7 × 8$ in size. The doctor thinks that a patient will recover sooner if the picture made by the pills will be special. Unfortunately, putting the pills in the box so as to get the required picture is not a very easy task. That's why doctor asks you to help. Doctor has some amount of pills of each of $10$ painting types. They all contain the same medicine, that's why it doesn't matter which $28$ of them will be stored inside the box. Place the pills in the box so that the required picture was formed. If it is impossible to place the pills in the required manner, then place them so that the number of matching colors in all $56$ cells in the final arrangement and the doctor's picture were maximum.
Consider all partitions of $7 \times 8 board$ into dominoes. There is only 12988816 of them (you can get this number using some simple bruteforce algorithm) Also, consider all "paintings" of $7 \times 8 board$ (i.e. number of cells of every color) and find number of patritions into set of pills of 10 types for every of them. In the worst case you will get 43044 partitions (this number you can get using another bruteforce algo). In the first part of solution you should iterate over all partitions of board into dominoes and find all sets of pills that you will get. You will have no more than 43044 of them. In the second part of solution you should try to distribute all available pills for every of sets that you recieved in the first part. You should distribute them in such way that maximal number of colors match. You should build a graph that composed from 4 parts - source, the first part of 10 nodes, the second part of 10 nodes and sink. There are edges between all pairs of nodes from neighbour parts. From source to the first part you should set capacities of edges equal to numbers of available pills of every type. From the second part to sink you should set capacities of edges equal to numbers of pills in the current partition. From the first part to the second part you should use infty capacities and set costs equal to number of MISmatched colors in the types of pills (it is some numbers in range from 0 to 2). At the end, you should find maximal flow of minimal cost (MCMF) if this graph and save a flow that gets minimal cost. In the third part of solution you should restore answer from optimal flow. In the second part of solution you can replace MCMF by usual maxflow. You can see that at the beginning MCMF will fill edges of cost 0. So, you can fill them by hand. After that you can drop all edges of cost 0 and 2 and just find maxflow. Complexity of solution is difficult, but it is clear that this solution fits into limits. The first jury solution in C++ that was written carelessly works in 1 sec. Some more clever solutions works in 0.4 sec, but you can write something more faster.
[ "brute force", "flows" ]
2,900
null
127
A
Wasted Time
Mr. Scrooge, a very busy man, decided to count the time he wastes on all sorts of useless stuff to evaluate the lost profit. He has already counted the time he wastes sleeping and eating. And now Mr. Scrooge wants to count the time he has wasted signing papers. Mr. Scrooge's signature can be represented as a polyline $A_{1}A_{2}... A_{n}$. Scrooge signs like that: first it places a pen at the point $A_{1}$, then draws a segment from point $A_{1}$ to point $A_{2}$, then he draws a segment from point $A_{2}$ to point $A_{3}$ and so on to point $A_{n}$, where he stops signing and takes the pen off the paper. At that the resulting line can intersect with itself and partially repeat itself but Scrooge pays no attention to it and never changes his signing style. As Scrooge makes the signature, he never takes the pen off the paper and his writing speed is constant — $50$ millimeters per second. Scrooge signed exactly $k$ papers throughout his life and all those signatures look the same. Find the total time Scrooge wasted signing the papers.
In this problem you should find length of polyline, multiply it by $k / 50$ and output that you will recieve. Length of polyline is sum of lengths of its segments. You can calculate length of every segment using Pythagorean theorem: $d(A,B)={\sqrt{(x_{A}-x_{B})^{2}+(y_{A}-y_{B})^{2}}}$.
[ "geometry" ]
900
null
127
B
Canvas Frames
Nicholas, a painter is going to paint several new canvases. Nicholas is sure that the canvases will turn out so great that each one will need framing and being hung on the wall. Frames are what Nicholas decided to begin with. Nicholas has $n$ sticks whose lengths equal $a_{1}, a_{2}, ... a_{n}$. Nicholas does not want to break the sticks or glue them together. To make a $h × w$-sized frame, he needs two sticks whose lengths equal $h$ and two sticks whose lengths equal $w$. Specifically, to make a square frame (when $h = w$), he needs four sticks of the same length. Now Nicholas wants to make from the sticks that he has as many frames as possible; to be able to paint as many canvases as possible to fill the frames. Help him in this uneasy task. Note that it is not necessary to use all the sticks Nicholas has.
Idea of this problem was offered by RAD. It was the last problem in the problemset and I had no any easy idea:) I thank him for it. Here you should calculate an array $cnt[100]$. $i$-th element of it stores number of sticks whose lengths equal $i$. Now you should calculate number of pairs of sticks of equal lengths. This number is $k=\sum_{i=1}^{100}[c n t[a]/2]$, where $[x]$ is floor of $x$. For every frame you need 2 if such pairs and you can choose it in any order. Therefore the answer will be $z = [k / 2].$
[ "implementation" ]
1,000
null
128
B
String
One day in the IT lesson Anna and Maria learned about the lexicographic order. String $x$ is lexicographically less than string $y$, if either $x$ is a prefix of $y$ (and $x ≠ y$), or there exists such $i$ ($1 ≤ i ≤ min(|x|, |y|)$), that $x_{i} < y_{i}$, and for any $j$ ($1 ≤ j < i$) $x_{j} = y_{j}$. Here $|a|$ denotes the length of the string $a$. The lexicographic comparison of strings is implemented by operator < in modern programming languages​​. The teacher gave Anna and Maria homework. She gave them a string of length $n$. They should write out all substrings of the given string, including the whole initial string, and the equal substrings (for example, one should write out the following substrings from the string "aab": "a", "a", "aa", "ab", "aab", "b"). The resulting strings should be sorted in the lexicographical order. The cunning teacher doesn't want to check all these strings. That's why she said to find only the $k$-th string from the list. Help Anna and Maria do the homework.
Impossibility Let us denote the sequence by $a_{1}, ..., a_{n}$ and assume it has been sorted already. We can note immediately that there are some easy cases we can rule out. If $n$ is odd, by a parity argument it is impossible. Moreover, let $m = a_{n} - a_{1}$, i.e. the range of the values. If $m = 0$ it is impossible since $n \ge 3$, and if $m > n / 2$ it is impossible since we cannot get from $a_{1}$ to $a_{n}$ and back going around the circle. Now that these cases are out of the way we move on to the actual algorithm. Transformation It's natural to transform the input we're given into a form that's easier to work with, i.e. a histogram. As such, we define $c_{i}$ to be the number of values $a_{j}$ with $a_{j} - a_{1} = i$ for $i = 0, 1, ..., m$. Now we replace each $a_{i}$ with $a_{i} - a_{1}$ so that they are all in the range $[0, m]$. Observation A nice observation we can make about any valid sequence is the following. Consider the positions of any $0$ and any $m$ in the circle. There are two paths from $0$ to $m$. We observe that if any valid sequence exists, then there exists one for which, along each of these paths, the value never decreases twice in a row (that is, we can think of each path as "increasing" with some oscillation). Suppose this does happen in our sequence, i.e. we have something like $0, 1, ..., i - 1, i, i - 1, ..., j + 1, j, j + 1, ..., m - 1, m$ where $j < i - 1$ so $i, i - 1, ..., j + 1, j$ is the decreasing sequence. Then we note that $j + 1$ appeared somewhere between $0$ and $i$, so we can take the values $j, j + 1$ and move them directly after the $j + 1$ that was between $0$ and $i$ (easy to see that the sequence is still valid). Repeating this for whenever we have a decrease of two or more gives us paths that never decreases twice in a row. Validation Now with our transformation and observation, we can come up with the method of checking whether or not the histogram can produce a valid sequence. To do so, first place a $0$ on the circle. Then we have $L = c_{0} - 1$ zeros left to place. Note, however, that each zero must be adjacent to a one. So in fact there must be at least $L + 2$ ones to "hide" all of the zeros from the rest of the numbers (one on each side and one for each additional zero). If there are fewer than that many, it is impossible. After placing the remaining zeros and ones arbitrarily (but alternating) on each side of the initial $0$, we see that there are $L = c_{1} - (L + 2)$ ones remaining. By the same argument, we know how many twos there must be (again, $L + 2$). We can continue like this until we get to $m$. If there are $L$ remaining values of $m - 1$, we need $c_{m} = L + 1$ to complete the circle (one to be the "end" and one for each additional $m - 1$). If this is true, then it is possible and otherwise it is not. Note that the above placement strategy works because of the observation we made (we know we can use the small numbers greedily) and the fact that it doesn't matter how many of each number we put in each path as long as they end in the same value.
[ "brute force", "constructive algorithms", "hashing", "implementation", "string suffix structures", "strings" ]
2,100
null
131
A
cAPS lOCK
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if: - either it only contains uppercase letters; - or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed. Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
Just do what the statement asks you to. Check if all letters are uppercase, except for the first one, that you don't need to check. If so, change the case of the entire string. If not, do nothing. Please notice that an one-letter string must have its case changed. It can be easly done in O(n), where n is the lenght of the string.
[ "implementation", "strings" ]
1,000
null
131
B
Opposites Attract
Everybody knows that opposites attract. That is the key principle of the "Perfect Matching" dating agency. The "Perfect Matching" matchmakers have classified each registered customer by his interests and assigned to the $i$-th client number $t_{i}$ ($ - 10 ≤ t_{i} ≤ 10$). Of course, one number can be assigned to any number of customers. "Perfect Matching" wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of $t$. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence $t_{1}, t_{2}, ..., t_{n}$. For example, if $t = (1, - 1, 1, - 1)$, then any two elements $t_{i}$ and $t_{j}$ form a couple if $i$ and $j$ have different parity. Consequently, in this case the sought number equals 4. Of course, a client can't form a couple with him/herself.
First, let count(i) be the numbers of occurrences of the number i in the input, for -10 <= i <= 10. Remember that there may be negative numbers in the input, so one can use an offset to store these values (use an 21-sized array C and store count(i) in C[i+10]). Except for 0, possible matching are pairs (i,-i), for 1 <= i <= 10. It's easy to see that there will be exactly count(i)*count(-i) valid matching for each i, so just sum them all. Since 0 "is opposite to itself", but "a client can't form a couple with him/herself", the number of valid pairs (0,0) will be (count(0) 2). Just sum this value to the previous computed sum and print. Use 64 bits-types to do the math.
[ "implementation", "math" ]
1,200
null
131
C
The World is a Theatre
There are $n$ boys and $m$ girls attending a theatre club. To set a play "The Big Bang Theory", they need to choose a group containing exactly $t$ actors containing no less than 4 boys and no less than one girl. How many ways are there to choose a group? Of course, the variants that only differ in the composition of the troupe are considered different. Perform all calculations in the 64-bit type: long long for С/С++, int64 for Delphi and long for Java.
Since the constraints are small, let's just iterate through all possible numbers b of boys in the group and count how many ways we can form the group with b boys. First, consider only the values where b >= 4. Given b, it's clear that the number of girls in the group must be g = t - b. If g < 1, don't consider this case. Given the values of b and g, there are (n b)*(m g) ways to form the group, since we can combine the boys independently the girls. Just sum (n b)*(m g) for each pair (b,g). Again, use 64 bits-types to do the math. One could precompute all the values of (i j) using the Pascal triangle, but one could also compute it with the traditional formula, if its implementation takes care of possible overflow (30! doesn't fit in 64-bit integer type).
[ "combinatorics", "math" ]
1,400
null
131
D
Subway
A subway scheme, classic for all Berland cities is represented by a set of $n$ stations connected by $n$ passages, each of which connects exactly two stations and does not pass through any others. Besides, in the classic scheme one can get from any station to any other one along the passages. The passages can be used to move in both directions. Between each pair of stations there is no more than one passage. Berland mathematicians have recently proved a theorem that states that any classic scheme has a ringroad. There can be only one ringroad. In other words, in any classic scheme one can find the only scheme consisting of stations (where any two neighbouring ones are linked by a passage) and this cycle doesn't contain any station more than once. This invention had a powerful social impact as now the stations could be compared according to their distance from the ringroad. For example, a citizen could say "I live in three passages from the ringroad" and another one could reply "you loser, I live in one passage from the ringroad". The Internet soon got filled with applications that promised to count the distance from the station to the ringroad (send a text message to a short number...). The Berland government decided to put an end to these disturbances and start to control the situation. You are requested to write a program that can determine the remoteness from the ringroad for each station by the city subway scheme.
A graph-related problem. The statement makes you sure that the given graph is connected and contains one (and exactly one) cycle. What you have to do is to compute the distance, in number of edges, from all vertexes to the cycle (print 0 for the vertex that are in the cycle. We will call these vertexes 'in-cycle'). First, let's find the cycle and find the vertexes whose answer is 0. The cycle can be found with a regular Depth-First-Search (DFS), storing the fathers of the vertexes. Notice that, during the search, there will be exactly one back edge, say (vi, vj). When this edge is found, iterate from vi to vj (using the father array) and label the vertexes as 'in-cycle'. After that, let's compute the answers for the other vertexes. One could "compact" the graph by merging all the 'in-cycle' vertexes into a single vertex. Then, just do another search starting by this vertex and compute the distances, knowing that the distance of a vertex vi is the distance of father[vi] plus one. Also, it's also possible to do as many searchs as the number of 'in-cycle' vertexes if you don't consider others 'in-cycle' vertexes during the search. The running time would still be O(n + m), that, in this problem, is O(n + n) = O(n).
[ "dfs and similar", "graphs" ]
1,600
null
131
E
Yet Another Task with Queens
A queen is the strongest chess piece. In modern chess the queen can move any number of squares in any horizontal, vertical or diagonal direction (considering that there're no other pieces on its way). The queen combines the options given to the rook and the bishop. There are $m$ queens on a square $n × n$ chessboard. You know each queen's positions, the $i$-th queen is positioned in the square $(r_{i}, c_{i})$, where $r_{i}$ is the board row number (numbered from the top to the bottom from 1 to $n$), and $c_{i}$ is the board's column number (numbered from the left to the right from 1 to $n$). No two queens share the same position. For each queen one can count $w$ — the number of other queens that the given queen threatens (attacks). For a fixed attack direction only the first queen in this direction is under attack if there are many queens are on the ray of the attack. Obviously, for any queen $w$ is between 0 and 8, inclusive. Print the sequence $t_{0}, t_{1}, ..., t_{8}$, where $t_{i}$ is the number of queens that threaten exactly $i$ other queens, i.e. the number of queens that their $w$ equals $i$.
Let's first consider that the queens can only attack the other pieces standing in the same line - the case with the columns and both diagonals will be analogous. Let line[i] be an array that will store all the queens that are in the i-th line on the chessboard. Since it's indexed by the line number, it's only necessary to store the column number of the pieces. So, for example, if we have queens at positions (4,6), (4,8) and (6,5), we will have line[4] = {6,8} and line[6] = {5}. To check if the queen at position (i,j) is attacking someone in its line, you must check if there is some number greater than j and/or less than j in line[i]. To do that, presort line[i] and binary search j in it. Notice that j will always be successful found by the search. Notice also that there will be some number greater than j iff the found element is not the last one of line[i]. The same applies for the other case: check if j is not the first element of line[i]. If j is not the first nor the last element, the queen is attacking 2 pieces in its line. If j is the only element, the queen is attacking no one, and it's attacking 1 piece otherwise. Do the same thing (compute all column[i], sort them and, for each queen, binary search) to the column, to the "/" diagonal, and to the "\" diagonal. Remember that a piece at position (i,j) is at the diagonals i+j and i-j. Like in problem B, use an offset to handle the negative numbers in the last case. Store the line number in the column[i] array. There's no different in witch index (line or column) to use in the diagonals arrays (but, of course, use the same chosen index for everyone). It seems that the sorting part of the algorithm will run in O(n*n*logn) time, since we have O(n) lines, columns and diagonals. However, the sum of the sizes of all these arrays will be m, the numbers of queens. So the running time will be actually near O(m*logm). Binary searching for every queen will take less than O(m*logm), too.
[ "sortings" ]
1,700
null
131
F
Present to Mom
How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of $n$ lines each containing $m$ characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black. Polycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white: \begin{center} \begin{verbatim} 1 111 1 \end{verbatim} {\small a star on the photo} \end{center} Polycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than $k$ stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders. Now Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number.
The main idea is to, for each pair of lines i1 and i2, count the ways you can form the rectangle using a sweep line-like algorithm. The idea is similar to the somewhat classic idea used for the problem that is, given an array of numbers, count how many contiguous sub arrays exists witch sum is equal or greater to some given k. Let's first of all identify all the points where a star can be found, in its "starting" position and "finish" position. These are the S and F position shown below. 1 S1F 1 For each pair of lines i1 and i2 (i2 > i1) we will keep two indices (or pointers) j1 and j2 for the columns, with j2 > j1. During the algorithm, we will always analyze the rectangle formed by lines i1,i2 and columns j1,j2. Let's start with j1 = 0 and j2 = 2 (there won't be any star in the rectangle i1,i2,0,(0 or 1) simply because a star won't fit in it). Let's then count the number of stars found in this rectangle. It will be equal to countfinish(i1+1,i2-1,j2), where countfinish(I1,I2,J) is the number of "finish" positions in the column J between the lines I1 and I2. If this number is equal or greater than k, this rectangle and all the rectangles (i1,i2,j1,j) for j >= j2 will be valid, so you need to sum m-j2 to the answer. Then, increment j1 and recalculate the numbers of stars in the rectangle. It will be equal to the previous number minus countstart(i1+1,i2-1,j1-1), (the definition of countstart() is analogous) since it's the number of starts that are "lost" when we move from j1-1 to j1. Check again if the new number is greater or equal than k and repeat the process until the number is less than k. Notice that j1 will always be less than j2, since a star needs 3 columns to exists. Then, increment j2 and, without changing the value of j1, repeat the process. Notice that this part of the algorithm will take O(m)*T time (where T is the time needed to calculate countstart and countfinish), since both j2 and j1 will "walk" in the columns only one time. A trick can be made to make T = O(1). For each column j, precompute an array countstart[j], where countstart[j][i] = countstart[j][i-1] + (1 if (i,j) is a "starting" position, 0 otherwise). To compute countstart(I1,I2,J), just use the formula countstart[J][I2] - countstart[J][I1-1], that gives the value in constant time. Do the same with countfinish. Precomputing countstart and countfinish takes, for each column, O(n) time, so all the precomputing can be done in O(n*m) time. Since we use an O(m)*O(1) = O(m) time for O(n2) pairs of lines, the total time used for the algorithm is O(n*m) + O(n2*m) = O(n2*m). A bit high for n=m=500, but the time limit for this problem was higher than the usual too (5 seconds instead of 2).
[ "binary search", "two pointers" ]
2,000
null
132
A
Turing Tape
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one by one, starting from the first. Processing $i$-th element of the array is done in three steps: 1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0. 2. The $i$-th element of the array is subtracted from the result of the previous step modulo 256. 3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the $i$-th character to be printed. You are given the text printed using this method. Restore the array used to produce this text.
This was another implementation problem, inspired by another great language INTERCAL. Technically it was a bit more complicated than the previous one, due to the usage of byte reversal and having to implement not the described procedure but its inverse. For i-th character of input data reverse it and store in $rev[i]$; then i-th number of the output can be calculated as $(rev[i - 1] - rev[i] + 256)%256$ (for $i = 0$ $rev[i - 1] = 0$).
[ "implementation" ]
1,300
null
132
B
Piet
Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules. The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes. The program is interpreted using movement of instruction pointer (IP) which consists of three parts: - current block pointer (BP); note that there is no concept of current pixel within the block; - direction pointer (DP) which can point left, right, up or down; - block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively. Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below). One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of \textbf{CP}. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise. This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black). You are given a Piet program. You have to figure out which block of the program will be current after $n$ steps.
As you've already noticed, Piet differs from most other esoteric programming languages in the way it interprets the image - the problem offered a very simplified version of it, and still it was quite cruel. The first step of the solution is finding colored blocks. Given that they are rectangular, this can be done without BFS; once you've found a colored pixel which is not part of any block you've seen before, you just find the maximal contiguous sequence of pixels of the same color in the same line that starts with this pixel, and assume that it's horizontal dimension of its block. ............ ..X----->... ..|XXXXXX... ..vXXXXXX... ............ I found it convenient to index the blocks and store their colors and dimensions at this point, so that this doesn't need to be re-done later. After this I calculated "state transition function" - a function which for each state of instruction pointer defined the next state. The IP has at most 50x50x4x2 states, and they can be indexed with 8*(index of current block) + 2*(direction pointer) + (block chooser). Thus, the transition function can be described with a one-dimensional array (index is current state of IP, and value is the next one), and the simulation of interpretation steps becomes just updating the current state of IP, which is easier than repeating the full procedure described in the statement on each step. It was also possible to note that at some point there will be a loop in the states of the IP, since the maximal possible number of distinct states is less than the number of steps to be done. But exploiting this wasn't necessary.
[ "implementation" ]
2,100
null
132
C
Logo Turtle
A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward"). You are given a list of commands that will be given to the turtle. You have to change exactly $n$ commands from the list (one command can be changed several times). How far from the starting point can the turtle move after it follows \textbf{all} the commands of the modified list?
This was the only problem of the round which featured a non-esoteric language. The solution is dynamic programming, and it could be used in several ways. My solution was to store two three-dimensional arrays: the leftmost and the rightmost position of a turtle after it used I commands from the list, made J changes in these commands and is now facing direction K. The initial condition is that left=right=0 when I = J = 0 and the turtle faces right (the initial direction can be chosen arbitrarily). The rule of moving between states is: if currently executed command is T (either it is the current command of the list and no change is done, or it is a result of a change), the coordinate stays the same and the direction changes; otherwise the direction stays the same and the coordinate changes accordingly to the direction. It's convenient to do at most one change for each command; in this case after all the arrays are calculated, one has to take the maximal absolute value among all distances which use all commands from the list, all facing directions of the turtle and all quantities of changes which have the same parity as the required quantity (any command can be changed an even number of times without affecting the result).
[ "dp" ]
1,800
null
132
D
Constants in the language of Shakespeare
Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare. Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations. You are given an integer $n$. You have to represent it as $n = a_{1} + a_{2} + ... + a_{m}$, where each of $a_{i}$ is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of $m$.
Two last problems of the round were inspired by Shakespeare programming language. The original idea was to make them one problem - "How to print the given sequence using as few adjectives as possible?". But later we came to our senses and split this monster of a problem in two. The evident greedy solution (break the binary notation into contiguous groups of 1s, if the size of the group is 1, write it as a single power, otherwise write it as a difference of two powers) is wrong. You can see this from test 4 "10110111": the greedy solution will return 5 ($+ 2^{7} + 2^{6} - 2^{4} + 2^{3} - 2^{0}$), while it's possible to find a notation of size 4 ($+ 2^{8} - 2^{6} - 2^{4} - 2^{1}$). The correct solution is based on the following idea. Let us have a fragment of binary notation which contains bits for powers of 3 between N and M (N < M), inclusive, which has K 0s and L 1s. It can be written as a sum of powers which correspond to positions of 1s, using L powers. Alternatively, it can be written as $2^{M + 1} - 2^{N} - ...$, where ... are powers which correspond to positions of 0s, using 2 + K powers. It's evident that using second method makes sense only if the fragment starts and ends with 1s (otherwise it can be used for shorter fragment without the leading/trailing 0s, and save at least one power on this) and contains no 00 sequence inside (otherwise you can break the fragment into two in place of these 00 and write these fragments separately with the same or better result). After you've noted this, you can solve the problem using DP: for each position in binary notation store the sign "write it as sum of powers or as difference of powers", and in second case store the length of the fragment which is written using difference (storing the length of the fragment which is written using sums only is unnecessary, since this can be done for individual bits with the same result as for longer fragments.
[ "constructive algorithms", "dp", "greedy" ]
2,100
null
133
A
HQ9+
HQ9+ is a joke programming language which has only four one-character instructions: - "H" prints "Hello, World!", - "Q" prints the source code of the program itself, - "9" prints the lyrics of "99 Bottles of Beer" song, - "+" increments the value stored in the internal accumulator. Instructions "H" and "Q" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored. You are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.
The problem described HQ9+ programming language and asked whether the given program will print anything. Given the extraordinary simplicity of the language, it was enough to check whether the program contains at least one of the characters H, Q and 9.
[ "implementation" ]
900
null
133
B
Unary
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm. First, replace each command with a corresponding binary code, using the following conversion table: - ">" $ → $ 1000, - "<" $ → $ 1001, - "+" $ → $ 1010, - "-" $ → $ 1011, - "." $ → $ 1100, - "," $ → $ 1101, - "[" $ → $ 1110, - "]" $ → $ 1111. Next, concatenate the resulting binary codes into one binary number in the same order as in the program. Finally, write this number using unary numeral system — this is the Unary program equivalent to the original Brainfuck one. You are given a Brainfuck program. Your task is to calculate the size of the equivalent Unary program, and print it modulo $1000003$ $(10^{6} + 3)$.
A lovely language Brainfuck has dialects for literally every occasion; I guess one could write a whole round about it (not Unknown Language Round, of course, it's too well-known for it), but this time I used it in one problem only. The solution is quite simple: all you have to do is to follow the described procedure of transforming code from Brainfuck to Unary. If your language has built-in long arithmetics, the solution is straightforward: replace characters of each type with corresponding binary codes, convert the resulting string into a long integer and take it modulo 1000003. Having no long arithmetics is not a big deal either. The program can be created step by step, adding one character at a time from left to right. On each step the length of the program is multiplied by 16 (the binary code added has length of 4 bits), then the code of the current character is added and the result is taken modulo 1000003, so that the result never gets really large.
[ "implementation" ]
1,200
null
135
A
Replacement
Little Petya very much likes arrays consisting of $n$ integers, where each of them is in the range from $1$ to $10^{9}$, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from $1$ to $10^{9}$, inclusive. It is \textbf{not allowed} to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.
If the largest number in our array is equal to 1 then let's replace it with 2, otherwise let's replace it with 1. After that let's sort the array and output it. It is easy to see that the array obtained in that way is the one we are looking for. The complexity is $O(NlogN)$.
[ "greedy", "implementation", "sortings" ]
1,300
null
135
B
Rectangle and Square
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures \textbf{do not have} to be parallel to the coordinate axes, though it might be the case.
Let's iterate over all partitions of our set of 8 points into two sets of 4 points. We want to check whether the first set forms a square and the second set forms a rectangle. To check if 4 points lay at the vertexes of a rectangle one can iterate over all permutations of the last 3 points. Then one need to ensure that every two consecutive sides intersect at a 90 degrees angle. That can be done using the fact that the scalar product of two vectors is equal to 0 iff they intersect at a 90 degrees angle. To check if 4 points lay at the vertexes of a square one can check whether they lay at the vertexes of a rectangle and ensure that two consecutive sides have equal length.
[ "brute force", "geometry", "math" ]
1,600
null
135
C
Zero-One
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card contains a digit: 0 or 1. Players move in turns and Masha moves first. During each move a player should remove a card from the table and shift all other cards so as to close the gap left by the removed card. For example, if before somebody's move the cards on the table formed a sequence 01\textbf{010}101, then after the fourth card is removed (the cards are numbered starting from 1), the sequence will look like that: 01\textbf{00}101. The game ends when exactly two cards are left on the table. The digits on these cards determine the number in binary notation: the most significant bit is located to the left. Masha's aim is to minimize the number and Petya's aim is to maximize it. An unpleasant accident occurred before the game started. The kids spilled juice on some of the cards and the digits on the cards got blurred. Each one of the spoiled cards could have either 0 or 1 written on it. Consider all possible variants of initial arrangement of the digits (before the juice spilling). For each variant, let's find which two cards are left by the end of the game, assuming that both Petya and Masha play optimally. An ordered pair of digits written on those two cards is called an outcome. Your task is to find the set of outcomes for all variants of initial digits arrangement.
First, let's solve the problem when there are no spoiled cards. Let a be the number of ones and b be the number of zeroes. It is easy to see that if a < b then the outcome is 00, because the first player can always remove ones until they are over, which will happen before the end of the game regardless of the second player's moves. Similarly, if a > b + 1 then the outcome is 11. If a = b or a = b + 1 then the outcome is either 01 or 10. That's because the first player will always remove ones, because otherwise the outcome will be 00 which is worse than any other outcome for him. Similarly, the second player will always remove zeroes. One may notice that the first player can always remove the first card to the left with 1 written on it, because it won't make the outcome worse for him. Similarly, the second player can always remove the first card to the left with 0 written on it. That means that the last card won't be removed by anyone. Thus is the last card is 1 then the outcome is 01, otherwise it is 10. We've learned how to solve the problem is there are no '?' signs. Now, suppose that the number of ones is a, the number of zeroes is b and the number of question signs is c. To check if the outcome 00 is possible, one can simply replace all question signs with zeroes and use the previous result, i.e. check if a < b + c. Similarly, the outcome 11 is possible is a + c > b + 1. Let's show how to check if the outcome 01 is possible. If the last character of the string is 0, then the string is not possible. If the last character is ? then we can replace it with 1, i.e. decrease c by 1 and increase a by 1. Suppose we want to replace x question signs with one and c - x question signs with zero. Then the following equality must hold: x + a = b + c - x + (a + b + c) mod 2. Thus, x = (b + c - a + (a + b + c) mod 2) / 2. If the resulting value of x is non-negative and is not greater than c, then the outcome 01 is possible, otherwise it is not possible. We can check if the outcome 10 is possible in the similar way. The complexity is $O(N)$.
[ "constructive algorithms", "games", "greedy" ]
1,900
null
135
D
Cycle
Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained $n$ rows and $m$ columns. The rows are numbered from top to bottom from $1$ to $n$, the columns are numbered from the left to the right from $1$ to $m$. Petya immediately decided to find the longest cool cycle whatever it takes. A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: - The cycle entirely consists of the cells that contain "1". - Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. - Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle $(i, j)$ ($i$ is the row number, $j$ is the column number) correspond to the point $(i, j)$ on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell $(r, c)$ lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates $(r, c)$ lies in the part with the infinite area. Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle.
One can notice that the only possible variant of a cool cycle which doesn't have zeroes inside it is a 2x2 square of ones. This case should be checked separately. From this point we'll assume that the cool cycle we are looking for contains at least one '0' inside it. Let's take any zero from the table. If it is adjacent to another zero by a side or a corner then it can't lay inside a cool cycle which doesn't have any other zeroes inside it. Thus, this zero can lay inside a cool cycle only together with all zeroes adjacent to it. Generalizing this fact one can show that the zero can lay inside a cool cycle only together with all zeroes reachable from it. We'll assume that one zero is reachable from another zero if they can be connected with a path which consists only of zeroes and in which every two consecutive cells share either a side or a corner. Let's find all the connected components of zeroes. Two zeroes are connected if they share either a side or a corner. If the component of zeroes has a cell adjacent to a border of the table, then it can't lay inside any cool cycle and thus it should be ignored. After that for each connected component of zeroes let's find all cells with 1, adjacent to it. By the statement all those cells should be connected. Also, each cell from this set should share a common side with exactly two other cells from the set. Note that if the set of cells with '1' satisfy those restrictions, then it forms a cycle which doesn't contain any other cells with '1' inside it. The above algorithm has the complexity $O(NM)$, if implemented carefully.
[ "brute force", "dfs and similar", "implementation" ]
2,500
null
135
E
Weak Subsequence
Little Petya very much likes strings. Recently he has received a voucher to purchase a string as a gift from his mother. The string can be bought in the local shop. One can consider that the shop has all sorts of strings over the alphabet of fixed size. The size of the alphabet is equal to $k$. However, the voucher has a string type limitation: specifically, the voucher can be used to purchase string $s$ if the length of string's longest substring that is also its weak subsequence (see the definition given below) equals $w$. String $a$ with the length of $n$ is considered the weak subsequence of the string $s$ with the length of $m$, if there exists such a set of indexes $1 ≤ i_{1} < i_{2} < ... < i_{n} ≤ m$, that has the following two properties: - $a_{k} = s_{ik}$ for all $k$ from $1$ to $n$; - there exists at least one such $k$ ($1 ≤ k < n$), for which $i_{k + 1} – i_{k} > 1$. Petya got interested how many different strings are available for him to purchase in the shop. As the number of strings can be very large, please find it modulo $1000000007$ ($10^{9} + 7$). If there are infinitely many such strings, print "-1".
Let cool substring be the substring which is also a weak subsequence. The main observation is that the longest cool substring in any string is either its prefix or its suffix. Moreover, if, for example, it is a prefix then it can be found in the following way. Let's start moving from the end of the string towards the beginning and memorize all characters met on our way. We'll stop after some character appear in the second time. The prefix with the end in the position where we stopped is the one we are looking for. Let's count the number of strings in which the longest cool substring is a suffix. First, we will iterate over the number of characters at the beginning of the string lying before the second appearance of some character. Let this number be t. Obviously, t is not greater than k, because all characters in the prefix of length t are distinct. We need to consider the following two cases: 1. If $t \le w - 1$. The first t characters of a resulting string are distinct, then there is a character which was present among the first t characters. After it there are w - 1 more characters. One should also consider that the last t characters are distinct, otherwise prefix of length greater than w will be also a weak subsequence. Thus, the corresponding summand is equal to $\frac{t k!^{2}k^{\omega-t-1}}{(k-t)^{2}}$. 2. If $t > w - 1$. The first t characters of a resulting string are distinct, then there is a character which was present among the first t characters. The last t characters should be distinct, but at this time the suffix of t characters overlaps with the prefix of t characters. The corresponding summand is equal to $\frac{k!\cdot w\cdot(k-t+w-1)!}{(k-t)!^{2}}$. After adding up everything for all t from 1 to k we will obtain the number of strings in which the longest cool substring is a suffix of length w. Similarly, we can find the number of strings in which the longest cool substring is a prefix. The only difference is that we should make sure that the first t + 1 characters of those strings are distinct in order to avoid a double-counting of the strings in which the first and the last t characters are distinct. Considering this the formulas are: 1. If $t + 1 \le w - 1$, then the summand is equal to $\frac{t\cdot k!^{2}\cdot k^{w-t}-2}{k-t}$. 2. If $t + 1 > w - 1$, then the summand is equal to $\frac{k!\cdot(w-1)\cdot(k-t+w-2)!}{(k-t)!.(k-t-1)!}$. The only thing left is to add up everything for all t from 1 to k - 1. To calculate the above formula quickly one need to precompute factorials for all numbers from 1 to k and they inverse modulo 109+7. The complexity is either $O(K)$ or $O(K \cdot log(MOD))$, depending on the way of computing inverse values to the factorials. As a bonus for those who made it to the end of the editorial, I'll describe a simple linear time algorithm of finding inverse values for all integers between 1 and N modulo prime number P (P > N). I think it will be useful for those who didn't hear about this trick. Let's consider an obvious equality (% means a remainder of division) and perform a few simple operations with it. $P^{9}\!y_{0}i=P-\lfloor{\frac{P}{i}}\rfloor\cdot i$ $P^{9}\!\vartheta\cdot\!\lbrack\equiv-\lbrack{\textstyle\frac{P}{i}}\rbrack\cdot i(m o d P)$ $i\equiv-(P\nabla_{0i})\cdot\lfloor{\frac{P}{i}}\rfloor^{-1}(m o d P)$ $i^{-1}\equiv-(P\nabla_{c i})^{-1}\cdot\,\lfloor{\frac{P}{i}}\rfloor(m o d P)$ Thus, in order to compute $i^{ - 1}$ we only need to know $(P%i)^{ - 1}$, which is less than $i$. That means we can compute inverse values successively for all integers between 1 and $N$ in $O(N)$ time.
[ "combinatorics" ]
3,000
null
136
A
Presents
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited $n$ his friends there. If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from $1$ to $n$. Petya remembered that a friend number $i$ gave a gift to a friend number $p_{i}$. He also remembered that each of his friends received exactly one gift. Now Petya wants to know for each friend $i$ the number of a friend who has given him a gift.
In this problem one had to read a permutation and output the inverse permutation to it. It can be found with the following algorithm. When reading the i-th number, which is equal to a one can store i into the a-th element of the resulting array. The only thing left is to output this array. The complexity is $O(N)$.
[ "implementation" ]
800
null
136
B
Ternary Logic
Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the $xor$ operation is performed on this computer (and whether there is anything like it). It turned out that the operation does exist (however, it is called $tor$) and it works like this. Suppose that we need to calculate the value of the expression $a tor b$. Both numbers $a$ and $b$ are written in the ternary notation one under the other one ($b$ under $a$). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: $14_{10} tor 50_{10} = 0112_{3} tor 1212_{3} = 1021_{3} = 34_{10}$. Petya wrote numbers $a$ and $c$ on a piece of paper. Help him find such number $b$, that $a tor b = c$. If there are several such numbers, print the smallest one.
It is easy to see that the answer is always unique. Let's consider an operation which is opposite to tor. From each ternary digit of c we will subtract a corresponding digit of a and take a result modulo 3. We'll obtain a number b which has the following property: a tor b = c. The complexity is $O(logC + logA)$.
[ "implementation", "math" ]
1,100
null
137
A
Postcards and photos
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not carry in his hands objects of two different types. In other words, Polycarpus can't carry both postcards and photos simultaneously. Sometimes he goes to the closet and puts the objects there, thus leaving his hands free. Polycarpus must put \textbf{all} the postcards and photos to the closet. He cannot skip objects. What minimum number of times he should visit the closet if he cannot carry more than 5 items?
We will move from the left of string to the right. When we passed the whole string, or in the hands of us have 5 pieces, or current object is different from what we hold in our hands, we remove all the items in the pantry. The answer to the problem is the number of visits to the pantry. The complexity is O(n).
[ "implementation" ]
900
null
137
B
Permutation
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once. You are given an arbitrary sequence $a_{1}, a_{2}, ..., a_{n}$ containing $n$ integers. Each integer is not less than $1$ and not greater than $5000$. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
We can count the number of integers from 1 to n, which occur in sequence at least once. Then the answer is n minus that number. The complexity is O(n).
[ "greedy" ]
1,000
null
137
C
History
Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history. Everybody knows that the World history encompasses exactly $n$ events: the $i$-th event had continued from the year $a_{i}$ to the year $b_{i}$ inclusive ($a_{i} < b_{i}$). Polycarpus easily learned the dates when each of $n$ events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event $j$ includes an event $i$ if $a_{j} < a_{i}$ and $b_{i} < b_{j}$. Your task is simpler: find the number of events that are included in some other event.
Denote a[i], b[i] - ends of the i-th event. Let's sort pairs (a[i], b[i]) by a[i] and iterate over all pairs. Denote rg the maximal b[i] from already processed. If current b[i] < rg than we must increment answer by one. If b[i] > rg than we must assign rg by b[i]. The complexity is O(n logn).
[ "sortings" ]
1,500
null
137
D
Palindromes
Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings $a$, $b$ is a string $ab$ that results from consecutive adding of string $b$ to string $a$. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than $k$ palindromes. Innocentius can't complete the task and therefore asks you to help him.
Let's preprocess array cnt[i][j] - the minimal number of changes tha we must do to make substring from position i to j palindrom. We can easy calc cnt[i][j] with complexity O(n^3). Now we can calculate dynamic programming z[i][j] - minimal number of changes that we can do to split prefix of length i into j palindromes. In begining we must assign z[i][j] = infinity for all (i, j) and assign z[0][0] = 0. If we want to make updates from state (i, j) we must fix the length of j-th palindrom - len. We can update z[i + len][j + 1] by value z[i][j] + cnt[i][i + len - 1]. Answer to the problem is the min(z[n][i]), where n is the length of string and i from range [1, k]. The complexity is O(n^3).
[ "dp", "strings" ]
1,900
null
137
E
Last Chance
Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task. The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string $s$. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with $v$ vowels and $c$ consonants is good if and only if $v ≤ 2c$. The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string $s$.
Let's replace all vowels by -1 and all consonants by +2. Obviously substring from position i to j is good if sum in the substring [i, j] is nonnegative. Denote this sum by sum[i][j]. Obviously sum[i][j] = p[j + 1] - p[i], where p[i] is the sum of first i elements. Now for all i we want to find maximal j such that j >= i and sum[i][j] >= 0. For this let's sort the array of (p[i], i) and build segment tree on this array by i. Let's iterate over all p[i] in nondescending order. Obsiously for fixed i we have that j = max(index[i]), where index[i] is the index of i-th partial sum in nondescending order and i from range [x, n], where x is the position of the first partial sum with value p[i] in sorted array. Than we must update position i by value of negative infinity and update answer by j - i. The complexity is O(n logn).
[ "data structures", "implementation", "strings" ]
2,000
null
138
A
Literature Lesson
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the $k$-th vowels (counting from the end) match. If a line has less than $k$ vowels, then such line can't rhyme with any other line. For example, if $k = 1$, lines $commit$ and $hermit$ rhyme (the corresponding suffixes equal $it$), and if $k = 2$, they do not rhyme ($ommit ≠ ermit$). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): - Clerihew ($aabb$); - Alternating ($abab$); - Enclosed ($abba$). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by $aaaa$). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is $aaaa$. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
The hardest part is to check whether two lines rhyme or not. We have to check the suffixes starting in K-th vowels from the ends for equality. Notice that if a line has less then K vowels, it can NOT be part of any rhyme (even with the identical string). To check this we can use two pointers running from two ends simultaneously, or use some built-in functions for taking substrings (like s.substr(...) in C++). Now, let us take three boolean variables: aabb, abab and abba. Each one says if every quatrain we have seen before satisfies the corresponding type of rhyme. To support them, for each new quatrain we must check for rhyming every pair of lines it and change variables if needed. If at the end of the poem all variables are set to TRUE, then the type is aaaa. If all of them are FALSE's, then the answer is NO. Otherwise exactly on of them is TRUE, and answer is clear. Complexity - O(S), where S is the sum of all lines' sizes.
[ "implementation" ]
1,600
null
138
B
Digits Permutations
Andrey's favourite number is $n$. Andrey's friends gave him two identical numbers $n$ as a New Year present. He hung them on a wall and watched them adoringly. Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers. Given number $n$, can you find the two digit permutations that have this property?
It turned out to be surprisingly hard, possibly because of lots of cases to think of. How to determine the number of zeros at the end of the sum of two numbers? First we skip all the positions from the end where both numbers have zeros. If on the next position the sum of digits is not 10, that's it. If it is, we go on while the sum of digits is 9. Now we take two transitions of digits in N. Let's fix the number of common zeros at the end of both transitions. If, moreover, we fix the digits that sum up to 10 at the next positions, we can find the maximal number of zeros to get with the remaining digits as $min(a_{0}, b_{9}) + ... + min(a_{9}, b_{0})$, where $a_{0}, ..., a_{9}$ are the quantities of every remaining digit in the first transition after taking out the last zeroes and the digit for the 10-sum, and $b_{0}, ..., b_{9}$ are the same numbers for second transition (initially these quantities are equal to quantities of digits in N). So, if we store $a_{0}, ..., a_{9}$ and $b_{0}, ..., b_{9}$, and then run through the numbers of common zeros at the end and the 10-sum digits, we determine the maximal zeros number (and configuration giving that answer) in O(10 * 10 * N) = O(N) time. Getting the transitions now is easy - we build them from right to left according to the saved answer. The most common mistake was to think that maximal number of zeros at the end gives the maximal answer. It was disproved by 4-th pretest - 1099. As we can see, the optimal configuration is 1901 + 1099, giving three zeros, which cannot be achieved by placing both zeros at the ends.
[ "greedy" ]
1,900
null
138
C
Mushroom Gnomes - 2
One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story: Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are $n$ trees and $m$ magic mushrooms in the woods: the $i$-th tree grows at a point on a straight line with coordinates $a_{i}$ and has the height of $h_{i}$, the $j$-th mushroom grows at the point with coordinates $b_{j}$ and has magical powers $z_{j}$. But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate $x$ and height $h$ falls to the left, then all the mushrooms that belong to the right-open interval $[x - h, x)$, are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval $(x, x + h]$ are destroyed. Only those mushrooms that are not hit by a single tree survive. Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death. Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.
First of all - the answer is the sum for all mushrooms of the probabilities of not being destroyed multiplied by that mushroom's power. That is a simple property of random variables' means. So we come to the equivalent statement: we still have mushrooms, but now instead of trees we have a family of segments with probabilities arranged to them. Every segment "exists" with this probability, otherwise it doesn't, and all these events are independent. We want to count the sum of probabilities (with weights) for each mushroom not to lie in any "existing" segment. (Note that we can reformulate the statement this way because any segments containing any fixed point are truly independent: they can't belong to the same tree. Thus the probability to survive for any point in this statement is equal to the probability for this point in the original statement). Now, how do we count this? There are several ways: 1) "Scanning line". If we go from left to right, we can meet three kinds of events: "the segment $i$ started", "the segment $i$ finished", "the mushroom $j$ found". We can easily support the probability of current point being covered by "existing" segment if we multiply it by segment's probability when we find its beginning and divide by it if we find its end. If we find a mushroom by the way, we can add the known probability to answer (multiplied by its power). To perform the above trick we just sort the array of events by x-coordinate and iterate over it. This solution is good in theory, but in practice it has a flaw: if the number of segments is large, after multiplying lots of real numbers less then 1 we can exceed the negative explonent of the real type used, and thus get a 0 in a variable instead of desired value. And after any number of divisions it still would be 0, so we couldn't get any sane answer anymore. This trouble can be resolved in several ways (without changing the solution much): a) We can have no more than 101 distinct values of probabilities for segments. So, if we store an array for quantities of segments containing current point and having a corresponding probability, we just add and substract 1's from array's elements. When we find a mushroom we find the product of degrees with exponents stored in array, spending ~100 operations. b) We can store a set of segments containing current point. Every operation with set works in O(log N) time, and iterating over the whole set works in O(N) time. So, upon meeting mushroom we iterate over set and multiply the probabilities for all segments in it. The next thing that helps us is that we can drop the answer for current mushroom if it's too small. If we don't store the segments with probability 1, the most number of segments which probabilities' product more than 1e-8 is about 2000 (since 0.99 ^ 2000 < 1e-8). So we can count everything in time. c) If we use logs of probabilities instead of themselves, we have to add and substract them instead of multiplying and dividing. This way we won't encounter any precision troubles. 2) Segment tree. Let's sort the mushrooms by their coordinates. Let's also assume we have some set of segments and already counted the desired probabilities. And now we want to add a new segment to the set. What will change? The probabilities of mushrooms lying in this segment (and thus forming a segment in the array) will multiply by segment's probability. Now it's clear we can use multiplication segment tree (or simple addition segment tree if we use logs again) to perform the queries for all segments and then sum up the elements in the end. About the strange score and pretest: we discovered the trouble with precision quite late, and realized that it makes the problem way harder ('cause it's hard to predict during writing and submission phases). What's worse, it won't show itself on the small tests. So we decided to "show up" the test and let the contestants solve this additional problem, for additional score. (However, not all solutions from above list do actually deal with this problem. Unfortunately, we didn't came up with them beforehand.)
[ "binary search", "data structures", "probabilities", "sortings" ]
2,200
null
138
D
World of Darkraft
Recently Roma has become the happy owner of a new game World of Darkraft. This game combines elements of virtually all known genres, and on one of the later stages of the game Roma faced difficulties solving a puzzle. In this part Roma fights with a cunning enemy magician. The battle takes place on a rectangular field plaid $n × m$. Each cell contains one magical character: L, R or X. Initially all the squares of the field are "active". The players, Roma and enemy magician, take turns. Roma makes the first move. During a move a player selects one of the active cells. Then depending on the image in the character in the cell one of the following actions takes place: - L — magical waves radiate from the cell to the left downwards and to the right upwards along diagonal paths. All cells on the path of the waves (including the selected cell too) become inactive. The waves continue until the next inactive cell or to the edge of the field if there are no inactive cells on the way. - R — the magical waves radiate to the left upwards and to the right downwards. - X — the magical waves radiate in all four diagonal directions. If the next player cannot make a move (i.e., all cells are inactive), he loses. Roma has been trying to defeat the computer opponent for three days but he just keeps losing. He asks you to help him and determine whether it is guaranteed that he can beat the opponent, or he will have to hack the game.
Notice that the game can be separated into two independent: for only even and only odd coordinate sum cells. The player chooses the game he would like to make a move in. Thus, if we find a Grundy function for each of this games we can find the whole game result. Now let's observe only even cells, for instance. We can prove that every diagonally connected piece formed during the game is constructed as the intersection of the field rectangle with some diagonally oriented semi-planes, with exactly one semi-plane for every orientation. Let's enumerate every possible edges of semi-planes, which obviously are some diagonals of the grid. Now we have an enumeration of all possible pieces - by four diagonals being "edges" of this piece. Now we want to count the Grundy function for some piece. To do this we iterate over all cells in this piece and find XORs of all Grundy functions of pieces formed by making a move in each cell, then find a minimal exclused non-negative number of this set (see the page on the Sprague-Grundy theorem above). All these pieces are smaller than current, so we can use the DP to count the functions. To easily iterate over cells in the piece we can iterate over numbers of two diagonals the cell lies on (going right-and-upwards and right-and-downwards), as we have exactly the bounds on their numbers as the parameters of the piece. For each case of diagonals we also have to check if the piece is inside the field. So we have counted the Grundy functions for even- and odd-numbered cells separately. If they are equal, the answer is "LOSE", otherwise it's a "WIN" (see the theorem again). Complexity - $O((n + m)^{4}$ (number of pieces) $mn$ (number of pieces inside one piece and counting MEX)).
[ "dp", "games" ]
2,500
null
138
E
Hellish Constraints
Katya recently started to invent programming tasks and prepare her own contests. What she does not like is boring and simple constraints. Katya is fed up with all those "$N$ does not exceed a thousand" and "the sum of $a_{i}$ does not exceed a million" and she decided to come up with something a little more complicated. The last problem written by Katya deals with strings. The input is a string of small Latin letters. To make the statement longer and strike terror into the people who will solve the contest, Katya came up with the following set of $k$ restrictions of the same type (characters in restrictions can be repeated and some restrictions may contradict each other): - The number of characters $c_{1}$ in a string is not less than $l_{1}$ and not more than $r_{1}$. - ... - The number of characters $c_{i}$ in a string is not less than $l_{i}$ and not more than $r_{i}$. - ... - The number of characters $c_{k}$ in a string is not less than $l_{k}$ and not more than $r_{k}$. However, having decided that it is too simple and obvious, Katya added the following condition: a string meets no less than $L$ and not more than $R$ constraints from the above given list. Katya does not like to compose difficult and mean tests, so she just took a big string $s$ and wants to add to the tests all its substrings that meet the constraints. However, Katya got lost in her conditions and asked you to count the number of substrings of the string $s$ that meet the conditions (each occurrence of the substring is counted separately).
Let's start with the case when we have only one constriction - "$c$ $l$ $r$". For a string $s$ let's count an array $A$ with a length equal to $s$'s. $A[i] = 1$ if the suffix of $s$ starting at position $i$ satisfies the condition, and $A[i] = 0$ otherwise. So, we have $s$ and already counted $A$. What happens if we write another symbol $c'$ at the of $s$? Let $s' = s + c'$, $A' = A(s')$. If $c' \neq c$, than the part of $A'$ corresponding to everything beside the last symbol does not change. The last element is 1 or 0 depending on the condition (it's easy to count). If $c' = c$, some elements of $A$ might change. Let's denote the $i$-th occurence of $c$ in $s'$ counting from the end as $p_{i}(c)$ (symbols and occurences are enumerated from 1). If there are less then $i$ occurences, $p_{i}(c) = 0$. It's easy to see that elements from $A'[p_{l + 1}(c) + 1..p_{l}(c)]$ are incremented by 1, and elements from $A'[p_{r + 2}(c) + 1..p_{r + 1}(c)]$ are decremented by 1. It's also clear that as we add the symbols these invervals won't intersect for $l$ and $r$ separately (that is, every $A[i]$ will be incremented and decremented not more than one time each). Now we can have more then one constriction. We count $B[i]$ as the number of constrictions the suffix starting at $i$-th position satisfies. Clearly, $B[i]$ is the sum of $A[i]$'s for all constrictions. Also, we support the variable $C$ - number of $i$-s that satisfy $L \le B[i] \le R$. Similarly, we add symbols one after another and change $B[i]$. To do that, we must consider all the constrictions concerning new symbols and change the numbers in the intervals mentioned above. Changing the numbers is just iterating over symbols in the mentioned intervals and incrementing/decrementing $B[i]$'s (this procedure also lets us to support $C$ effectively). As the intervals for each constriction do not intersect, we will not change any $B[i]$ more than twice for each constriction, so the number of operations concerning any constriction is $O(n)$, giving total number of operations $O(nk)$. To get the answer, we just sum up $C$'s states after adding every symbol (as every substring will be a suffix of some prefix exactly one time). To find borders of every interval used (in which the $B[i]$'s are changed) we can enumerate all occurences of every symbols and count the borders easily, knowing how many times every symbol occured. The other way to do that is to keep two pointers for each constriction, showing where last intervals ended. On the next occurence we move these pointers to next occurences of corresponding symbol (however, we need to handle the case when not enough symbols have occured to changed $B$).
[ "brute force", "dp", "two pointers" ]
2,900
null
139
A
Petr and Book
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly $n$ pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Some days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week. Assuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.
If the total number of pages doesn't exceed the number of pages for Monday, the answer is Monday. Otherwise we can substract the Monday number from total and go on to Tuesday. If Tuesday isn't enough, we subtract and continue to Wednesday, and so on. We are sure that no more than N weeks will pass, as at least one page is read every week. Complexity - O(N).
[ "implementation" ]
1,000
null
139
B
Wallpaper
Having bought his own apartment, Boris decided to paper the walls in every room. Boris's flat has $n$ rooms, each of which has the form of a rectangular parallelepiped. For every room we known its length, width and height of the walls in meters (different rooms can have different dimensions, including height). Boris chose $m$ types of wallpaper to paper the walls of the rooms with (but it is not necessary to use all the types). Each type of wallpaper is sold in rolls of a fixed length and width (the length, naturally, shows how long the unfolded roll will be). In addition, for each type we know the price of one roll of this type. The wallpaper of each type contains strips running along the length of the roll. When gluing the strips must be located strictly vertically (so the roll cannot be rotated, even if the length is less than the width). Besides, a roll can be cut in an arbitrary manner, but the joints of glued pieces should also be vertical. In addition, each room should be papered by only one type of wallpaper. And pieces of the same roll cannot be used to paper different rooms. That is, for each room the rolls are purchased separately. Also, some rolls can be used not completely. After buying an apartment Boris is short of cash, so he wants to spend the minimum money on wallpaper. Help him.
Unluckily, the translated statement was quite tough even tougher to understand than the original statement. Say we fixed the roll type and the room. The only possible way to cut the roll is to cut it into vertical stripes with length equal to room's height (though it was said we can cut it any way we want, there were some conditions to fulfill, namely there could be no joints other than vertical). So we find the total width of stripes we can cut our roll into as the (length of the roll / height of the room) (rounded down) * (width of the roll). If the roll length is smaller than room height, we obviously can not use this type of rolls (though the statement said there must exist at least one type we can use). The number of rolls is (perimeter of the wall rooms) / (total stripes width) (rounded up). Then we just try all types for every room and sum the minimal costs. Complexity - O(MN).
[ "implementation", "math" ]
1,600
null
140
A
New Year Table
Gerald is setting the New Year table. The table has the form of a circle; its radius equals $R$. Gerald invited many guests and is concerned whether the table has enough space for plates for all those guests. Consider all plates to be round and have the same radii that equal $r$. Each plate must be completely inside the table and must touch the edge of the table. Of course, the plates must not intersect, but they can touch each other. Help Gerald determine whether the table is large enough for $n$ plates.
The plates must touch the edge of the table, so their centers must lie on the circle with radius R - r (see the figure). In case the plates have the largest radius possible for the given table, their centers are situated in the vertices of the regular polygon (n-gon) inscribed in this circle. The problem is to find the length of the side of the inscribed regular n-gon and to compare it with 2r. The formula for the length of the side is $a = 2(R - r)sin ( \pi / n)$, it can be easily deduced. For that you should consider the right triangle (the green one in the figure). In implementation, be careful with a case when the equality $r = (R - r)sin( \pi / n)$ (*) holds. Because of the computational error the right-hand side can get larger than the left-hand one. This can result in answer "NO" instead of "YES". Comparison in such cases should be performed with a small $ \epsilon $: $a + \epsilon < b$ instead of $a < b$ , $a < b + \epsilon $ instead of $a \le b$. A constant $ \epsilon $ should be chosen in such a way, that it is smaller than any possible difference between precise values of $a$ and $b$, if they are distinct. In particular, for computations by the formula (*), taking into account the constraints of the problem, this difference may be approximately $7 \cdot 10^{ - 7}$. So $ \epsilon = 10^{ - 7}$ is sufficient, but $ \epsilon = 10^{ - 6}$ is not. Once again, I focus your attention on the fact that the choice of $ \epsilon $ depends on specific formulas used for computations and comparisons. Different solutions can be accepted or not with the same $ \epsilon $.
[ "geometry", "math" ]
1,700
null
140
B
New Year Cards
As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has $n$ friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from $1$ to $n$ in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the $i$-th friend sent to Alexander a card number $i$. Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules: - He will never send to a firend a card that this friend has sent to him. - Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times. Alexander and each his friend has the list of preferences, which is a permutation of integers from $1$ to $n$. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card. Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible. Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.
This problem was just a problem on implementation. Note that a number of a send card is uniquely determined by a number of a friend and a set of cards Alexander already has at the moment. Consider the sample form the statement. 12 3 4 {1} -1 1 1 {1, 2}21 1 1 {3, 1, 2}3 3 1 3 {3, 1, 2, 4}33 1 3 The first column of the table contains sets of cards that Alexander gets after having received a next card each time. Numbers in the sets are written in order of Alexander's preferences. Each i-th of the next four columns contains numbers of cards that the i-th friend will get from the corresponding sets. Our goal is to choose for each friend the most preferred card in his column. Note that to determine by the current Alexander's set and the number of the friend a number of a card received by this friend, it is not necessary to know the whole Alexander's set. The two most preferable cards are sufficient. So for each time moment find the two most preferable cards for Alexander. Using them, determine which of them will be send to each friend (find the numbers in the columns). Then choose the element with the maximum priority in each column. We get the $O(n^{2})$ solution.
[ "brute force", "greedy", "implementation" ]
1,800
null
140
C
New Year Snowmen
As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made $n$ snowballs with radii equal to $r_{1}$, $r_{2}$, ..., $r_{n}$. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii $1$, $2$ and $3$ can be used to make a snowman but $2$, $2$, $3$ or $2$, $2$, $2$ cannot. Help Sergey and his twins to determine what \textbf{maximum} number of snowmen they can make from those snowballs.
Solution 1. Suppose that the answer is k. If there are more than k equal among the given numbers, it's clear that we can't use them all (we can't use equal snowballs in the same snowman). So we leave k snowballs of them, and discard the rest. Then, sort the radii in the non-decreasing order. After that every two snowballs with numbers i and k + i are different. Make snowmen of snowballs with numbers (1, k + 1, 2k + 1), (2, k + 2, 2k + 2), (3, k + 3, 2k + 3) and so on. If the total number of snowballs is not less than 3k, we always manage to make k snowmen. Now we can for the fixed k answer to the question, if k snowmen can be made, so k can be chosen by binary search. Solution 2. Count quantities of snowballs of each size, choose greedily the three largest quantities, take a snowball from each of them, make snowman and continue the process, while it's possible. Why is it correct? Let k be the answer for the problem. If there are quantities larger than k, we will count them as k, because other snowballs in them will not be used in any way. We prove the correctness of the algorithm using Proposition: if every quantity is $ \le k$ and the total quantity of snowballs is $ \ge 3k$, then it's possible to perform a step of the algorithm. Proposition is valid because by Pigeonhole principle there are no less than three non-zero quantities. If there are 3 (or more) quantities equal k, then k steps of the algorithm can be performed. If there is one or two such quantities, by the first step we certainly decrease them and come to a similar situation with k - 1. If there are no quantities equal k, after the first step we obtain quantities $ \le k - 1$, and their total sum is $ \ge 3(k - 1)$. Thus, we always can perform k steps and get the answer k. From the point of view of implementation, in the second solution it is easy to calculate quantities for each size of snowballs (using sorting and scaling). Use set to work with these quantities. The time for the both solutions is $O(n \log n)$.
[ "binary search", "data structures", "greedy" ]
1,800
null
140
D
New Year Contest
As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest. The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are $n$ problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.). Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the $i$-th problem will take $a_{i}$ minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the $i$-th problem always equals $a_{i}$ minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.). Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.
Solution 1 (greedy). Optimal order to solve problems is an increasing (non-decreasing) order by their difficulties. Problems solved before the New Year must be submitted at 0:00, ones solved after the New Year must be submitted just after finishing their solutions. Let us prove the optimality of this solution by the descent method. General scheme of reasoning is the following. Suppose you have the optimal order which is not the increasing order by problems' dificulties. Show that it is possible to come (to descend) from it to another variant, that is not less optimal. As a result you come to the sorted variant by such steps. So suppose that there is a pair of problems in the optimal solution such that their difficulties are going in decreasing order. Then there are consecutive problems with this property. Suppose they both are solved before the New Year. Then the swap of them doesn't influence the penalty (it doesn't decrease). If the both problems are solved after the New Year, then their contribution to the total penalty is $(T + a_{i}) + (T + a_{i} + a_{j})$, where T is a time of the beginning of solution for the first problem, $a_{i}$ is a time for the solution for the first problem, $a_{j} < a_{i}$ is a time for the solution for the second problem. After the swap of these problems we get the penalty $(T + a_{j}) + (T + a_{j} + a_{i})$, that is less than $(T + a_{i}) + (T + a_{i} + a_{j})$. It remains to consider cases when one of the consecutive problems that are in the "wrong" order "intersects the New Year". These cases can be treated similarly. In case when Gennady hasn't time to solve all problems, you should choose the maximal possible number of the easiest problems. Indeed, it doesn't make sense to solve a more difficult problem instead of an easy one: change of a larger $a_{i}$ to a smaller one doesn't spoil an answer. Rigorous proof can be obtained by the same descent method. Solution 2 (dynamic). First of all, as in the previous solution, choose the maximal number of the easiest problems that Gennady has time to solve. Discard the remaining tasks. Try every problem as one being solved in the moment of the New Year (0:00). Remaining problems (except it) must be divided into two sets. One is for solving before the New Year, and another is for solving after the New Year. Problems in the second set must be solved in increasing order of their difficulties (it is a well-known fact for everybody participating in contests by ACM rules). In the first set an order of solving is immaterial. Sort the given numbers in increasing order, and count the dynamics d[i][j][k] that is the smallest possible penalty, if there are the first i problems solved, j from them are solved after the New Year, and the last problem after the New Year was solved at the moment k. Note that the triple (i, j, k) uniquely determines the number of problems solved before the New Year and the total time needed for their solutions. After calculating the dynamics, recollect the problem being solved exactly at 0:00 (it was not taken into account in the dynamics). Try moments of time before the New Year when its solutions starts, and count remaining problems using the dynamics we already has.
[ "greedy", "sortings" ]
1,800
null
140
E
New Year Garland
As Gerald, Alexander, Sergey and Gennady are already busy with the usual New Year chores, Edward hastily decorates the New Year Tree. And any decent New Year Tree must be decorated with a good garland. Edward has lamps of $m$ colors and he wants to make a garland from them. That garland should represent a sequence whose length equals $L$. Edward's tree is $n$ layers high and Edward plans to hang the garland so as to decorate the first layer with the first $l_{1}$ lamps, the second layer — with the next $l_{2}$ lamps and so on. The last $n$-th layer should be decorated with the last $l_{n}$ lamps, $\textstyle\sum_{i=1}^{n}l_{i}=L.$ Edward adores all sorts of math puzzles, so he suddenly wondered: how many different ways to assemble the garland are there given that the both following two conditions are met: - Any two lamps that follow consecutively in the same layer should have different colors. - The sets of used colors in every two \textbf{neighbouring} layers must be different. We consider unordered sets (not multisets), where every color occurs no more than once. So the number of lamps of particular color does not matter. Help Edward find the answer to this nagging problem or else he won't manage to decorate the Tree by New Year. You may consider that Edward has an unlimited number of lamps of each of $m$ colors and it is not obligatory to use all $m$ colors. The garlands are considered different if they differ in at least one position when represented as sequences. Calculate the answer modulo $p$.
First, let us solve the subtask for one layer. It consists in finding the number of ways to compose a garland of lengths s with lamps of exactly k colors such that no two consecutive lamps have the same color. Variants different only by an order of colors are considered to be the same (we always can multiply by k! if we need). The solution of the subtasks is required only for $k \le s \le 5000$, so can be done by $O(s^{2})$-dynamics: a[s][k] = a[s-1][k-1] + a[s-1][k] * (k -1). They would be Stirling numbers of the second kind, if there was not a restriction about different colors of consecutive lamps. Then, calculate the dynamics d[i][j] that is a number of ways to compose a garland for the first i layers according to the rules, such that the i-th layer contains exactly j different colors. There will be about L positions (the total length of the garland), because every layer can't contain more colors than its length: $j \le l_{i}$ (!). All d[i][j] can be calculated in $O(L)$ operations, because sets of colors with different cardinalities are always different (!!). Indeed, put d[i][j] = $A_{m}^{j}$ * a[l[i]][j] * (sum of all d[i-1][k]), and then subtract variants with equal sets on the i-th and (i-1)-th layers. Coefficients $A_{m}^{j} = m(m - 1)... (m - j + 1)$ can be pre-calculated because they are required only for $j \le 5000$. Thus, the author's solutions works in $O(L + s^{2})$ ($L \le 10^{7}$, $s \le 5000$), and it doesn't use division (only addition and multiplication modulo p).
[ "combinatorics", "dp" ]
2,600
null
140
F
New Year Snowflake
As Gerald ..., in other words, on a New Year Eve Constantine prepared an unusual present for the Beautiful Lady. The present is the magic New Year snowflake that can make any dream come true. The New Year snowflake consists of tiny ice crystals, which can be approximately regarded as points on the plane. The beauty of the New Year snowflake is that it has a center of symmetry. This is a point such that for each crystal of the snowflake exists another crystal, symmetrical to it relative to that point. One of the crystals can be placed directly in the center of symmetry. While Constantine was choosing a snowflake among millions of other snowflakes, no less symmetrical and no less magical, then endured a difficult path through the drifts to the house of his mistress, while he was waiting with bated breath for a few long moments before the Beautiful Lady opens the door, some of the snowflake crystals melted and naturally disappeared. Constantine is sure that there were no more than $k$ of such crystals, because he handled the snowflake very carefully. Now he is ready to demonstrate to the Beautiful Lady all the power of nanotechnology and restore the symmetry of snowflakes. You are given the coordinates of the surviving snowflake crystals, given in nanometers. Your task is to identify all possible positions of the original center of symmetry.
Start with the check of a candidate symmetry center $(x_{c}, y_{c})$. Consider all points symmetrical to $(x_{i}, y_{i})$ with this center. They are of form $(2x_{c} - x_{i}, 2y_{c} - y_{i})$. It is necessary to check that they all except may be k of them are in the set ${(x_{i}, y_{i})}$. It can be done in $O(n \log n)$ by binary search (if the set was previously sorted). But there is more effective way of check in $O(n)$. Note that if initially the points $(x_{i}, y_{i})$ were sorted, say, by x-coordinate in increasing order and in case of equal x by y, then the points of the form $(2x_{c} - x_{i}, 2y_{c} - y_{i})$ will be sorted in the reverse order. The order doesn't depend on the center $(x_{c}, y_{c})$. So we can check the points $(2x_{c} - x_{i}, 2y_{c} - y_{i})$ in the order of sorting moving a pointer in the sorted array $(x_{i}, y_{i})$. It follows from the previous reasoning, that if a set has a symmetry center, then the first point (in the order of sorting) forms a pair with n'th, the second one with (n-1)-th and so on. Since up to k points have not a pair, try the first (k+1) points from the beginning and (k+1) from the end of the array. For every pair of these points find the midpoint and check it in $O(n)$. Asymptotics of the solution is $O(nk^{2})$.
[ "geometry", "sortings" ]
2,600
null
141
A
Amusing Joke
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. One night, when everyone went to bed, someone took all the letters of our characters' names. Then he may have shuffled the letters and put them in one pile in front of the door. The next morning it was impossible to find the culprit who had made the disorder. But everybody wondered whether it is possible to restore the names of the host and his guests from the letters lying at the door? That is, we need to verify that there are no extra letters, and that nobody will need to cut more letters. Help the "New Year and Christmas Men" and their friends to cope with this problem. You are given both inscriptions that hung over the front door the previous night, and a pile of letters that were found at the front door next morning.
It was enough for solving this problem to calculate for each letter: $a_{c}$ - amount of occurrences of letter $c$ in first and second strings in input, $b_{c}$ - amount of occurrences of letter $c$ in third string in input. If $\forall c:a_{c}=b_{c}$ the answer is "YES" else "NO".
[ "implementation", "sortings", "strings" ]
800
null
141
B
Hopscotch
So nearly half of the winter is over and Maria is dreaming about summer. She's fed up with skates and sleds, she was dreaming about Hopscotch all night long. It's a very popular children's game. The game field, the court, looks as is shown in the figure (all blocks are square and are numbered from bottom to top, blocks in the same row are numbered from left to right). Let us describe the hopscotch with numbers that denote the number of squares in the row, staring from the lowest one: 1-1-2-1-2-1-2-(1-2)..., where then the period is repeated (1-2). The coordinate system is defined as shown in the figure. Side of all the squares are equal and have length $a$. Maria is a very smart and clever girl, and she is concerned with quite serious issues: if she throws a stone into a point with coordinates $(x, y)$, then will she hit some square? If the answer is positive, you are also required to determine the number of the square. It is believed that the stone has fallen into the square if it is located \textbf{strictly} inside it. In other words a stone that has fallen on the square border is not considered a to hit a square.
Let's bust the "level" $0 \le i \le 10^{6}$, in which assumedly the stone could hit. Let's find the minimal number of square on this level. Then we can understand, how many squares there are on this level: one or two. Then we check with one or two ifs (if on this level two squares) if the stone is in corresponding square or not. If the stone is inside then output the answer. If we didn't find any square, where the stone is, output "-1".
[ "geometry", "math" ]
1,400
null
141
C
Queue
In the Main Berland Bank $n$ people stand in a queue at the cashier, everyone knows his/her height $h_{i}$, and the heights of the other people in the queue. Each of them keeps in mind number $a_{i}$ — how many people who are taller than him/her and stand in queue in front of him. After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order. When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number $a_{i}$. Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers $h_{i}$ — the heights of people in the queue, so that the numbers $a_{i}$ are correct.
Let's sort the pairs ($name_{i}$, $a_{i}$) by ascending of $a_{i}$. If there is an index i: $0 \le i < n$ that $a_{i} > i$, then answer is "-1". Otherwise the answer exists. We will iterate through the array of sorted pairs from left to right with supporting of vector of results $res$. Let on the current iteration $a_{i} = n - i$, then we must transfer the current man in the position $a_{i}$. It can be done in C++ with one line: res.insert(res.begin() + a[i], man);
[ "constructive algorithms", "greedy", "sortings" ]
1,800
null
141
D
Take-off Ramps
Vasya participates in a ski race along the $X$ axis. The start is at point $0$, and the finish is at $L$, that is, at a distance $L$ meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second. Besides, there are $n$ take-off ramps on the track, each ramp is characterized by four numbers: - $x_{i}$ represents the ramp's coordinate - $d_{i}$ represents from how many meters Vasya will land if he goes down this ramp - $t_{i}$ represents the flight time in seconds - $p_{i}$ is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second. Vasya is allowed to move in \textbf{any direction} on the $X$ axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that $x_{i} + d_{i} ≤ L$, that is, Vasya cannot cross the finish line in flight. \textbf{Vasya can jump from the ramp only in the positive direction of $X$ axis. More formally, when using the $i$-th ramp, Vasya starts gathering speed at point $x_{i} - p_{i}$, jumps at point $x_{i}$, and lands at point $x_{i} + d_{i}$. He cannot use the ramp in opposite direction.} Your task is to find the minimum time that Vasya will spend to cover the distance.
Let's generate the weighted directed graph of all ramps. The graphs' vertexes are the important points on the line $Ox$, there are points: $0, L, x_{i} - p_{i}, x_{i} + d_{i}$. The graphs' edges are the possible ramp jumps: transfer from point $x_{i} - p_{i}$ to point $x_{i} + d_{i}$ or transfer from vertex in neighboring vertexes (neighboring means that we get the next and previous important points on the line). The weights of these edges are correspondingly $p_{i} + t_{i}$ and $x_{v + 1} - x_{v}$, $x_{v} - x_{v - 1}$. We must note that in the transfers we can't get in the negative part of $Ox$, and we must delete this transfers. Then we must find and output the shortest path in this graph from vertex $0$ to $L$. This can be done, for example, with Dijkstra's algorithm for the sparse graphs.
[ "graphs", "shortest paths" ]
2,300
null
141
E
Clearing Up
After Santa Claus and his assistant Elf delivered all the presents and made all the wishes come true, they returned to the North Pole and found out that it is all covered with snow. Both of them were quite tired and they decided only to remove the snow from the roads connecting huts. The North Pole has $n$ huts connected with $m$ roads. One can go along the roads in both directions. The Elf offered to split: Santa Claus will clear up the wide roads and the Elf will tread out the narrow roads. For each road they decided who will clear it: Santa Claus or the Elf. To minimize the efforts they decided to clear the road so as to fulfill both those conditions: - between any two huts should exist \textbf{exactly one simple path} along the cleared roads; - Santa Claus and the Elf should clear the same number of roads. At this point Santa Claus and his assistant Elf wondered which roads should they clear up?
In this problem we must find the minimum spanning tree, in which the half of edges are marked with letter 'S'. There are $n - 1$ edges in this tree, because of it if $n$ is even then the answer is "-1". Let's delete from the given graph all S-edges. And there are $cnt$ components in obtained graph. For making this graph be connected we must add $cnt - 1$ edges or more, that's why if $cnt - 1 > (n - 1) / 2$ the answer is "-1". Then we find $cnt - 1$ S-edges, that we must add to the graph, so that it become connected. If $cnt - 1 < (n - 1) / 2$ then we will try to add in this set of edges another S-edges, so that the S-edges don't make circle. We must do all of this analogically to Kruskal's algorithm of finding a minimum spanning tree. If we could get a set of S-edges of $(n - 1) / 2$ elements, that there are exactly $cnt - 1$ edges and no S-circles, then the answer exists, Then we must add to this set $(n - 1) / 2$ M-edges, that forms with our set of edges the minimum spanning tree, it must be done analogically with Kruskal's algorithm.
[ "constructive algorithms", "dp", "dsu", "graphs" ]
2,300
null
142
A
Help Farmer
Once upon a time in the Kingdom of Far Far Away lived Sam the Farmer. Sam had a cow named Dawn and he was deeply attached to her. Sam would spend the whole summer stocking hay to feed Dawn in winter. Sam scythed hay and put it into haystack. As Sam was a bright farmer, he tried to make the process of storing hay simpler and more convenient to use. He collected the hay into cubical hay blocks of the same size. Then he stored the blocks in his barn. After a summer spent in hard toil Sam stored $A·B·C$ hay blocks and stored them in a barn as a rectangular parallelepiped $A$ layers high. Each layer had $B$ rows and each row had $C$ blocks. At the end of the autumn Sam came into the barn to admire one more time the hay he'd been stacking during this hard summer. Unfortunately, Sam was horrified to see that the hay blocks had been carelessly scattered around the barn. The place was a complete mess. As it turned out, thieves had sneaked into the barn. They completely dissembled and took away a layer of blocks from the parallelepiped's front, back, top and sides. As a result, the barn only had a parallelepiped containing $(A - 1) × (B - 2) × (C - 2)$ hay blocks. To hide the evidence of the crime, the thieves had dissembled the parallelepiped into single $1 × 1 × 1$ blocks and scattered them around the barn. After the theft Sam counted $n$ hay blocks in the barn but he forgot numbers $A$, $B$ и $C$. Given number $n$, find the minimally possible and maximally possible number of stolen hay blocks.
Due to quite low constraint this problem is easily solvable by brute-force. Without loss of generality assume that A <= B <= C. Then it is clear that A cannot exceed $\textstyle{\sqrt{n}}$, and, given A, B cannot exceed ${\sqrt{(}}n/A)$. Then all solution is just two cycles: for (long long a = 1; a*a*a <= n; ++a) if (n%a == 0){ for (long long b = a; b*b <= n/a; ++b) if ((n/a)%b == 0){ long long c = n/a/b; ... } } Since we assumed A <= B <= C, now it is not clear which parameter (A, B or C) is the height of haystack, so inside the cycle one should consider all three possibilities. For any N <= 10^9 the code inside the second loop runs no more than 25000 times, so this solution fits timelimit even for N <= 10^11 and maybe larger. Why it's so quick? It's because of the fact that number of divisors of arbitrary number N does not exceed about ${\dot{\sqrt{N}}}$. That's why all similar solutions and maybe some other streetmagic that has anything common with divisors of N, should get AC.
[ "brute force", "math" ]
1,600
null
142
B
Help General
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot had a major argument with the Fairy Godmother (there were rumors that the argument occurred after the general spoke badly of the Godmother's flying techniques. That seemed to hurt the Fairy Godmother very deeply). As the result of the argument, the Godmother put a rather strange curse upon the general. It sounded all complicated and quite harmless: "\underline{If the squared distance between some two soldiers equals to $5$, then those soldiers will conflict with each other!}" The drill exercises are held on a rectangular $n × m$ field, split into $nm$ square $1 × 1$ segments for each soldier. Thus, the square of the distance between the soldiers that stand on squares $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ equals exactly $(x_{1} - x_{2})^{2} + (y_{1} - y_{2})^{2}$. Now not all $nm$ squad soldiers can participate in the drill exercises as it was before the Fairy Godmother's curse. Unless, of course, the general wants the soldiers to fight with each other or even worse... For example, if he puts a soldier in the square $(2, 2)$, then he cannot put soldiers in the squares $(1, 4)$, $(3, 4)$, $(4, 1)$ and $(4, 3)$ — each of them will conflict with the soldier in the square $(2, 2)$. Your task is to help the general. You are given the size of the drill exercise field. You are asked to calculate the maximum number of soldiers that can be simultaneously positioned on this field, so that no two soldiers fall under the Fairy Godmother's curse.
This problem was not on derivation of the general formula m*n - (m*n)/2 (only this would be too simple for the second/fourth problem, isn't it?) but rather on accurate investigation of several cases. Unfortunately, many participants were very eager to submit the formula above, that's why there were so many hacks. I would say: this is not jury fault - pretests were made very weak intentionally, partially - to give you some space for hacks; but jury didn't presume there would be so many hacks. This is your fault of submitting unproven solutions. This is large risk given Codeforces rules, and this time risk-lovers were not lucky =) Ok, let's come to the solution. Without loss of generality let's assume m <= n. Then we have the following cases: 1. m = 1 x n fields. It is obvious that here the answer is n. 2. m = 2 x n >= 2 fields. Here the correct formula is 2*[2*(n/4) + min(n%4, 2)]. Why so? To see this draw the board for arbitrary n and draw all possible knight moves on it. In general, you'll see four not overlapping chains. Since you cannot place soldiers in the neighboring cells of any chain, then for a chain of length L the answer doesn't exceed (L - L/2). On the other hand, it is clear that the answer (L - L/2) is always possible since soldiers on different chains never hurt each other. If you consider fields with different remainders n%4, the formula above becomes clear. 3. m >= 3 x n >= 3 fields, except the cases 3 x 3, 3 x 5, 3 x 6 and 4 x 4. Here one may use general formula m*n - (m*n)/2. Why so? It is known (or becomes known with google) that for all such fields knight tours exists. Any knight tour is just a chain of lenght m*n, so by the logic above one cannot place more than m*n - (m*n)/2 soldiers on it. On the other hand, if one makes chessboard coloring of the field, it is clear that the answer above is always achievable if one chooses cells of one color as places for soldiers. So, formula above is proved. 4. Cases 3 x 3, 3 x 5, 3 x 6 and 4 x 4. Here we can't use the logic above to prove that the above formula is also right here. The easiest way is to verify it using brute-force or pen and paper. This concludes the solution.
[ "constructive algorithms", "greedy", "implementation" ]
1,800
null
142
C
Help Caretaker
Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse. He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space): \begin{center} {\begin{verbatim} ### ..# .#. #.. .#. ### .#. ### .#. ..# ### #.. \end{verbatim}} \end{center} Simon faced a quite natural challenge: placing in the given $n × m$ cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse. Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?
This is technical problem, one may use several approaches to solve it. Additional complexity is to restore the answer after you got it. 1. Dynamic programming "on the broken profile" - I'll not explain the approach here in detail, you can find explanation of it on the Internet or even on Codeforces. Worth to point out, care should be taken of your code memory usage. 2. Search with memorization - one jury solution uses logic like DP with usual (not broken) profile: move by rows (or by columns), try all possible T placements such that upper cell of T's is in the given row and run the same search procedure for the next raw, passing the state of the two last filled rows of the board to it. For the given board state save the answer recursive function returned (max number of T's one may place on the not-yet-filled part of the board) and use it in the future as the answer for the given state. This requires only O(n*2^(2^m)) of memory and works about 2 sec. on maxtest 9 x 9. 3. Branch and bound. Another jury solution recursively tries all possible tilings of the board with T's. If on some step it occured that number of T's on the board plus number of T's one can theoretically place on the remaining part of the board doesn't exceed existing best answer - trim this node. Such solution is the easiest to code and it works only 0.5 sec. on maxtest, however it is not obvious from the very beginning. 4. Precalc - not to write a lot of code (applying DP or search with memorization) and not to deal with possible time/memory limits, some participants did the right thing: using the third approach, just precalculated answers for large (or for all possible) inputs.
[ "brute force", "dp" ]
2,300
null
142
D
Help Shrek and Donkey 2
Having learned (not without some help from the Codeforces participants) to play the card game from the previous round optimally, Shrek and Donkey (as you may remember, they too live now in the Kingdom of Far Far Away) have decided to quit the boring card games and play with toy soldiers. The rules of the game are as follows: there is a battlefield, its size equals $n × m$ squares, some squares contain the toy soldiers (the green ones belong to Shrek and the red ones belong to Donkey). Besides, each of the $n$ lines of the area contains not more than two soldiers. During a move a players should \textbf{select} not less than $1$ and not more than $k$ soldiers belonging to him and make them either attack or retreat. An attack is moving all of the selected soldiers along the lines on which they stand \textbf{in the direction of} an enemy soldier, if he is in this line. If this line doesn't have an enemy soldier, then the selected soldier on this line can move in any direction during the player's move. Each selected soldier has to move at least by one cell. Different soldiers can move by a different number of cells. During the attack the soldiers are not allowed to cross the cells where other soldiers stand (or stood immediately before the attack). It is also not allowed to go beyond the battlefield or finish the attack in the cells, where other soldiers stand (or stood immediately before attack). A retreat is moving all of the selected soldiers along the lines on which they stand \textbf{in the direction from} an enemy soldier, if he is in this line. \underline{The other rules repeat the rules of the attack.} For example, let's suppose that the original battlefield had the form (here symbols "G" mark Shrek's green soldiers and symbols "R" mark Donkey's red ones): \begin{center} {\begin{verbatim} -G-R- -R-G- \end{verbatim}} \end{center} Let's suppose that $k = 2$ and Shrek moves first. If he decides to attack, then after his move the battlefield can look like that: \begin{center} {\begin{verbatim} --GR- --GR- -G-R- -RG-- -R-G- -RG-- \end{verbatim}} \end{center} If in the previous example Shrek decides to retreat, then after his move the battlefield can look like that: \begin{center} {\begin{verbatim} G--R- G--R- -G-R- -R--G -R-G- -R--G \end{verbatim}} \end{center} On the other hand, the followings fields cannot result from Shrek's correct move: \begin{center} {\begin{verbatim} G--R- ---RG --GR- -RG-- -R-G- GR--- \end{verbatim}} \end{center} Shrek starts the game. To make a move means to attack or to retreat by the rules. A player who cannot make a move loses and his opponent is the winner. Determine the winner of the given toy soldier game if Shrek and Donkey continue to be under the yellow pills from the last rounds' problem. Thus, they always play optimally (that is, they try to win if it is possible, or finish the game in a draw, by ensuring that it lasts forever, if they cannot win).
Solving this problem involves two basic steps: firstly, to recognize that we have nothing else than generalised version of Nim and secondly, to solve it. The first part is not difficult: assuming we don't have rows with soldiers of only one color (in which case the game usually becomes trivial, since one or both players may play infinitely long), let the number of cells between two soldiers in every non-empty line be the size of the corresponding piles in nim. Then attack according to the rules of the given game is the move in the corresponding nim that allows you to take as much as you like stones from at most k piles (but at least 1 stone should be taken). Such generalized nim is called Moore's nim-k, and we should solve it to find the winner in the initial game. As any source you may google (except Russian Wikipedia) shows, solution to the Moore's nim-k is the following: Let's write binary expansions of pile sizes, and for any position check that sum of digits on the given position in all expansions is divisible by k+1. If this holds for all positions - then the winner is the second player, otherwise - the first player. Proof of the fact may be found here: http://www.stat.berkeley.edu/~peres/yuvalweb/gath9.pdf Let's consider the following case for k = 2: R-G-- R--G- R---G R---G Corresponding 4-piles nim-2 for this test is (1, 2, 3, 3). After writing binary expansions of piles sizes we get 01 10 11 11 Sums of digits in both positions (3) are divisible by k+1=3, so here Second wins. But this is still not full solution to the initial game, because we forget about retreat possibility. But it is simple here: only player losing the game in which only attacks allowed may want to retreat (winner just plays corresponding nim by attacking). But if loser retreats, winner just restores initial position attacking in the corresponding rows. And since loser cannot retreat infinitely, he cannot improve his win chances with retreat moves. That's it. And finally, don't forget about tests like: 2 2 2 GG RR Answer: Second All such tricky cases were in pretests.
[ "games" ]
2,600
null
142
E
Help Greg the Dwarf 2
Greg the Dwarf has been really busy recently with excavations by the Neverland Mountain. However for the well-known reasons (as you probably remember he is a very unusual dwarf and he cannot stand sunlight) Greg can only excavate at night. And in the morning he should be in his crypt before the first sun ray strikes. That's why he wants to find the shortest route from the excavation point to his crypt. Greg has recollected how the Codeforces participants successfully solved the problem of transporting his coffin to a crypt. So, in some miraculous way Greg appeared in your bedroom and asks you to help him in a highly persuasive manner. As usual, you didn't feel like turning him down. After some thought, you formalized the task as follows: as the Neverland mountain has a regular shape and ends with a rather sharp peak, it can be represented as a cone whose base radius equals $r$ and whose height equals $h$. The graveyard where Greg is busy excavating and his crypt can be represented by two points on the cone's surface. All you've got to do is find the distance between points on the cone's surface. The task is complicated by the fact that the mountain's base on the ground level and even everything below the mountain has been dug through by gnome (one may wonder whether they've been looking for the same stuff as Greg...). So, one can consider the shortest way to pass not only along the side surface, but also along the cone's base (and in a specific case both points can lie on the cone's base — see the first sample test) Greg will be satisfied with the problem solution represented as the length of the shortest path between two points — he can find his way pretty well on his own. He gave you two hours to solve the problem and the time is ticking!
This problem was "just" about finding the shortest path on a cone. Unfortunately, even though jury lowered precision requirements to 10^-6 and included all possible general cases in pretests, nobody tried it =( For solution, let's consider all possible cases of two points on the cone surface (including its basement): 1. Both points on the basement. Here it is clear that Euclidean distance between points is the answer to our problem. 2. Both points on the lateral surface. One may think that optimal path is also always lies on the lateral surface. In this case it is easy to find length of an optimal path from geometric considerations (by considering loft of the lateral surface). But 10-th pretest disproves that it is always optimal: 100 100 99 0 1 -99 0 1 Answer: 202.828427124746210 So, optimal path may go through the basement. In this case it has two points that lie at the same time on the basement and on the lateral surface (let's call them A' and B'), so length of the path through this points is easy to find by adding length of the three different segments - AA', A'B' and B'B. So the problem is reduced to finding optimal positions of A' and B'? Let's assume that polar angle of the first point in XOY plane is a1 (0 <= a1 < 2*PI) and polar angle of the second point is a2 (0 <= a2 < 2*PI). Length of the shortest path between A and B passing through the points A' and B' (AA' + A'B' + B'B) is some function of two arguments that we want to minimize - f (a1, a2). One may minimize it using, for example, grid or any other suitable numerical approach. 3. One point on the basement and another point on the lateral surface. This case is similar to the previous one - optimal path passes some point C' on the "brink" whose optimal polar angle we are to find. In this case we optimize function of one argument g(polar angle(C')) = AC' + C'B.
[ "geometry" ]
3,000
null
143
A
Help Vasilisa the Wise 2
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that. The box's lock looks as follows: it contains $4$ identical deepenings for gems as a $2 × 2$ square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below. The box is accompanied with $9$ gems. Their shapes match the deepenings' shapes and each gem contains one number from $1$ to $9$ (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below. Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
There are many ways of solving this easiest problem of the contest. I list them in the order of increasing realization difficulty: 1. If you use C++. Take permutation (1, 2, ..., 9). Suppose elements 1-4 are numbers we're looking for. Use next_permutation() to generate all possible combinations of numbers and just check that all conditions are met. 2. Pure brute-force - just 4 nested for() cycles for each unknown number. Here one should not forget to check that all numbers are pairwise different. This takes additional 6 comparisons. 3. One may note that, given the first number in the left upper cell, one may restore rest of the numbers in O(1). So, just check 9 numbers in the first cell (let it be x), restore other numbers from the given conditions: (x, a) (b, c) a = r1-x, b = c1-x, c = r2-b = r2-c1+x and check that they all lie in [0..9] and rest of the conditions are met. 4. O(1) solution - one may derive it from the previous approach: since x+c = d1 => 2*x + r1 - c1 = d1 => x = (d1+c1-r1)/2 So, you find x, check that it is in [0..9], restore all other numbers as in the previous approach and check that all conditions are met.
[ "brute force", "math" ]
1,000
null
143
B
Help Kingdom of Far Far Away 2
For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to $0.01$, and not up to an integer. The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows: - A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point). - To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678 - In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply \textbf{discarded} (they are not rounded: see sample tests). - When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets. - Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)". The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?
This was purely technical problem. String type is the best way to store the number. The main steps to get this problem is just to follow problem statement on how a number in the financial format is stored: 1. Divide the number in the input into integer and fractional parts looking for position of the decimal point in the input number (if input number doesn't have decimal point - assume fractional part is empty string) 2. Insert commas into integer part. This is done with one for() / while() cycle 3. Truncate/add zeroes to length 2 in the fractional part 4. Form the answer [integer part].[fractional part]. If initial number had minus in the beginning - add brackets to both sides of the answer.
[ "implementation", "strings" ]
1,200
null
144
A
Arrival of the General
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all $n$ squad soldiers to line up on the parade ground. By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the \textbf{first} and the \textbf{last} soldier are important. For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong. Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.
It's clear that the leftmost soldier with the maximum height should be the first and the rightmost soldier with the minimum height should be the last. Thus we will minimize the number of swaps. And the answer is number of leftmost soldier with the maximum height$- 1 + n -$number of rightmost soldier with the minimum height. And if the leftmost soldier with the maximum height is more right then the rightmost soldier with the minimum height we should subtract one from the answer.
[ "implementation" ]
800
null
144
B
Meeting
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits. Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number $r_{i}$ — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to $r_{i}$, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points $(x_{1}, y_{1})$ and $(x_{2}, y_{2})$ is $\sqrt{(x_{1}-x_{2})^{2}+(y_{1}-y_{2})^{2}}$ Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place. The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.
Let's try to check all integer points of the table perimeter and add to the answer such of them that don't cover by circles of radiators. Let $x_{a} < x_{b}$ and $y_{a} < y_{b}$, and if it's not true then swap $x_{a}$ and $x_{b}$, $y_{a}$ and $y_{b}$. So generals sit in the next integer points: $(x_{a}, y), (x_{b}, y), (x, y_{a}), (x, y_{b})$, where $x_{a} \le x \le x_{b}$ and $y_{a} \le y \le y_{b}$. We should be attentive when we count the generals who sits in points: $(x_{a}, y_{a}), (x_{a}, y_{b}), (x_{b}, y_{a}), (x_{b}, y_{b})$, that don't count them twice.
[ "implementation" ]
1,300
null
144
C
Anagram Search
A string $t$ is called an anagram of the string $s$, if it is possible to rearrange letters in $t$ so that it is identical to the string $s$. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not. The string $t$ is called a substring of the string $s$ if it can be read starting from some position in the string $s$. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". You are given a string $s$, consisting of lowercase Latin letters and characters "?". You are also given a string $p$, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string $p$ from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string $p$ = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string $s$ (identical substrings must be counted in the answer several times).
Let's count number of each letter in the second string and save it, for example, in array $a[1..26]$. For the first strings' prefix of length $n$, where $n$ is the length of second string, (it's the first substring) we count number of each letter in array $b[1..26]$. We don't count characters ``\texttt{?}''. If there are $b[i] \le a[i]$ for all $i$, then it's good substring. Then go to the second substring: subtract from the array $b$ the first character: $b[s[1] - 'a' + 1] -$ and add $n + 1$ character: $b[s[n + 1] - 'a' + 1] + +$. If some of these characters is ``\texttt{?}'' then we shouldn't do for it the subtraction or addition. Then repeat the showed check and go to the next substring. Let's repeat this procedure for all substrings of length $n$.
[ "implementation", "strings" ]
1,500
null
144
D
Missile Silos
A country called Berland consists of $n$ cities, numbered with integer numbers from $1$ to $n$. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance $l$ from the capital. The capital is located in the city with number $s$. The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly $l$. Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
$d[i]$ --- the minimum distance from vertex $s$ to vertex $i$, that counted by algorithm of Dijkstra. "et's count the number of points on each edge of the graph that are on the distance $l$ form the vertex $s$ (and $l$ --- the minimum distance from these points to $s$). For edge (u, v): if $d[u] < l$ and $l - d[u] < w(u, v)$ and $w(u, v) - (l - d[u]) + d[v] > l$ then add to the answer the point on this edge, the distance of which to the vertex $u$ is $l - d[u]$; if $d[v] < l$ and $l - d[v] < w(u, v)$ and $w(u, v) - (l - d[v]) + d[u] > l$ then add to the answer the point on this edge, the distance of which to the vertex $v$ is $l - d[v]$; if $d[v] < l$ and $d[u] < l$ and $d[u] + d[v] + w(u, v) = 2 * l$ then add to the answer the point on this edge, the distance of which to the vertex $v$ is $l - d[v]$ and to the vertex $u$ is $l - d[u]$. And if $d[i] = l$, then let's add to the answer this point.
[ "data structures", "dfs and similar", "graphs", "shortest paths" ]
1,900
null
144
E
Competition
The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an $n$-degree staircase as a square matrix $n × n$ containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase). The squares of the $n$-degree staircase contain $m$ sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones. You are given positions of $m$ sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts.
It's clear that the nearest squares of the secondary diagonal to some sportsman form the "segment" of the squares of the secondary diagonal. Let's write these segments for each sportsman. Let's consider sportsmen so that we should compare to each sportsman excactly one square of the secondary diagonal from his "segment" and to each square of the secondary diagonal no more then one sportsman. It's clear that sportsmen can reach theirs squares without occupying the same square simultaneously with another sportsman. We should maximize the number of choosen sportsmen. And solution of this reformulated problem is greedy.
[ "data structures", "greedy" ]
2,200
null
145
A
Lucky Conversion
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has two strings $a$ and $b$ of the same length $n$. The strings consist only of lucky digits. Petya can perform \underline{operations} of two types: - replace any one digit from string $a$ by its opposite (i.e., replace $4$ by $7$ and $7$ by $4$); - swap any pair of digits in string $a$. Petya is interested in the minimum number of operations that are needed to make string $a$ equal to string $b$. Help him with the task.
You need to find two numbers: $c47$ (number of such positions $i$, that $a_{i} = 4$ and $b_{i} = 7$) and $c74$ (number of such positions that $a_{i} = 7$ and $b_{i} = 4$). After that the result will be $max(c47, c74)$ (because you need to obtain $min(c47, c74)$ swaps, the rest $max(c47, c74) - min(c47, c74)$ are editings of digits).
[ "greedy", "implementation" ]
1,200
null
145
B
Lucky Number 2
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya loves long lucky numbers very much. He is interested in the \textbf{minimum} lucky number $d$ that meets some condition. Let $cnt(x)$ be the number of occurrences of number $x$ in number $d$ as a substring. For example, if $d = 747747$, then $cnt(4) = 2$, $cnt(7) = 4$, $cnt(47) = 2$, $cnt(74) = 2$. Petya wants the following condition to fulfil simultaneously: $cnt(4) = a_{1}$, $cnt(7) = a_{2}$, $cnt(47) = a_{3}$, $cnt(74) = a_{4}$. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Let we have some string result $s$. Let then delete all repititions, i. e. while we have some pair adjacent equal digits, we delete one of them. Let call formed string a root. In root there will be no adjacent equal digits, so $|cnt(47) - cnt(74)| \le 1$. So, if $|a_{3} - a_{4}| > 1$, then answer is "-1". Now, if we would know the root, that will be used in our result, we can create result. You can see, that if $a_{3} = a_{4}$, then root must be $47474747...474$ or $747474...747$. If $a_{3} < a_{4}$, then root is $74747474....74$. If $a_{3} > a_{4}$, then root is $474747...47$. Length of the root must be such that it fulfill $a_{3}$ and $a_{4}$. Now, when you have a root, you can build result. You just need to find first occurrence of $4$ in root and insert the rest of $4$ from $a_{1}$ right next to that digit. To add the rest of $7$, you need to find last occurrence of $7$ in root. The answer does not exits if, after constructing the root, you have used more $4$ than $a_{1}$ or more $7$ than $a_{2}$.
[ "constructive algorithms" ]
1,800
null
145
C
Lucky Subsequence
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has sequence $a$ consisting of $n$ integers. The subsequence of the sequence $a$ is such subsequence that can be obtained from $a$ by removing zero or more of its elements. Two sequences are considered different if index sets of numbers included in them are different. That is, the values ​of the elements ​do not matter in the comparison of subsequences. In particular, any sequence of length $n$ has exactly $2^{n}$ different subsequences (including an empty subsequence). A subsequence is considered lucky if it has a length exactly $k$ and does not contain two identical lucky numbers (unlucky numbers can be repeated any number of times). Help Petya find the number of different lucky subsequences of the sequence $a$. As Petya's parents don't let him play with large numbers, you should print the result modulo prime number $1000000007$ $(10^{9} + 7)$.
As you probably know, the number of lucky numbers in range $[1;10^{9}]$ is $1022$. We use this fact to solve problem. Let $C[i]$ - number of occurrences of $i$-th lucky number in array $a$. Now we schould calculate DP with parameters DP[pos][cnt] - what is the number of subsequences that we use lucky numbers up to $pos$-th and our subsequence contains exactly $cnt$ lucky number. If we are on state DP[pos][cnt] we can do two things: do not use $pos$-th lucky number (and do DP[pos+1][cnt] += DP[pos][cnt]) or use $pos$-th lucky (and do DP[pos+1][cnt+1] += DP[pos][cnt]*C[pos], because you have C[pos] of $pos$-th lucky number). Now we need to find total result. To do that we iterate through the number of lucky numbers in our subsequence $i$. Then you need to multiple that number by $C(count_{unlucky}, k - i)$ (bin. coefficient), where $count_{unlucky}$ - number of unlucky numbers of sequence. Sum for all such $i$ will be the total result.
[ "combinatorics", "dp", "math" ]
2,100
null
145
D
Lucky Pair
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya has an array $a$ of $n$ integers. The numbers in the array are numbered starting from $1$. Unfortunately, Petya has been misbehaving and so, his parents don't allow him play with arrays that have many lucky numbers. It is guaranteed that no more than $1000$ elements in the array $a$ are lucky numbers. Petya needs to find the number of pairs of non-intersecting segments $[l_{1};r_{1}]$ and $[l_{2};r_{2}]$ ($1 ≤ l_{1} ≤ r_{1} < l_{2} ≤ r_{2} ≤ n$, all four numbers are integers) such that there's no such lucky number that occurs simultaneously in the subarray $a[l_{1}..r_{1}]$ and in the subarray $a[l_{2}..r_{2}]$. Help Petya count the number of such pairs.
The main point of this problem is that number of lucky numbers in array is $ \le 1000$. Imagine that there is array of $1000$ number in range $[1;1000]$ each, and you want to find number of such pairs that there is no equal number in both segments. How to solve this problem? Let we have fixed left point of right segment, let it be $i$. The you should iterate through all $j$ $(i \le j)$ - right point of right segment. If you have some fixed right segment $[i;j]$, then there is some set $S$ of numbers that are in that right segment. So, segment $[0;i - 1]$ will be divided in some subsegments that don't contain any number from $S$. For example, let $S$ = ${1, 2, 3}$ and segment $[0;i - 1]$ is $[2, 4, 2, 3, 6, 5, 7, 1]$, then there will be such subsegments (0-based numeration): $[1;1]$, $[4;6]$. Of course, any subsegment of that subsegments will be good too: they dont contain any number from $S$, too. So, you can keep in $set$ (or some structure like $set$) all good subsegments and keep number of all good subsegments in $[0;i - 1]$. When you iterate $j$ from $i$ to $n - 1$, you will add some numbers to $S$. When you add some number in $S$, you should add all occurrences of that number in subarray $[0;i]$. Notice, that when some number is already in $S$, you don't need to look at that numbers. So, for fixed $i$ you should do $O(n * logn)$ operations - any number from $a[0;i - 1]$ will be added at most once to $set$. Now, we have not only lucky numbers. So, the problem is the same, but between number there are some "bad" numbers - in this case this are unlucky numbers. But, you can notice, that if we will fix only such $i$ that $a[i]$ is lucky and iterate $j$ only such that $a[j]$ is lucky then you can calculate result in the same way that in simpler problem. But that method allow you to only count such pairs that right one contains some lucky number. So you also need to count other ones. To do so you can fix some $i$ - left point of right segment, such that $a[i]$ is unlucky. Let $F(i)$ equals to minimum such $j$ $(j > i)$ that $a[i]$ is lucky. Then there are $F(i) - i$ ways to expand right segment. All such right segments doesn't contain any lucky number. So any left segment will be good. And there are $i * (i + 1) / 2$ of such left segments (0-based).
[ "combinatorics", "data structures", "implementation" ]
2,900
null
145
E
Lucky Queries
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya brought home string $s$ with the length of $n$. The string only consists of lucky digits. The digits are numbered from the left to the right starting with $1$. Now Petya should execute $m$ queries of the following form: - \underline{switch $l$ $r$} — "switch" digits (i.e. replace them with their opposites) at all positions with indexes from $l$ to $r$, inclusive: each digit $4$ is replaced with $7$ and each digit $7$ is replaced with $4$ $(1 ≤ l ≤ r ≤ n)$; - \underline{count} — find and print on the screen the length of the longest non-decreasing subsequence of string $s$. Subsequence of a string $s$ is a string that can be obtained from $s$ by removing zero or more of its elements. A string is called non-decreasing if each successive digit is not less than the previous one. Help Petya process the requests.
To solve this problem you need to handle segment tree with following information: n4: number of $4$-digits in node range. n7: number of $7$-digits in node range. n47: maximum non-decreasing subsequence in range. n74: maximum non-increasing subsequence in range. When we reverse digits in some node we just swap(n4, n7), swap(n47, n74). When we update node we keep n4(father) = n4(left_son) + n4(right_son), n47(father) = max(n47(left_son) + n7(right_son), n4(left_son) + n47(right_son), n4(left_son) + n7(right_son)). Then for each $count$ query result is $n47$.
[ "data structures" ]
2,400
null
146
A
Lucky Ticket
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. Its length equals $n$ ($n$ is always even). Petya calls a ticket lucky if the ticket's number is a lucky number and the sum of digits in the first half (the sum of the first $n / 2$ digits) equals the sum of digits in the second half (the sum of the last $n / 2$ digits). Check if the given ticket is lucky.
In this problem everything is obvious: if all digits are lucky and sum of the digits of the first half equals to the sum of the digits of the second half, then answer is YES, in other case - NO. All this can be checked by single loop through all the digits.
[ "implementation" ]
800
null
146
B
Lucky Mask
\underline{Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits \textbf{4} and \textbf{7}. For example, numbers \textbf{47}, \textbf{744}, \textbf{4} are lucky and \textbf{5}, \textbf{17}, \textbf{467} are not.} Petya calls a \underline{mask} of a positive integer $n$ the number that is obtained after successive writing of all lucky digits of number $n$ from the left to the right. For example, the mask of number $72174994$ is number $7744$, the mask of $7$ is $7$, the mask of $9999047$ is $47$. Obviously, mask of any number is always a lucky number. Petya has two numbers — an arbitrary integer $a$ and a lucky number $b$. Help him find the minimum number $c$ $(c > a)$ such that the mask of number $c$ equals $b$.
You can see that, in worst case, the answer will be equal to $177777$. It can't be greater. So, only thing you need is to write some function $F(x)$ which will return mask of the $x$. After that you need to write such kind of code: $x$ = $a + 1$; while ($F(x)$ is not equal to $b$) increase $x$; and $x$ will contain the answer.
[ "brute force", "implementation" ]
1,300
null
148
A
Insomnia cure
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every $k$-th dragon got punched in the face with a frying pan. Every $l$-th dragon got his tail shut into the balcony door. Every $m$-th dragon got his paws trampled with sharp heels. Finally, she threatened every $n$-th dragon to call her mom, and he withdrew in panic. How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of $d$ dragons?
The number of dragons D can be quite small, so the problem can be solved in a straightforward way, by iterating over dragons 1 through D and checking each dragon individually. Time complexity of such solution is O(D). There exists a smarter solution with O(1) complexity, based on inclusion-exclusion principle. You'll have to count the numbers of dragons which satisfy at least one, two, three or four of the damage conditions $N_{i}$, i.e., dragons who have index divisible by LCM of the corresponding sets of numbers. Remember that the number of numbers between 1 and D which are divisible by T equals $D / T$. Finally, the number of dragons that get damaged equals $N_{1} - N_{2} + N_{3} - N_{4}$. You'd have to use this method if the total number of dragons was too large for iterating over it.
[ "constructive algorithms", "implementation", "math" ]
800
null
148
B
Escape
The princess is going to escape the dragon's cave, and she needs to plan it carefully. The princess runs at $v_{p}$ miles per hour, and the dragon flies at $v_{d}$ miles per hour. The dragon will discover the escape after $t$ hours and will chase the princess immediately. Looks like there's no chance to success, but the princess noticed that the dragon is very greedy and not too smart. To delay him, the princess decides to borrow a couple of bijous from his treasury. Once the dragon overtakes the princess, she will drop one bijou to distract him. In this case he will stop, pick up the item, return to the cave and spend $f$ hours to straighten the things out in the treasury. Only after this will he resume the chase again from the very beginning. The princess is going to run on the straight. The distance between the cave and the king's castle she's aiming for is $c$ miles. How many bijous will she need to take from the treasury to be able to reach the castle? If the dragon overtakes the princess at exactly the same moment she has reached the castle, we assume that she reached the castle before the dragon reached her, and doesn't need an extra bijou to hold him off.
In this problem it was enough to simulate the sequence of events that happen on the line between the cave and the castle. My solution focused on two types of evens - "the dragon is in the cave and sets off after the princess" and "the dragon and the princess are at the same coordinate"; in this case it's enough to keep track of time and princess' coordinate, no need to store dragon's one. The first type of event happens for the first time at time T, when the princess' coordinate is $T * V_{p}$. If at this time she has already reached the castle, no bijous are needed. Otherwise we can start iterating. The time between events of first and second type equals the princess' coordinate at the moment of first event, divided by $V_{d} - V_{p}$. Adjust the princess' coordinate by the distance she will cover during this time and check whether she reached the castle again. If she didn't, she'll need a bijou - increment the number of bijous required. The second part of the loop processes the return of the dragon, i.e., the transition from second type of event to the first one. The time between the events equals princess' new coordinate, divided by the dragon's speed, plus the time of straightening things out in the treasury. Adjust princess' coordinate again and return to the start of the loop (you don't need to check whether the princess reached the castle at this stage, since it doesn't affect the return value). The complexity of the algorithm can be estimated practically: the number of loop iterations will be maximized when dragon's speed and distance to the castle are maximum, and the rest of parameters are minimum. This results in about 150 bijous and the same number of iterations. You'll also need to check for the case $V_{p} \ge V_{d}$ separately - the dragon can be old and fat and lazy, and he might never catch up with the princess.
[ "implementation", "math" ]
1,500
null
148
D
Bag of mice
The dragon and the princess are arguing about what to do on the New Year's Eve. The dragon suggests flying to the mountains to watch fairies dancing in the moonlight, while the princess thinks they should just go to bed early. They are desperate to come to an amicable agreement, so they decide to leave this up to chance. They take turns drawing a mouse from a bag which initially contains $w$ white and $b$ black mice. The person who is the first to draw a white mouse wins. After each mouse drawn by the dragon the rest of mice in the bag panic, and one of them jumps out of the bag itself (the princess draws her mice carefully and doesn't scare other mice). \textbf{Princess draws first.} What is the probability of the princess winning? If there are no more mice in the bag and nobody has drawn a white mouse, the dragon wins. Mice which jump out of the bag themselves are not considered to be drawn (do not define the winner). Once a mouse has left the bag, it never returns to it. Every mouse is drawn from the bag with the same probability as every other one, and every mouse jumps out of the bag with the same probability as every other one.
Initially this problem was a boring homework one about drawing balls out of the bag. But seriously, do you think a dragon would have something so mundane as a bag of balls in his cave? And he definitely could find some use for a bag of mice - for example, using them to scare the princess or as a snack. If mice were balls and never jumped out of the bag, the problem would be doable in a single loop. Suppose that at some step we have W white and B black mice left in the bag, and the probability to get into this state is P (initially W and B are input values, and P = 1). The absolute probability to get a white mouse at this step is $P * W / (B + W)$ (the probability of getting to this state, multiplied by the conditional probability of getting white mouse). If it's princess' turn to draw, this probability adds to her winning probability, otherwise her winning probability doesn't change. To move to the next iteration, we need the game to continue, i.e., a black mouse to be drawn on this iteration. This means that the number of black mice decreases by 1, and the probability of getting to the next iteration is multiplied by $B / (B + W)$. Once we've iterated until we're out of black mice, we have the answer. Unfortunately, the mice in the bag behave not as calmly as the balls. This adds uncertainty - we don't know for sure what state we will get to after the dragon's draw. We'll need a recursive solution to handle this (or dynamic programming - whichever one prefers). When we solve a case for (W, B), the princess' and the dragon's draws are processed in a same way, but to process the mouse jumping out of the bag, we'll need to combine the results of solving subproblems (W, B - 3) and (W - 1, B - 2). The recursive function of the reference solution is: map<pair<int, int>, double> memo; double p_win_1_rec(int W, int B) { if (W <= 0) return 0; if (B <= 0) return 1; pair<int, int> args = make_pair(W, B); if (memo.find(args) != memo.end()) { return memo[args]; } // we know that currently it's player 1's turn // probability of winning from this draw double ret = W * 1.0 / (W + B), cont_prob = B * 1.0 / (W + B); B--; // probability of continuing after player 2's turn cont_prob *= B * 1.0 / (W + B); B--; // and now we have a choice: the mouse that jumps is either black or white if (cont_prob > 1e-13) { double p_black = p_win_1_rec(W, B - 1) * (B * 1.0 / (W + B)); double p_white = p_win_1_rec(W - 1, B) * (W * 1.0 / (W + B)); ret += cont_prob * (p_black + p_white); } memo[args] = ret; return ret; }The time complexity of recursion with memoization is O(W*B), i.e., the number of different values the input can take. Note that in this implementation access to the map adds log(W*B) complexity, but you can avoid this by storing the values in an 2-dimensional array.
[ "dp", "games", "math", "probabilities" ]
1,800
null
148
E
Porcelain
During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed. The collection of porcelain is arranged neatly on $n$ shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items — the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves. You are given the values of all items. Your task is to find the maximal damage the princess' tantrum of $m$ shrieks can inflict on the collection of porcelain.
This problem involved dynamic programming with precalculation. The first part of the solution was to precalculate the maximal cost of i items taken from the shelf (i ranging from 1 to the number of items on the shelf) for each shelf. Note that this can't be done greedily: this can be seen on the shelf 6: 5 1 10 1 1 5. The second part is a standard dynamic programming, which calculates the maximal cost of items taken for index of last shelf used and total number of items taken. To advance to the next shelf, one has to try all possible numbers of items taken from it and increase the total cost of items taken by corresponding precalculated values.
[ "dp" ]
1,900
null
149
A
Business trip
What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the $i$-th ($1 ≤ i ≤ 12$) month of the year, then the flower will grow by $a_{i}$ centimeters, and if he doesn't water the flower in the $i$-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by $k$ centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by $k$ centimeters.
First, it is clear that if the sum of all numbers $a_{i}$ is less than $k$, then Peter in any case will not be able to grow a flower to the desired height, and you should output <<-1>>. Secondly, it is easy to see that if we want to choose a one month of two, in which we watered the flower, it is better to choose one where the number of $a_{i}$ is more. Thus, the solution is very simple: let's take months in descending order of numbers $a_{i}$ and in these months water flowers. As soon as the sum of the accumulated $a_{i}$ becomes greater than or equal to $k$ - should stop the process, the answer is found.
[ "greedy", "implementation", "sortings" ]
900
null
149
B
Martian Clock
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" — you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored adventure stories that featured lasers and robots. Today Petya is watching a shocking blockbuster about the Martians called "R2:D2". What can "R2:D2" possibly mean? It might be the Martian time represented in the Martian numeral system. Petya knows that time on Mars is counted just like on the Earth (that is, there are $24$ hours and each hour has $60$ minutes). The time is written as "$a$:$b$", where the string $a$ stands for the number of hours (from $0$ to $23$ inclusive), and string $b$ stands for the number of minutes (from $0$ to $59$ inclusive). The only thing Petya doesn't know is in what numeral system the Martian time is written. Your task is to print the radixes of all numeral system which can contain the time "$a$:$b$".
In this task required only the ability to work with different numeral systems. Let's try to go through numeral bases, each base to check whether it is permissible, as well as convert hours and minutes to the decimal system and compared with 24 and 60, respectively. What is maximal base, that we need to check? In fact, it is enough to 60, because 60 - upper limit on the allowable number. It follows from the fact that if the number in an unknown number system consists of one digit, then its value in decimal not ever change, otherwise its value is not less than the base. It is also worth to consider the case with the response <<-1>>, for this example, you can check a big base, such as 100, and even if the time for him correct, then for all large, it is also correct and the answer is <<-1>>.
[ "implementation" ]
1,600
null
149
C
Division into Teams
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the game begins. There are $n$ boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic $a_{i}$ (the larger it is, the better the boy plays). Let's denote the number of players in the first team as $x$, the number of players in the second team as $y$, the individual numbers of boys who play for the first team as $p_{i}$ and the individual numbers of boys who play for the second team as $q_{i}$. Division $n$ boys into two teams is considered fair if three conditions are fulfilled: - Each boy plays for exactly one team ($x + y = n$). - The sizes of teams differ in no more than one ($|x - y| ≤ 1$). - The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: \[ |\sum_{i=1}^{x}a_{p_{i}}-\sum_{i=1}^{y}a_{q_{i}}|\leq\operatorname*{max}_{i=1}^{n}a_{i} \] Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
Sort all the boys on playing skill. Then, if we send in the first team all the boys standing in a sorted array for odd places, and the second - even standing on the ground, then all requirements for division executed. The first two requirements are obviously satisfied. To prove the third we consider the geometric representation: Let each child designated point on the X axis with a value equal his playing skill. Connect the points with segments numbered 1 and 2, 3 and 4, and so on. If $n$ is odd, then join the last point with the nearest the previous one. Obviously, all these segments don't intersect in pairs, except at the points, and their total length is equal to the difference amounts to play boys' skills contained into the first team and second team. It is also clear that all of these segments completely contained in the interval $[0, max(a_{i})]$, as well as the pairs are a length of zero crossing, the third requirement is satisfied, which we proved.
[ "greedy", "math", "sortings" ]
1,500
null
149
D
Coloring Brackets
Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it. You are given string $s$. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not. In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one. You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled: - Each bracket is either not colored any color, or is colored red, or is colored blue. - For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored. - No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo $1000000007$ ($10^{9} + 7$).
We introduce the notation of colors: 0 - black, 1 - red, 2 - blue. Note that a single pair of brackets has 4 different coloring: 0-1, 1-0, 0-2, 2-0. Consider the dynamic programming, where the state is $(l, r, c_{l}, c_{r})$, where the pair $(l, r)$ defines a pair of brackets, and $c_{l}$ and $c_{r}$ denote a fixed color for them. The value of the dynamic is a number of ways to paint all the parenthesis brackets inside the interval $(l, r)$ in compliance with all conditions. We write down all the pairs of brackets that are directly placed into a pair of $(l, r)$, let $k$ of their pieces. Moreover, we consider only the first level of nesting, it is directly attached. In order to calculate the value of the dynamics for the state, within this state shall calculate the another dynamic, where the state is a pair $(i, c)$ which means the number of correct colorings of the first $i$ directly nested parentheses, and all inside them, if the latter closing bracket has a color $c$. Calcing the values of this dynamic is very simple, let's try to paint a $(i + 1)$-th parenthesis in one of four variants, but you should keep in mind possible conflicts. In such dynamics the initial state is a pair $(0, c_{l})$, and the final result is sum over the states of the form $(k, c)$, where $c$ must not conflict with the $c_{r}$. The answer to the whole problem may be calced as the internal dynamic. Time of solution - $O(n^{2})$ by a factor of about 12.
[ "dp" ]
1,900
null
149
E
Martian Strings
During the study of the Martians Petya clearly understood that the Martians are absolutely lazy. They like to sleep and don't like to wake up. Imagine a Martian who has exactly $n$ eyes located in a row and numbered from the left to the right from $1$ to $n$. When a Martian sleeps, he puts a patch on each eye (so that the Martian morning doesn't wake him up). The inner side of each patch has an uppercase Latin letter. So, when a Martian wakes up and opens all his eyes he sees a string $s$ consisting of uppercase Latin letters. The string's length is $n$. "Ding dong!" — the alarm goes off. A Martian has already woken up but he hasn't opened any of his eyes. He feels that today is going to be a hard day, so he wants to open his eyes and see something good. The Martian considers only $m$ Martian words beautiful. Besides, it is hard for him to open all eyes at once so early in the morning. So he opens two non-overlapping segments of consecutive eyes. \textbf{More formally, the Martian chooses four numbers $a$, $b$, $c$, $d$, ($1 ≤ a ≤ b < c ≤ d ≤ n$) and opens all eyes with numbers $i$ such that $a ≤ i ≤ b$ or $c ≤ i ≤ d$.} After the Martian opens the eyes he needs, he reads all the visible characters from the left to the right and thus, he sees some word. Let's consider all different words the Martian can see in the morning. Your task is to find out how many beautiful words are among them.
We will solve the problem separately for each $m$ strings. Thus, suppose we have a string $p$, its length is $l$, and we need to check whether the Martian be seen. We introduce additional arrays: let $pref[i]$ is minimal position in the $s$ of the begin of occurrence $p$ with length exactly $i$, and let $suff[j]$ is the maximum position in the $s$ of the end of occurrence $p$ with length exactly $j$ It is easy to understand that a Martian could see the $p$, if there exists an $i$, that $suff[l - i] \ge pref[i] + l - 1$. How to calculate the arrays? For $pref$ array is sufficient to find Z-function p#s, but for an array of $suff$ - Z-function r(p)#r(s), where $r(t)$ means the reversed string $t$. Using an array of Z-functions calcing of arrays $suff$ and $pref$ is trivial.
[ "string suffix structures", "strings" ]
2,300
null
150
A
Win or Freeze
You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer $q$. During a move a player should write any integer number that is a \underline{non-trivial} divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called \underline{non-trivial} if it is different from one and from the divided number itself. The first person who \textbf{can't make a move wins} as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.
if $Q$ is prime or $Q = 1$ than it's victory. We loose if: $Q = p * q$ or $Q = p^{2}$, where $p$ and $q$ are prime. It is quite obvious that it is always possible to move in bad position in any other case. That means all other numbers grants us the victory. We only have to check if $Q$ has a divisor of the loose type. We can easily do it in $O(sqrt(Q))$ time.
[ "games", "math", "number theory" ]
1,400
null