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
722
F
Cyclic Cipher
You are given $n$ sequences. Each sequence consists of positive integers, not exceeding $m$. All integers in one sequence are distinct, but the same integer may appear in multiple sequences. The length of the $i$-th sequence is $k_{i}$. Each second integers in each of the sequences are shifted by one to the left, i.e....
Let's solve the problem for a particular number $X$. Without loss of generality, we assume that $X$ appeared in each sequence. If not, then the whole sequence is divided into contigous subsegments, for which above statement is true, and the answer for the number $X$ is equal to the maximum of the answers for these subs...
[ "chinese remainder theorem", "data structures", "implementation", "number theory", "two pointers" ]
2,800
null
723
A
The New Year: Meeting Friends
There are three friend living on the straight line $Ox$ in Lineland. The first friend lives at the point $x_{1}$, the second friend lives at the point $x_{2}$, and the third friend lives at the point $x_{3}$. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total dist...
To solve this problem you need to understand that friends must meet in the middle point of the given points, so friends who live in the leftmost and in the rightmost points must go to the middle point. Because of that the answer equals to $max(x_{1}, x_{2}, x_{3}) - min(x_{1}, x_{2}, x_{3})$.
[ "implementation", "math", "sortings" ]
800
null
723
B
Text Document Analysis
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters. In this problem you should implement the similar functionality. You are given a string which only consists of: - uppercase and lowercase English l...
It is an implementation problem. Let's store in the variable $cnt$ the number of words inside brackets and in the variable $maxL$ - the maximum length of the word outside brackets. You can add the symbol <<_>> to the end of the given string, to correctly process the last word. Let's iterate through the given string fro...
[ "expression parsing", "implementation", "strings" ]
1,100
null
723
C
Polycarp at the Radio
Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence $a_{1}, a_{2}, ..., a_{n}$, where $a_{i}$ is a band, which performs the $i$-th song. Polycarp likes bands with the numbers from $1$ to $m$, but he doesn't really like others. We define as $b_{j}$...
It is easy to understand that we always can get the maximum value of the minimum of the values $b_{j}$ which equals to $n / m$. So, we need to make vector $can$ which will store positions of the given array in which we will change values. At first it is all positions of the given array, in which the values are more tha...
[ "greedy" ]
1,600
null
723
D
Lakes in Berland
The map of Berland is a rectangle of the size $n × m$, which consists of cells of size $1 × 1$. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such t...
To solve this problem we need to find all connected components consisting of dots, which do not have common border with ocean. For that we need to implement depth search which returns vector of the points from which the current connected component consists. Then we need to sort all connected components in order of incr...
[ "dfs and similar", "dsu", "graphs", "greedy", "implementation" ]
1,600
null
723
E
One-Way Reform
There are $n$ cities and $m$ two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roa...
Let's solve this problem for each connected component separately. At first we need to understand fact that in each connected component there are even number of vertices with odd degree. Let in the current connected component there are $k$ vertices with odd degree and they have numbers $o_{1}, o_{2}, ..., o_{k}$. Then w...
[ "constructive algorithms", "dfs and similar", "flows", "graphs", "greedy" ]
2,200
null
723
F
st-Spanning Tree
You are given an undirected connected graph consisting of $n$ vertices and $m$ edges. There are no loops and no multiple edges in the graph. You are also given two distinct vertices $s$ and $t$, and two values $d_{s}$ and $d_{t}$. Your task is to build any spanning tree of the given graph (note that the graph is not w...
At first lets delete vertices $s$ and $t$ from the graph, find all connected components in the remaining graph and build for every component any spanning trees. Now we need to add in spanning tree vertices $s$ and $t$. At first let add edges from $s$ to all components, which have no edges to $t$. Then let add edges fro...
[ "dsu", "graphs", "greedy", "implementation" ]
2,300
null
724
A
Checking the Calendar
You are given names of two days of the week. Please, determine whether it is possible that during some \textbf{non-leap year} the first day of some month was equal to the first day of the week you are given, while the first day of \textbf{the next month} was equal to the second day of the week you are given. \textbf{B...
Days of the week in two adjacent months may either be the same (in February and March), or differ by two (in April and May) or differ by three (in January and February). Also, it was necessary to pay attention to direction of that difference (monday and tuesday is not the same as tuesday and monday).
[ "implementation" ]
1,000
null
724
B
Batch Sort
You are given a table consisting of $n$ rows and $m$ columns. Numbers in each row form a permutation of integers from $1$ to $m$. You are allowed to pick two elements in one row and swap them, but \textbf{no more than once} for each row. Also, \textbf{no more than once} you are allowed to pick two columns and swap th...
Order of swaps of numbers in each row is not important. In fact, the order is not important even when we will swap the entire columns (because we can always change the swaps in the rows so that the result will remain the same). Therefore we can choose columns which we will swap (or choose not to swap them at all), and ...
[ "brute force", "greedy", "implementation", "math" ]
1,500
null
724
C
Ray Tracing
There are $k$ sensors located in the rectangular room of size $n × m$ meters. The $i$-th sensor is located at point $(x_{i}, y_{i})$. All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points $(0, 0)$ and $(n, m)$. Walls of the room are parallel to coo...
Let's simulate the flight of the beam. It can be seen that for any segment between two successive reflections is true that the sum of the coordinates for each point of this segment is constant or the difference of the coordinates is constant. Thus, we can make lists of sensors for each possible sum and difference of co...
[ "greedy", "hashing", "implementation", "math", "number theory", "sortings" ]
1,800
null
724
D
Dense Subsequence
You are given a string $s$, consisting of lowercase English letters, and the integer $m$. One should choose some symbols from the given string so that any contiguous subsegment of length $m$ has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves. Then one uses the ...
It is not hard to see that if we choose some subset of the letters then to achieve lexicographically smallest string you must first write all of the letters 'a', then all of the letters 'b' and so on. Let's assume that the string in the answer consists only of the letters 'a'. Then it should be as small of them as poss...
[ "data structures", "greedy", "strings" ]
1,900
null
724
E
Goods transportation
There are $n$ cities located along the one-way road. Cities are numbered from $1$ to $n$ in the direction of the road. The $i$-th city had produced $p_{i}$ units of goods. No more than $s_{i}$ units of goods can be sold in the $i$-th city. For each pair of cities $i$ and $j$ such that \textbf{$1 ≤ i < j ≤ n$} you can...
Build a network of the following form: The network will consist of $n + 2$ vertices, the source located at the node with the number $n + 1$ and the sink at the node with the number $n + 2$. For each node $i$ such that $1 \le i \le n$ add the arc $(n + 1, i)$ with a capacity $p_{i}$ and arc $(i, n + 2)$ with capacit...
[ "dp", "flows", "greedy" ]
2,900
null
724
F
Uniformly Branched Trees
A tree is a connected graph without cycles. Two trees, consisting of $n$ vertices each, are called isomorphic if there exists a permutation $p: {1, ..., n} → {1, ..., n}$ such that the edge $(u, v)$ is present in the first tree if and only if the edge $(p_{u}, p_{v})$ is present in the second tree. Vertex of the tree...
At first, we will calculate the following dynamic programming: $trees(i, j, k)$ will be the number of rooted trees, where the root has exactly $j$ directed subtrees, the maximum size of which does not exceed $k$, and the degree of internal vertices is equal to $d$ (except for the root). Calculation of the value of the ...
[ "combinatorics", "dp", "trees" ]
2,700
null
724
G
Xor-matic Number of the Graph
You are given an undirected graph, constisting of $n$ vertices and $m$ edges. Each edge of the graph has some non-negative integer written on it. Let's call a triple $(u, v, s)$ \textbf{interesting}, if $1 ≤ u < v ≤ n$ and there is a path (\textbf{possibly non-simple}, i.e. it can visit the same vertices and edges mul...
Without loss of generality, let's assume that the graph is connected. If not, we will calculate the answer for each connected component and then sum them up. Let's choose two arbitrary vertices $u$ and $v$ such that $u < v$ and try to find all the interesting triples of the form $(u, v, ...)$. Let's find any path $p_{0...
[ "bitmasks", "graphs", "math", "number theory", "trees" ]
2,600
null
725
A
Jumping Ball
In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of $n$ bumpers. The bumpers are numbered with integers from $1$ to $n$ from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at positio...
Let's divide the sequence into three parts: a sequence (possibly, empty) of '<' bumpers in the beginning, a sequence (possibly, empty) of '>' bumpers in the end, and a sequence (possibly, empty) of any type bumpers between the first and the second parts. It can be easily seen that if the ball starts in the left part, i...
[ "implementation" ]
1,000
null
725
B
Food on the Plane
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with $1$ from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while sea...
The only observation one has to make to solve this problem is that flight attendants move $4$ rows forward at $16$ seconds. Here, $6$ seconds are required to serve everyone in one row, then $1$ second to move forward, $6$ seconds to serve one more row, then $3$ more seconds to move. Thus, $6 + 1 + 6 + 3 = 16$ in total....
[ "implementation", "math" ]
1,200
null
725
C
Hidden Word
Let’s define a grid to be a set of tiles with $2$ rows and $13$ columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: \begin{center} \begin{verbatim} ABCDEFGHIJKLM NOPQRSTUVWXYZ \...
1. The input string $s$ contains 27 letters and it contains every letter in the English alphabet. The English alphabet has 26 letters, so there is exactly one repeated letter. 2. If the instances of the repeated letter are adjacent in the string, there can be no solution. That's because every English letter occurs in $...
[ "brute force", "constructive algorithms", "implementation", "strings" ]
1,600
null
725
D
Contest Balloons
One tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by $1$. For example, if ther...
Previous ones describe how to find a correct approach. It may lead to a slightly more complicated solution, but you will learn something for sure. To come up with a solution, you must try iterating over some value or maybe binary searching an optimal value. Let's list a few reasonable ideas. Try to binary search the an...
[ "data structures", "greedy" ]
1,800
null
725
E
Too Much Money
Alfred wants to buy a toy moose that costs $c$ dollars. The store doesn’t give change, so he must give the store exactly $c$ dollars, no more and no less. He has $n$ coins. To make $c$ dollars from his coins, he follows the following algorithm: let $S$ be the set of coins being used. $S$ is initially empty. Alfred repe...
1. If there is a solution where Bob gives Alfred $n$ coins, then there is a solution where Bob gives Alfred only one coin. We can prove it by induction on $n$. The base case $n = 1$ is trivial. In the inductive case, let $x$ and $y$ be the highest-valued coins that Bob uses (where $x \ge y$). The sequence of coins ch...
[ "brute force", "greedy" ]
2,600
null
725
F
Family Photos
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are $n$ stacks of photos. Each stack c...
1. We are going to transform the stacks in such a way that every move is no worse than passing. 2. Consider a stack with values $a, b, c, d$. (The top photo is worth $a$ for Alice and $b$ for Bonnie and the bottom photo is worth $c$ for Alice and $d$ for Bonnie.) If $a + b \ge c + d$ then taking the top photo is no w...
[ "games", "greedy" ]
2,900
null
725
G
Messages on a Tree
Alice and Bob are well-known for sending messages to each other. This time you have a rooted tree with Bob standing in the root node and copies of Alice standing in each of the other vertices. The root node has number $0$, the rest are numbered $1$ through $n$. At some moments of time some copies of Alice want to send...
Hint: Sort the queries somehow so that the answer on every query will depend only on previous queries. After that, use heavy-light decomposition to answer the queries quickly. Solution: First, sort the queries by $d[x_{i}] + t_{i}$, where $d[a]$ is the depth of the vertex $a$. It can be easily shown that the answer for...
[]
3,300
null
727
A
Transformation: from A to B
Vasily has a number $a$, which he wants to turn into a number $b$. For this purpose, he can do two types of operations: - multiply the current number by $2$ (that is, replace the number $x$ by $2·x$); - append the digit $1$ to the right of current number (that is, replace the number $x$ by $10·x + 1$). You need to he...
Let's solve this problem in reverse way - try to get the number $A$ from $B$. Note, that if $B$ ends with 1 the last operation was to append the digit $1$ to the right of current number. Because of that let delete last digit of $B$ and move to the new number. If the last digit is even the last operation was to multiply...
[ "brute force", "dfs and similar", "math" ]
1,000
null
727
B
Bill Total Value
Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "{$name_{1}price_{1}name_{2}price_{2}...name_{n}price_{n}$}", where $name_{i}$ (nam...
In this problem we need to simply implement calculating the sum of prices. At first we need to find all prices - sequences of consecutive digits and dots. Then we need to find the integer number of dollars in each price and count integer sum of dollars in the variable $r$. Also we need to make the same thing for cents ...
[ "expression parsing", "implementation", "strings" ]
1,600
null
727
C
Guess the Array
This is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output). In this problem you should guess an array $a$ which is unknown for you. The only information you have init...
At first let's make three queries on sum $a_{1} + a_{2} = c_{1}$, $a_{1} + a_{3} = c_{2}$ and $a_{2} + a_{3} = c_{3}$. After that we got a system of three equations with three unknown variables $a_{1}, a_{2}, a_{3}$. After simple calculating we got that $a_{3} = (c_{3} - c_{1} + c_{2}) / 2$. The values of $a_{1}$ and $...
[ "constructive algorithms", "interactive", "math" ]
1,400
null
727
D
T-shirts Distribution
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this si...
Let in the array $cnt$ we store how many t-shirts of each size are in the typography. At first let's give the t-shirts to participants who wants exactly one size of the t-shirt and decrease appropriate values in $cnt$. If in some moment we have no t-shirt of needed size the answer is "NO". Now we need to give the t-shi...
[ "constructive algorithms", "flows", "greedy" ]
1,800
null
727
E
Games on a CD
Several years ago Tolya had $n$ computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD \textbf{in clockwise order}. The names were distinct, the length of each name was equal to $k$. The names didn't overlap. Thus,...
With help of Aho Corasick algorithm we need to build the suffix tree on the set of game names ans in the vertex of the tree (which correspond to the name of some game, this vertex will be on the depth $k$) we will store the number of this game. Builded tree allows to add symbols to some string one by one and find the v...
[ "data structures", "hashing", "string suffix structures", "strings" ]
2,300
null
727
F
Polycarp's problems
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter. He sent to the coordinator a set of $n$ problems. Each problem has it's quality, the quality of the $i$-th problem is $a_{i}$ ($a_{i}$ can be positive, negative or equal to zero). The problems are ordered...
At first let's solve the problem for one value of $Q$. It is easy to show that optimal solution is the following: add to the set of tasks next task with quality equals to $a_{i}$. While the value of mood (the sum of qualities and $Q$) is less than 0, delete from the set of remaining task the task with worst quality. Th...
[ "binary search", "dp", "greedy" ]
2,300
null
729
A
Interview with Oleg
Polycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string $s$ consisting of $n$ lowercase English letters. There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the...
In this problem it is enough to iterate through the given string from the left to the right and find the longest substring like "ogo...go" from each position of the string. If such substring was founded add "***" and move to the end of this substring. In the other case, add current letter to the answer and move to the ...
[ "implementation", "strings" ]
900
null
729
B
Spotlights
Theater stage is a rectangular field of size $n × m$. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not. You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the f...
Let's find the number of good positions where projector directed to the left. It can be done separately for each row. To make it we need to iterate through the row from the left to the right and store information about we met '{1}', for example, in the variable $f$. Then if we process the current value: if it is equal ...
[ "dp", "implementation" ]
1,200
null
729
C
Road to Cinema
Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in $t$ minutes. There is a straight road of length $s$ from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point $0$, and the cinema is at the poi...
Let's note that there is a value for the fuel tank capacity (call it $w$), that if the car has the fuel tank capacity equal or more than $w$ it will be able to reach the cinema if time, else - will not be able. The value $w$ can be found with help of binary search because the function $can(w)$ (it is possible and it ha...
[ "binary search", "greedy", "sortings" ]
1,700
null
729
D
Sea Battle
Galya is playing one-dimensional Sea Battle on a $1 × n$ grid. In this game $a$ ships are placed on the grid. Each of the ships consists of $b$ consecutive cells. No cell can be part of two ships, however, the ships \textbf{can touch} each other. Galya doesn't know the ships location. She can shoot to some cells and a...
Let's note that in on the field there are $b$ zeroes in a row we must to shoot in at least one of them. We suppose that all ships was pressed to the right. Let's put the number 2 in cells where ships can be placed. Then iterate through the field from the left to the right and shoot in the cell if there is 0 and before ...
[ "constructive algorithms", "greedy", "math" ]
1,700
null
729
E
Subordinates
There are $n$ workers in a company, each of them has a unique id from $1$ to $n$. \textbf{Exaclty} one of them is a chief, his id is $s$. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors a...
At first if the chief reported that he has one or more superiors let's change $a_{s}$ in zero. If there are workers who do not chiefs but reported that they have no superiors let assume that they reported a number which more than the other workers, for example, number $n$. It is necessarily that there must be the worke...
[ "constructive algorithms", "data structures", "graphs", "greedy", "sortings" ]
1,900
null
729
F
Financiers Game
This problem has unusual memory constraint. At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared $n$ papers with the income of some company for some time periods. Note that the income can be positive, zero or negative. Igor and Zhenya placed the papers in a row and d...
Let's solve this problem using dynamic programming. We can see that any position in the game can be described with three integers: the left and right bounds of the segment of papers that are still on the table, and the number of papers the previous player took; and who's turn it is. So, let $I_{lrk}$ be the game result...
[ "dp" ]
2,500
null
731
A
Night at the Museum
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition. Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character...
In this problem you have to implement exactly what is written in the statement, i. e. you should find minimum number of rotations from letter a to the first letter in the input, then to the second one and so on. The only useful knowledge that may simplify the solution is that the distance between points $x$ and $y$ on ...
[ "implementation", "strings" ]
800
null
731
B
Coupons and Discounts
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
In a correct answer we may guarantee that for any two consecutive days we use no more than one coupon for bying pizzas in these days. Indeed, if we have two coupons for buying pizzas in days $i$ and $i + 1$, replace these coupons for two discounts, one for each of the days $i$ and $i + 1$. Consider the first day. Accor...
[ "constructive algorithms", "greedy" ]
1,100
null
731
C
Socks
Arseniy is already grown-up and independent. His mother decided to leave him alone for $m$ days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular cl...
When solving this problem, it is convenient to use graph interpretation of the problem. Consider the graph, whose vertices correspond to the socks and edges connect those socks that Arseniy wears on some day. By the statement, we have to make that any two vertices connected by an edge have the same color. It actually m...
[ "dfs and similar", "dsu", "graphs", "greedy" ]
1,600
null
731
D
80-th Level Archeology
Archeologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of $n$ words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hierogl...
Denote as $x$ the number of alphabet cyclic shifts we will perform. Our goal is to formulate the statement of lexicographical order in terms of $x$. Note that $x$ may be considered as an integer between $0$ and $c - 1$, i. e., as a residue modulo $c$. Let's also consider all characters as values between $0$ to $c - 1$ ...
[ "brute force", "data structures", "greedy", "sortings" ]
2,200
null
731
E
Funny Game
Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them. The game they came up with has the following rules. In...
First of all, comment on such type of games. In CS the game where two players are willing to maximize the difference between their own score and the score of their opponent is called a "zero-sum game". A useful knowledge is that problems for such a kind of games are usually solved using dynamic programming. Note that a...
[ "dp", "games" ]
2,200
null
731
F
Video Cards
Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated. There are $n$ video cards in the shop, the power of the $i$-th video card is equal t...
First observation is that if we fix the leading video card power $x$, we may take all the video cards of power at least $x$, as each of them brings the positive power value. So, we may sort all the cards in the ascending power order and then we will always choose some suffix of cards in such an order. The final total p...
[ "brute force", "data structures", "implementation", "math", "number theory" ]
1,900
null
732
A
Buy a Shovel
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for $k$ burles. Assume that there is an unlimited number of such shovels in the shop. In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of $r$ burles ($1...
In this problem we have to find the minimal possible value of $x$ such that $k \cdot x mod 10 = 0$ or $k \cdot x mod 10 = r$. It's easy to see that this $x$ always exists and it is not greater than $10$ (because $k \cdot 10 mod 10 = 0$). Let's iterate on $x$, and if its current value satisfies any of the requirements, ...
[ "brute force", "constructive algorithms", "implementation", "math" ]
800
null
732
B
Cormen --- The Best Friend Of a Man
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least $k$ walks for any two consecutive days in order to feel good. For example, if $k = 5$ and yesterday Polycarp went fo...
If we don't make enough walks during days $i$ and $i + 1$, it's better to make an additional walk on day $i + 1$ because it also counts as a walk during days $i + 1$ and $i + 2$ (and if we walk one more time on day $i$, it won't help us in the future). So we can start iterating from the second day ($1$"=indexed). We wi...
[ "dp", "greedy" ]
1,000
null
732
C
Sanatorium
Vasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how...
Let's iterate on the time of day when Vasiliy arrived at the sanatorium (breakfast, dinner or supper) and on the time when Vasiliy left. We sum the changed values of $b$, $d$ and $s$ (considering that we take all possible meals during the first and the last day) into the variable $sum$, find $mx$ - the maximum of these...
[ "binary search", "constructive algorithms", "greedy", "implementation", "math" ]
1,200
null
732
D
Exams
Vasiliy has an exam period which will continue for $n$ days. He has to pass exams on $m$ subjects. Subjects are numbered from 1 to $m$. About every day we know exam for which one of $m$ subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any da...
Let's use binary search to find the answer (the latest day when we have passed all the exams). To check whether we can pass all the exams until some fixed day $x$, we will take all the examples as late as possible. We will prepare to the earliest exam, then to the second earliest, and so on. If we are not ready for som...
[ "binary search", "greedy", "sortings" ]
1,700
null
732
E
Sockets
The ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations. There are $n$ computers for participants, the $i$-th of which has power...
Firstly, we need to sort both arrays (with computers and with sockets) in non-descending order (also we need to sustain their indices to print the answer). Then we iterate on the value $x$ until it reaches the logarithm of the maximum value in $s$ (or until it reaches 31). For each value of $x$ we iterate on computers ...
[ "greedy", "sortings" ]
2,100
null
732
F
Tourist Reform
Berland is a tourist country! At least, it can become such — the government of Berland is confident about this. There are $n$ cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possi...
Firstly, we have to find all the bridges and divide the graph into 2"=edge"=connected components. Then we calculate the size of each component. It can be easily proved that the answer is equal to size of the largest component. Then we need to orient the edges somehow. Start DFS from any vertex of the largest component....
[ "dfs and similar", "graphs" ]
2,300
null
733
A
Grasshopper And the String
One day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of ...
In this problem you have to find the longest sequence of consonants. The answer is its length + 1. Iterate over each letter of string maintaining $cur$ - current number of consecutive consonants and $len$ - length of longest sequence. If current letter is consonant then increase $cur$ by 1, otherwise update $len = max(...
[ "implementation" ]
1,000
null
733
B
Parade
Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg...
Let's calculate $L$ and $R$ values before update moves. Result will be stored in $maxk$ - maximum beauty that can be achieved. So initially $maxk = |L - R|$. Now for every columm let's calculate $k_{i}$ - beauty of the parade after switching starting leg of $i$-th column. $k_{i} = |(L - l_{i} + r_{i}) - (R - r_{i} + l_...
[ "math" ]
1,100
null
733
C
Epidemic in Monstropolis
There was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city. Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is \textbf{strictly greater} than the weight of th...
The key observation to solution is to notice that $b_{1}$ is union (monsters eat one another one by one in such a way that only one is being left) of elements of some prefix of $a$. And if you remove this prefix and first element of $b$ then this condition will remain true for new arrays $a$ and $b$. Answer is "NO" whe...
[ "constructive algorithms", "dp", "greedy", "two pointers" ]
1,800
null
733
D
Kostya the Sculptor
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has $n$ stones which are rectangu...
Radius of inscribed sphere = $min(a, b, c) / 2$. Let's create list of pairwise distinct edges where two edges is condered different when either minimal sides of edges differ or maximal ones. For every edge $(a, b)$ let's find two maximal lengths of adjacent side $c_{1}$ and $c_{2}$. These are two parallelepipeds of max...
[ "data structures", "hashing" ]
1,600
null
733
E
Sleep in Class
The academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of $n$ steps. The steps are numbered from bottom to top, it means that the lowest st...
Olga is always able to go beyond stairs. To prove that let's consider some segment of stairs. If we enter it from upper step then we move down until reaching 'U' which reverses our moving direction. After that we leave segment from above. Now this 'U' became 'D' and other symbols remained the same as they were either v...
[ "constructive algorithms", "data structures", "math", "two pointers" ]
2,400
null
733
F
Drivers Dissatisfaction
In one kingdom there are $n$ cities and $m$ two-way roads. Each road connects a pair of cities, and for each road we know the level of drivers dissatisfaction — the value $w_{i}$. For each road we know the value $c_{i}$ — how many lamziks we should spend to reduce the level of dissatisfaction with this road by one. Th...
If you choose any $n - 1$ roads then price of reducing overall dissatisfaction is equal to $min(c_{1}, c_{2}, ..c_{n - 1})$ where $c_{i}$ is price of reducing by $1$ dissatisfaction of $i$-th edge. So the best solution is to choose one edge and reduce dissatisfaction of it until running out of budget. Let's construct m...
[ "data structures", "dsu", "graphs", "trees" ]
2,200
null
734
A
Anton and Danik
Anton likes to play chess, and so does his friend Danik. Once they have played $n$ games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this.
Let $k_{a}$ will be amount of characters "A" in the string and $k_{d}$ will be amount of characters "D" in the string. Then, if $k_{a} > k_{d}$, we print "Anton". If $k_{a} < k_{d}$, we print "Danik". If $k_{a} = k_{d}$, we print "Friendship". Time complexity is $O(n)$.
[ "implementation", "strings" ]
800
#include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; string s; cin >> s; int k_a = 0, k_d = 0; for (int i = 0; i < n; i++) if (s[i] == 'A') k_a++; else k_d++; if (k_a > k_d) cout << "Anton" << endl; if (k_a < k_d) cout << "Danik" << endl; if (k_a == k_d) cout << "Friendshi...
734
B
Anton and Digits
Recently Anton found a box with digits in his room. There are $k_{2}$ digits $2$, $k_{3}$ digits $3$, $k_{5}$ digits $5$ and $k_{6}$ digits $6$. Anton's favorite integers are $32$ and $256$. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help hi...
We will act greedily. At first we'll make maximal possible amount of $256$ numbers. It will be equal to $n_{256}=\operatorname*{min}(k_{2},k_{5},k_{6})$. From the rest of the digits we'll make maximal possible amount of $32$ numbers. It will be equal to $n_{32}=\operatorname*{min}(k_{3},k_{2}-n_{256})$ (we use $k_{2} -...
[ "brute force", "greedy", "implementation", "math" ]
800
#include <iostream> #include <algorithm> using namespace std; int main() { int k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; int n256 = min(k2, min(k5, k6)); int n32 = min(k3, k2 - n256); cout << 32 * n32 + 256 * n256 << endl; return 0; }
734
C
Anton and Making Potions
Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare $n$ potions. Anton has a special kettle, that can prepare one potions in $x$ seconds. Also, he knows spells of two types that can faster the process of preparing potions. - Spells o...
At first, observe that if we'll take the $i$-th potion of the first type and the $j$-th potion of the second type, then we can prepare all the potions in $a_{i}\cdot(n-c_{j})$ seconds. So, we have to minimize this number. Let's iterate over what potion of the first type we'll use. Then we must find such spell of the se...
[ "binary search", "dp", "greedy", "two pointers" ]
1,600
#include <iostream> using namespace std; const int max_n = 1000000; int n, m, k; int x, s; int a[max_n], b[max_n], c[max_n], d[max_n]; inline int max_complete(int money_left) { int l = 0, r = k; while (l < r) { int m = (l + r + 1) / 2; if (d[m] <= money_left) l = m; else r = m-1; } return c[l]; } int main...
734
D
Anton and Chess
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on $8$ to $8$ board to too simple, he uses an infinite one instead. The first task he faced is to check whether the king is in check. Anton doesn't know how to implement...
Let's observe that the king can attack only pieces that lay in eight directions (up, down, left, right vertically and horizontally, and also up-left, up-right, down-left and down-right diagonally from the cell where the king stands). Also we can observe that from all the pieces that lay in the eight directions, only th...
[ "implementation" ]
1,700
#include <cstdio> #include <algorithm> using namespace std; inline char in_char() { char c = '\0'; while (c <= ' ') c = getchar(); return c; } inline int in_int() { int n; scanf("%d", &n); return n; } struct figurine { char kind; int x, y; }; int n; int x0, y0; figurine nearest[8]; inline int dist(int x...
734
E
Anton and Tree
Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph. There are $n$ vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white). To...
At first, let's observe that if we unite some two vertices connected by an edge, that are the same color, in one vertex, the answer will not change. Let's do this. Then, for instance, the tree will look in this way: We'll also do such tree "compression" after every painting operation. Then, for instance, the tree will ...
[ "dfs and similar", "dp", "trees" ]
2,100
#include <iostream> #include <vector> #include <algorithm> using namespace std; int n; vector <int> color; vector < vector <int> > g; vector <char> used; vector <int> comp; int n1; vector < vector <int> > g1; vector <int> dp; int ans = 0; void dfs1(int v, int col, int cmp) { if (used[v]) return; if (color[v]...
734
F
Anton and School
Anton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays $b$ and $c$ of length $n$, find array $a$, such that: $\begin{array}{l}{{\displaystyle\int b_{i}=(a_{i}~a n d~a_{1})+(a_{i}~a n d~a_{2})+\cdo...
We'll prove that $(a\;a n d\;b)+(a\;o r\;b)=(a+b)$. At first, let's prove that it's true when $a\in0.1$ and $b\in0.1$. To do it, let's consider all the possible values of $a$ and $b$: $\left[\begin{array}{l l l}{{\frac{\alpha}{1}\left[\begin{array}{l l l}{{0}}&{{\mid\alpha{\mathrm{~and~}}\underbrace{{\mathrm{b}}}{0}}\r...
[ "bitmasks", "constructive algorithms", "implementation", "math" ]
2,500
#include <iostream> using namespace std; const int max_n = 300000; int n; int b[max_n]; int c[max_n]; int a[max_n]; int d[max_n]; int b1[max_n]; int c1[max_n]; int bits[31][max_n]; int kbit[31]; int main() { // input ios_base::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; i++) cin >> b[i]; for (int ...
735
A
Ostap and Grasshopper
On the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length $n$ such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The gr...
Problem on programming technique. You have to find at which positions are grasshoper and insect. If k does not divide the difference of position, then answer is NO. Otherwise we have to check positions pos+k, pos+2k, ..., where pos is the minimal poisiton of grasshoper and insect. If somewhere is an obstacle, then answ...
[ "implementation", "strings" ]
800
null
735
B
Urbanization
Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are $n$ people who plan to move to the cities. The wealth of the $i$ of them is equal to $a_{i}$. Authorities plan to build two cities, first for $n_{1}$ people and sec...
First of all, note that n1+n2 chosen ones should be people with top (n1+n2) coeficients. Secondly, if the person with intelegence C will be in the first city then he will contribute to our overall IQ with C/n1 points. So, if n1<n2, then top-n1 ratings should be in the small city and the top-n2 from others - in the big ...
[ "greedy", "number theory", "sortings" ]
1,100
null
735
C
Tennis Championship
Famous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be $n$ players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately. Organizers are st...
Let us solve the inverse problem: at least how many competitors should be, if the champion will have n matches. Then there's obvious reccurrent formula: f(n+1)=f(n)+f(n-1) (Let us make the draw in a way, where the champion will play n matches to advance to finals and the runner-up played (n-1) matches to advance the fi...
[ "combinatorics", "constructive algorithms", "greedy", "math" ]
1,600
null
735
D
Taxes
Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to $n$ ($n ≥ 2$) burles and the amount of tax he has to pay is calculated as the maximum divisor of $n$ (not equal to $n$, of course). For example, if $n = 6$ then Funt has to pay $3$ burles, while for ...
The first obvious fact is that the answer for prime numbers is 1. If the number is not prime, then the answer is at least 2. When is it possible? It is possible in 2 cases; when it is sum of 2 primes of its maximal divisor is 2. If 2 divides n, then so does integer n/2. n/2<=2=>n<=4=>n=4, where n is prime. According to...
[ "math", "number theory" ]
1,600
null
735
E
Ostap and Tree
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has $n$ vertices. He wants to paint some vertices of the tree black such that from any vertex $u$ there is at least one black vertex $v$ at distance...
Problem can be solved by the method of dynamic programming. Let dp[v][i][j] be the number of possibilities to color subtree of vertex v in such a way that the closest black vertex is on depth i, and the closest white vertex - on depth j (we also store dp[v][-1][j] and dp[v][i][-1] in the cases where there are no black ...
[ "dp", "trees" ]
2,500
null
736
D
Permutations
Ostap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length $n$. He has a list of $m$ valid pairs, pair $a_{i}$ and $b_{i}$ means that he is allowed to place integers $b_{i}$ at position $a_{i}$. ...
This problem consists of 3 ideas. Idea 1: remainder modulo 2 of the number of permutation is equal to the remainder modulo 2 of the determinant of the matrix whose entries are 1 if (ai,bi) is in our list and 0 otherwise. Idea 2: If we cahnge 1 by 0, then the determinant will differ by algebraic compliment. That is, if ...
[ "math", "matrices" ]
2,800
null
736
E
Chess Championship
Ostap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were $m$ players participating and each pair of players played exactly one game. The victory gives $2$ points, draw — $1$ points, lose — $0$ points. Ostap is lazy, so he never...
Suppose set (a1,a2,...,am). Then the list is valid if set {2m-2, 2m-4, 2m-6, ..., 0} majorizes the set {a1,a2,...,am}. Let us prove it! Part 1: Suppose n<=m. Top n players will play n(n-1)/2 games with each other and n(m-n) games with low-ranked contestants. In these games they will collect 2*n(n-1)/2 points (in each g...
[ "constructive algorithms", "flows", "greedy", "math" ]
2,900
null
737
E
Tanya is 5!
Tanya is now five so all her friends gathered together to celebrate her birthday. There are $n$ children on the celebration, including Tanya. The celebration is close to its end, and the last planned attraction is gaming machines. There are $m$ machines in the hall, they are numbered $1$ through $m$. Each of the child...
The problem was invented by the recollections of the recent celebration of the fifth birthday of Tanya Mirzayanova. At first let's solve this problem in simplified form: let there is no duplicate machines (in the other word it does not enough the budget $b$ to rent any duplicate). We consider, that each kid would like ...
[ "graph matchings", "graphs", "greedy", "schedules" ]
3,300
null
737
F
Dirty plates
After one of celebrations there is a stack of dirty plates in Nikita's kitchen. Nikita has to wash them and put into a dryer. In dryer, the plates should be also placed in a stack also, and the plates sizes should increase down up. The sizes of all plates are distinct. Nikita has no so much free space, specifically, h...
At first we wil try to solve the problem without taking the restrictions placed on $a$ and $b$ into consideration. If we can't solve the new problem, we surely can't solve the original one with the restrictions on $a$ and $b$. Let's examine the operations we can and can't do. It's easy to understand that we can't place...
[ "constructive algorithms", "math" ]
3,300
null
739
A
Alyona and mex
Alyona's mother wants to present an array of $n$ non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects $m$ of its subarrays. Subarray is a set of some subsequent elements of the array. The $i$-th subarray is described with two integers $l_{i...
Obviously, the answer to the problem can not be greater than the minimum length among the lengths of the sub-arrays. Suppose that the minimum length of all the sub-arrays is equal to len. Then the desired array is: $0, 1, 2, 3, ..., len - 1, 0, 1, 2, 3, ... len - 1...$. Not hard to make sure that mex of any subarray wi...
[ "constructive algorithms", "greedy" ]
1,700
null
739
B
Alyona and a tree
Alyona has a tree with $n$ vertices. The root of the tree is the vertex $1$. In each vertex Alyona wrote an positive integer, in the vertex $i$ she wrote $a_{i}$. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges). Let's define $dist(v, u)$ as the su...
Let's fix a vertex $v$. This node adds +1 to all the ancestors whose depth $depth[v] - a[v] \le depth[p]$ ($depth[v]$ = the sum of the weights of edges on the path from the root to the vertex $v$). It's a segment of the ancestors, ending in v, as the depth increases when moving to the leaves. It remains to find the f...
[ "binary search", "data structures", "dfs and similar", "graphs", "trees" ]
1,900
null
739
C
Alyona and towers
Alyona has built $n$ towers by putting small cubes some on the top of others. Each cube has size $1 × 1 × 1$. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row. Sometimes Alyona chooses some segment towers, and put on the top of each tower several...
Let's consider the difference between two adjacent elements of array: $a[i] = arr[i + 1] - arr[i]$. Let us add $d$ in the segment from $l$ to $r$. Then it is clear that in the array $a$ will change no more than two values (at the ends of the addition of the segment), because if $l < i < r$, then $a[i] = arr[i + 1] + d ...
[ "data structures" ]
2,500
#pragma comment(linker, "/stack:20000000") #define _CRT_SECURE_NO_WARNINGS # include <iostream> # include <cstdio> using namespace std; template<class T> int sign(T x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } struct Node { int lval, mval, rval; }; Node tr[2340400]; long long a[1010101]; inline void recalc(int...
739
D
Recover a functional graph
Functional graph is a directed graph in which all vertices have outdegree equal to $1$. Loops are allowed. Some vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem). Let's co...
Let's think what has to hold after we put numbers in place of question marks: number of vertices with $precycle = 0$ and $cycle = y$ should be divisible by $y$. if there exists a vertex with $precycle = x > 0$ and $cycle = y$, then there should also exist a vertex with $precycle = x - 1$ and $cycle = y$. Now looking at...
[ "graph matchings" ]
3,400
null
739
E
Gosha is hunting
Gosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has $a$ Poke Balls and $b$ Ultra Balls. There are $n$ Pokemons. They are numbered $1$ through $n$. Gosha knows that if he throws a Poke Ball at the $i$-th Pokemon he catches it with probability $p_{i}$. If he throws an Ultra Ball at the $i$-th P...
Let's divide Pokemons into 4 types: $0, A, B$ and $AB$ depending on Balls that we throw to them. Let's sort them by $u$ in descending order. Let's iterate over last Pokemon in which we throw Ultra Ball (his type is $B$ or $AB$). Let $i$ be the index of this Pokemon. It is not hard to prove that there are no Pokemons to...
[ "brute force", "data structures", "dp", "flows", "math", "probabilities", "sortings" ]
3,000
null
740
A
Alyona and copybooks
Little girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for $a$ rubles, a pack of two copybooks for $b$ rubles, and a pack ...
Let $k$ - is the smallest non-negative integer such that $n + k$ is a multiple of 4. If $k$ is 0, then, obviously, the answer is 0. If $k$ is equal to 1, then you can buy one set of one notebook, you can buy 3 sets of three notebooks, you can buy 1 set of three notebooks and 1 set of two notebooks. Take the most optima...
[ "brute force", "implementation" ]
1,300
null
740
B
Alyona and flowers
Little Alyona is celebrating Happy Birthday! Her mother has an array of $n$ flowers. Each flower has some mood, the mood of $i$-th flower is $a_{i}$. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choo...
If you restate the problem, it is clear that you need to take sub-arrays that have positive sum.
[ "constructive algorithms" ]
1,200
null
741
A
Arpa's loud Owf and Mehrdad's evil plan
As you have noticed, there are lovely girls in Arpa’s land. People in Arpa's land are numbered from $1$ to $n$. Everyone has exactly one crush, $i$-th person's crush is person with the number $crush_{i}$. Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are...
Make a directed graph and put edge from $i$ and $crush_{i}$. If the graph has vertex such that its in-degree is 0 then obviously answer doesn't exist. Otherwise, the graph consists of some cycles. For each cycle suppose that its length is $len$. If it has odd length, add $len$ to $S$, otherwise, add $len / 2$. The answ...
[ "dfs and similar", "math" ]
1,600
null
741
B
Arpa's weak amphitheater and Mehrdad's valuable Hoses
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight $w_{i}$ and some beauty $b_{i}$. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses $x$ and $y$ are in the same friendship group ...
It's a simple knapsack problem. Let's solve this version of knapsack problem first: we have $n$ sets of items, each item has value and weight, find the maximum value we can earn if we can choose at most one item from each set and the sum of the chosen items must be less than or equal to $W$. Let $dp_{w}$ be the max val...
[ "dfs and similar", "dp", "dsu" ]
1,600
null
741
C
Arpa’s overnight party and Mehrdad’s silent entering
Note that girls in Arpa’s land are really attractive. Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw $n$ pairs of friends sitting around a table. $i$-th pair consisted of a boy, sitting on the $a_{i}$-th chair, and his girlfriend, sitting on the $b_{i}$-th chair. ...
Build a graph and put an edge between each $2 \cdot i, 2 \cdot i + 1$ and each BF and GF. This graph doesn't have cycles with odd length. So it is a bipartite graph. Now give Kooft to some part and Zahre-mar to other. Time complexity: ${\cal O}(n)$.
[ "constructive algorithms", "dfs and similar", "graphs" ]
2,600
null
741
D
Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths
Just in case somebody missed it: we have wonderful girls in Arpa’s land. Arpa has a rooted tree (connected acyclic graph) consisting of $n$ vertices. The vertices are numbered $1$ through $n$, the vertex $1$ is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He c...
Please read my dsu on tree (sack) tutorial before you read. Let's calculate for each vertex such $v$, length of longest Dokhtar-kosh path that starts in some vertex of subtree of $v$, passes from $v$, and ends in some other vertex of subtree of $v$ using sack (explained below); then we can sum up this values and get an...
[ "data structures", "dfs and similar", "trees" ]
2,900
null
741
E
Arpa’s abnormal DNA and Mehrdad’s deep interest
All of us know that girls in Arpa’s land are... ok, you’ve got the idea :D Anyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor. Sipa put A...
First sort all of the options. Use suffix array to compare two options. Give rank to each option. Then problem is to find minimum rank in each query. Use sqrt decomposition and divide queries into two groups: - $K\geq{\sqrt{n}}$ There are less than $\sqrt{n}$ segments that satisfy the conditions. Keep all of them, solv...
[ "data structures", "string suffix structures" ]
3,400
null
742
A
Arpa’s hard exam and Mehrdad’s naive cheat
There exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do. Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given $n$, print the last digit of $1378^{n}$. Mehrdad has become quite confused and wants you to help him. Please help, ...
You know $1378^{n}\;\;\mathrm{mod}\;10=8^{n}\;\;\mathrm{mod}\;10$. If $n = 0$ answer is 1, otherwise, you can prove with induction that if: - $n\ \mathrm{\mod}\ 4=0$ then answer is 6. - $n\ \mathrm{\mod}\ 4=1$ then answer is 8. - $n\ \mathrm{\mod}\ 4=2$ then answer is 4. - $n\ \mathrm{\mod}\ 4=3$ then answer is 2. Time...
[ "implementation", "math", "number theory" ]
1,000
null
742
B
Arpa’s obvious problem and Mehrdad’s terrible solution
There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number $x$, count the number of pairs of indices $i, j$ ($1 ≤ i < j ≤ n$) such that $a_{i}\oplus a_{j}=x$, where $\mathbb{C}$ is bitwise xor operation (see notes for explanation). Immedi...
Note that if $a_{i}\oplus a_{j}=X$ then $a_{i}\oplus X=a_{j}$. Keep in $num_{x}$ the number of repetitions of number $x$. Now for each $x$, add $\scriptstyle n=n\,m_{X\in X}$ to answer. Then divide answer by 2 (if $X$ is 0, don't). Time complexity: ${\mathcal{O}}(n)$. Corner case #1: Some codes got WA when $X$ is 0. Co...
[ "brute force", "math", "number theory" ]
1,500
null
743
A
Vladik and flights
Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad. Vladik knows $n$ airports. All the airports are located on a straight line. Each airport has u...
The answer is $0$, if airports with numbers $a$ and $b$ belong to one company. Otherwise there are two adjacent airports, that belong to different companies. We can get to one of them for free, then pay $1$ to fly from one to another and then fly to airport number $b$ for free. So, in this case the answer is $1$. Compl...
[ "constructive algorithms", "greedy", "implementation" ]
1,200
int n, a, b; string s; cin >> n >> a >> b >> s; a--, b--; cout << ((s[a] - '0') ^ (s[b] - '0'));
743
B
Chloe and the sequence
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad. Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element eq...
Consider the string after $n$ steps of algorithm. We can split it into three parts: string from previous step, new character, another one string from previous step. Lets find the part, where our $k$-th character is, and reduce our string to the string from the previous step. The complexity is $O(n)$.
[ "binary search", "bitmasks", "constructive algorithms", "implementation" ]
1,200
int go(ll l, ll r, ll need, int alphSize) { ll m = l + (r - l) / 2LL; if (need < m) return go(l, m - 1, need, alphSize - 1); else if (need > m) return go(m + 1, r, need, alphSize - 1); else return alphSize; } void solveABig() { int n; ll k; cin >> n >> k; ll sz ...
743
C
Vladik and fractions
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer $n$ he can represent fraction $\frac{2}{n}$ as a sum of three distinct positive fractions in form $\frac{1}{m}$. Help Vladik with that, i.e for a given $n$ find three distinct positive integers $x$, $y$ an...
Note that for $n = 1$ there is no solution, and for $n > 1$ there is solution $x = n, y = n + 1, z = n \cdot (n + 1)$. To come to this solution, represent ${\frac{2}{n}}={\frac{1}{n}}+{\frac{1}{n}}$ and reduce the problem to represent $\frac{1}{n}$ as a sum of two fractions. Let's find the difference between $\frac{1}{...
[ "brute force", "constructive algorithms", "math", "number theory" ]
1,500
int n; cin >> n; if (n == 1) cout << -1 << endl; else cout << n << ' ' << n + 1 << ' ' << n * (n + 1) << endl;
743
D
Chloe and pleasant prizes
Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took $n$ prizes for the contestants and wrote on each of them a unique id (integer ...
Our task is to choose two disjoint subtrees, such that sum of numbers in the first plus the sum in the second is maximal. Lets calculate for each vertex this dynamic programming using dfs seach: $sum_{v}$ - sum of all the numbers in subtree of vertex $v$, and $mx_{v}$ - maximal value from all $sum_{k}$ in subtree of ve...
[ "dfs and similar", "dp", "graphs", "trees" ]
1,800
int a[maxn]; vector<int> g[maxn]; ll sum_subTree[maxn], mx_subTree[maxn]; void dfs1(int v, int p) { sum_subTree[v] = a[v]; mx_subTree[v] = -llinf; for (int i = 0; i < g[v].size(); i++) { int to = g[v][i]; if (to == p) continue; dfs1(to, v); sum_subTree[v] += sum...
743
E
Vladik and cards
Vladik was bored on his way home and decided to play the following game. He took $n$ cards and put them in a row in front of himself. Every card has a positive integer number not exceeding $8$ written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: - the number of o...
Suppose we have taken at least $len$ cards of each color and $b$ colors of them have $len + 1$ cards. Then the answer will look like: $(8 - b) * len + b * (len + 1)$. Obviously, if our sequence of cards allows us to take $len$ cards of each color, then it allows to take $len - 1$, and $len - 2$, so on. Lets binary sear...
[ "binary search", "bitmasks", "brute force", "dp" ]
2,200
int can(int len) { for (int i = 0; i < 8; i++) cur[i] = 0; for (int i = 0; i <= n; i++) for (int j = 0; j < (1 << 8); j++) dp[i][j] = -inf; dp[0][0] = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < (1 << 8); j++) { if (dp[i][j] == -inf) ...
744
A
Hongcow Builds A Nation
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with $n$ nodes and $m$ edges. $k$ of the nodes are home to the governments of the $k$ countries that make up the world. There is at ...
First, let's make all connected components cliques. This graph is still stable. Now, there are some components without special nodes. Where should we connect them? If there is a component with size A and a component with size B, we can add A*B edges if we connect these two components. So, it makes sense to choose the l...
[ "dfs and similar", "graphs" ]
1,500
n,m,k = map(int, raw_input().split()) special = map(int, raw_input().split()) root = range(n+1) def par(p): if p != root[p]: root[p] = par(root[p]) return root[p] def c2(n): return n * (n - 1) / 2 for __ in xrange(m): u,v = map(par, map(int, raw_input().split())) root[v] = u sz = [0 for i in range(n+1)] for...
744
B
Hongcow's Game
\textbf{This is an interactive problem. In the interaction section below you will see the information about flushing the output.} In this problem, you will be playing a game with Hongcow. How lucky of you! Hongcow has a hidden $n$ by $n$ matrix $M$. Let $M_{i, j}$ denote the entry $i$-th row and $j$-th column of the ...
For the bits solution: We want to create 20 questions where for every i != j, there exists a question that contains j and not i, and also a qusetion that contains i and not j. If we can do this, we can find the min for each row. Note that i != j implies that there exists a bit index where i and j differ. So, let's ask ...
[ "bitmasks", "divide and conquer", "interactive" ]
1,900
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class HiddenMatrix { public static void main (String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); ...
744
C
Hongcow Buys a Deck of Cards
One day, Hongcow goes to the store and sees a brand new deck of $n$ special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store. This game takes some number of turns to complete. On a turn, Hongcow may do one of...
Also note that if r_i or b_i >= n, we need to collect tokens no matter what since those costs can't be offset. So, we can assume that r_i, b_i <= n. Let's only buy tokens when we need them. Note that after buying a card, you will have either 0 red tokens or 0 blue tokens, so our dp state can be described by [mask][whic...
[ "bitmasks", "brute force", "dp" ]
2,400
import java.util.Arrays; import java.util.Scanner; public class RedAndBlueCards { public static int n; public static char[] color; public static int[] r,b; public static int[] countred, countblue; public static void main (String[] args) { Scanner in = new Scanner(System.in); n = in....
744
D
Hongcow Draws a Circle
Hongcow really likes the color red. Hongcow doesn't like the color blue. Hongcow is standing in an infinite field where there are $n$ red points and $m$ blue points. Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the b...
First to check if an answer can be arbitrarily large, we can see if there is any red point that is on the convex hull of all our points. So from now on, we can assume the answer is finite. We can show that the optimal circle must touch a blue point. To see this, consider any optimal circle that doesn't touch a blue poi...
[ "geometry" ]
3,200
#pragma comment(linker, "/STACK:1000000000") #include <cstdio> #include <cmath> #include <cstdlib> #include <cassert> #include <ctime> #include <cstring> #include <string> #include <set> #include <map> #include <vector> #include <list> #include <deque> #include <queue> #include <sstream> #include <iostream> #include <a...
744
E
Hongcow Masters the Cyclic Shift
Hongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him. You are given a list of $n$ strings $s_{1}, s_{2}, ..., s_{n}$ contained in the list $A$. A list $X$ of strings is called stable if the following condition holds. First, a message is defined as ...
Let M denote the total number of characters across all strings. Consider how long it takes to compute f(L) for a single list. Consider a graph where nodes are suffixes of strings. This means we already spelled out the prefix, and still need to spell out the suffix. There are at most M nodes in this graph. Now, draw at ...
[ "strings", "two pointers" ]
3,200
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class CyclicShiftsAgainAgain { public static int n; public static String[] s; public static int[] len; public static void main (String[] args) { InputReader in = new InputReader(Syste...
745
A
Hongcow Learns the Cyclic Shift
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
We only need to consider at most |s| cyclic shifts (since |s| cyclic shifts returns us back to the original string). So, we can put these all in a set, and return the size of the set.
[ "implementation", "strings" ]
900
print (lambda s: len(set(s[i:] + s[:i] for i in range(len(s)))))(raw_input())
745
B
Hongcow Solves A Puzzle
Hongcow likes solving puzzles. One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an $n$ by $m$ grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed tha...
I really apologize for the ambiguity of this problem. We worked hard to make it concise and accurate, but we left out too many details. Basically, the idea is we want to overlay two of these pieces together so that no square has more than 1 X, and the region of X's forms a rectangle. Now for the solution: First, let's ...
[ "implementation" ]
1,400
n,m = map(int, raw_input().split()) piece = [raw_input().rstrip() for i in range(n)] maxx, minx, maxy, miny = -1, n, -1, m count = 0 for i in range(n): for j in range(m): if piece[i][j] == 'X': maxx = max(maxx, i) minx = min(minx, i) maxy = max(maxy, j) miny = min(miny, j) count += 1 print ((maxx -...
746
A
Compote
Nikolay has $a$ lemons, $b$ apples and $c$ pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio $1: 2: 4$. It means that for each lemon in the compote should be exactly $2$ apples and exactly $4$ pears. You can't crumble up, break up or cut these fruits into pieces. These fruit...
At first let's calculate how many portions of stewed fruit (in one portion - $1$ lemon, $2$ apples and $4$ pears) we can cook. This number equals to $min(a, b div 2, c div 4)$, where $x div y$ is integer part of $x / y$. After that we need to multiply this number of 7, because there is 7 fruits in 1 portion, and print ...
[ "implementation", "math" ]
800
null
746
B
Decoding
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: {con\textbf{...
To find the answer we can iterate through the given string from the left to the right and add each letter in the answer string - one letter to the begin, next letter to the end, next letter to begin and so on. If $n$ is even than the first letter must be added to the begin and the second letter to the end. In the other...
[ "implementation", "strings" ]
900
null
746
C
Tram
The tram in Berland goes along a straight line from the point $0$ to the point $s$ and back, passing $1$ meter per $t_{1}$ seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points $x = 0$ and $x = s$. Igor is at the point $x_{1}$. He sh...
It is easy to show that if Igor faster than the tram the answer is $|x_{1} - x_{2}| \cdot t_{2}$. In the other case we need to use the following hint: the time of arrive does not depend on how much Igor walk before enter the tram, if the tram will reach the finish point faster than Igor. So Igor can wait the tram in th...
[ "constructive algorithms", "implementation", "math" ]
1,600
null
746
D
Green and Black Tea
Innokentiy likes tea very much and today he wants to drink exactly $n$ cups of tea. He would be happy to drink more but he had exactly $n$ tea bags, $a$ of them are green and $b$ are black. Innokentiy doesn't like to drink the same tea (green or black) more than $k$ times in a row. Your task is to determine the order ...
Let's use greedy to solve this problem. On the current step we choose tea, which left more, but if the last $k$ cups were equal we need to use the other tea. If we can't use the other tea - there is no answer and we need to print <<NO>>. So, we need to store the number of last cups, which were equals and how many of gr...
[ "constructive algorithms", "greedy", "math" ]
1,500
null
746
E
Numbers Exchange
Eugeny has $n$ cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be \textbf{distinct}. Nikolay has $m$ cards, distinct numbers from $1$ to ...
Because of all resulting numbers must be distinct we necessarily need to change all numbers with meet more than once in the given sequence $a$. We will use two pointers: pointer on next even number in the sequence $b$ (at first this pointer equals to 2) and pointer on next odd number in the sequence $b$ (at first it is...
[ "greedy", "implementation", "math" ]
1,900
null
746
F
Music in Car
Sasha reaches the work by car. It takes exactly $k$ minutes. On his way he listens to music. All songs in his playlist go one by one, after listening to the $i$-th song Sasha gets a pleasure which equals $a_{i}$. The $i$-th song lasts for $t_{i}$ minutes. Before the beginning of his way Sasha turns on some song $x$ an...
This problem can be solved with help of two pointers. We will store two sets - set with songs with full time and set with songs with partly time. How to move left and right pointers and recalculate current answer? Let left end of the current segment is $l$ and right end of the segment is $r$. Let the set of songs with ...
[ "data structures", "greedy", "two pointers" ]
2,200
null
746
G
New Roads
There are $n$ cities in Berland, each of them has a unique id — an integer from $1$ to $n$, the capital is the one with id $1$. Now there is a serious problem in Berland with roads — there are no roads. That is why there was a decision to build $n - 1$ roads so that there will be exactly one simple path between each p...
The statement of this problem equals to: we need to build rooted tree with $k$ leafs and for each $i$ from 1 to $n$ on the depth $i$ there are $a_{i}$ vertices. Let $m$ is sum of all numbers from $a$ - the number of vertices in the tree without root. At first let build the path from the root to the leaf on the depth $n...
[ "constructive algorithms", "graphs", "trees" ]
2,100
null
747
A
Display Size
A big company decided to launch a new series of rectangular displays, and decided that the display must have exactly $n$ pixels. Your task is to determine the size of the rectangular display — the number of lines (rows) of pixels $a$ and the number of columns of pixels $b$, so that: - there are exactly $n$ pixels on ...
We can iterate through the values of $a$ from 1 to $n$. For each $i$ if $n mod i = 0$ and if $abs(i - n / i)$ is less than already found different we need to update answer with values $min(i, n / i)$ and $max(i, n / i)$ (because $a$ must be less than $b$).
[ "brute force", "math" ]
800
null