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...
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 sho...
[ "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, ...
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 t...
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,...
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()) typ...
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", "r...
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 sourc...
[ "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 t...
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...
[ "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...
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...
[ "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...
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 numb...
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 ...
[ "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 dr...
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 ...
[ "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$ nu...
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 arra...
[ "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 arr...
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 l...
[ "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 nu...
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 wa...
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$ ran...
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 ...
[ "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...
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 sq...
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...
[ "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;...
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 t...
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 sequenc...
[ "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_JU...
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 ...
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 numbe...
[ "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++) ...
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 e...
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 ri...
[ "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]...
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, ...
[ "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 ...
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 ho...
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 ...
[ "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...
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] ...
[ "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-read...
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 describ...
[ "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=...
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. ...
[ "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...
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 ever...
[ "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 ...
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...
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. Th...
[ "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|$ denote...
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 impossibl...
[ "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...
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 ...
[ "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 nu...
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 <=...
[ "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 th...
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...
[ "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 t...
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'). Fir...
[ "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. ...
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...
[ "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 ...
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 ...
[ "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 ...
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]$;...
[ "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 col...
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 witho...
[ "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 l...
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 t...
[ "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-negati...
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 bi...
[ "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-s...
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....
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...
[ "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...
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 ...
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...
[ "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 c...
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 pl...
[ "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$ ...
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 adjacen...
[ "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...
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 b...
[ "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...
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 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 ...
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 cal...
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 Wo...
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 ga...
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....
[ "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 Inn...
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 >= ...
[ "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 ...
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 simul...
[ "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 ...
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 ...
[ "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...
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 probab...
[ "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...
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 p...
[ "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...
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 wr...
[ "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. S...
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...
[ "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 c...
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 s...
[ "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 th...
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...
[ "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. ...
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 t...
[ "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, ...
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 snowba...
[ "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 ...
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 de...
[ "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 whos...
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 w...
[ "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...
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...
[ "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. O...
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...
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 ...
[ "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...
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...
[ "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...
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 neighbor...
[ "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 connect...
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 grap...
[ "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 simple...
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...
[ "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 h...
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 wou...
[ "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 wi...
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,...
[ "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 f...
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 player...
[ "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. T...
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...
[ "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 tha...
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 chec...
[ "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 operatio...
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 t...
[ "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...
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 he...
[ "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...
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),...
[ "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 fr...
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 a...
[ "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 M...
$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(...
[ "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 ...
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...
[ "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 ...
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 editin...
[ "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 lo...
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 ...
[ "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 sequ...
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...
[ "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 a...
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 segme...
[ "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 ...
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), ...
[ "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 ti...
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 ...
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...
[ "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 ...
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 h...
[ "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 t...
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...
[ "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 chanc...
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 bal...
[ "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...
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. ...
[ "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 ...
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 w...
[ "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...
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, ...
[ "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 ...
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 repre...
[ "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 ...
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 col...
[ "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...
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 th...
[ "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 n...
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. ...
[ "games", "math", "number theory" ]
1,400
null