Dataset Viewer
Auto-converted to Parquet Duplicate
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
1
A
Theatre Square
Theatre Square in the capital city of Berland has a rectangular shape with the size $n × m$ meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size $a × a$. What is the least number of flagstones needed to pave the Square?...
The constraint that edges of each flagstone much be parralel to edges of the square allows to analyze X and Y axes separately, that is, how many segments of length 'a' are needed to cover segment of length 'm' and 'n' -- and take product of these two quantities. Answer = ceil(m/a) * ceil(n/a), where ceil(x) is the leas...
[ "math" ]
1,000
null
1
B
Spreadsheet
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th...
Let each letter representation of column number be associated with integer in radix-26, where 'A' = 0, 'B' = 1 ... 'Z'=25. Then, when converting letter representation to decimal representation, we take associated integer and add one plus quantity of valid all letter representations which are shorter than letter represe...
[ "implementation", "math" ]
1,600
null
1
C
Ancient Berland Circus
Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different. In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec...
The points can be vertices of regular N-polygon, if, and only if, for each pair, difference of their polar angles (as viewed from center of polygon) is a multiple of 2*pi/N. All points should lie on the circle with same center as the polygon. We can locate the center of polygon/circle [but we may avoid this, as a chord...
[ "geometry", "math" ]
2,100
null
2
A
Winner
The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla...
To solve the problem we just need accurately follow all rules described in the problem statement. Let's describe in more details required sequence of actions. First of all, we need to find the maximum score m at the end of the game. This can be done by emulating. After all rounds played just iterate over players and ch...
[ "hashing", "implementation" ]
1,500
null
2
B
The least round way
There is a square matrix $n × n$, consisting of non-negative integer numbers. You should find such a way on it that - starts in the upper left cell of the matrix; - each following cell is to the right or down from the current cell; - the way ends in the bottom right cell. Moreover, if we multiply together all the num...
First of all, let's consider a case when there is at least one zero number in the square. In this case we can easily create a way with only one trailing zero in resulting multiplication - just output way over this zero number. The only case when this is not optimal way is when a way exists with no trailing zeroes at al...
[ "dp", "math" ]
2,000
null
2
C
Commentator problem
The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to cho...
Let's take two stadiums and find out a set of points from which the stadiums are observed at the same angle. Not very hard mathematical calculation shows that this is a line if stadiums have the same radius and this is a circle if they have different radiuses. Let's define S(i,j) as a set of points from which the stadi...
[ "geometry" ]
2,600
null
5
A
Chat Servers Outgoing Traffic
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands: - Include a person ...
Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.
[ "implementation" ]
1,000
null
5
B
Center Alignment
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck!
Both are implementation problems. The only difficult, many participants faced with - to read data correctly. It is recommended to use gets(s) or getline(cin, s) in C++, readLine() method of BufferedReader class in Java.
[ "implementation", "strings" ]
1,200
null
5
C
Longest Regular Bracket Sequence
This is yet another problem dealing with regular bracket sequences. We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not....
First of all, for each closing bracket in our string let's define 2 values: d[j] = position of corresponding open bracket, or -1 if closing bracket doesn't belong to any regular bracket sequence. c[j] = position of earliest opening bracket, such that substring s(c[j], j) (both boundaries are inclusive) is a regular bra...
[ "constructive algorithms", "data structures", "dp", "greedy", "sortings", "strings" ]
1,900
null
5
D
Follow Traffic Rules
Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the ro...
This problem can be solved by careful case handling. Let's construct O(1) solution for it. First of all, let's define 2 functions: $dist(speed, time)$ - calculates the distance will be covered in specified time, if car's current speed is speed. This function will not take car's speed limit into account. Also it assumes...
[ "implementation", "math" ]
2,100
null
5
E
Bindian Signalizing
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by $n$ hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman co...
Let's reduce the problem from the circle to the straight line. Perform the following actions to do it: Find the hill with the maximal height (if it is not unique, choose any). Rotate all the sequence in such a way that hill with maximal height goes first. For convenience, add one more hill with maximum height to the en...
[ "data structures" ]
2,400
null
6
A
Triangle
Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo...
For each of the possible combinations of three sticks , we can make a triangle if sum of the lengths of the smaller two is greater than the length of the third and we can make a segment in case of equality.
[ "brute force", "geometry" ]
900
#include <iostream> using namespace std; bool tr(int a,int b,int c) { return ((a+b>c)&&(a+c>b)&&(b+c>a)); } bool seg(int a,int b,int c) { return ((a==b+c)||(b==a+c)||(c==a+b)); } int main() { bool normal=false; bool deg=false; int a,b,c,d; cin>>a>>b>>c>>d; normal=normal||(tr(a,b,c)); normal=normal...
6
B
President's Office
President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all ...
For each cell of president's desk , we check all its neighbors and add their colors to a set. easy as pie!
[ "implementation" ]
1,100
#include <iostream> #include <string> #include <set> using namespace std; set<char> adj; int main() { int n,m; char c; cin>>n>>m>>c; string room[n]; for(int i=0;i<n;i++) cin>>room[i]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(room[i][j]==c) { ...
6
C
Alice, Bob and Chocolate
Alice and Bob like games. And now they are ready to start a new game. They have placed $n$ chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them wi...
This one can be solved easily by simulation. see the code.
[ "greedy", "two pointers" ]
1,200
#include <iostream> #include <deque> #include <algorithm> using namespace std; struct eater{ int ate; int wait; void init() { ate=wait=0; } }; int main() { eater alice,bob; bob.init(); alice.init(); int n; cin>>n; deque<int> chocs; for(int i=0;i<n;i++) { int t; cin>>t; ...
6
E
Exposition
There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were pub...
I solved this one in O(nlgn) time using a segment-tree and keeping track of minimum and maximum element in each segment. Adding a number is O(lgn) because we need to update minimum and maximum for the log2n segments containing that number. For each start point we query the tree to find the maximal endpoint. This is aga...
[ "binary search", "data structures", "dsu", "trees", "two pointers" ]
1,900
null
8
D
Two Friends
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wan...
The main observation for this problem is the following: If Alan and/or Bob is at some point X and moves following some curve and travels distance d, then the point at which they finish can be ANY point on or inside the circle with center X and radius d. In other words: If you start at some point X and go to some point ...
[ "binary search", "geometry" ]
2,600
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> #include <complex> using namespace std; const double eps = 1e-10; const int DIM = 2; typedef complex<double> point; typedef pair<point, double> circle; double T1, T2; point cinema, shop, ...
8
E
Beads
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if on...
This is quite an interesting problem for me. We must find the k-th lexicographically smallest number from a subset of the numbers from 0 to 2^N(It is easier to increase K with one and consider the all zeroes and all ones case, too). The numbers which we want to count are those which are smaller or equal to their invert...
[ "dp", "graphs" ]
2,600
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstring> #include <cmath> #include <ctime> using namespace std; const int MAXN = 50; typedef long long ll; int n, nPrefix; ll rem; int s[MAXN]; ll dp[MAXN + 1][2][2]; ll f(int pos, int less, int lessRev) { if (dp[pos][less][...
9
A
Die Roll
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
If the maximum of Yakko's and Wakko's points is a, then Dot will win, if she has not less than a points. So the probability of her win is (6 - (a-1)) / 6. Since there are only 6 values for a, you can simply hardcode the answers.
[ "math", "probabilities" ]
800
null
9
B
Running Student
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point $(0, 0)$, he got on a minibus and they drove along a straight line, parallel to axis $OX$, in the direction of increasing $x$. Poor Student knows the following: - during one run the minibus makes $...
It is simple to calculate the time $ti$ that the Student will need, if he gets off the bus at the i-th stop: $ti = bi + si$, where $bi = xi / vb$ is the time he will drive on the bus, and $s_{i}=\sqrt{(x_{i}-x_{u})^{2}+y_{u}^{2}}/v_{s}$ is the time he will need to get from the i-th stop to the University. We need to ch...
[ "brute force", "geometry", "implementation" ]
1,200
null
9
C
Hexadecimal's Numbers
One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. He loaded there a huge amount of $n$ different natural numbers from 1 to $n$ to obtain total control over her energy. But his plan failed. The reason for th...
Brute force solution, when you try each number from 1 to n, will not fit into the time limit.Note, however, that all good numbers have at most 10 digits, and each of the digits is 0 or 1. That is, there are at most $210$ binary strings to check. Each of these strings is a number from 1 to $210 - 1$ in binary representa...
[ "brute force", "implementation", "math" ]
1,200
null
9
D
How many trees?
In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terribl...
Denote by $tnh$ the number of binary search trees on n nodes with height equal to h. We will derive a recurrent formula for $tnh$. For the base case note that $t00 = 1$ (empty tree), and $ti0 = t0i = 0$ if i>0.Now take any binary search tree on n nodes with height equal to h. Let m be the number written at its root, $1...
[ "combinatorics", "divide and conquer", "dp" ]
1,900
null
9
E
Interestring graph and Apples
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A f...
Interesting graph and Apples The funny ring consists of n vertices and n edges. If there is another edge except for these n, then the vertices it connects belong to more than one cycle. So, an interesting graph is just a funny ring. A graph is a funny ring if and only if the following conditions hold:A1. The degree of ...
[ "dfs and similar", "dsu", "graphs" ]
2,300
null
13
A
Numbers
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18. Now he wonders what is an average value of sum of digits of the number $A$ written in all bases from $2$ to $A - 1$. Note that all c...
It is sufficient to iterate over all bases from 2 to A-2 and find the sum of digits in them. Then one should find the greatest common divisor of found sum and A-2 (which is equal to number of bases in which we found the sums). The numerator of the answer is equal to founded sum divided by this GCD and the denominator i...
[ "implementation", "math" ]
1,000
null
13
B
Letter A
Little Petya learns how to write. The teacher gave pupils the task to write the letter $A$ on the sheet of paper. It is required to check whether Petya really had written the letter $A$. You are given three segments on the plane. They form the letter $A$ if the following conditions hold: - Two segments have common en...
This problem appeared to be quite unpleasant to code, but all what one need to do is to check whether all three statements are true. It is recommended to perform all computations using integer arithmetics and to use scalar and vector product instead of computing cosines of angles or angles itself.
[ "geometry", "implementation" ]
2,000
null
13
C
Sequence
Little Petya likes to play very much. And most of all he likes to play the following game: He is given a sequence of $N$ integer numbers. At each step it is allowed to increase the value of any number by $1$ or to decrease it by $1$. The goal of the game is to make the sequence non-decreasing with the smallest number ...
Note, that there exists a non-decreasing sequence, which can be obtained from the given sequence using minimal number of moves and in which all elements are equal to some element from the initial sequence (i.e. which consists only from the numbers from the initial sequence).Suppose {ai} is the initial sequence, {bi} is...
[ "dp", "sortings" ]
2,200
null
13
D
Triangles
Little Petya likes to draw. He drew $N$ red and $M$ blue points on the plane in such a way that no three points lie on the same line. Now he wonders what is the number of distinct triangles with vertices in red points which do not contain any blue point inside.
We will solve the problem using the following algorithm:Fix some red point.Find the number of triangles with vertices in the red points which don't contain any blue points inside and which have the fixed red point as one of the vertices.Remove the fixed red point and go back to statement 1, if there remain any red poin...
[ "dp", "geometry" ]
2,600
null
13
E
Holes
Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules: There are $N$ holes located in a single row and numbered from left to right with numbers from 1 to $N$. Each hole has it's own power (hole number $i$ has the power $a_{i}$). If you throw a...
Let's divide all row into blocks of length K=sqrt(N) of consecutive holes. If N is not a complete square, then we will take K=sqrt(N) rounded down. For each hole we will maintain not only it's power (let's call it power[i]), but also the number of the first hole which belongs to other block and which can be reached fro...
[ "data structures", "dsu" ]
2,700
null
14
A
Letter
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with $n$ rows and $m$ columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the w...
To find the smallest rectangle containing the picture, iterate through the pairs (i,j) such that the j-th symbol in i-th line is '*'; find the minimum and maximum values of i and j from these pairs. The rectangle to output is $[imin, imax] \times [jmin, jmax]$.
[ "implementation" ]
800
null
14
B
Young Photographer
Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position $x_{0}$ of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training a...
First we find the intersection of all segments. To do this, denote by m the rightmost of left ends of the segments and denote by M the leftmost of right ends of the segments. The intersection of the segments is [m,M] (or empty set if m>M). Now determine the nearest point from this segment. If $x0 < m$, it's $m$, and th...
[ "implementation" ]
1,000
null
14
C
Four Segments
Several months later Alex finally got his brother Bob's creation by post. And now, in his turn, Alex wants to boast about something to his brother. He thought for a while, and came to the conclusion that he has no ready creations, and decided to write a program for rectangles detection. According to his plan, the progr...
There must be many ways to solve this problem. The following one seems quite easy to code.First count the number of distinct points among segments' ends. If it's not equal to 4, the segments can't form a rectangle and we output "NO". Then calculate the minimum and maximum coordinates of the 4 points: $xmin$, $xmax$, $y...
[ "brute force", "constructive algorithms", "geometry", "implementation", "math" ]
1,700
null
14
D
Two Paths
As you know, Bob's brother lives in Flatland. In Flatland there are $n$ cities, connected by $n - 1$ two-way roads. The cities are numbered from 1 to $n$. You can get from one city to another moving along the roads. The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A...
Take any pair of non-intersecting paths. Since Flatland is connected, there must be a third path, connecting these two. Remove a road from the third path. Then Flatland is divided into two components - one containing the first path, and the other containing the second path. This observation suggests us the algorithm: i...
[ "dfs and similar", "dp", "graphs", "shortest paths", "trees", "two pointers" ]
1,900
null
14
E
Camels
Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with $t$ humps, representing them as polylines in the plane. Each polyline consists of $n$ vertices with coordinates $(x_{1}, y_{1})$, $(x_{2}, y_{2})$, ..., $(...
Let us call an index j such that $yj - 1 > yj < yj + 1$ a cavity. Also, we'll call humps and cavities by the common word break. Then there must be exactly $T = 2t - 1$ breaks, and the first one must be a hump.Denote by $fnth$ the number of ways in which a camel with $t$ breaks, ending at the point (n,h), can be extende...
[ "dp" ]
1,900
null
17
A
Noldbach problem
Nick is interested in prime numbers. Once he read about \underline{Goldbach problem}. It states that every even integer greater than $2$ can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it \underline{Noldbach problem}. Since Nick is interested o...
To solve this problem you were to find prime numbers in range $[2..N]$. The constraints were pretty small, so you could do that in any way - using the Sieve of Eratosthenes or simply looping over all possible divisors of a number.Take every pair of neighboring prime numbers and check if their sum increased by $1$ is a ...
[ "brute force", "math", "number theory" ]
1,000
null
17
B
Hierarchy
Nick's company employed $n$ people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are $m$ applications written in the following form: \underline{«employee $a_{i}$ is ready to become a super...
Note that if employee, except one, has exactly one supervisor, then our hierarchy will be tree-like for sure.For each employee consider all applications in which he appears as a subordinate. If for more than one employee there are no such applications at all, it's obvious that $- 1$ is the answer. In other case, for ea...
[ "dfs and similar", "dsu", "greedy", "shortest paths" ]
1,500
null
17
C
Balance
Nick likes strings very much, he likes to rotate them, sort them, rearrange characters within a string... Once he wrote a random string of characters a, b, c on a piece of paper and began to perform the following operations: - to take two adjacent characters and replace the second character with the first one, - to ta...
Consider the input string $A$ of length $n$. Let's perform some operations from the problem statement on this string; suppose we obtained some string $B$. Let compression of string $X$ be a string $X'$ obtained from $X$ by replacing all consecutive equal letters with one such letter. For example, if $S = "aabcccbbaa"$,...
[ "dp" ]
2,500
null
17
D
Notepad
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base $b$ caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length $n$ without leading zeros in this num...
The answer to the problem is $bn - 1 * (b - 1)$ mod $c$. The main thing you should be able to do in this problem - count the value of $AB$ mod $C$ for some long numbers $A$ and $B$ and a short number $C$. Simple exponentiation by squaring exceeds time limit since to converse of $B$ to binary you need about $O(|B|2)$ op...
[ "number theory" ]
2,400
null
17
E
Palisection
In an English class Nick had nothing to do at all, and remembered about wonderful strings called \underline{palindromes}. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «ab...
The first thing to do is to find all subpalindromes in the given string. For this you may use a beautiful algorithm described for example here. In short, this algorithm find the maximal length of a subpalindrome with its center either at position $i$ of the string or between positions $i$ and $i + 1$ for each possible ...
[ "strings" ]
2,900
null
19
A
World Football Cup
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: - the final tournament features $n$ teams ($n$ is always even) - the first $n / 2$ teams...
I think is' just a problem about writing code quickly and correctly.Just follow the statement. if you use c++ STL will make you life easier
[ "implementation" ]
1,400
null
19
B
Checkout Assistant
Bob came to a cash & carry store, put $n$ items into his trolley, and went to the checkout counter to pay. Each item is described by its price $c_{i}$ and time $t_{i}$ in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from h...
First,for every i increase ti by 1..then you will see that statement require sum of t of the items bigger or equal to n..and their sum of c should be minimal..so it's just a 0-1 knapsack problem.
[ "dp" ]
1,900
null
19
C
Deletion of Repeats
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length $x$ is such a substring of length $2x$, that its first half ...
First let's generate all repeats.In a repeat,the first number and the middle number must be the same, so we just look at all pair of postion which have same number..Thank to the statement..There are at most O(10N) such pair..And use suffix array to check if each pair can build a repeat...Then just sort all the interval...
[ "greedy", "hashing", "string suffix structures" ]
2,200
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) fo...
19
D
Points
Pete and Bob invented a new interesting game. Bob takes a sheet of paper and locates a Cartesian coordinate system on it as follows: point $(0, 0)$ is located in the bottom-left corner, $Ox$ axis is directed right, $Oy$ axis is directed up. Pete gives Bob requests of three types: - add x y — on the sheet of paper Bob ...
First of all,do the discretization.Then the biggest value of x is n,so we can build a Segment Tree to Ask the question "what is the first place from postion x and its value is bigger than y"..if we find such postion we just find the smallest Y-value bigger than y in such postion--it can be done using set's operation up...
[ "data structures" ]
2,800
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) fo...
19
E
Fairy
Once upon a time there lived a good fairy A. One day a fine young man B came to her and asked to predict his future. The fairy looked into her magic ball and said that soon the fine young man will meet the most beautiful princess ever and will marry her. Then she drew on a sheet of paper $n$ points and joined some of t...
It's a interesting problem.If you for every edge, try to remove it and check if it is a bipartite graph..I think it will get TLE..so let's analysis the property of bipartite graph..http://en.wikipedia.org/wiki/Bipartite_graphAfter reading it...we know.. It should never contain a cycle of odd length... and it can be 2-c...
[ "dfs and similar", "divide and conquer", "dsu" ]
2,900
#include <vector> #include <algorithm> #include <utility> #include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <set> #include <map> #include <cstring> #include <time.h> #define rep(i,n) for(int i=0;i<n;i++) #define pb push_back #define Debug(x) cout<<#x<<"="<<x<<endl; #define For(i,l,r) fo...
22
A
Second Order Statistics
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
In this problem one should find a minimal element from all elements, that are strictly greater, then the minimal one or report that it doesn't exist. Of course, there can be a lot of different solutions, but one of the simplest - to sort the given sequence and print the first element, that's not equal to the previous. ...
[ "brute force" ]
800
null
22
B
Bargaining Table
Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room $n × m$ meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that ...
In this problem one should find the maximal perimeter of a rectangle that contains no '1'. Define these rectangles "correct". To solve a problem you are to check each possible rectangle for correctness and calculate its perimeter. The easiest way to check all rectangles is using 6 nested cycles. Using 4 of them you fix...
[ "brute force", "dp" ]
1,500
null
22
C
System Administrator
Bob got a job as a system administrator in X corporation. His first task was to connect $n$ servers with the help of $m$ two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair o...
In this problem you are to construct a connected graph, which contains n vertexes and m edges, and if we delete vertex with number v, our graph stops being connected or to report that such a graph doesn't exist. Moreover, each pair of vertexes can have no more than one edge connecting them. Obviously, a connected graph...
[ "graphs" ]
1,700
null
22
D
Segments
You are given $n$ segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails ne...
In this problem one should place minimal number of points on the line such that any given segment touches at least one of these points. Let's call the coordinate of ending of any segment as event. There will be events of two types: beginning of a segment and its ending. Let's sort this events by coordinates. In the cas...
[ "greedy", "sortings" ]
1,900
null
22
E
Scheme
To learn as soon as possible the latest news about their favourite fundamentally new operating system, BolgenOS community from Nizhni Tagil decided to develop a scheme. According to this scheme a community member, who is the first to learn the news, calls some other member, the latter, in his turn, calls some third mem...
Given an oriented graph, find the minimal number of edges one should add to this graph to make it strongly connected. Looking at statement we can get the fact that each vertex has exactly one outcoming edge. It means that starting at some point we'll get stuck in some cycle. So each connected (not strongly) component i...
[ "dfs and similar", "graphs", "trees" ]
2,300
null
23
A
You're Given a String...
You're given a string of lower-case Latin letters. Your task is to find the length of its longest substring that can be met in the string at least twice. These occurrences can overlap (see sample test 2).
Iterate over all substrings, starting with the longest ones, and for each one count the number of appearances. The complexity is $O(L4)$ with a small multiplicative constant.
[ "brute force", "greedy" ]
1,200
null
23
B
Party
$n$ people came to a party. Then those, who had no friends among people at the party, left. Then those, who had exactly 1 friend among those who stayed, left as well. Then those, who had exactly $2, 3, ..., n - 1$ friends among those who stayed by the moment of their leaving, did the same. What is the maximum amount o...
It's clear that at least one person (the one with the least number of friends) will have to leave. We claim that at least two persons will leave. Indeed, suppose that only one person left, and he had $d$ friends. Then all other people had more than $d$ friends before he left, and after that they had less than $d + 1$ f...
[ "constructive algorithms", "graphs", "math" ]
1,600
null
23
C
Oranges and Apples
In $2N - 1$ boxes there are apples and oranges. Your task is to choose $N$ boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.
Sort the boxes in increasing number of oranges. Count the total number of apples in boxes with odd and even numbers. If the boxes with odd numbers contain at least half of all apples, choose them (there are exactly $N$ boxes with odd numbers). If the boxes with even numbers contain at least half of all apples, take the...
[ "constructive algorithms", "sortings" ]
2,500
null
23
D
Tetragon
You're given the centers of three equal sides of a strictly convex tetragon. Your task is to restore the initial tetragon.
Let ABCD be the quadrangle that we're looking for, and K, L, and M be the middle points of equal sides AB, BC and CD, correspondingly. Let M' be the point symmetric to M with respect to L. Triangles BLM' and CLM are equal by two sides and angle, so BM' = CM = BL = BK, i. e. B is the circumcenter of the triangle KLM'. K...
[ "geometry", "math" ]
2,600
null
23
E
Tree
Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can...
Lemma. In one of optimal solutions there are no simple paths of length 3.Proof. We can remove the middle edge from such a path. The connected component will split into two components of sizes $a$ and $b$, where $a \ge 2, b \ge 2$, and therefore $ab \ge a + b$.We'll root the tree and calculate recursively the numb...
[ "dp" ]
2,500
null
24
A
Ring road
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all $n$ cities of Berland were connected by $n$ two-way roads in the ring, i. e. each city was connected directly to exactly tw...
This is pretty simple task - we have cycle and must direct all edges on it in one of 2 directions. We need to calculate cost of both orientation and print smallest of them.There is a small trick - we can calculate cost of only one orientation and then cost of the other will be sum of costs of all edges minus cost of fi...
[ "graphs" ]
1,400
null
24
B
F1 Champions
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha...
Also very simple - we need literary do what we asked. We put all data in a map where for each pilot we have number of points and array of 50 elements - number of times pilot finished at corresponding place. Then we just need to find maximum in this array according to 2 given criteria.
[ "implementation" ]
1,500
null
24
C
Sequence of points
You are given the following points with integer coordinates on the plane: $M_{0}, A_{0}, A_{1}, ..., A_{n - 1}$, where $n$ is odd number. Now we define the following infinite sequence of points $M_{i}$: $M_{i}$ is symmetric to $M_{i - 1}$ according ${\cal A}_{\{i-1\}}\,\mathrm{\mod}\,\,n$ (for every natural number $i$)...
Reflection over 2 points is just a parallel shift for a doubled vector between them. So $M2n$ = $M0$ because sequence of reflections may be replaced with sequence of shifts with doubled vectors $A0A2$, $A2A4$, ..., $An - 2A0$ - and their sum is 0. So we can replace j with $j' = jmod2N$. Now we can just perform j' refle...
[ "geometry", "implementation", "math" ]
1,800
null
24
D
Broken robot
You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of $N$ rows and $M$ columns of cells. The robot is initially at some cell on the $i$-th row and the $j$-th column. Then at every step the...
If robot is at last row then answer is 0. Suppose that for every cell of the next row we now expected number of steps to reach last row - $zi$. Let $xi$ be expected value of steps to reach the last row from current row. Then we have following system of equations:$x1 = 1 + x1 / 3 + x2 / 3 + z1 / 3$$xi = 1 + xi / 4 + xi ...
[ "dp", "math", "probabilities" ]
2,400
null
24
E
Berland collider
Recently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains $n$ particles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the col...
At first we need to exclude answer -1. Answer is -1 if and only if first part of particles moves left and second part moves right (any of this parts may be empty)Let's use binary search. Maximal answer is 1e9. Suppose we need to unserstand - whether answer is more then t or less then t. Let's itirate particles from lef...
[ "binary search" ]
2,300
null
25
A
IQ test
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given $n$ numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given $n$ numbers finds one that i...
We can store two values, $count_{odd}$ and $count_{even}$, as the number of odd or even elements in the series. We can also store $last_{odd}$ and $last_{even}$ as the index of the last odd/even item encountered. If only one odd number appears --- output $last_{odd}$; otherwise only one even number appears, so output $...
[ "brute force" ]
1,300
null
25
B
Phone numbers
Phone number in Berland is a sequence of $n$ digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three...
There are many ways of separating the string into clusters of 2 or 3 characters. One easy way is to output 2 characters at a time, until you have only 2 or 3 characters remaining.
[ "implementation" ]
1,100
null
25
C
Roads in Berland
There are $n$ cities numbered from 1 to $n$ in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance ...
If you are familiar with the Floyd-Warshall algorithm, then this solution may be easier to see.Initially, we are given a matrix $D$, where $D[i][j]$ is the distance of shortest path between city $i$ and city $j$. Suppose we build a new road between $a$ and $b$ with length shorter than $D[a][b]$. How do we update the re...
[ "graphs", "shortest paths" ]
1,900
null
25
D
Roads not only in Berland
Berland Government decided to improve relations with neighboring countries. First of all, it was decided to build new roads so that from each city of Berland and neighboring countries it became possible to reach all the others. There are $n$ cities in Berland and neighboring countries in total and exactly $n - 1$ two-w...
Before we start this problem, it is helpful to know about the union find data structure. The main idea is this: given some elements $x_{1}, x_{2}, x_{3}, ..., x_{n}$ that are partitioned in some way, we want to be able to do the following:merge any two sets together quicklyfind the parent set of any $x_{i}$This is a ge...
[ "dsu", "graphs", "trees" ]
1,900
null
25
E
Test
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring $s_{1}$, the second enters an infinite l...
The way I solved this problem is with a hash function. Hash functions can fail on certain cases, so in fact, my solution is not 'correct'. However, it passed all the test cases =PLet the input strings be $s_{0}, s_{1}, s_{2}$. We can build the shortest solution by permuting the strings and then trying to 'attach' them ...
[ "hashing", "strings" ]
2,200
null
26
A
Almost Prime
A number is called almost prime if it has exactly two distinct prime divisors. For example, numbers 6, 18, 24 are almost prime, while 4, 8, 9, 42 are not. Find the amount of almost prime numbers which are between 1 and $n$, inclusive.
This is a straightforward implementation problem: factor every number from 1 to n into product of primes and count the number of distinct prime divisors.
[ "number theory" ]
900
null
26
B
Regular Bracket Sequence
A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. One day Johnny got bracket sequence. He decided to remove some...
Read the string from left to right and calculate the balance of brackets at each step (i.e., the difference between the number of "(" and ")" characters written out). We need to keep this balance non-negative. Hence, every time when the balance equals 0 and we read the ")" character, we must omit it and not write it ou...
[ "greedy" ]
1,400
null
26
C
Parquet
Once Bob decided to lay a parquet floor in his living room. The living room is of size $n × m$ metres. Bob had planks of three types: $a$ planks $1 × 2$ meters, $b$ planks $2 × 1$ meters, and $c$ planks $2 × 2$ meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it ...
We'll derive several necessary conditions for the parquet to be possible. If some of them is not fulfilled, the answer is "IMPOSSIBLE".1. m*n must be even, because it equals the total area of the parquet, and the area of each plank is even.2. Suppose m (the number of columns) is odd. Paint the living room in two colors...
[ "combinatorics", "constructive algorithms", "greedy", "implementation" ]
2,000
null
26
D
Tickets
As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for t...
If we picture the graph of the number of 10-euro banknotes, it will be a broken line, starting at the point (0, k) and ending at the point (m+n, n+k-m). Exactly $m$ segments on the line are 'going down', and other $n$ segments are 'going up'. Hence the total number of possible graphs is $C(m + n, m)$ (the binomial coef...
[ "combinatorics", "math", "probabilities" ]
2,400
null
26
E
Multithreading
You are given the following concurrent program. There are $N$ processes and the $i$-th process has the following pseudocode: \begin{verbatim} repeat $n_{i}$ times $y_{i}$ := $y$ $y$ := $y_{i} + 1$ end repeat \end{verbatim} Here $y$ is a shared variable. Everything else is local for the process. All actions on a giv...
It's clear that we must have $1 \le w \le \Sigma _{i} n_{i}$. If this condition is true, we show how to achieve the desired result in the following cases:1. $N = 1, w = n_{1}$. Obvious.2. $N \ge 2, w \ge 2$. For $w = 2$, the schedule is the following: 1, all loops of processes 3..N, $n_{2} - 1$ loops of the se...
[ "constructive algorithms" ]
2,400
null
27
A
Next Test
«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated ...
We will create an array of boolean used[1..3001] ans fill it with "false" values. For each of n given number, we will assign corresponding used value to "true". After that, the index of first element of used with "false" value is the answer to the problem.
[ "implementation", "sortings" ]
1,200
null
27
B
Tournament
The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. $n$ best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. $n·(n - 1) / 2$ games were played during the tournament, and each participant had...
To solve this problem first of all we should find such numbers A and B that occur in the input data not (n - 1) times, but (n - 2). We can notice, that winner-loser relation in this problem is transitive. This means that if X wins against Y and Y wins against Z, than X wins against Z. So to find out who is harsher A or...
[ "bitmasks", "brute force", "dfs and similar", "greedy" ]
1,300
null
27
C
Unordered Subsequence
The sequence is called \underline{ordered} if it is non-decreasing or non-increasing. For example, sequnces [3, 1, 1, 0] and [1, 2, 3, 100] are ordered, but the sequence [1, 3, 3, 1] is not. You are given a sequence of numbers. You are to find it's shortest subsequence which is not ordered. A subsequence is a sequence...
First of all, we should notice, that if answer exists, it consist of 3 elements. Here is linear time solution. Let's path with for-loop through the given array and on each iteration let's store current minimul and maximun elements positions. When we are looking at some element, it is enough to check, whereas this eleme...
[ "constructive algorithms", "greedy" ]
1,900
null
27
D
Ring Road 2
It is well known that Berland has $n$ cities, which form the Silver ring — cities $i$ and $i + 1$ ($1 ≤ i < n$) are connected by a road, as well as the cities $n$ and $1$. The goverment have decided to build $m$ new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should ...
Consider all m given roads as segments on numeric axis. Road from town a to town b should correspond to segment [min(a, b), max(a, b)]. For each pair of segments there are three types of positions: both ends of one segment are inside of the other one, both ends of one segment are outside of the other one and only one e...
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
2,200
null
27
E
Number With The Given Amount Of Divisors
Given the number $n$, find the smallest positive integer which has exactly $n$ divisors. It is guaranteed that for the given $n$ the answer will not exceed $10^{18}$.
Consider the number, that is our answer and factorize it. We will get such product $p_{1}^{None} \cdot p_{2}^{None} \cdot ... \cdot p_{k}^{None}$. Product through each i $a_{i} + 1$ will be the number of divisors. So, if we will take first 10 prime numbers, their product will have 1024 divisors. This means that we ...
[ "brute force", "dp", "number theory" ]
2,000
null
28
A
Bender Problem
Robot Bender decided to make Fray a birthday present. He drove $n$ nails and numbered them from $1$ to $n$ in some order. Bender decided to make a picture using metal rods. The picture is a closed polyline, which vertices should be nails (in the given order). The segments of the polyline should be parallel to the coord...
Let's look at the first nail. If it is occupied by the fold place, then Bender will put next fold place on the third nail, then on fifth and so on. Else, is the first nail occupied by end, than second, fourth, sixth and so on nail will be occupied by the fold places. Let's see, if we can complete our polyline with the ...
[ "implementation" ]
1,600
null
28
B
pSort
One day $n$ cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from $1$). Also each cell determined it's favourite number. On it's move $i$-th cell can exchange it's value with the value of some other $j$-th cell, if $|i - j| = d...
Let's consider a graph. Vertexes will correspond to place of the permutation. Places will be connected by an edge if and only if we can swap theirs values. Our problem has a solution when for every i, vertex p[i] can be reached from vertex i.
[ "dfs and similar", "dsu", "graphs" ]
1,600
null
28
C
Bath Queue
There are $n$ students living in the campus. Every morning all students wake up at the same time and go to wash. There are $m$ rooms with wash basins. The $i$-th of these rooms contains $a_{i}$ wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students select...
This problem is solved by dynamic programming Consider the following dynamics: $d[i][j][k]$. $i$ --- number of not yet processed students, $j$ --- number of not yet processed rooms, $k$ --- maximum queue in the previous rooms. The value we need is in state $d[n][m][0]$. Let's conside some state $(i, j, k)$ and search t...
[ "combinatorics", "dp", "probabilities" ]
2,200
null
28
D
Don't fear, DravDe is kind
A motorcade of $n$ trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is ...
Let's split all trucks into different classes by the sum of $l_{i} + c_{i} + r_{i}$. Answer sequence consists of trucks from only one class, so let's solve problem for different classes independently. Let's loop through trucks from fixed class in the order, then follow in the motorcade and update values in dynamics $z[...
[ "binary search", "data structures", "dp", "hashing" ]
2,400
null
28
E
DravDe saves the world
How horrible! The empire of galactic chickens tries to conquer a beautiful city "Z", they have built a huge incubator that produces millions of chicken soldiers a day, and fenced it around. The huge incubator looks like a polygon on the plane $Oxy$ with $n$ vertices. Naturally, DravDe can't keep still, he wants to dest...
Let's look at geometrical locus where DravDe can land. It can be eigher an angle or a line(half-line). 1. Locus is an angle if and only if projection of vector $v$ and vector $u$ on Oxy plane is not collinear. This angle is easy to calculate. Angular vertex is DravDe starting point and one of half-lines is collinear wi...
[ "geometry", "math" ]
2,800
null
29
A
Spit Problem
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
Check whether exist a pair i and j,they satisfy xi+di = xj && xj+dj = xi;
[ "brute force" ]
1,000
null
29
B
Traffic Lights
A car moves from point A to point B at speed $v$ meters per second. The action takes place on the X-axis. At the distance $d$ meters from A there are traffic lights. Starting from time 0, for the first $g$ seconds the green light is on, then for the following $r$ seconds the red light is on, then again the green light ...
Pay attention to Just Right or Red. use Div and Mod can solve it easily;
[ "implementation" ]
1,500
null
29
C
Mail Stamps
One day Bob got a letter in an envelope. Bob knows that when Berland's post officers send a letter directly from city «A» to city «B», they stamp it with «A B», or «B A». Unfortunately, often it is impossible to send a letter directly from the city of the sender to the city of the receiver, that's why the letter is sen...
As we know, there are only two path -- forward and reverse, so we can do DFS from the one-degree nodes (only two nodes).As their index may be very larger, so I used map<int,int> to do hash.
[ "data structures", "dfs and similar", "graphs", "implementation" ]
1,700
null
29
D
Ant on the Tree
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too. An ant stands at the root of some tree. He sees that there are $n$ vertexes in the tree, and they are connected by $n - 1$ edges so that there is a path between any pair of...
First, Floyd pretreat the path from I to J, and save the path. Then get the answer.The order is a1,a2...ak, K is the number of the leaves, we can assume a0 = ak+1 = 1, the root.then, answer push_back the path[ai][ai+1].if the ans.size() > 2*N-1 , cout -1;else cout the answer.
[ "constructive algorithms", "dfs and similar", "trees" ]
2,000
null
30
A
Accounting
A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself. The total income $A$ of his kingdom during $0$-th year is known, as well as the total income $B$ during $n$-th year (these numbers can be negative — it means that there...
First solution: naive brute Let's brute all possible values of $X$, and check each of them. It's easy to understand, that $X$ will be constrained in the same limits as values $A$ and $B$, that is, from -1000 to 1000 inclusive (obviously, there exists a test for each such $X$, so we can't decrease these limits). When we...
[ "brute force", "math" ]
1,400
null
30
B
Codeforces World Finals
The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that a...
To solve this problem we had to learn how to check the given date XD.XM.XY for correctness (taking into account number of days in each month, leap years, and so on). After implementing this, we had just to iterate over all 6 possible permutations of three given numbers (BD,BM,BY), checking each of them for correctness ...
[ "implementation" ]
1,700
null
30
D
King's Problem?
Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom. King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordina...
In this problem to create a wright solution you need to perform the following chain of inferences (though, if you skip some steps or do them not completely, you can still get an AC solution :) ): Note that after we visit the city numbered $n + 1$, the further answer depends only from the leftmost and the rightmost unvi...
[ "geometry", "greedy" ]
2,600
null
30
E
Tricky and Clever Password
In his very young years the hero of our story, king Copa, decided that his private data was hidden not enough securely, what is unacceptable for the king. That's why he invented tricky and clever password (later he learned that his password is a palindrome of odd length), and coded all his data using it. Copa is afrai...
Scheme of the author solution The author solution has the following scheme. Let's brute over each possible position $pos$ of the center of the middle part (the part that must be palindrome by problem statement). Then let's take as a $middle$ the maximum palindrome among all centered in the position $pos$. After that we...
[ "binary search", "constructive algorithms", "data structures", "greedy", "hashing", "strings" ]
2,800
null
32
A
Reconnaissance
According to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most $d$ centimeters. Captain Bob has $n$ soldiers in his detachment. Their heights are $a_{1}, a_{2}, ..., a_{n}$ centimeters. Som...
Problem A is quite straight-forward. You can simply enumerate all pairs using two for loops since N is not greater than 1000. Or you can sort the list and for every Ai, find the first Aj such that Aj-Ai>d in the range [i+1,N] using binary search.
[ "brute force" ]
800
null
32
B
Borze
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Problem B doesn't need an array at all. You can consume a single character at a time using getchar and then output a '0' if the character is '.' or consume another character to determine whether to output '1' or '2' otherwise.
[ "expression parsing", "implementation" ]
800
null
32
C
Flea
It is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to $s$ centimeters. A flea has found herself at the center of some cell of the checked board of the size $n × m$ centimeters (each cell is $1 × 1$ centimeters). She can jump as she wishes for an arbit...
Problem C is a little tricky. Two cells are reachable from each other if and only if their horizontal or vertical distance is exactly S if they are on the same row or column, which is identical to the property that their indexes of one dimension is the same while those of the other are congruent modulo S. So you are to...
[ "math" ]
1,700
null
32
D
Constellation
A star map in Berland is a checked field $n × m$ squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer $x$ (\underline{radius of the constellation}) th...
Problem D requires you to scan the map multiple times with increasing radii.
[ "implementation" ]
1,600
null
33
A
What is for dinner?
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". ...
The solution of the problem is rather trivial. It was needed to make an array, where for each row of teeth the value of residual viability of the sickest thooth in this row would have kept (sickest tooth in the row is called the one with the lowest residual viability). Thus we define for each row of teeth the maximum n...
[ "greedy", "implementation" ]
1,200
null
33
C
Wonderful Randomized Sum
Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite th...
This problem can be solved in linear time, using the following idea: 1. If desired prefix and suffix intersect, then their common part is remaining with the initial sign and therefore, this case is equivalent to the case when we take the same suffix and prefix, but without their common part: (s1 [s2 )s3 ] is equal to (...
[ "greedy" ]
1,800
null
End of preview. Expand in Data Studio

CREST (Code, Ratings, Editorials, Statements, and Tags) is a dataset of 8,941 annotated Codeforces problems. For each problem, the dataset includes:

  • The problem statement and tutorial (editorial) text, both of which are math-rich and contain LaTeX-formatted mathematical notation.
  • Reference solution code from the tutorial, when available.
  • A set of algorithmic tags.
  • A numerical difficulty rating.

The dataset supports tasks such as multilabel tag classification and rating regression from competitive programming content.

This dataset is derived from publicly available Codeforces problem metadata. All original problem content remains the property of its respective authors and platforms.

Downloads last month
10