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
150
B
Quantity of Strings
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly $n$, based on the alphabet of size $m$. Any its substring with length equal to $k$ is a palindrome. How many such strings exist? Your task ...
We can offer you two solitions: You can build a graph with positions in sting as a nodes and equality in any substring of length $k$ as edges. Lets denote $e$ the number of components in the graph. The answer is $m^{e}$. Analyze four cases: $k = 1$ or $k > n$, the answer is $m^{n}$. $k = n$, the answer is $m^{(n + 1) /...
[ "combinatorics", "dfs and similar", "graphs", "math" ]
1,600
null
150
C
Smart Cheater
I guess there's not much point in reminding you that Nvodsk winters aren't exactly hot. That increased the popularity of the public transport dramatically. The route of bus $62$ has exactly $n$ stops (stop $1$ goes first on its way and stop $n$ goes last). The stops are positioned on a straight line and their coordinat...
First lets use the linearity of expected value and solve task independently for each passanger. For each path segment (route between neighboring stations) we calculate expected value of profit in case we do not sell a ticket for this segment. In case we sell it the expectation of profit is 0. Now we only need to find t...
[ "data structures", "math", "probabilities" ]
2,200
null
150
D
Mission Impassable
Market stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest ("We don't go to Nvodsk..."). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (...
In this problem you have to use dynamic programming. For our convenience we will calulate three type of values: $Best[l][r]$ - best result player can achieve on the segment $[l, r]$. $Full[l][r]$ - best result player can achieve on the segment from $[l, r]$ if he fully destroys it. $T[l][r][Len]$ - best result player c...
[ "dp", "strings" ]
2,600
null
150
E
Freezing with Style
This winter is so... well, you've got the idea :-) The Nvodsk road system can be represented as $n$ junctions connected with $n - 1$ bidirectional roads so that there is a path between any two junctions. The organizers of some event want to choose a place to accommodate the participants (junction $v$), and the place to...
If there exists a path with the median $ \ge k$, for some $k$, then there exists a path with the median $ \ge q$, for each $q \le k$. That means we can use binary search to calculate the answer. So now the task is: is there any path with the median greater or equal to $Mid$ ? We will calc the edge as $+ 1$ if it's ...
[ "binary search", "data structures", "divide and conquer", "trees" ]
3,000
null
151
A
Soft Drinking
This winter is so cold in Nvodsk! A group of $n$ friends decided to buy $k$ bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has $l$ milliliters of the drink. Also they bought $c$ limes and cut each of them into $d$ slices. After that they found $p$ grams of salt. To make a toast, each frie...
Soda will be enough for $gas$ = $(K$ * $L)$ / $(N$ * $l)$ toasts. Limes will last for $laim = (C * D) / N$ toasts. Salt is enough for $sol = P / (p * N)$ toasts. Total result: $res = min(gas, laim, sol)$.
[ "implementation", "math" ]
800
null
151
B
Phone Numbers
Winters are just damn freezing cold in Nvodsk! That's why a group of $n$ friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size $s_{i}$ (that's the number of phone numbers). We know that ta...
In this task you were to implement the described selection of the maximum elements.
[ "implementation", "strings" ]
1,200
null
152
A
Marks
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook. Overall the group has $n$ students. They received marks for $m$ subjects. Each student got a mark from $1$ to $9$ (inclusive) for each subject. Let's consider a student the best...
In this problem you should do exactly what is written in the statement.
[ "implementation" ]
900
null
152
B
Steps
One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple. Vasya noticed that the yard is a rectangu...
Let's find a formula for the position $(x, y)$ and vector $(dx, dy)$, how many steps to stop the boy can do. You should use "almost" binary search, for example, see the code written by RAD.
[ "binary search", "implementation" ]
1,300
null
152
C
Pocket Book
One day little Vasya found mom's pocket book. The book had $n$ names of her friends and unusually enough, each name was exactly $m$ letters long. Let's number the names from $1$ to $n$ in the order in which they are written. As mom wasn't home, Vasya decided to play with names: he chose three integers $i$, $j$, $k$ ($...
In this task, it was necessary to understand that in position $1$ Vasya can get any name of a special form. More exactly, it's the name of form $s$ = $s_{1}$ $s_{2}$ $s_{3}$ $s_{4}$ $...$ $s_{m}$, where $s_{1}$ - the first letter of any of the names, $s_{2}$ - the second letter of any of the names, $...$ $s_{m}$ - $m$-...
[ "combinatorics" ]
1,400
null
152
D
Frames
One day Vasya got hold of a sheet of checkered paper $n × m$ squares in size. Our Vasya adores geometrical figures, so he painted two rectangles on the paper. The rectangles' sides are parallel to the coordinates' axes, also the length of each side of each rectangle is no less than 3 squares and the sides are painted b...
It was necessary to understand if there are two borders or not. Let's distinguish those $x$ - and $y$-coordinates, in which there are at least $3$ consecutive symbols '#', becouse the length of each border is no less then $3$. It is clear that the coordinates of the corners of borders should be chosen only from those s...
[ "brute force" ]
2,600
null
152
E
Garden
Vasya has a very beautiful country garden that can be represented as an $n × m$ rectangular field divided into $n·m$ squares. One beautiful day Vasya remembered that he needs to pave roads between $k$ important squares that contain buildings. To pave a road, he can cover some squares of his garden with concrete. For e...
The solution of this problem is based on dynamic programming. $dp[mask][v]$ - the value of the minimum correct concrete cover, if we consider as important elements only elements of the mask $mask$, and there are additionally covered the vertex $v = (i, j)$ of the field. There are two types of transfers. First of all we...
[ "bitmasks", "dp", "graphs", "trees" ]
2,500
null
154
A
Hometask
Sergey attends lessons of the $N$-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the $N$-ish language. Sentences of the $N$-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot ...
Constriction saying that no letter occurs in more than one forbidden pair lets us to use the greedy solution. Without the constriction the problem is quite hard. Let's look at all occurences of letters from some pair. They form several continuous substrings divided by some other letters. We can note that in optimal sol...
[ "greedy" ]
1,600
null
154
B
Colliders
By 2312 there were $n$ Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from $1$ to $n$. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling disc...
The clueless solution ''store all the enabled numbers and compare each new number with each of them'' works too slow, as we can add all the prime numbers below $n$, number of which is O(n / log n). We can note that for each number k > 1 at any time no more than one collider is turned on which number is divided by k. Le...
[ "math", "number theory" ]
1,600
null
154
C
Double Profiles
You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user. The social network contains $n$ registered profiles, numbered from $1$ to $n$. Some pairs there are friends (the "friendship" relationship is mutu...
We want to count the number of pairs of vertices in a undirected graph which neighbours' sets are equal up to these vertices. To count the pairs which sets of neighbours are equal we can hash these sets (for instance, count the polynomial hash of adjacency matrix row) and sort the hashes. Than we have to add the pairs ...
[ "graphs", "hashing", "sortings" ]
2,300
null
154
D
Flatland Fencing
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on o...
As the moves choices are symmetrical for both players, if one player can reach another in one move from some disposition, the other player also can reach the first. So, if we are allowed to stand in one place (i.e. a <= 0 <= b), we can just stand still and wait for another player to come. If she wants to win, she will ...
[ "games", "math" ]
2,400
null
154
E
Martian Colony
The first ship with the Earth settlers landed on Mars. The colonists managed to build $n$ necessary structures on the surface of the planet (which can be regarded as a plane, and the construction can be regarded as points on it). But one day the scanners recorded suspicious activity on the outskirts of the colony. It w...
We have to find the area of intersection of all circles containing the given set of points (it's clear that the intersection has the least area, and we have an unlimited number of circles). First, what shape does such an intersection have? Its border contains some circle arcs of radius R meeting at some points of conve...
[ "geometry" ]
3,000
null
155
A
I_love_\%username\%
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
You should do what is written: go through the sequence and count the elements which are greater or less than all of its predecessors. We don't even have to store the whole sequence, just the current minimum and maximum. Complexity - O(N), but squared still works fine.
[ "brute force" ]
800
null
155
B
Combination
Ilya plays a card game by the following rules. A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number $a_{i}$, and the bott...
Clearly, we can play the cards with $b_{i}$ > 0 first as each of them gives at least one extra move. After that, the number of extra moves left doesn't depend on the order of playing. The left cards all have $b_{i}$ = 0, so we play those of them which have larger $a_{i}$. Simpler version of this solution: sort all the ...
[ "greedy", "sortings" ]
1,100
null
158
A
Next Round
"Contestant who earns a score equal to or greater than the $k$-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of $n$ participants took part in the contest ($n ≥ k$), and you already know their scores. Calculate how...
Just sort. Notice 0 in the array.
[ "*special", "implementation" ]
800
null
158
B
Taxi
After the lessons $n$ groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the $i$-th group consists of $s_{i}$ friends ($1 ≤ s_{i} ≤ 4$), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. W...
Choose the 3 and 1 as much as possible. And let 2 combine with themselves. If there are more 1s and 2s, let two 1s combine with 2, and every four 1s take same taxi.
[ "*special", "greedy", "implementation" ]
1,100
null
158
C
Cd and pwd commands
Vasya is writing an operating system shell, and it should have commands for working with directories. To begin with, he decided to go with just two commands: cd (change the current directory) and pwd (display the current directory). Directories in Vasya's operating system form a traditional hierarchical tree structure...
Implement with stack. If the string begin with '/', let top = 0, else remain the top; Then process the substring one by one, when meeting ".." , top--; else remain the top;
[ "*special", "data structures", "implementation" ]
1,400
null
158
D
Ice Sculptures
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus $n$ ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they...
The number of new regular polygon's edges must be the factor of the given polygon. Listing all the factors take O(sqrt(n)) time. Then choose the best point take O(n). So the time complexity is O(n*sqrt(n)).
[ "*special", "brute force", "number theory" ]
1,300
null
158
E
Phone Talks
Cool J has recently become a businessman Mr. Jackson, and he has to make a lot of phone calls now. Today he has $n$ calls planned. For each call we know the moment $t_{i}$ (in seconds since the start of the day) when it is scheduled to start and its duration $d_{i}$ (in seconds). All $t_{i}$ are different. Mr. Jackson ...
It's a classic DP problem. Array dp[i][j] stands for the min rightmost endpoint when choosing at most j segments from the first i segments . dp[i][j] =dp[i][j] = min(dp[i-1][j-1], max(dp[i-1][j],left[i])+length[i]). When the dp array is completed , find the max value of left[i+1]-dp[i][k] and rightmost point - dp[n][k]...
[ "*special", "dp", "sortings" ]
1,900
null
159
A
Friends or Not
Polycarpus has a hobby — he develops an unusual social network. His work is almost completed, and there is only one more module to implement — the module which determines friends. Oh yes, in this social network one won't have to add friends manually! Pairs of friends are deduced in the following way. Let's assume that ...
Compare every two records and find the right friends. Give every name a unique number so as to avoid counting same friend twice. If a and b is friends, let friend[a][b] = true.
[ "*special", "greedy", "implementation" ]
1,400
null
159
B
Matchmaker
Polycarpus has $n$ markers and $m$ marker caps. Each marker is described by two numbers: $x_{i}$ is the color and $y_{i}$ is the diameter. Correspondingly, each cap is described by two numbers: $a_{j}$ is the color and $b_{j}$ is the diameter. Cap $(a_{j}, b_{j})$ can close marker $(x_{i}, y_{i})$ only if their diamete...
Establish two hash tables counting the number of the size (say 2) exiting in set makers and set caps. Obviously the sum of min number of every size in two sets is the first answer. Similarly establish two hash tables in order to count the number of the same size and same color. The hash function can be hash(color, size...
[ "*special", "greedy", "sortings" ]
1,100
null
159
C
String Manipulation 1.0
One popular website developed an unusual username editing procedure. One can change the username only by deleting some characters from it: to change the current name $s$, a user can pick number $p$ and character $c$ and delete the $p$-th occurrence of character $c$ from the name. After the user changed his name, he can...
Because the length of string is at most 100*2000, so we can build 26 line-segment-trees to count the 26 Latin letters. The way to build tree and find the position of K-th letter is quite simple if you under stand line-segment-tree :)
[ "*special", "binary search", "brute force", "data structures", "strings" ]
1,400
null
159
D
Palindrome pairs
You are given a non-empty string $s$ consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string. In a more formal way, you have to find the quantity of tuples $(a, b, x, y)$ such that $1 ≤ a ≤ b < x ≤ y ≤ |s|$ and substrings $s[a... b]$, $s[x... y]$ are palindrom...
A dp method is really great~ , sum[i] stands for the number of palindrome string in the first i letters. palindrome[i][j] judges weather the substring i...j is a palindrome string. dp[i] is the answer for the first i letters. dp[i] = dp[i-1]+Sum( palindrome[j][i]*sum[j-1] ) for all j<=i && j>0 . sum[i] = sum[i-1]+Sum(p...
[ "*special", "brute force", "dp", "strings" ]
1,500
null
159
E
Zebra Tower
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color $c_{i}$ and size $s_{i}$. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the...
sort the array with compare condition (cube[i].color < cube[j].color ||(cube[i].color==cube[j].color && cube[i].size>cube[j].size)). Then for the first i cubes , there is a array Max_cube, Max_cube[j] records the max sum of j cubes' size with same color. To the cube i+1, if it's the k-th largest size of its color. Comp...
[ "*special", "data structures", "greedy", "sortings" ]
1,700
null
160
A
Twins
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
It's obvious that you should take the most valueable coins. so sort values in non-decreasing order, then take coins from the most valueable to the least, until you get strictly more than half of total value. Time complexity depends on the sorting algorithm you use. O(n^2) is also acceptable, but if you use bogosort whi...
[ "greedy", "sortings" ]
900
null
160
B
Unlucky Ticket
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an \textbf{even} number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half m...
Deal with the situation that "first half is strictly less than second half" first. the other one can be solved accordingly. You can use greedy here: sort digits in first and second half seperately. then if the i-th digit in first half is always less than i-th in second half for 1<=i<=n, answer is YES. Time complexity i...
[ "greedy", "sortings" ]
1,100
null
160
C
Find Pair
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing $n$ (not necessarily different) integers $a_{1}$, $a_{2}$, ..., $a_{n}$. We are interested in all possible pairs of numbers ($a_{i}$, $a_{j}$), ($1 ≤ i, j ≤ n$). In other words, let's consider all $n^{2}$ pairs of numbers, p...
This is a tricky problem. When contest ends, I found there are 12 pages of accepted submissions while 60 pages of "WA on pretest 3" submissions. First of all, sort a[]. A natural consideration is that the answer equals to (a[k/n] , a[k%n]). This algorithm will pass the sample and get "WA on pretest 3". In fact, it work...
[ "implementation", "math", "sortings" ]
1,700
null
160
D
Edges in MST
You are given a connected weighted undirected graph without any loops and multiple edges. Let us remind you that a graph's \underline{spanning tree} is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The \underline{weight} of a tree is defined as the sum of weight...
Let's take a look at Kruskal Algorithm which solve MST in O(m log m) time. Sort the edges first in weight non-decreasing order, then process each edges. if the edge connects two different connected compoments, add this edge to MST then combine two compoments. We use disjoint-set union here to maintain connectivity. The...
[ "dfs and similar", "dsu", "graphs", "sortings" ]
2,300
null
160
E
Buses and People
The main Bertown street is represented by a straight line. There are $10^{9}$ bus stops located on the line. The stops are numbered with integers from $1$ to $10^{9}$ in the order in which they follow on the road. The city has $n$ buses. Every day the $i$-th bus drives from stop number $s_{i}$ to stop number $f_{i}$ ($...
As what problem setter say, we sort the people and bus together with non-decreasing order of time first(if a bus and a person has same time, put the person first). Solving it by "For each person find which bus he should take" will become rather difficult, so let's take another idea: For each bus, find who it will take....
[ "binary search", "data structures", "sortings" ]
2,400
null
161
A
Dress'em in Vests!
The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line. The Two-dimensional kingdom has a regular army of $n$ people. Each soldier registered him...
Consider troopers in the sorted order, as in the input data. One can prove that for the current (minimal) trooper the best choice is the vest with the minimal possible $b_{j}$. So we can solve this problem using "moving pointers" method. The first pointer iterates over troopers and the second one chooses minimal unused...
[ "binary search", "brute force", "greedy", "two pointers" ]
1,300
null
161
B
Discounts
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a $50%$ discount on the cheapest item in the cart (that is, it becomes two times chea...
This problem can be solved greedy. Let us have $x$ stools. One can prove that it is always correct to arrange $min(k - 1, x)$ maximal stools into $min(k - 1, x)$ carts one by one. All remaining stools and pencils should be put into remaining empty carts. Finally, we have either zero or one empty cart.
[ "constructive algorithms", "greedy", "sortings" ]
1,700
null
161
C
Abracadabra
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: - On the first step the string consists of a single character "a". - On the $k$-th step Polycarpus concatenates two copies of the string obtained on the $(k - 1)$-th step, while inserting the $k$-th character of ...
Consider the case when the maximal character in the string is in the answer. Then the answer equals $min(r_{1}, r_{2}) - max(l_{1}, l_{2})$. Otherwise, we cut both strings around this character (here we might get empty strings) and run the algorithm recursively for every pair of strings we get. One can prove that this ...
[ "divide and conquer" ]
2,400
null
161
D
Distance in Tree
A tree is a connected graph that doesn't contain any cycles. The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices. You are given a tree with $n$ vertices and a positive number $k$. Find the number of distinct pairs of the vertices which have a distance of ex...
This problem can be solved using dynamic programming. Let us hang the tree making it rooted. For every vertex $v$ of the tree, let us calculate values $d[v][lev]$ ($0 \le lev \le k$) - the number of vertices in the subtree, having distance $lev$ to them. Note, that $d[v][0] = 0$. Then we calculate the answer. It eq...
[ "dfs and similar", "dp", "trees" ]
1,800
null
161
E
Polycarpus the Safecracker
Polycarpus has $t$ safes. The password for each safe is a square matrix consisting of decimal digits '0' ... '9' (the sizes of passwords to the safes may vary). Alas, Polycarpus has forgotten all passwords, so now he has to restore them. Polycarpus enjoys prime numbers, so when he chose the matrix passwords, he wrote ...
We need to count the number of symmetric matrices with a given first row, where each row is a prime number. Since the matrix is symmetric, it is determined by its cells above or on the main diagonal. Let's examine all possible values of digits above the main diagonal (at most $10^{6}$ cases). Now the values of the rema...
[ "brute force", "dp" ]
2,500
null
163
A
Substring and Subsequence
One day Polycarpus got hold of two non-empty strings $s$ and $t$, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "$x$ $y$" are there, such that $x$ is a substring of string $s$, $y$ is a subsequence of string $t$, and the content of ...
The problem could be solved with the following dynamic programming. Let $f[i, j]$ be the number of distinct pairs ("substring starting at position $i$" and "subsequence of the substring $t[j... |t|]$") Then: f[i, j] = f[i, j + 1]; if (s[i] == t[j]) add(f[i, j], f[i + 1, j + 1] + 1)Answer = $\textstyle\sum$ f[i,0]
[ "dp" ]
1,700
#include <cstdio> char s[5005], t[5005]; int a[5005][5005], i, j, ans; #define mod 1000000007 int main(void) { gets(s); gets(t); for (i = 0; s[i]; i++) for (j = 0; t[j]; j++) a[i + 1][j + 1] = (a[i + 1][j] + (t[j] == s[i]) * (a[i][j] + 1)) % mod; for (i = 0; s[i]; i++) ans = (ans + a[i + 1][...
163
B
Lemmings
As you know, lemmings like jumping. For the next spectacular group jump $n$ lemmings gathered near a high rock with $k$ comfortable ledges on it. The first ledge is situated at the height of $h$ meters, the second one is at the height of $2h$ meters, and so on (the $i$-th ledge is at the height of $i·h$ meters). The le...
We need to find the minimal time $T$. Let us find it using binary search. Once the time is fixed, one can arrange lemmings using greedy approach starting either from the top or from the bottom. In this solution we consider the way to start from the bottom. Among all lemmings, that can get on the first ledge, let's choo...
[ "binary search" ]
2,000
/** * Author: Sergey Kopeliovich (Burunduk30@gmail.com) * Date: 2012.03.24 */ #include <cstdio> #include <cassert> #include <algorithm> using namespace std; #define forn(i, n) for (int i = 0; i < (int)(n); i++) const int maxN = (int)1e5; int N, K, H, m[maxN], v[maxN], p[maxN], o[maxN]; inline bool mless( int i...
163
C
Conveyor
Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end. The conveyor is a looped belt with a total length of $2l$ meters, of which $l$ meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any mome...
Wherever Anton starts, he will run along the conveyor a segment of length $D={\frac{v_{1}x t}{v_{1}+v_{2}}}$. Consider one candy. To eat it, he needs to get on the conveyor in any moment of the segment $[a_{i} - D..a_{i}]$. Consider all points like $a_{i} - D$ and $a_{i}$ (add $2l$ if that is negative). Also add points...
[ "sortings", "two pointers" ]
2,100
/** * Author: Sergey Kopeliovich (Burunduk30@gmail.com) * Date: 2012.03.25 */ #include <cstdio> #include <cassert> #include <algorithm> using namespace std; #define forn(i, n) for (int i = 0; i < (int)(n); i++) typedef double dbl; const int maxN = (int)1e5 + 3; int dn, n, l, v1, v2; dbl a[maxN * 2]; dbl dist, ...
163
D
Large Refrigerator
Vasya wants to buy a new refrigerator. He believes that a refrigerator should be a rectangular parallelepiped with integer edge lengths. Vasya calculated that for daily use he will need a refrigerator with volume of at least $V$. Moreover, Vasya is a minimalist by nature, so the volume should be no more than $V$, eithe...
The solution consists of three main ideas: $V = ABC$, $A \le B \le C$ then $A \le N^{1 / 3}, B \le (N / A)^{1 / 2}$. $A$ and $B$ are divisors of $V$, as we are already given the factorization of $V$, we can run only through the divisors Given fixed $A$, the optimal real $B$ and $C$ are $(N / A)^{1 / 2}$ (denote...
[ "brute force" ]
2,900
/** * Author: Sergey Kopeliovich (Burunduk30@gmail.com) * Date: 2012.03.22 */ #include <ctime> #include <cmath> #include <cstdio> #include <cassert> #include <map> using namespace std; #ifdef _WIN32 # define I64 "%I64d" #else # define I64 "%Ld" #endif #define forn(i, n) for (int i = 0; i < (int)(n); i++) #def...
163
E
e-Government
The best programmers of Embezzland compete to develop a part of the project called "e-Government" — the system of automated statistic collecting and press analysis. We know that any of the $k$ citizens can become a member of the Embezzland government. The citizens' surnames are $a_{1}, a_{2}, ..., a_{k}$. All surnames...
We assume that the reader is familiar with the Aho-Corasick algorithm (http://en.wikipedia.org/wiki/Aho-Corasick) Consider a trie of names and suffix links over it. For every vertex $v$ one can calculate the number of names, ending in that vertex ($end[v]$). Then, the "add name $i$" operation is $end[v[i]]$ += 1, where...
[ "data structures", "dfs and similar", "dp", "strings", "trees" ]
2,800
#include <cstdio> #include <cassert> #include <vector> using namespace std; struct node { int ne[26], suff; vector <int> rsuff; int a, b, cur, was; }; #define maxn 1000100 int fen[maxn * 2], fen_n; int f_get (int i) { int res = 0; while (i >= 0) { res += fen[i]; i = (i & (i + 1)) - 1; } ret...
165
A
Supercentral Point
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points $(x_{1}, y_{1}), (x_{2}, y_{2}), ..., (x_{n}, y_{n})$. Let's define neighbors for some fixed point from the given set $(x, y)$: - point $(x', y')$ is $(x, y)$'s right neighbor, if $x' > x$ and $y' = y$ - point $(x', y...
In this problem you should just code what was written in the problem. For every point you can check if it is supercentral. Consider every point consecutively and find neighbors from every side. The complexity is $O(N^{2})$.
[ "implementation" ]
1,000
null
165
B
Burning Midnight Oil
One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of $n$ lines of code. Vasya is already exhausted, so he works like that: first he writes $v$ lines of code, drinks a cup of tea, then he writes as much as $\left\lfloor{\frac{v}{k}}\right\rfloor$ lines, drinks...
This problem can be solved using binary search for the answer. obviously, if number $v$ is an answer than every number $w > v$ is also the answer, because the number of written lines of code could only become more. To check some number $v$ you can use formula given in the problem, because it will have less than $O(logN...
[ "binary search", "implementation" ]
1,500
null
165
C
Another Problem on Strings
A string is \underline{binary}, if it consists only of characters "0" and "1". String $v$ is a substring of string $w$ if it has a non-zero length and can be read starting from some position in string $w$. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered dif...
You was to find number of segments $[lf;rg]$ of the strings on which the sum equals to $k$ (we are working with array of integers $0$ and $1$). We will count array $sum$ where the value $sum[i]$ equals to sum on segment $[0;i]$. We will count the answer going from left to right. Let's say we are in position $pos$. Now ...
[ "binary search", "brute force", "dp", "math", "strings", "two pointers" ]
1,600
null
165
D
Beard Graph
Let's define a non-oriented connected graph of $n$ vertices and $n - 1$ edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that conne...
Beard-graph is a tree. It consists of one root and several paths from this root. There is a single path between every pair of vertices. That's why you should check whether every edge on the path between two vertices is black. If some edge is white there is no path between two vertices now. The distances could be found ...
[ "data structures", "dsu", "trees" ]
2,100
null
165
E
Compatible Numbers
Two integers $x$ and $y$ are \underline{compatible}, if the result of their bitwise "AND" equals zero, that is, $a$ $&$ $b = 0$. For example, numbers $90$ $(1011010_{2})$ and $36$ $(100100_{2})$ are compatible, as $1011010_{2}$ $&$ $100100_{2} = 0_{2}$, and numbers $3$ $(11_{2})$ and $6$ $(110_{2})$ are not compatible,...
Consider some number $x$ from the array. Inverse all bits in $x$ and say it is number $y$. Consider an integer $a[i]$ from array. It can be an answer to the number $x$ if for every position of zero bit from $y$ there is zero bit in $a[i]$ in the same position. Other bits in $a[i]$ we can change to ones. Then we will us...
[ "bitmasks", "brute force", "dfs and similar", "dp" ]
2,200
null
166
A
Rank List
Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place. You know the rules of comparing the results of two give...
This is simple straight-forward problem - you were asked to sort the teams with the following comparator: ($p_{1} > p_{2}$) or ($p_{1} = p_{2}$ and $t_{1} < t_{2}$). After that you can split the teams into groups with equal results and find the group which shares the $k$-th place. Many coders for some reason used wrong...
[ "binary search", "implementation", "sortings" ]
1,100
null
166
B
Polygons
You've got another geometrical task. You are given two non-degenerate polygons $A$ and $B$ as vertex coordinates. Polygon $A$ is strictly convex. Polygon $B$ is an arbitrary polygon without any self-intersections and self-touches. The vertices of both polygons are given in the clockwise order. For each polygon no three...
Polygon A is convex, so it is sufficient to check only that every vertex of polygon B is strictly inside polygon A. In theory the simplest solution is building common convex hull of both polygons. You need to check that no vertex of polygon B belongs to this hull. But there is a tricky detail: if there are many points ...
[ "geometry", "sortings" ]
2,100
null
166
C
Median
A median in an array with the length of $n$ is an element which occupies position number $\textstyle{\left|{\frac{n+1}{2}}\right\rfloor}$ after we sort the elements in the non-decreasing order (the array elements are numbered starting with $1$). A median of an array $(2, 6, 1, 2, 3)$ is the number $2$, and a median of ...
If the initial array doesn't contain number $x$, than you definitely need to add it (that's +1 to answer). Than do the following. While median is strictly less than $x$ you need to increase it. Obviously the surest way to increase the median is to add a maximal possible number ($10^{5}$). Similarly while the median is ...
[ "greedy", "math", "sortings" ]
1,500
null
166
D
Shoe Store
The warehouse in your shop has $n$ shoe pairs. Each pair is characterized by two integers: its price $c_{i}$ and its size $s_{i}$. We know that on this very day all numbers $s_{i}$ are different, that is, there is no more than one pair of each size. The shop has $m$ customers who came at the same time. The customer nu...
Let's sort the people by decreasing of shoes size. Observe that when considering the $i$-th man we are interested in no more than 2 pairs of shoes: with size $l_{i}$ and $l_{i} + 1$. It allows solving with dynamics. The state will be (the number of first unconsidered man $i$, is pair of shoes with size $l_{i}$ availabl...
[ "dp", "graph matchings", "greedy", "sortings", "two pointers" ]
2,500
null
166
E
Tetrahedron
You are given a tetrahedron. Let's mark its vertices with letters $A$, $B$, $C$ and $D$ correspondingly. An ant is standing in the vertex $D$ of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. ...
Obvious solution with dynamics: you need to know only how many moves are left and where is the ant. This is $4n$ states, each with 3 options - most of such solution passes. Observe that the vertices A, B, C are equivalent. This allows writing such solution: int zD = 1; int zABC = 0; for (int i = 1; i <= n; i++) { int n...
[ "dp", "math", "matrices" ]
1,500
null
167
A
Wizards and Trolleybuses
In some country live wizards. They love to ride trolleybuses. A city in this country has a trolleybus depot with $n$ trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of $d$ meters from the depot. We know for the $i$-th trolleybus that ...
This was the first problem where you had a little bit away from translating statements to a programming language. Because acceleration trolleybuses are all the same and they can slow down immediately, the answer for the next trolleybus is the maximum of the time when it would come if it were not to stop when he reach t...
[ "implementation", "math" ]
1,600
null
167
B
Wizards and Huge Prize
One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees. One of such magic schools consists of $n$ tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've...
This problem can be solved using dynamic programming. Let d[i][j][m] - the probability we won j of first i days and get bags total capacity of m. For convenience, we assume that the bag is also a prize and the prize is a bag of capacity 0. To do that, retaining a task we must add 1 to all a[i]. Then from d[i][j][m] we ...
[ "dp", "math", "probabilities" ]
1,800
null
167
C
Wizards and Numbers
In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — $a$ and $b$. The order of the numbers is not important. Let's consider $a ≤ b$ for the sake of definiteness. The players can cast one of the two spells in turns: - Replace $b$ with $b - a^{k}$. Number $k$ can ...
Consider the position (a, b). Let a < b. From this there is a move to $(b{\mathrm{~mod~}}a,a)$. Recursively check if this position is a winning or a losing. If it is losing, then (a, b) exactly winning. Otherwise, no one will take the remainder. So everyone will subtract from larger number nonnegative degree of smaller...
[ "games", "math" ]
2,300
null
167
D
Wizards and Roads
In some country live wizards. They love to build cities and roads. The country used to have $k$ cities, the $j$-th city ($1 ≤ j ≤ k$) was located at a point ($x_{j}$, $y_{j}$). It was decided to create another $n - k$ cities. And the $i$-th one ($k < i ≤ n$) was created at a point with coordinates ($x_{i}$, $y_{i}$): ...
This was the first really hard problem in the contest. One of the challenges was to understand the statement. I hope that we had written the statement as clear as it possible in this problem. Consider this graph. In particular, we consider more closely the point with the largest y. 1) It is connected with the highest p...
[ "data structures", "divide and conquer", "graph matchings", "graphs", "greedy" ]
3,000
null
167
E
Wizards and Bets
In some country live wizards. They like to make weird bets. Two wizards draw an acyclic directed graph with $n$ vertices and $m$ edges (the graph's vertices are numbered from $1$ to $n$). A source is a vertex with no incoming edges, and a sink is the vertex with no outgoing edges. Note that a vertex could be the sink ...
This task was about the pathes from the sources to sinks. For this pathes there was a condition which made them dependent - they should not interfere at vertexes. But in any combinatorics is much easier when everything is independent. So we should try to get rid of the condition of the absence of crossings at the verti...
[ "dfs and similar", "graphs", "math", "matrices" ]
2,900
null
168
A
Wizards and Demonstration
Some country is populated by wizards. They want to organize a demonstration. There are $n$ people living in the city, $x$ of them are the wizards who will surely go to the demonstration. Other city people ($n - x$ people) do not support the wizards and aren't going to go to the demonstration. We know that the city adm...
In this task, it was necessary to write exactly what has been described in statement. In particular, it was necessary to have $\textstyle\left[{\frac{N Y}{100}}\right]$ people, who come to the meeting. For this it was necessary to create ${\mathrm{max}}(0,\lceil{\frac{N\cdot Y}{100}}\rceil-X)$ clones.
[ "implementation", "math" ]
900
null
168
B
Wizards and Minimal Spell
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells. Each spell consists of several lines. The line, whose first non-space chara...
In this problem you had to write exactly what has been described in statment too. Read lines one by one. Also keep the last block of lines that are not amplyfying. If the next line is amplyfying (which can be checked by linear search), we print the last block, if any, and the line itself. Otherwise, remove all spaces f...
[ "implementation", "strings" ]
1,700
null
173
A
Rock-Paper-Scissors
Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!). Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scisso...
Naive solution in $O(n)$ (some simulation all of n rounds) gets TL. Let's speed up this solution. Let's consider rounds on segments [1..mk], [mk+1..2mk], [2mk+1..3mk] and so on. You can see that results of games on these segments will repeat. So you can simulate over exactly one segment and then take into consideration...
[ "implementation", "math" ]
1,300
null
173
B
Chamber of Secrets
"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anyb...
In this problem you should build bipartite graph with n+m vertices. All vertices of the firts part correspond to the rows of the table, vertices of the second part correspond to the columns of the one. Edge connects vertices iff some regular column is placed in the cross of corresponding row and column. Firstly death r...
[ "dfs and similar", "shortest paths" ]
1,800
null
173
C
Spiral Maximum
Let's consider a $k × k$ square, divided into unit squares. Please note that $k ≥ 3$ and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one ...
Let's iterate over all spirals and chose one of them that has maximal sum of elements. Because you have $O(n^{3})$ spirals, you should calculate sum of any of them in $O(1)$. Only in this case your solution will fit into time limits. Let's define a way for iterate over all spirals. Let's fix one of cells and then itera...
[ "brute force", "dp" ]
1,900
null
173
D
Deputies
The Trinitarian kingdom has exactly $n = 3k$ cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side. Some cities are connected by bridges built between them. Each bridge co...
You have bipartite graph with $3k$ vertices and should to color its vertices by $k$ colors. Every color should be used exactly 3 times and there should be no edges that connect vertices at same color. At the first, you should find both of parts of our birartite graph using, for example, DFS. Now let's consider sizes of...
[ "constructive algorithms", "graphs", "greedy", "implementation" ]
2,500
null
173
E
Camping Groups
A club wants to take its members camping. In order to organize the event better the club directors decided to partition the members into several groups. Club member $i$ has a responsibility value $r_{i}$ and an age value $a_{i}$. A group is a non-empty subset of club members with one member known as group leader. A gr...
Let's transform all people into points on a plane with coordinates ($x = a_{i}, y = r_{i}$). What the maximal number in group of people that can be formed with some fixed leader? Answer is number of points inside rectangle $(x, y): x_{i} - k \le x \le x_{i} + k, y \le y_{i}$. Let's we allready found size of group...
[ "data structures", "sortings" ]
2,600
null
175
A
Robot Bicorn Attack
Vasya plays Robot Bicorn Attack. The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string $s$. Vasya decided ...
Go over all possible partitions of the given string into 3 substrings (for example, go over a pair of indexes - the ends of the first and the second substrings). If all three substrings of the partition satisfy constraints (there are no leading zeroes and the corresponding number does not exceed 1000000), then update t...
[ "brute force", "implementation" ]
1,400
null
175
B
Plane of Tanks: Pro
Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has...
The solution is to simulate actions described in the statement. Find the best result for each player and count total amount of players N. Then find a number of players C for each player , those results are not better than best result of the considering player (this can be done by going over all players). Then it is nec...
[ "implementation" ]
1,400
null
175
C
Geometry Horse
Vasya plays the Geometry Horse. The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are $n$ types of geometric figures. The number of figures of type $k_{i}$ and figure cost $c_...
Obvious, that figures should be destroyed in the cost increasing order. Sort figures type in ascending order of their costs. Consider two pointers - position i in the array P (current factor) and position j in the array of figures type. Consider the current answer and the number of figures G, those need to be destroyed...
[ "greedy", "implementation", "sortings", "two pointers" ]
1,600
null
175
D
Plane of Tanks: Duel
Vasya plays the Plane of Tanks. Tanks are described with the following attributes: - the number of hit points; - the interval between two gun shots (the time required to recharge the gun); - the probability that the gun shot will not pierce armor of the enemy tank; - the damage to the enemy's tank. The gun damage is...
First consider case when at least one probability of not-piercing is equal to 100%. If Vasya does not pierce the enemy tank with probability 100%, then the answer is 0. If the enemy tank cannot pierce Vasya's tank with probability 100% then the answer is 1. Then consider that the probability of shot does not pierce tan...
[ "brute force", "dp", "math", "probabilities" ]
2,400
null
175
E
Power Defence
Vasya plays the Power Defence. He must pass the last level of the game. In order to do this he must kill the Main Villain, who moves in a straight line at speed 1 meter per second from the point $( - ∞, 0)$ to the point $( + ∞, 0)$ of the game world. In the points $(x, 1)$ and $(x, - 1)$, where $x$ is an integer numbe...
If we reflect the position of towers alogn the line OX then the interval where towers will affect the Villain will not change. So, we can consider that towers can be built in the points (_x_, 1), not more than two towers in the same point. If there exists point X that there are towers to the left and to the right from ...
[ "brute force", "dp", "geometry", "greedy" ]
2,600
null
175
F
Gnomes of Might and Magic
Vasya plays a popular game the Gnomes of Might and Magic. In this game Vasya manages the kingdom of gnomes, consisting of several castles, connected by bidirectional roads. The kingdom road network has a special form. The kingdom has $m$ main castles $a_{1}, a_{2}, ..., a_{m}$, which form the Good Path. This path cons...
Construct the graph with vertices corresponding to castles and edges to roads. Note, that a degree of each graph vertex does not exceed 4, so the amount of edges does not exceed E <= 2 * N. In order to solve the problem let's find out how we can handle each query with time O(_log_(_N_)). Consider the query to find amou...
[ "data structures", "graphs", "implementation", "shortest paths" ]
3,000
null
176
A
Trading Business
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin...
In this problem some greedy solution expected. Let fix 2 planets: in planet i we will buy items, in planet j we will sell the ones. Profit of item of type k will be b_jk-a_ik. Every item has size 1, so you should greedy take items in order of decreasing of profits of items while you have place in the hold. Scheme of fu...
[ "greedy", "sortings" ]
1,200
null
176
B
Word Cut
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word $w$, let's split this word into two non-empty parts $x$ and $y$ so, that $w = xy$. A split operation is transforming word $w = xy$ into word $u = yx$. For example, a spli...
You can see that split oparetion is just cyclically shift of string. You can go from any cyclically shift to any other one except the current one. Let's call some cyclically shift good iff it equal to the final string. All others cyclically shifts we will call bad. You can check all shifts in $O(|w|^{2})$ time. Let's y...
[ "dp" ]
1,700
null
176
C
Playing with Superglue
Two players play a game. The game is played on a rectangular board with $n × m$ squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue. We'll describ...
The second player have easy strategy to hold some chip in position $(X, Y)$ in one of four half-planes - $x \le X + 2$, $x \ge X - 2$, $y \le Y + 2$ and $y \ge Y - 2$. He can chose one of these half-planes by himself. So, in case $max(|x1 - x2|, |y1 - y2|) > 4$ the second player wins - he just holds chips in ha...
[ "combinatorics", "constructive algorithms" ]
2,000
null
176
D
Hyper String
Paul Erdős's prediction came true. Finally an alien force landed on the Earth. In contrary to our expectation they didn't asked the humans to compute the value of a Ramsey number (maybe they had solved it themselves). They asked another question which seemed as hard as calculating Ramsey numbers. Aliens threatened that...
Let's define $dp[pre][len]$ as the minimal prefix of hyperstring that have with prefix of $t$ of length $len$ largest common sequence of length $len$. Then you have see reccurences: $dp[pre][len] = min(dp[pre - 1][len],$ leftmost position of letter $s[pre]$ in $t$ that right than $dp[pre - 1][len - 1])$. For finding va...
[ "dp" ]
2,500
null
176
E
Archaeology
This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out $n$ villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overa...
At the first let's try to solve another problem: we have $k$ chosed vertices in the tree and we want to find sum of subtree that "spanned" dy them in time $O(k \log n)$ (with any preprocessing time). Let's sort all $k$ vertices in order of dfs traversal - $v_{1}$, $v_{2}$, ... , $v_{k}$. Consider pathes v1-v2, v2-v3, ....
[ "data structures", "dfs and similar", "trees" ]
3,100
null
178
A1
Educational Game
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some...
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes o...
[]
1,000
null
178
A2
Educational Game
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some...
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes o...
[ "greedy" ]
1,000
null
178
A3
Educational Game
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of $n$ non-negative integers $a_{i}$ numbered from $1$ to $n$. The goal of the game is to make numbers $a_{1}, a_{2}, ..., a_{k}$ (i.e. some...
It is the simplest task of the set. The solution is based on greedy algorithmm. First of all, we need to zero out $a_{1}$. One needs to make $a_{1}$ steps with $i = 1$ and some $t$ on each step. Which $t$ is the most efficient? The maximum $t$, where $1 + 2^{t} \le n$. In that case later zeroing out longer prefixes o...
[ "greedy" ]
1,100
null
178
B1
Greedy Merchants
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two dif...
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the ...
[]
1,600
null
178
B2
Greedy Merchants
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two dif...
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the ...
[]
1,600
null
178
B3
Greedy Merchants
In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants. The Roman Empire consisted of $n$ cities numbered from $1$ to $n$. It also had $m$ bidirectional roads numbered from $1$ to $m$. Each road connected two dif...
First of all note that merchants will pay only for those edge which are bridges. All other edges don't match as after their deletion graph stay connected and between any nodes of graph the way stay. So first step to solve problem is to search bridges. Use this algorithm which works at $O(n + m)$ After deletion all the ...
[]
1,800
null
178
C1
Smart Beaver and Resolving Collisions
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail. We assume that the hash table consists of $h$ cells nu...
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this proper...
[]
1,600
null
178
C2
Smart Beaver and Resolving Collisions
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail. We assume that the hash table consists of $h$ cells nu...
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this proper...
[]
1,900
null
178
C3
Smart Beaver and Resolving Collisions
The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail. We assume that the hash table consists of $h$ cells nu...
Let's iterate through the cells of the hash table with step m (modulo h). So, all cells are separated into some cycles modulo h (all cycles have the same number of elements). It can be proven that the number of cycles is $gcd(h, m)$ and the number of elements in each cycle is $h / gcd(h, m)$. How can we use this proper...
[]
2,000
null
178
D1
Magic Squares
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size $n × n$. The elements of this matrix are integer...
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on tw...
[]
1,500
null
178
D2
Magic Squares
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size $n × n$. The elements of this matrix are integer...
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on tw...
[]
1,900
null
178
D3
Magic Squares
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size $n × n$. The elements of this matrix are integer...
Let's consider two different ways to solve this problem. Note that firstly (before finding correct magic square) we can easily determine the value of $s$. This value equal to the sum of all given numbers divided by $n$. So next, we will use this value. The first way to solve problem is brute force. This way based on tw...
[]
2,100
null
178
E1
The Beaver's Problem - 2
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem. You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ...
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of a...
[]
1,900
null
178
E2
The Beaver's Problem - 2
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem. You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ...
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of a...
[]
2,000
null
178
E3
The Beaver's Problem - 2
Offering the ABBYY Cup participants a problem written by the Smart Beaver is becoming a tradition. He proposed the following problem. You are given a monochrome image, that is, an image that is composed of two colors (black and white). The image is given in raster form, that is, as a matrix of pixels' colors, and the ...
Solving this problem can be divided into two parts: Noise deletion on the picture; Fugures' classification. For noise deletion one can use the following methods: a. Do following steps: scan picture and build new on using it. If sone black pixel have white neighbours, we make it white. During thise steps we get rid of a...
[]
2,300
null
181
A
Series of Crimes
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang. The Berland capital's map is represented by an $n × m$ rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked...
Required row is row that have only one star inside. Requred column is comumn that also have only one star inside. So, you can iterate over all rows/columns, calculate number of stars inside them and find the answer.
[ "brute force", "geometry", "implementation" ]
800
null
181
B
Number of Triplets
You are given $n$ points on a plane. All points are different. Find the number of different groups of three points $(A, B, C)$ such that point $B$ is the middle of segment $AC$. The groups of three points are considered unordered, that is, if point $B$ is the middle of segment $AC$, then groups $(A, B, C)$ and $(C, B...
Naive solution $O(n^{3})$ (where you check all triplets) doesn't fin into time limits. You can see that for every two points from triplet (for example, for A and C) you can find place of the third point. So you can find number of requred triplets just inerate over all pairs of points and check middle point between poin...
[ "binary search", "brute force" ]
1,300
null
183
A
Headquarters
Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters e...
Ad Hoc I supppose... This problem is equivalent to calculating the number of reachable locations from point (0, 0) by doing the allowed moves. The naive solution is to process the information one by one from first to last, and to keep track on all the reachable positions. Claim: At any moment in time, all reachable loc...
[ "constructive algorithms", "math" ]
1,700
null
183
B
Zoo
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has $n$ observation binoculars located at the $OX$ axis. For each $i$ between $1$ and $n$, inclusive, there exists a single binocular located at the point with coordinates $(i, 0)$. There are $m$ flamingos in the Zoo, located at points with positiv...
Geometry Since there are at least one flamingo, all binoculars will be able to see at least one flamingo. When a binocular is able to see more than one flamingos, then those two flamingos and the binocular must form a line. How many such lines are there? Instead of iterating for each pair of binocular and flamingo, we ...
[ "brute force", "geometry" ]
1,700
#include <cstdio> #include <numeric> #include <iostream> #include <vector> #include <set> #include <cstring> #include <string> #include <map> #include <cmath> #include <ctime> #include <algorithm> #include <bitset> #include <queue> #include <sstream> #include <deque> using namespace std; #define mp make_pair #define ...
183
C
Cyclic Coloring
You are given a \textbf{directed} graph $G$ with $n$ vertices and $m$ arcs (\textbf{multiple arcs and self-loops} are allowed). You have to paint each vertex of the graph into one of the $k$ $(k ≤ n)$ colors in such way that for all arcs of the graph leading from a vertex $u$ to vertex $v$, vertex $v$ is painted with t...
DFS Let's drop the (modulo K). That is, the rule becomes: X->Y implies that Y = X+1 Y->X implies that Y = X-1 Notice that this problem is then equivalent to finding the maximum possible K such that the above equation holds for all edges, modulo K.While we still dropping the "modulo K" thingy, we try to calculate the va...
[ "dfs and similar" ]
2,200
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <sstream> #include <map> #include <set> #include <cstdio> #include <cstdlib> #include <cmath> #include <ctime> #include <utility> #include <cstring> using namespace std; typedef long long LL; #define x1 x1_ #define y1 y1_ template<t...
183
D
T-shirt
You are going to work in Codeforces as an intern in a team of $n$ engineers, numbered $1$ through $n$. You want to give each engineer a souvenir: a T-shirt from your country (T-shirts are highly desirable in Codeforces). Unfortunately you don't know the size of the T-shirt each engineer fits in. There are $m$ different...
Dynamic Programming, Probabilities, and a little Greedy Suppose we have decided to bring N1 T-shirts of size 1, N2 T-shirts of size 2, ... NM T-shirts of size M. By the linearity of expectation, the expected number of engineers that will receive a T-shirt is equal to the sum of the expected number of engineers that wil...
[ "dp", "greedy", "probabilities" ]
2,700
#include <stdio.h> #include <ctype.h> #include <iostream> #include <math.h> #include <string.h> #include <algorithm> #include <stdlib.h> #include <time.h> #include <queue> #include <set> #include <map> #include <string> #include <vector> #include <utility> #include <assert.h> #define MPI 3.141592653589793238462643 #de...
183
E
Candy Shop
The prestigious Codeforces kindergarten consists of $n$ kids, numbered $1$ through $n$. Each of them are given allowance in rubles by their parents. Today, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all $i$ between $1$ and $m$, inclusive, it sells a package contai...
Very greedy Brute force P: the number of Packages each kid will have at the end. There are at most N/M possible such value. We will assume that P is fixed during our discussion. If we know P, we know that if kid i purchases a total of X candies, then kid i+1 must purchase at least X+P candies (1 more than each package ...
[ "greedy" ]
2,900
#include <iostream> #include <sstream> #include <string> #include <vector> #include <deque> #include <queue> #include <set> #include <map> #include <algorithm> #include <functional> #include <utility> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> using namespace std; #define REP(i,n) for((i)=...
185
A
Plant
Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divide...
Let's propose, that after the $i$-th year, there is $x$ triangles up and $y$ triangles down. After another iteration we can see, that amount of triangles became - $3x + y$ up and $x + 3y$ down. Let's see the difference between them: at the $i$-th it's $x - y$ and at the $i + 1$-th - it's $(3x + y) - (x + 3y) = 2 * (x -...
[ "math" ]
1,300
null
185
B
Mushroom Scientists
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates $(x, y, z)$. In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: $\...
This problem was made by my love to inequalities. :-)! The answer for this problem is $\left({\frac{d\S}{a+b+c}}\colon{\frac{b\S}{a+b+c}}\cdot{\frac{c\S}{a+b+c}}\right)$. Prove: $x^{a}y^{b}z^{c}=a^{a}b^{b}c^{c}\frac{a}{b}\frac{\bar{c}^{c}}{c}\leq a^{a}b^{b}c^{c}(\frac{a\pi^{a}+b+c}{a+b+c}\bar{c})^{a+b+c}=a^{a}b^{b}c^{c...
[ "math", "ternary search" ]
1,800
null