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
223
D
Spider
A plane contains a not necessarily convex polygon without self-intersections, consisting of $n$ vertexes, numbered from 1 to $n$. There is a spider sitting on the border of the polygon, the spider can move like that: - Transfer. The spider moves from the point $p_{1}$ with coordinates $(x_{1}, y_{1})$, lying on the po...
You were given a polygon consisting of $n$ vertices, you had to find the shortest way from one of its vertices to another. You were allowed to move along the border and go stricktly down without going outside the polygon All the sides of the polygon can be divided into three groups: top, bottom and vertical. The side i...
[ "geometry", "graphs" ]
3,000
null
223
E
Planar Graph
A graph is called planar, if it can be drawn in such a way that its edges intersect only at their vertexes. An articulation point is such a vertex of an undirected graph, that when removed increases the number of connected components of the graph. A bridge is such an edge of an undirected graph, that when removed inc...
In the problem we were given an undirected planar graph without bridges, cutpoints, loops and multiedge laid on the plane. We get requests of the following type: to calculate the number of vertices inside the cycle or on it. Let us take an arbitrary vertex on the border of the graph, for example a vertex that has the l...
[ "flows", "geometry", "graphs" ]
3,000
null
224
A
Parallelepiped
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped.
You were given areas of three faces of a rectangular parallelepiped. Your task was to find the sum of lengths of it's sides. Let $a$, $b$ and $c$ be the lengths of the sides that have one common vertex. Then the numbers we are given are $s_{1} = ab$, $s_{2} = bc$ and $s_{3} = ca$. It is easy to find the lengths in term...
[ "brute force", "geometry", "math" ]
1,100
null
224
B
Array
You've got an array $a$, consisting of $n$ integers: $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a minimal by inclusion segment $[l, r]$ $(1 ≤ l ≤ r ≤ n)$ such, that among numbers $a_{l},  a_{l + 1},  ...,  a_{r}$ there are exactly $k$ distinct numbers. Segment $[l, r]$ ($1 ≤ l ≤ r ≤ n;$ $l, r$ are integers) of l...
You were given an array $a$ consisting of $n$ integers. Its elements $a_{i}$ were positive and not greater than $10^{5}$ for each $1 \le i \le n$. Also you were given positive integer $k$. You had to find minimal by inclusion segment $[l, r]$ such that there were exactly $k$ different numbers among $a_{l}, ..., a_{...
[ "bitmasks", "implementation", "two pointers" ]
1,500
null
225
A
Dice Tower
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). Alice...
You should iterate over all dices from up to down and restore answer. You can easily find number of the bottom side of the 1st dice. Using known sides of the 2nd dice you can find pair of numbets on top and bottom side of the 2nd dice. If one of them equal to number on bottom of the 1st dice, you can restore all number...
[ "constructive algorithms", "greedy" ]
1,100
null
225
B
Well-known Numbers
Numbers $k$-bonacci ($k$ is integer, $k > 1$) are a generalization of Fibonacci numbers and are determined as follows: - $F(k, n) = 0$, for integer $n$, $1 ≤ n < k$; - $F(k, k) = 1$; - $F(k, n) = F(k, n - 1) + F(k, n - 2) + ... + F(k, n - k)$, for integer $n$, $n > k$. Note that we determine the $k$-bonacci numbers, ...
Firstly you should generate all k-bonacci numbers less than $n$. For $k \le 32$ you can do it straightforward, for bigger $k$ you can see that all $k$-bonacci numbers less $10^{9}$ are powers of two only (and 0). So you will have no more then 100 numbers. Then you should use greedy algo. You should substract from $n$...
[ "binary search", "greedy", "number theory" ]
1,600
null
225
C
Barcode
You've got an $n × m$ pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture. A picture is a barcode if the following conditions are fulfilled: - All pixels in each column are of the same color. - The width of each monochrome vertica...
Firstly you should calculate number of white and black pixels in every column. After that you should calculate number of white and black pixels for every prefix in sequence of columns. Now you can calculate number of black or white pixels in every vertical line of any width in $O(1)$. Now you should use dynamic program...
[ "dp", "matrices" ]
1,700
null
225
D
Snake
Let us remind you the rules of a very popular game called "Snake" (or sometimes "Boa", "Python" or "Worm"). The game field is represented by an $n × m$ rectangular table. Some squares of the field are considered impassable (walls), all other squares of the fields are passable. You control a snake, the snake consists ...
There is just BFS. State is head place and mask that store place of tail: using 2 bits you can code position of every segment in relation to previous segment. Mask will contain no more than 16 bits, and number of all states will be no more than $4^{8} \times 15 \times 15$ (also you can try understand that number of...
[ "bitmasks", "dfs and similar", "graphs", "implementation" ]
2,200
null
225
E
Unsolvable
Consider the following equation: \[ z=\left[{\frac{x}{2}}\right]+y+x y, \] where sign $[a]$ represents the integer part of number $a$.Let's find all integer $z$ $(z > 0)$, for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive int...
You have $z = [x / 2] + y + xy$. That is equivalent to $z = [2k / 2] + y + 2ky$, where $x = 2k, k > 0$ or $z = [(2k + 1) / 2] + y + (2k + 1)y$, where $x = 2k + 1, k \ge 0$. $z = k + y + 2ky, k > 0$ or $z = k + y + (2k + 1)y, k \ge 0$. Still more steps: $2z + 1 = 2k + 2y + 4ky + 1, k > 0$ or $z + 1 = k + 2y + 2ky + ...
[ "math", "number theory" ]
2,100
null
226
A
Flying Saucer Segments
An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!). The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the...
Let $F_{n}$ be the answer for the task, where $n$ is equal to the amount of aliens. Let's assume, that we've solved problem for $n - 1$ aliens, i.e. we know the value of $F_{n - 1}$. Let's try to find value of $F_{n}$. Notice, that the most junior alien in rank will be able to leave the $3^{rd}$ section, if and only if...
[ "math" ]
1,400
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (A...
226
B
Naughty Stone Piles
There are $n$ piles of stones of sizes $a_{1}, a_{2}, ..., a_{n}$ lying on the table in front of you. During one move you can take one pile and add it to the other. As you add pile $i$ to pile $j$, the size of pile $j$ increases by the current size of pile $i$, and pile $i$ stops existing. The cost of the adding opera...
Consider the following interpretation of the problem: stone piles are graph vertices. Operation "add pile $a$ to pile $b$" changes to operation of suspencion of subtree of vertice $b$ to vertice $a$. Numbers, written on vertices, - piles' sizes. Your task is to get such tree configuration, that each vertice has no more...
[ "greedy" ]
1,900
#include <algorithm> #include <iostream> #include <cstring> #include <cassert> #include <cstdlib> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <set> #include <map> using namespace std; typedef long long LL; typedef long double LD; #define pb push_back #define mp make_pair #define s...
226
C
Anniversary
There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations. Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set $A$, consisting of numb...
At first, let's prove the statement: $GCD(F_{n}, F_{m}) = F_{GCD(n, m)}$. Let's express $F_{n + k}$ using $F_{n}$ and $F_{k}$. We'll get the formula: $F_{n + k} = F_{k} \cdot F_{n + 1} + F_{k - 1} \cdot F_{n}$, which is easy to prove by induction. Then use the derived formula and notice, that $GCD(F_{n + k}, F_{n}) = G...
[ "data structures", "implementation", "math", "matrices", "number theory" ]
2,400
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std...
226
D
The table
Harry Potter has a difficult homework. Given a rectangular table, consisting of $n × m$ cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative th...
Let's get the required table. Act in the following way: find any row or column with negative sum and invert it. Notice, that sum of numbers in the entire table will always increase (at least, by $2$). It can't increase permanently, because its maximal possible summary change is $200 \cdot n \cdot m$. So we'll get the r...
[ "constructive algorithms", "greedy" ]
2,100
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <bitset> #include <sstream> #include <algorithm> #include <functional> #include <numeric> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <cas...
226
E
Noble Knight's Path
In Berland each feudal owns exactly one castle and each castle belongs to exactly one feudal. Each feudal, except one (the King) is subordinate to another feudal. A feudal can have any number of vassals (subordinates). Some castles are connected by roads, it is allowed to move along the roads in both ways. Two castle...
It's easy to guess that castles form a tree. Let's build heavy-light decomposition over it. Moreover, let's build persistent segment tree (with sum as the function) over each path. Tree's vertex will contain $0$, if castle wasn't attacked by barbarians, and $1$ otherwise. Each knight's path should be divided into not m...
[ "data structures", "trees" ]
2,900
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std...
227
A
Where do I Turn?
Trouble came from the overseas lands: a three-headed dragon Gorynych arrived. The dragon settled at point $C$ and began to terrorize the residents of the surrounding villages. A brave hero decided to put an end to the dragon. He moved from point $A$ to fight with Gorynych. The hero rode from point $A$ along a straight...
Let's consider cross product of vectors $\stackrel{\longrightarrow}{A B}$ and $\overline{{B C}}$, which is equal to $\overline{{{A B_{x}}}}\cdot\overline{{{B C_{u}}}}-\overline{{{A B_{y}}}}\cdot\overline{{{B C_{x}}}}$. Sign of cross product defines sign of a sine of oriented angle between vectors (because cross product...
[ "geometry" ]
1,300
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <complex> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std...
227
B
Effective Approach
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array. According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ...
Let's assume that number $t$ is on the $ind_{t}^{th}$ position in the original permutation. Then, obviously, during iterating from left to right this number will be found in $ind_{t}$ comparisons, and during iterating from right to left - in $n - ind_{t} + 1$ comparisons. Let's declare additional array, in $i^{th}$ ele...
[ "implementation" ]
1,100
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <cctype> #include <string> #include <ctime> #include <cmath> #include <set> #include <map> typedef long double LD; typedef long long LL; using namespace std; #define sz(A) (i...
228
A
Is your horseshoe on the other hoof?
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
In this problem you should count different numbers from input $cnt$ and print $4-cnt$. You could do it in different ways. For example, you could use set.
[ "implementation" ]
800
null
228
B
Two Tables
You've got two rectangular tables with sizes $n_{a} × m_{a}$ and $n_{b} × m_{b}$ cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the $i$-th row and the $j$-th co...
In this problem you should carefully consider every shift $- N < = x, y < = N$, count the answer and find the maximum value. The complexity of solution is $O(N^{4})$.
[ "brute force", "implementation" ]
1,400
null
228
C
Fractal Detector
Little Vasya likes painting fractals very much. He does it like this. First the boy cuts out a $2 × 2$-cell square out of squared paper. Then he paints some cells black. The boy calls the cut out square a fractal pattern. Then he takes a clean square sheet of paper and paints a fractal by the following algorithm: - H...
This problem could be solved using dynamic programming. State $z[x][y][st][mask]$ means if the square with upper left corner $(x, y)$ is fractal with nesting level $st$ and colors $mask$. The value $z[x][y][st][mask]$ is $0$ or $1$. There are $O(N^{2} \cdot Log(N) \cdot 2^{4})$ states in this dynamic programming. The t...
[ "dp", "hashing" ]
2,000
null
228
D
Zigzag
The court wizard Zigzag wants to become a famous mathematician. For that, he needs his own theorem, like the Cauchy theorem, or his sum, like the Minkowski sum. But most of all he wants to have his sequence, like the Fibonacci sequence, and his function, like the Euler's totient function. The Zigag's sequence with the...
In this problem we will use that sequence $s$ is cyclic because of its structure. Also, it is important that $2 < = z < = 6$. For every $z$ we will write the sequence $s$ and note that its period is $2 * (z-1)$. So, for every $z$ and modulo $0 < = mod < 2 * (z-1)$ we will build separate segment tree or Fenwick tree. Yo...
[ "data structures" ]
2,100
null
228
E
The Road to Berland is Paved With Good Intentions
Berland has $n$ cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not. The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roa...
This problem can be solved in different ways. It was expected the solution that solved the system of modular equations using Gauss algorithm. Here is another simple solution. The vertices from the result call switched-on. Firstly, note that every vertex should be switched-on no more than once. Then, consider every edge...
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
1,900
null
229
A
Shifts
You are given a table consisting of $n$ rows and $m$ columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right. To \underline{cyclically shift} a table row one cell to the right means ...
Let's compute the minimum number of operations needed to get all 1s in each of the $m$ columns. For this, traverse each row twice - one time to the left and one time to the right, recording the index of the nearest cell with 1 (in corresponding direction) for each column in this row. Then the number of operations for a...
[ "brute force", "two pointers" ]
1,500
#include <algorithm> #include <climits> #include <iostream> using namespace std; const int maxn = 100, maxm = 10000; int d[maxn][maxm]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n, m; cin >> n >> m; string s; s.reserve(m); for (int i = 0; i < n; i++) { cin >> s;...
229
B
Planets
Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet. Overall the galaxy has $...
Observe that when we visit some planet, the best strategy is to arrive as early as we can and then wait for the nearest free moment of time to move further. Hence this problem can be solved with the Dijkstra's algorithm by slightly altering the definition of a shortest distance. When we process a planet (meaning that w...
[ "binary search", "data structures", "graphs", "shortest paths" ]
1,700
#include <algorithm> #include <climits> #include <iostream> #include <set> #include <utility> #include <vector> using namespace std; const int maxn = 100000, maxm = 100000; vector<pair<int, int> > edges[maxn]; vector<int> times[maxn]; int dist[maxn]; struct compar { bool operator ()(int v1, int v2) const {...
229
C
Triangles
Alice and Bob don't play games anymore. Now they study properties of all sorts of graphs together. Alice invented the following task: she takes a complete undirected graph with $n$ vertices, chooses some $m$ edges and keeps them. Bob gets the ${\frac{n(n-1)}{2}}-m$ remaining edges. Alice and Bob are fond of "triangles...
Let's call Alice's edges simply edges, and Bob's edges the antiedges. For each edge pair of the initial complete graph that pass through the same vertices, assign a weight: for each pair of edges the weight +2, for each pair of edge and antiedge -1 and for each pair of antiedges +2. Now calculate the sum of all the wei...
[ "combinatorics", "graphs", "math" ]
1,900
#include<cstdio> using namespace std; int n, m, d[1000005]; int main() { scanf("%d %d", &n, &m); for(int i = 0; i < m; i++) { int a, b; scanf("%d %d", &a, &b); d[a]++; d[b]++; } long long res = 0; for(int v = 1; v <= n; v++) { long long a = d[v], b = n-1-a; res += a*(a-1)+b*(b-1)-a*b; } printf("%I...
229
D
Towers
The city of D consists of $n$ towers, built consecutively on a straight line. The height of the tower that goes $i$-th (from left to right) in the sequence equals $h_{i}$. The city mayor decided to rebuild the city to make it \underline{beautiful}. In a \underline{beautiful} city all towers are are arranged in non-desc...
Let's calculate the dynamics d[i][k] - the minimal possible height of the last tower that we can obtain by merging the first $i$ left towers into at least $k$ towers. Assume we already have calculated the dynamics' values for the first $i$ towers. Now we iterate over the all possible tower intervals $[i + 1;j]$; say th...
[ "dp", "greedy", "two pointers" ]
2,100
#include<cstdio> #include<cstring> using namespace std; #define MAXN 5005 int dp[MAXN][MAXN], inf = 1000000000; int main() { int n, a[MAXN]; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &a[i]); } for(int i = 0; i <= n; i++) { for(int j = 0; j <= n; j++) { dp[i][j] = inf; } } dp[0][0]...
229
E
Gifts
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with $n$ gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their...
First let's establish some facts that we will use in the solution. With how much probability can the fisherman get a particular set of gifts, among which there are $a_{i}$ gifts of $i$-th name? In total there are ${\binom{k_{1}}{a_{1}}}\cdot\ {\binom{k_{2}}{a_{2}}}\cdot\ \cdot\ \cdot\ \cdot\ \cdot\ {\binom{k_{m}}{a_{m}...
[ "combinatorics", "dp", "math", "probabilities" ]
2,600
#include<cstdio> #include<vector> #include<algorithm> #include<functional> #include<iostream> #include<iomanip> using namespace std; #define MAXN 1005 int Got[MAXN], Left[MAXN]; long double f[MAXN][MAXN]; int main() { int n, m; scanf("%d %d", &n, &m); vector<pair<int,int> > g; g.reserve(MAXN); for(int i = 0; i...
230
A
Dragons
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all $n$ dragons that live on this level. Kirito and the dragons have \underline{strength}, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Init...
Observe that if Kirito fights a dragon whose strength is less than Kirito's strength, then Kirito does not lose anything - in fact, he even gains a nonnegative strength increase. Taking note of this, let's for each step choose some dragon whose strength is less than Kirito's current strength, and fight it. After perfor...
[ "greedy", "sortings" ]
1,000
#include <algorithm> #include <iostream> #include <utility> using namespace std; const int maxn = 1000; pair<int, int> arr[maxn]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int s, n; cin >> s >> n; for (int i = 0; i < n; i++) { cin >> arr[i].first >> arr[i].second; }...
230
B
T-primes
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer $t$ \underline{Т-prime}, if $t$ has exactly three distinct positive divisors. You are given an array of $n$ positive integers. For each of them determine whether it is Т-prime or ...
It can be shown that only squares of prime numbers are T-primes, and that there are not too many of them - as many as there are prime numbers not greater than ${\sqrt{10^{12}}}=10^{6}$. Precompute these numbers (using, for example, the sieve of Eratosthenes) and store them in an array or an std::set, then we can answer...
[ "binary search", "implementation", "math", "number theory" ]
1,300
#include <iostream> #include <set> using namespace std; const int sqrt_lim = 1000001; set<long long> prime_squares() { static bool arr[sqrt_lim]; for (int i = 2; i*i < sqrt_lim; i++) { if (!arr[i]) { for (int j = i*i; j < sqrt_lim; j += i) { arr[j]...
231
A
Team
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
It is needed just to implement actions described in statement. You had to read data and to calculate number of members of team, which were sure about the solution, for every task. If this number is greater than one, the answer must be increased by one.
[ "brute force", "greedy" ]
800
null
231
B
Magic, Wizardry and Wonders
Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into...
Let's see, what will be the last number of array after $i$ iterations. After the first iteration it will be $a_{n - 1}-a_{n}$ (and total number of elements will be decreased by one). After the second iteration the last number will be $a_{n - 2}-a_{n - 1} + a_{n}$. It is not hard to see, that after $n - 1$ iterations re...
[ "constructive algorithms", "greedy" ]
1,500
null
231
C
To Add or Not to Add
A piece of paper contains an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Your task is to find a number that occurs the maximum number of times in this array. However, before looking for such number, you are allowed to perform not more than $k$ following operations — choose an arbitrary element from the array and...
One of the main observations, needed to solve this problem, is that the second number in answer always coincides with someone $a_{j}$. Let's see why it is true. Suppose, the second number of the answer is $a_{j} + d$ for someone $j$ and $a_{j} + d \neq a_{i}$ for all $i$. This means, we increased some numbers, which ...
[ "binary search", "sortings", "two pointers" ]
1,600
null
231
D
Magic Box
One day Vasya was going home when he saw a box lying on the road. The box can be represented as a rectangular parallelepiped. Vasya needed no time to realize that the box is special, as all its edges are parallel to the coordinate axes, one of its vertices is at point $(0, 0, 0)$, and the opposite one is at point $(x_{...
The main subtask of this problem is to check whether we can observe the center of face of parallelepiped from point $p = (x, y, z)$. Let's see the case, when the face belongs to plane $z = z_{1}$. For performing all calculations in integer numbers, multiply all coordinates $x, y, z, x_{1}, y_{1}, z_{1}$ by $2$. Take th...
[ "brute force", "geometry" ]
1,600
null
231
E
Cactus
A connected undirected graph is called a \underline{vertex cactus}, if each vertex of this graph belongs to at most one simple cycle. A simple cycle in a undirected graph is a sequence of distinct vertices $v_{1}, v_{2}, ..., v_{t}$ $(t > 2)$, such that for any $i$ $(1 ≤ i < t)$ exists an edge between vertices $v_{i}$...
In this problem you should find the number of simple paths between some pair of vertices in vertex cactus. If you learn the structure of these graphs, it is not hard to see, that if we'll squeeze each cycle in one vertex, we get a tree. So let's squeeze all cycles in source graph and get this tree. Also every vertex of...
[ "data structures", "dfs and similar", "dp", "graphs", "trees" ]
2,100
null
232
A
Cycles
John Doe started thinking about graphs. After some thought he decided that he wants to paint an undirected graph, containing exactly $k$ cycles of length $3$. A cycle of length $3$ is an unordered group of three distinct graph vertices $a$, $b$ and $c$, such that each pair of them is connected by a graph edge. John h...
Let's add edge in order of increasing $a$ and for equal $b$ in order of increasing $b$ (here $a$ and $b$ - the least and the greatest vertices of the edge). If the new edge adds too much 3-cycles, we won't add it. We can count the number of new 3-cycles in $O(n)$ complexity (they all contain the new edge, so it's enoug...
[ "binary search", "constructive algorithms", "graphs", "greedy" ]
1,600
null
232
B
Table
John Doe has an $n × m$ table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size $n × n$ have exactly $k$ points. John Doe wondered, how many distinct ways to fill the table with points are there, provide...
Let $s_{i}$ number of points in the column $i$. Two neighboring squares are drawn at this picture, $A$ is the number of point it the left area (it is one column), $B$ is the number of points in the middle area and $C$ is the number of points in the right area (it is one column too). That's why by definition we have: $\...
[ "bitmasks", "combinatorics", "dp", "math" ]
1,900
null
232
C
Doe Graphs
John Doe decided that some mathematical object must be named after him. So he invented the Doe graphs. The Doe graphs are a family of undirected graphs, each of them is characterized by a single non-negative number — its order. We'll denote a graph of order $k$ as $D(k)$, and we'll denote the number of vertices in the...
Let's reduce the problem to the same problem for graphs with less orders. Vertex $|D(n - 1)| + 1$ is cutpoint (except cases $n \le 2$ but equations below is true for these cases). Without loss of generality $a < b$. Let $dist(a, b, n)$ - length of the shortest path in graph of order $n$. The first case is $a \le |D...
[ "constructive algorithms", "divide and conquer", "dp", "graphs", "shortest paths" ]
2,600
null
232
D
Fence
John Doe has a crooked fence, consisting of $n$ rectangular planks, lined up from the left to the right: the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has width 1 and height $h_{i}$. We will assume that the plank that goes $i$-th $(1 ≤ i ≤ n)$ (from left to right) has index $i$. A piece of the fence fr...
Let $d$ and $d'$ be arrays such that $d_{i} = h_{i} - h_{i + 1}, d'_{i} = - d_{i}$ for every $1 \le i \le (n - 1)$. With that notation the conditions of matching look somehow like these: the pieces do not intersect, that is, there isn't a single plank, such that it occurs in both pieces of the fence; the pieces are...
[ "binary search", "data structures", "string suffix structures" ]
2,900
null
232
E
Quick Tortoise
John Doe has a field, which is a rectangular table of size $n × m$. We assume that the field rows are numbered from 1 to $n$ from top to bottom, and the field columns are numbered from 1 to $m$ from left to right. Then the cell of the field at the intersection of the $x$-th row and the $y$-th column has coordinates ($x...
Let's choose central column of the area and for all cells to the left from column calc masks of achieveable cells in the central column and for all cells to the right from column calc masks of cells of which this is achievable. It's easy dp with bitsets. $d p[i][j]=d p[i-1][j]\vee d p[i][j-1]$ for the right part of boa...
[ "bitmasks", "divide and conquer", "dp" ]
3,000
null
233
A
Perfect Permutation
A permutation is a sequence of integers $p_{1}, p_{2}, ..., p_{n}$, consisting of $n$ distinct positive integers, each of them doesn't exceed $n$. Let's denote the $i$-th element of permutation $p$ as $p_{i}$. We'll call number $n$ the size of permutation $p_{1}, p_{2}, ..., p_{n}$. Nickolas adores permutations. He li...
Consider permutation $p$ such that $p_{i} = i$. Actually $p$ is a sequence of numbers from $1$ to $n$. Obviously $p_{pi} = i$. Now the only trick is to change the permutation to satisfy the second equation: $p_{i} \neq i$. Let's swap every two consequtive elements. More formally, for each $k: 2k \le n$ let's swap $...
[ "implementation", "math" ]
800
null
233
B
Non-square Equation
Let's consider equation: \[ x^{2} + s(x)·x - n = 0, \] where $x, n$ are positive integers, $s(x)$ is the function, equal to the sum of digits of number $x$ in the decimal number system. You are given an integer $n$, find the smallest positive integer root of equation $x$, or else determine that there are no such roo...
Firstly let's find the interval of possible values of $s(x)$. Hence $x^{2} \le n$ and $n \le 10^{18}$, $x \le 10^{9}$. In other words, for every considerable solution $x$ the decimal length of $x$ does not extend $10$ digits. So $s_{max} \le s(9999999999) = 10 \cdot 9 = 90$. Let's bruteforce the value of $s(x)$...
[ "binary search", "brute force", "math" ]
1,400
null
235
A
LCM Challenge
Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it. But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than $n$. Can you help me to find ...
It is a simple problem, but many competitors used some wrong guesses and failed. First of all, we should check if n is at most 3 and then we can simply output 1,2,6. Now there are two cases: When n is odd, the answer is obviously n(n-1)(n-2). When n is even, we can still get at least (n-1)(n-2)(n-3), so these three num...
[ "number theory" ]
1,600
null
235
B
Let's Play Osu!
You're playing a game called Osu! Here's a simplified version of it. There are $n$ clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of $n$ characters "O" and "X". Using the play sequence you can calculate...
Let us take a deep look at how this score is calculated. For an $n$ long 'O' block, it contributes $n^{2}$ to the answer. Let us reformat this problem a bit and consider the following alternative definition of the score: (1) For each two 'O' pair which there is no 'X' between them, they add 2 to the score. (2) For each...
[ "dp", "math", "probabilities" ]
2,000
null
235
C
Cyclical Quest
Some days ago, WJMZBMR learned how to answer the query "how many times does a string $x$ occur in a string $s$" quickly by preprocessing the string $s$. But now he wants to make it harder. So he wants to ask "how many consecutive substrings of $s$ are cyclical isomorphic to a given string $x$". You are given string $s...
This problem can be solved by many suffix structures. Probably using suffix automaton is the best way to solve it since suffix automaton is simple and clear. Let us build a suffix automaton of the input string S, and consider the query string x. Let us also build a string t as x concatenated with x dropping the last ch...
[ "data structures", "string suffix structures", "strings" ]
2,700
/** * Created by IntelliJ IDEA. * User: mac * Date: 12-10-17 * Time: 下午1:30 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; public class CJava { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; List<Node> nodes = new...
235
D
Graph Game
In computer science, there is a method called "Divide And Conquer By Node" to solve some hard problems about paths on a tree. Let's desribe how this method works by function: $solve(t)$ ($t$ is a tree): - Chose a node $x$ (it's common to chose weight-center) in tree $t$. Let's call this step "Line A". - Deal with all...
First of all, let us consider the simpler case of trees. Let us use Event(A,B) to denote the following event "when we select A as the deleting point, B is connected to A". Clearly, if Event(A,B) happens, it would add 1 to $totolCost$. So we can just simply calculate the probability of every Event(A,B), and add them up....
[ "graphs" ]
3,000
import java.util.List; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is...
235
E
Number Challenge
Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum: \[ \textstyle\sum_{i=1}^{a}\sum_{j=1}^{b}\sum_{k=1}^{c}d(i\cdot j\cdot k). \] Find the sum modulo $1073741824$ $(2^{30})$.
Let us consider each prime in one step, the upper limit for $a, b, c$ is recorded. So if we fixed the power of 2 in each $i, j, k$ like $2^{x}, 2^{y}, 2^{z}$, then their upper limit becomes $a / 2^{x}, b / 2^{y}, c / 2^{z}$, and the power of 2 in their multiplication is just x+y+z. Let us denote $dp(a, b, c, p)$ for th...
[ "combinatorics", "dp", "implementation", "math", "number theory" ]
2,600
/** * Created by IntelliJ IDEA. * User: mac * Date: 12-10-9 * Time: 下午12:41 * To change this template use File | Settings | File Templates. */ import java.io.*; import java.util.*; public class EJava { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; void run() { t...
236
A
Boy or Girl
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. But...
It is a very simple problem, just count how many distinct chars in the input and output the correct answer.
[ "brute force", "implementation", "strings" ]
800
null
236
B
Easy Number Challenge
Let's denote $d(n)$ as the number of divisors of a positive integer $n$. You are given three integers $a$, $b$ and $c$. Your task is to calculate the following sum: \[ \textstyle\sum_{i=1}^{a}\sum_{j=1}^{b}\sum_{k=1}^{c}d(i\cdot j\cdot k). \] Find the sum modulo $1073741824$ $(2^{30})$.
First of all, we can make a table of size a*b*c to store every number's d value. Then we can just brute force through every tripe to calculate the answer.
[ "implementation", "number theory" ]
1,300
null
238
A
Not Wool Sequences
A sequence of non-negative integers $a_{1}, a_{2}, ..., a_{n}$ of length $n$ is called a wool sequence if and only if there exists two integers $l$ and $r$ $(1 ≤ l ≤ r ≤ n)$ such that $a_{l}\ \oplus\ a_{l+1}\ \oplus\ \cdots\ \leftrightarrow a_{r}=0$. In other words each wool sequence contains a subsequence of consecuti...
Let $a_{1}, ..., a_{n}$ be a not-wool-sequence. We define another sequence called $b$ in which $b_{i}$ is xor of the first $i$ elements of $a$, $b_{i}=a_{i}\oplus b_{i-1}$ and $b_{0} = 0$. Now xor of elements of a consecutive subsequence like $a_{i}, ..., a_{j}$ will be equal to $b_{j}\oplus b_{i-1}$. So we know that a...
[ "constructive algorithms", "math" ]
1,300
null
238
C
World Eater Brothers
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are $n$ countries in the world. These countries are connected by $n - 1$ directed roads. If you don't consider di...
Consider we only want to change direction of minimum number of roads so that all other countries are reachable from a specific country $x$. This problem can be solved in $O(n)$ and it's exactly what 219D - Choosing Capital for Treeland asks for. If you don't know how to solve it you can read the editorial of that conte...
[ "dfs and similar", "dp", "greedy", "trees" ]
2,100
null
238
D
Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. - Current character pointer (CP); - Dire...
This problem was my favorite in the problemset. The primary point is that at any moment during the interpretation of a program only a prefix of the program is modified and used by IP. Consider we want to calculate the output of subsequence $s_{l}, ..., s_{r}$. While running the original program $s_{1}, ..., s_{n}$ if a...
[ "data structures", "implementation" ]
2,900
null
238
E
Meeting Her
Urpal lives in a big city. He has planned to meet his lover tonight. The city has $n$ junctions numbered from $1$ to $n$. The junctions are connected by $m$ directed streets, all the roads have equal length. Urpal lives in junction $a$ and the date is planned in a restaurant in junction $b$. He wants to use public tra...
Consider a bus passing a shortest path from $s_{i}$ to $t_{i}$. There are some points that are necessary to pass in order to obtain a shortest path. Firstly we compute them. This can be done in $O(n^{3})$ with Floyd-Warshall and some processing after that. Urpal is sure that a bus from $i$-th company always passes such...
[ "dp", "graphs", "shortest paths" ]
2,600
null
239
A
Two Bags of Potatoes
Valera had two bags of potatoes, the first of these bags contains $x$ $(x ≥ 1)$ potatoes, and the second — $y$ $(y ≥ 1)$ potatoes. Valera — very scattered boy, so the first bag of potatoes (it contains $x$ potatoes) Valera lost. Valera remembers that the total amount of potatoes $(x + y)$ in the two bags, firstly, was ...
The total number of potatoes is a multiple of $k$ and constraint $\xrightarrow[{k}]{\leq}10^{5}$ there will be at most $10^{5}$ multiples of $k$ in range $1$ to $n$. So you can iterate on multiples of $k$ and print the ones that satisfy the problem.
[ "greedy", "implementation", "math" ]
1,200
null
239
B
Easy Tape Programming
There is a programming language in which every program is a non-empty sequence of "<" and ">" signs and digits. Let's explain how the interpreter of this programming language works. A program is interpreted using movement of instruction pointer (IP) which consists of two parts. - Current character pointer (CP); - Dire...
In this problem you just need to simulate every thing which is written in the statement step by step.
[ "brute force", "implementation" ]
1,500
null
242
A
Heads or Tails
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin $x$ times, then Petya tosses a coin $y$ times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by t...
This problem was very easy, we should only use two cycles with $i$ and with $j$ ($a \le i \le x$, $b \le j \le y$), iterate all possible outcomes of the game and print such in that $i > j$. The time is $O(x \cdot y)$.
[ "brute force", "implementation" ]
1,100
null
242
B
Big Segment
A coordinate line has $n$ segments, the $i$-th segment starts at the position $l_{i}$ and ends at the position $r_{i}$. We will denote such a segment as $[l_{i}, r_{i}]$. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all ot...
At first, we must note that the answer is always unique, because if segment $i$ covers segment $j$, that segment $j$ can't cover segment $i$. It possible if and only if there are coincide segments in the set, but it's not permissible by the statement. Let's pay attention the answer covers the most left point of all seg...
[ "implementation", "sortings" ]
1,100
null
242
C
King's Path
The black king is standing on a chess field consisting of $10^{9}$ rows and $10^{9}$ columns. We will consider the rows of the field numbered with integers from $1$ to $10^{9}$ from top to bottom. The columns are similarly numbered with integers from $1$ to $10^{9}$ from left to right. We will denote a cell of the fiel...
The most important thing for accepted solution is that it is guaranteed that the total length of all given segments doesn't exceed $10^{5}$. We should use this feature, let's number allowed cells and found shortest path by BFS. It's easiest to use associative array such as map in C++ for numbering. The time is $O(n \cd...
[ "dfs and similar", "graphs", "hashing", "shortest paths" ]
1,800
null
242
D
Dispute
Valera has $n$ counters numbered from $1$ to $n$. Some of them are connected by wires, and each of the counters has a special button. Initially, all the counters contain number $0$. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly ...
Denote current value of counter number $i$ as $b_{i}$. Let's describe an algorithm. It takes any counter $i$ such that $b_{i} = a_{i}$ and presses its button. The algorithm finishes if there is no such $i$. Let's proof correctness of the algorithm: Why does Valera win the game? Because there is no such counter which ha...
[ "dfs and similar", "graphs", "greedy" ]
2,100
null
242
E
XOR on Segment
You've got an array $a$, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. You are allowed to perform two operations on this array: - Calculate the sum of current array elements on the segment $[l, r]$, that is, count value $a_{l} + a_{l + 1} + ... + a_{r}$. - Apply the xor operation with a given number $x$ to ea...
Let's write numbers $a_{1}, a_{2}, ..., a_{n}$ as a table which has size $n \times 20$, and $b_{i, j}$ is $j$th bit in $a_{i}$. Then sum of numbers on segment $[l, r]$ equals $\begin{array}{l}{{\sum_{i=l}^{r}\sum_{j=0}^{19}b_{i,j}\cdot2^{j}=\sum_{j=0}^{19}2^{j}\cdot(\sum_{i=l}^{r}b_{i,j})}}\end{array}$. The last nota...
[ "bitmasks", "data structures" ]
2,000
null
243
A
The Brand New Function
Polycarpus has a sequence, consisting of $n$ non-negative integers: $a_{1}, a_{2}, ..., a_{n}$. Let's define function $f(l, r)$ ($l, r$ are integer, $1 ≤ l ≤ r ≤ n$) for sequence $a$ as an operation of bitwise OR of all the sequence elements with indexes from $l$ to $r$. Formally: $f(l, r) = a_{l} | a_{l + 1} | ...  |...
Let's see how function $f$ changes for all suffixes of sequence $a$. Values of $f$ will increase when you will increase length of suffix. For every increase all 1-bits will stay 1-bits, but some 0-bits will be changed by 1-bits. So, you can see that no more than $k$ increasing will be, where $k$ number of bits (in this...
[ "bitmasks" ]
1,600
null
243
B
Hydra
One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes $u$ and $v$ connected by an edge, they are the hydra...
You should check for every edge: this one can be body of hydra or not. Let's fix some edge $(u, v)$ (order of vertices is important, i.e. you should also check edge $(v, u)$). Now you should chose some set of $h$ vertices connected with $u$ and some set of $t$ vertices connected with $v$. These sets should not contain ...
[ "graphs", "sortings" ]
2,000
null
243
C
Colorado Potato Beetle
Old MacDonald has a farm and a large potato field, $(10^{10} + 1) × (10^{10} + 1)$ square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the ins...
Firstly tou should emulate all process in "idle mode". Let farmer was in points $(x_{0} + 1 / 2, y_{0} + 1 / 2)$, $(x_{1} + 1 / 2, y_{1} + 1 / 2)$, ... , $(x_{n} + 1 / 2, y_{n} + 1 / 2)$. Coordinates $x_{0}$, $x_{0} + 1$, $x_{1}$, $x_{1} + 1$, ... $x_{n}$, $x_{n} + 1$ on axis $x$ are interesting for us. Coordinates $y_...
[ "dfs and similar", "implementation" ]
2,200
null
243
D
Cubes
One day Petya got a set of wooden cubes as a present from his mom. Petya immediately built a whole city from these cubes. The base of the city is an $n × n$ square, divided into unit squares. The square's sides are parallel to the coordinate axes, the square's opposite corners have coordinates $(0, 0)$ and $(n, n)$. O...
You need for every column find the lowermost cube that you can see. You will see all cubes above this cube. Consider the city from above. You will see drid of size $n \times n$. Now you should draw the line through every node of the grid parallel to vector $v$. We need know only that happens in every strip between tw...
[ "data structures", "dp", "geometry", "two pointers" ]
2,700
null
243
E
Matrix
Let's consider an $n × n$ square matrix, consisting of digits one and zero. We'll consider a matrix good, if it meets the following condition: in each row of the matrix all ones go in one group. That is, each row of the matrix looks like that $00...0011...1100...00$ (or simply consists of zeroes if it has no ones). Y...
We will build the matrix constructively. At any step we will have array of groups of columns. Order of groups is defined but order of columns inside every group is unknown. During building we will change order of rows because it is doesn't affect the answer (we can build answer using order of columns only). Consider th...
[ "data structures" ]
3,000
null
244
A
Dividing Orange
One day Ms Swan bought an orange in a shop. The orange consisted of $n·k$ segments, numbered with integers from 1 to $n·k$. There were $k$ children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and ...
Consider an array $A$ of integers in range from 1 to $nk$. Let's remove from $A$ all numbers $a_{i}$ and all other numbers store into an array $B$. The array $B$ will have $(n - 1)k$ elements. Now for $i$-th kid you should output numbers $a_{i}$, $B[(n - 1) * (i - 1) + 1]$, $B[(n - 1) * (i - 1) + 2]$, ... $B[(n - 1) * ...
[ "implementation" ]
900
null
244
B
Undoubtedly Lucky Numbers
Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits $x$ and $y$. For example, if $x = 4$, and $y = 7$, then numbers 47, 744, 4 are lucky. Let's call a positive integer $a$ undoubtedly lucky, if the...
Solution 1. You should write some bruteforce solution over all numbers with no more than 9 digits (number $10^{9}$ should be considered separately). Bruteforce algo seems like this: dfs( int num ) // run it as dfs(0) if (num > 0 && num <= n) ans++ if (num >= 10^8) return for a = 0..9 do if num*10+a>0 then if number num...
[ "bitmasks", "brute force", "dfs and similar" ]
1,600
null
245
A
System Administrator
Polycarpus is a system administrator. There are two servers under his strict guidance — $a$ and $b$. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a progra...
Let's define following variables: $A_{Reached}$ : Number of packets that reached $A$. $A_{Lost}$ : Number of packets which didn't reach $A$. $B_{Reached}$ : Number of packets that reached $B$. $B_{Lost}$ : Number of packets which didn't reach $B$. We iterate over input and update each variable accordingly. Now answer f...
[ "implementation" ]
800
#include <iostream> using namespace std; int A_Reached, A_Lost, B_Reached, B_Lost; int main() { int n; cin >> n; for (int i = 1 ; i <= n ; i++) { int t, x, y; cin >> t >> x >> y; if (t == 1) { A_Reached += x; A_Lost += y; } else { B_Reached += x; B_Lost += y; } } if (A_Reached >= A...
245
B
Internet Address
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: \begin{center} <protocol>://<domain>.ru[/<context>] \end{center} where: - <protocol> can equal either "http" (without the quote...
Problem guarantees that there exists an Internet resource address from which we can obtain our input. At first, let's find Protocol of address. It's sufficient to only check first letter of input, if it's $h$ then protocol is $http$ otherwise, it's $ftp$. Now, let's find position of $.ru$. We can iterate over our strin...
[ "implementation", "strings" ]
1,100
#include <iostream> using namespace std; string ans, s; int index; int main() { cin >> s; if (s[0] == 'h') { ans += "http://"; index = 4; } else { ans += "ftp://"; index = 3; } for (int i = (int)s.size()-3 ; i >= index ; i--) if (s[i] == 'r' && s[i+1] == 'u') { cout << ans + s.substr(index, i-...
245
C
Game with Coins
Two pirates Polycarpus and Vasily play a very interesting game. They have $n$ chests with coins, the chests are numbered with integers from 1 to $n$. Chest number $i$ has $a_{i}$ coins. Polycarpus and Vasily move in turns. Polycarpus moves first. During a move a player is allowed to choose a positive integer $x$ $(2·x...
First note that if $n \le 2$ or $n\equiv0{\bmod{2}}$ then answer is $- 1$. It's because of the following $2$ facts: 1. $2x+1\leq n\to x\leq{\frac{n-1}{2}}$ and $x\in\mathbb{N}$ so $n \ge 3$ otherwise $x$ won't be a natural number. 2. If $n\equiv0{\bmod{2}}$ then $n = 2k$ and $x\leq{\frac{2k-1}{2}}$ which means $x ...
[ "greedy" ]
1,700
#include <iostream> using namespace std; const int MAXN = 110; int n, a[MAXN], ans; int main() { cin >> n; if (n <= 2 || n % 2 == 0) { cout << -1 << endl; return 0; } for (int i = 1 ; i <= n ; i++) cin >> a[i]; for (int i = n ; i >= 2 ; i--) { while (a[i] && i & 1) { int x = (i-1)/2; a[i]--; ...
245
D
Restoring Table
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative ...
Consider $a[i]$, $a[j]$ and $b[i][j] = a[i]&a[j]$. Now consider binary representation of $b[i][j]$. For each $1$-bit of $b[i][j]$ at position $k$, ($0$-indexed) we conclude that $k$-th bit of $a[i]$ and $a[j]$ equals $1$ so we set $a[i] = a[i]|2^{k}$ and $a[j] = a[j]|2^{k}$. Now let's describe algorithm. We use $i$ to ...
[ "constructive algorithms", "greedy" ]
1,500
#include <iostream> using namespace std; const int MAXN = 110; int n, a[MAXN]; int main() { cin >> n; for (int i = 1 ; i <= n ; i++) for (int j = 1 ; j <= n ; j++) { int AND; cin >> AND; if (i != j) a[i] |= AND; } for (int i = 1 ; i <= n ; i++) cout << a[i] << " "; cout << endl; return 0; ...
245
E
Mishap in Club
Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen. On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, ...
Consider following interpretation of problem. We're standing in $(0, 0)$ at the center of Cartesian coordinate system. We iterate over the given sequence, for each $+$, we move from $(x, y)$ to $(x + 1, y + 1)$ and for each $-$, we move from $(x, y)$ to $(x + 1, y - 1)$. Consider the maximum $y$ coordinate we visit dur...
[ "greedy", "implementation" ]
1,400
#include <iostream> using namespace std; string s; int MAX, MIN, pos; int main() { cin >> s; for (int i = 0 ; i < (int)s.size() ; i++) if (s[i] == '+') { pos++; MAX = max(pos, MAX); } else { pos--; MIN = min(pos, MIN); } cout << MAX - MIN << endl; return 0; }
245
F
Log Stream Analysis
You've got a list of program warning logs. Each record of a log stream is a string in this format: \begin{center} "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). \end{center} String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determi...
First note that "MESSAGE" is useless and can be ignored. Year is always $2012$ so it can be ignored too. Now convert each date and time to seconds past from beginning of $2012$. Maintain a list, such as a vector, $V$, for storing seconds. Define pointer $head$ to be head of your vector. Define $sec$ to be conversion of...
[ "binary search", "brute force", "implementation", "strings" ]
2,000
#include <iostream> #include <sstream> #include <vector> using namespace std; vector <int> v; int months[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int n, m, head; string s; int input(string temp) { int val; stringstream sin; sin << temp; sin >> val; return val; } int main() { ios::sync_with_st...
245
G
Suggested Friends
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as $m$ username pairs $...
Use $map$ in order to map people to numbers. Construct the given graph using adjacency list. Now, let's find answer for each vertex $v$. Mark all of $v$'s neighbors. After that iterate over all other vertices, and iterate over their adjacency list and count their mutual neighbors with $v$ and update answer for $v$. Com...
[ "brute force", "graphs" ]
2,200
#include <iostream> #include <vector> #include <map> #include <cstring> using namespace std; const int MAXN = 10000 + 10; map <string, int> vertices; int n, m, mark[MAXN], ans[MAXN]; vector <int> g[MAXN]; int main() { ios::sync_with_stdio(0); cin >> m; for (int i = 1 ; i <= m ; i++) { string s1, s2; cin >> ...
245
H
Queries for Number of Palindromes
You've got a string $s = s_{1}s_{2}... s_{|s|}$ of length $|s|$, consisting of lowercase English letters. There also are $q$ queries, each query is described by two integers $l_{i}, r_{i}$ $(1 ≤ l_{i} ≤ r_{i} ≤ |s|)$. The answer to the query is the number of substrings of string $s[l_{i}... r_{i}]$, which are palindrom...
Note: Strings and arrays are considered $0$-based in the following solution. Let $isPal[i][j]$ be $1$ if $s[i...j]$ is palindrome, otherwise, set it $0$. Let's define $dp[i][j]$ to be number of palindrome substrings of $s[i...j]$. Let's calculate $isPal[i][j]$ and $dp[i][j]$ in $O(|S|^{2})$. First, initialize $isPal[i]...
[ "dp", "hashing", "strings" ]
1,800
#include <iostream> using namespace std; const int MAXN = 5000 + 10; string s; int n, q, dp[MAXN][MAXN]; bool isPal[MAXN][MAXN]; int main() { ios::sync_with_stdio(0); cin >> s; n = (int)s.size(); for (int i = 0 ; i < n ; i++) { isPal[i][i] = 1; dp[i][i] = 1; isPal[i+1][i]...
246
A
Buggy Sorting
Little boy Valera studies an algorithm of sorting an integer array. After studying the theory, he went on to the practical tasks. As a result, he wrote a program that sorts an array of $n$ integers $a_{1}, a_{2}, ..., a_{n}$ in the non-decreasing order. The pseudocode of the program, written by Valera, is given below. ...
In this problem you should hack the sorting algorithm, of course it was incorrect. It was correct only for arrays with $n < = 2$. In other cases you could print $n, n-1, ..., 1$ as a counter-example. To make the sorting right, the second cycle should be from $1$ but not from $i$.
[ "constructive algorithms", "greedy", "sortings" ]
900
null
246
B
Increase and Decrease
Polycarpus has an array, consisting of $n$ integers $a_{1}, a_{2}, ..., a_{n}$. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times: - he chooses two elements of the array $a_{i}...
Note, that you can always get the answer $n-1$. To get this result you should make first $n-1$ equal using the last element as the second element in pair of given operation. But after it, the whole array could become equal. It could happen if the sum of array's elements is divisible by $n$. So the answer is $n-1$ or $n...
[ "greedy", "math" ]
1,300
null
246
C
Beauty Pageant
General Payne has a battalion of $n$ soldiers. The soldiers' beauty contest is coming up, it will last for $k$ days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants. All soldiers in the battalion have different beauty that is represented by a positive integer. The v...
This problem was rather mathematical. The correct solution is: firstly take every element once, then take the maximum and any other, then two maximums and any other, then three maximums and any other and so on. In this case, you get as many sets as you need in this problem. It is easy to check, that all sums will be di...
[ "brute force", "constructive algorithms", "greedy" ]
1,600
null
246
D
Colorful Graph
You've got an undirected graph, consisting of $n$ vertices and $m$ edges. We will consider the graph's vertices numbered with integers from 1 to $n$. Each vertex of the graph has a color. The color of the $i$-th vertex is an integer $c_{i}$. Let's consider all vertices of the graph, that are painted some color $k$. Le...
This problem could be solved in this way: create new graph where vertices are the colors of the given graph. The edge between vertices $u$ and $v$ belongs this new graph if there are two vertices $a$ and $b$ in the given graph such that $c[a] = u$ and $c[b] = v$. So, the answer is such color $k$ with minimum number, th...
[ "brute force", "dfs and similar", "graphs" ]
1,600
null
246
E
Blood Cousins Return
Polycarpus got hold of a family tree. The found tree describes the family relations of $n$ people, numbered from 1 to $n$. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique. We call the man with a number $a$ a 1-ancestor of the man...
This problem had little in common with problem 208E - Blood Cousins. In comments to this problem there was given a solution using structure deque (array in which you can add or delete elements from both endings). Let's describe solution using this structure. Firstly all different names change with different integers an...
[ "binary search", "data structures", "dfs and similar", "dp", "sortings" ]
2,400
null
250
A
Paper Work
Polycarpus has been working in the analytic department of the "F.R.A.U.D." company for as much as $n$ days. Right now his task is to make a series of reports about the company's performance for the last $n$ days. We know that the main information in a day report is value $a_{i}$, the company's profit on the $i$-th day....
For every folder you should take reports as much as possible. In other words, you should stop forming a folder either before the third bad report or in the end of sequence. You can easily prove that this strategy is optimal. This solution works in $O(n)$.
[ "greedy" ]
1,000
null
250
B
Restoring IPv6
An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef"....
Firstly you should split string into substrings using ":" as separator. All empty substrings will go in the row; you should leave only one of them. Then you should calculate number of nonempty substrings and determine number of zero-blocks which will replace empty substring. After replacing you should increase every su...
[ "implementation", "strings" ]
1,500
null
250
C
Movie Critics
A film festival is coming up in the city N. The festival will last for exactly $n$ days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to $k$. On the $i$-th day the festival will show a movie of genre $a_{i}$. We know that a movie of each of $k$ genres occurs in the fe...
Consider some maximal by inclusion segment of movies of some genre $x$ (this number from 1 to $k$). Now let's see how changes number of stresses after removing this segment. If the segment adjoins to the end of all sequence $a$, improvement will be +1. Segment cannot adjoin to both ends of sequence because $k > 1$. For...
[ "greedy" ]
1,600
null
250
D
Building Bridge
Two villages are separated by a river that flows from the north to the south. The villagers want to build a bridge across the river to make it easier to move across the villages. The river banks can be assumed to be vertical straight lines $x = a$ and $x = b$ ($0 < a < b$). The west village lies in a steppe at point ...
For every point of the east river bank you should find optimal point of the west bank. After that you should chose optimal pair over all considered east points. Well, let's fix $j$-th east point ($1 \le j \le m$). Now consider how changes total distance depending on chosing the west point. The best point is interse...
[ "geometry", "ternary search", "two pointers" ]
1,900
null
250
E
Mad Joe
Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path. Joe's house has $n$ floors, each floor is a segment of $m$ cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that ea...
You should emulate the process. You can catch case of infinity walk if you will observe hits with concrete wall from the left and the right side. If for some floor both types of hits happened, you should output "Never". Stupid emulation is very slow. It has complexity $O(nm^{2})$ and answer can be about $10^{10}$. You ...
[ "brute force" ]
2,000
null
251
A
Points on Line
Little Petya likes points a lot. Recently his mom has presented him $n$ points lying on the line $OX$. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed $d$. Note that the order of the points inside the group of three chosen...
Let's select the rightmost point of our triplet. In order to do this we can iterate over all points in ascending order of their X-coordinate. At the same time we'll maintain a pointer to the leftmost point which lays on the distance not greater than $d$ from the current rightmost point. We can easily find out the numbe...
[ "binary search", "combinatorics", "two pointers" ]
1,300
null
251
B
Playing with Permutations
Little Petya likes permutations a lot. Recently his mom has presented him permutation $q_{1}, q_{2}, ..., q_{n}$ of length $n$. A permutation $a$ of length $n$ is a sequence of integers $a_{1}, a_{2}, ..., a_{n}$ $(1 ≤ a_{i} ≤ n)$, all integers there are distinct. There is only one thing Petya likes more than permuta...
First, we need to theck whether permutation $s$ is the identity permutation. If it is, then the answer is "NO". Now we'll describe an algorithm which works in all cases except for one. We'll tell about this case later. Let's apply our permutation $q$ until either the current permutation becomes equal to $s$ or we make ...
[ "implementation", "math" ]
1,800
null
251
C
Number Transformation
Little Petya likes positive integers a lot. Recently his mom has presented him a positive integer $a$. There's only one thing Petya likes more than numbers: playing with little Masha. It turned out that Masha already has a positive integer $b$. Petya decided to turn his number $a$ into the number $b$ consecutively perf...
Let $L$ be the least common multiple of all numbers from 2 to $k$, inclusive. Note that if $a$ is divisible by $L$, then we can't decrease it with applying an operation of the second type. It means that any optimal sequence of transformations will contain all numbers divisible by $L$ which are located between $b$ and $...
[ "dp", "greedy", "number theory" ]
2,000
null
251
D
Two Sets
Little Petya likes numbers a lot. Recently his mother has presented him a collection of $n$ non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to...
Let $X$ be the $xor$ of all numbers in the input. Also let $X1$ be the $xor$ of all numbers in the first collection and $X2$ be the $xor$ of all numbers in the second collection. Note, if the $i$-th bit in $X$ is equal to 1 then the same bit in numbers $X1$ and $X2$ is either equal 0 and 1 or 1 and 0, respectively. Ana...
[ "bitmasks", "math" ]
2,700
null
251
E
Tree and Table
Little Petya likes trees a lot. Recently his mother has presented him a tree with $2n$ nodes. Petya immediately decided to place this tree on a rectangular table consisting of 2 rows and $n$ columns so as to fulfill the following conditions: - Each cell of the table corresponds to exactly one tree node and vice versa,...
If $N = 1$, then the answer is 2. If there is a node with degree greater than 3 in the tree, then the answer is 0. That's because every cell of the table has at most 3 neighbors. If there is no vertex of degree 3 in the tree, then the answer is $2n^{2} - 2n + 4$. This formula can be derieved in natural way during the s...
[ "dfs and similar", "dp", "implementation", "trees" ]
3,000
null
252
A
Little Xor
Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of $n$ elements. Petya immediately decided to find there a segment of consecutive elements, such that the $xor$ of all numbers from this segment was maximal possible. Help him with that. ...
Let's iterate over all segments in our array. For each of them we'll find the $xor$ of all its elements. Then we need to output the maximal $xor$ we've seen.
[ "brute force", "implementation" ]
1,100
null
252
B
Unsorting Array
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of $n$ elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct ...
If all elements in the array are equal then there's no pair of numbers we are looking for. Now we can assume that there exist at least 2 different numbers in the array. Let's iterate over all pairs of different numbers in the array and for each such pair we'll check if it can be the answer. If some pair indeed can be t...
[ "brute force", "sortings" ]
1,800
null
253
A
Boys and Girls
There are $n$ boys and $m$ girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to $n + m$. Then the number of integers $i$ ($1 ≤ i < n + m$) such that positions with...
Lets assume that we have more boys than girls (the other case is solved similarly). Then we can construct one of the optimal solutions in the following way: we add pairs consisting of a boy and a girl (BG, in that order) to the end of the line until we don't have girls any more. Then add remaining boys to the end of th...
[ "greedy" ]
1,100
null
253
B
Physics Practical
One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as $n$ measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher h...
For each $x$ from 1 to 5000 calculate $count(x)$ - the number of measurements equal to $x$. The iterate over all possible minimal values $m$ (from 1 to 5000). For a fixed $m$ we can easily figure out which numbers we have to erase: we should erase every number $k$ that $k < m$ or $k > 2 \cdot m$. To find out the number...
[ "binary search", "dp", "sortings", "two pointers" ]
1,400
null
253
C
Text Editor
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, b...
One of the solutions to the problem is breadth-first-search (BFS). Vertices of the graph correspond to all possible pairs ($r, c$), denoting the row and the position of the cursor. Each vertex has at most four arcs leaving it (these arcs correspond to pressing the buttons). So we need to find the shortest path from one...
[ "data structures", "dfs and similar", "graphs", "greedy", "shortest paths" ]
1,600
null
253
D
Table with Letters - 2
Vasya has recently started to learn English. Now he needs to remember how to write English letters. He isn't sure about some of them, so he decided to train a little. He found a sheet of squared paper and began writing arbitrary English letters there. In the end Vasya wrote $n$ lines containing $m$ characters each. Th...
Lets iterate over all pairs of rows $i, j$ ($i < j$), that bounds the sub-table from the top and from the bottom. Then for each character $ch$ make a list of such column numbers $k$ that $T[i, k] = T[j, k] = ch$. Consider such list for some fixed character $ch$. All we need to count is the number of pairs $l, r$ ($l < ...
[ "brute force", "two pointers" ]
2,000
null
253
E
Printer
Let's consider a network printer that functions like that. It starts working at time 0. In each second it can print one page of a text. At some moments of time the printer receives printing tasks. We know that a printer received $n$ tasks. Let's number the tasks by consecutive integers from 1 to $n$. Then the task numb...
First lets learn how to simulate the process with all priorities known. We will keep the priority queue of tasks. The task enters the queue when the printer receives this task, and leaves the queue when the printer finishes it. Then every change in the queue happens when one of the two possible events occurs: the print...
[ "binary search", "data structures", "implementation", "sortings" ]
2,200
null
254
A
Cards with Numbers
Petya has got $2n$ cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from $1$ to $2n$. We'll denote the number that is written on a card with number $i$, as $a_{i}$. In order to play one entertaining game with his friends, Petya needs to spli...
For each $x$ from 1 to 5000 store a list $L(x)$ of such indexes $i$ that $a_{i} = x$. Then just check that all lists have even size and output the elements of each list in pairs.
[ "constructive algorithms", "sortings" ]
1,200
null
254
B
Jury Size
In 2013, the writers of Berland State University should prepare problems for $n$ Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to $n$. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the prob...
One of the possible solutions is: for each Olympiad find the period of the preparation. This can be done by iterating the days back from the day of the Olympiad. For each day $d$ of the preparation add $p_{i}$ to the number of distinct jury members that have to work on problems on day $d$. Then the answer is maximum ca...
[ "brute force", "implementation" ]
1,500
null
254
C
Anagram
String $x$ is an anagram of string $y$, if we can rearrange the letters in string $x$ and get exact string $y$. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not. You are given two strings $s$ and $t$ of the same length, consisting of uppercase...
Lets denote the number of character $x$ in $s$ by $C_{s}(x)$. Similarly $C_{t}(x)$ is defined. Then the minimum number of changes required to get anagram of $t$ from $s$ is equal to $\textstyle\sum(C_{s t}(x)-C_{t}(x)|}$. Now we need to obtain lexicographically minimum solution. Lets iterate through the positions in $s...
[ "greedy", "strings" ]
1,800
null
254
D
Rats
Rats have bred to hundreds and hundreds in the basement of the store, owned by Vasily Petrovich. Vasily Petrovich may have not noticed their presence, but they got into the habit of sneaking into the warehouse and stealing food from there. Vasily Petrovich cannot put up with it anymore, he has to destroy the rats in th...
Choose arbitrary rat (for say, the leftmost of the upmost). It's cell should be cleared. Make a BFS that never goes further than $d$ from this cell (we will call such a BFS by d-BFS). It will visit approximately $2d^{2}$ cells in the worst case. So, we have to blow the first grenade in one of the visited cells. Lets ch...
[ "brute force", "dfs and similar", "graphs", "implementation", "shortest paths" ]
2,300
null
254
E
Dormitory
Student Vasya came to study in Berland State University from the country, so he is living in a dormitory. A semester has $n$ days, and in each of those days his parents send him some food. In the morning of the $i$-th day he receives $a_{i}$ kilograms of food that can be eaten on that day and on the next one (then the ...
The problem can be solved by dynamic programming: denote as $D(n, r)$ the maximum rating that we can achieve in the first $n$ days with the condition that we have $r$ kilos of food remaining from the day $n - 1$. It is obvious that if we decide to feed $k$ friends on some day, the better way is to feed $k$ friends with...
[ "dp", "implementation" ]
2,100
null