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
412
B
Network Configuration
The R1 company wants to hold a web search championship. There were $n$ computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necess...
In this task you should sort array in descending order and print $k$-th element. Due to the weak constraints you could also solve the problem in the following manner. Let's brute $ans$ - the value of answer and calculate how many computers already have Internet's speed not less than $ans$. If there are not less than $k...
[ "greedy", "sortings" ]
900
null
412
C
Pattern
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules. In this task, a pattern will be a string con...
Let's find the answer symbol-by-symbol. Let's consider $i$-th symbol. If there are two different symbols differ from '?' on $i$-th positions in the given strings then we must place '?' on $i$-th position in the answer. If there are '?' on $i$-th positions in all string then we can write any symbol. Obviously, it is bet...
[ "implementation", "strings" ]
1,200
null
412
D
Giving Awards
The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else. Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one ...
Let's build sought permutation by adding employee one-by-one. Let's we already define the order of the first $k$ employees: $a_{1}, a_{2}, ..., a_{k}$. Let's place $k + 1$-th after $a_{k}$-th. If $a_{k}$-th employee owe money to $k + 1$-th then we will swap their positions (and will get permutation $a_{1}, a_{2}, ..., ...
[ "dfs and similar" ]
2,000
null
412
E
E-mail Addresses
One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day. Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume ...
Let's consider position $i$ such, that $s_{i} = '@'$. We are going to calculate the number of such substrings that are correct addresses and the symbol '@' in them is $s_{i}$. Let's go to the left from $i$ until we find '@' or '.' - the symbols that aren't allowed to be to the left of '@'. Let's calculate $cnt$ how man...
[ "implementation" ]
1,900
null
413
A
Data Recovery
Not so long ago company R2 bought company R1 and consequently, all its developments in the field of multicore processors. Now the R2 laboratory is testing one of the R1 processors. The testing goes in $n$ steps, at each step the processor gets some instructions, and then its temperature is measured. The head engineer ...
Count min and max values in given array of length $m$. If the min value is less then given $min$ or the max value is greater the given $max$ the answer is Incorrect. Count value $0 \le need \le 2$, which equals to minimal number of elements which should be added in given array so that the min value will become $min...
[ "implementation" ]
1,200
null
413
B
Spyke Chatting
The R2 company has $n$ employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke. R2 has $m$ Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges...
Process all queries and count some values: for each employee we will count number of messages which weer sent by this employee and for each chat we will count number of messages which were sent to this chat. Then the answer for some employee equals to sum of messages sent to all chats in which he participates minus all...
[ "implementation" ]
1,300
null
413
C
Jeopardy!
'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have $n$ questions, $m$ of them are auction qu...
Firstly choose all not auction questions and answer on them. So we have only auctions. Sort them in non-decreasing order. Consider each size of suffix of auctions and answer them on their initial price and try to answer other questions by multiplying by 2. It could be explained in this way: less than the cost value, th...
[ "greedy", "math" ]
1,400
null
413
D
2048
The programmers from the R2 company love playing 2048. One day, they decided to invent their own simplified version of this game — $2^{k}$ on a stripe. Imagine an infinite in one direction stripe, consisting of unit squares (the side of each square is equal to the height of the stripe). Each square can either be empty...
Consider some state in your game. Note that, we should maintain the maximum suffix if values in descending order. Also, we will maintain only first $k - 1$ powers of two and keep in mind if have already $k$-th power of two or greater. In fact in violation of this order we can not use these numbers because values could ...
[ "bitmasks", "dp" ]
2,000
null
413
E
Maze 2D
The last product of the R2 company in the 2D games' field is a new revolutionary algorithm of searching for the shortest path in a $2 × n$ maze. Imagine a maze that looks like a $2 × n$ rectangle, divided into unit squares. Each unit square is either an empty cell or an obstacle. In one unit of time, a person can move...
We will consider queries one by one. Firstly check if the one cell of the query is reachable from the second. Find all connected components. If the cells are in different connected components, the answer is -1. Otherwise assume that both cells are situated in columns with exactly one obstacle. To find the answer for su...
[ "data structures", "divide and conquer" ]
2,200
null
414
A
Mashmokh and Numbers
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of $n$ distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he re...
In each turn Bimokh will at least get one point so the result is at lease $\frac{n t}{2}$. So if $k\ll{\frac{n}{2}}$ the answer is -1. Let's denote $x=k-\lfloor{\frac{n-2}{2}}\rfloor$. Then you could output $x$ and $2x$ as the first two integers in the sequence then output $\lfloor{\frac{n-2}{2}}\rfloor$ consecutive in...
[ "constructive algorithms", "number theory" ]
1,500
null
414
B
Mashmokh and ACM
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
Lets define $dp[i][j]$ as number of good sequences of length $i$ that ends in $j$. Let's denote divisors of $j$ by $x_{1}, x_{2}, ..., x_{l}$. Then $d p[i][j]=\sum_{r=1}^{l}d p[i-1][x_{r}]$ This yields $O(nk sqrt(n))$ solution which is not fast enough. But one could use the fact that the following loops run in $O(n log...
[ "combinatorics", "dp", "number theory" ]
1,400
null
414
C
Mashmokh and Reverse Operation
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced prog...
Build a complete binary tree with height $n$. So its $i$-th leaf corresponds to $i$-th element of the initial array. For each vertex $v$ lets define its subarray as the subarray containing the elements that have a leaf corresponding to them in subtree rooted at $v$. For each non-leaf vertex $v$, suppose its left child'...
[ "combinatorics", "divide and conquer" ]
2,100
null
414
D
Mashmokh and Water Tanks
Mashmokh is playing a new game. In the beginning he has $k$ liters of water and $p$ coins. Additionally he has a rooted tree (an undirected connected acyclic graph) that consists of $m$ vertices. Each vertex of the tree contains a water tank that is empty in the beginning. The game begins with the fact that Mashmokh c...
Let's suppose instead of a tank there is a pile at each vertex and instead of water the game is played on tiles. Let's denote distance of each vertex $q$ from the root by $depth(q)$. Also Let's label each tile with number of the vertex it was initially put on. Suppose initially there was a tile at each of vertices $v$ ...
[ "binary search", "data structures", "greedy", "trees", "two pointers" ]
2,300
null
414
E
Mashmokh's Designed Problem
After a lot of trying, Mashmokh designed a problem and it's your job to solve it. You have a tree $T$ with $n$ vertices. Each vertex has a unique index from 1 to $n$. The root of $T$ has index $1$. For each vertex of this tree $v$, you are given a list of its children in a specific order. You must perform three types ...
Let's define the dfs-order of a tree as the sequence created by calling function dfs(root). We'll build another sequence from a dfs-order by replacing each vertex in dfs-order by '+1' and inserting a '-1' after the last vertex of its subtree. Note that all vertices of a particular subtree are a continuous part of dfs-o...
[ "data structures" ]
3,200
null
415
A
Mashmokh and Lights
Mashmokh works in a factory. At the end of each day he must turn off all of the lights. The lights on the factory are indexed from $1$ to $n$. There are $n$ buttons in Mashmokh's room indexed from $1$ to $n$ as well. If Mashmokh pushes button with index $i$, then each light with index not less than $i$ that is still t...
For this problem for each light $j$ you could just iterate over all pressed buttons and find the first button $b_{i}$ that $b_{i} < j$. Then you could output $b_{i}$ and move to next light.
[ "implementation" ]
900
null
415
B
Mashmokh and Tokens
Bimokh is Mashmokh's boss. For the following $n$ days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest o...
For this problem you can find the number of tokens you can save if you initally have $k$ tokens in $O(1)$. Then you can calculate the answer for all of numbers in $O(n)$. Suppose $\left\lfloor{\frac{w a}{b}}\right\rfloor$ by $p$. then $p * b \le w * a$. then ${\underline{{\{p_{a}^{b}\}}}}\leq w$. Suppose initially we...
[ "binary search", "greedy", "implementation", "math" ]
1,500
null
416
A
Guess a number!
A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show. The rules are simple. The host thinks of an integer $y$ and the participants guess it by asking questions to the host. There are four types of acceptable questions: - Is it true that $y$ is str...
Let's use the usual Div 2 problem A approach - the naive one. We will track the interval which might contain the number we're guessing. With each of the query we update this interval. If at the end the interval is non-empty then we output any number from it, otherwise the result is "Impossible".
[ "greedy", "implementation", "two pointers" ]
1,400
#include <iostream> void minimize(int &a, int b) { a = std::min(a, b); } void maximize(int &a, int b) { a = std::max(a, b); } using namespace std; int main() { int mx = 2 * 1000 * 1000 * 1000; int mn = -mx; int n; cin >> n; while (n --> 0) { string s; cin >> s; int x; cin >> x; string ans; cin >> ans;...
416
B
Art Union
A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of $n$ painters who decided to organize their work as follows. Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color...
All we need is to iterate over all painters and for each painter to iterate over all pictures. In the inner loop we also remember when the painter finished working on the picture to make sure that the next painter will not start working on it earlier.
[ "brute force", "dp", "implementation" ]
1,300
#include <iostream> #include <vector> using namespace std; int main() { int m; cin >> m; int n; cin >> n; int paintingTime[m][n]; for (int i = 0 ; i < m ; i++) { for (int j = 0 ; j < n ; j++) cin >> paintingTime[i][j]; } vector<int> finishTime(m); for (int i = 0 ; i < n ; i++) { int freeAt = 0; f...
416
C
Booking System
Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity! A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are $n$ booking requests received by now. Each request is characterized by two numbers: $c_{i}$...
Let's solve this one greedy. All we need to notice is that the optimal solution will be to place first the groups with biggest sum which they are ready to pay. For each such group it will be optimal to allocate the smallest matching table. The input limits allow to do a full search when looking for a table.
[ "binary search", "dp", "greedy", "implementation" ]
1,600
#include <algorithm> #include <iostream> #include <vector> using namespace std; class group { public: int id; int size; int income; }; class table { public: int id; int size; }; bool byIncomeDescending(const group &g1, const group &g2) { return g1.income > g2.income; } bool bySize(const table &t1,...
416
D
Population Size
Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions. Polycarpus believes that if...
One thing to notice for this problem is that if we cover some interval with a progression then it will better (at least no worse) to include as many elements to the right of it as possible. So the solution is to greedy - find the leftmost number not covered by a progression, start a new progression with that number (th...
[ "greedy", "implementation", "math" ]
2,400
#include <iostream> #include <vector> #define FOR(i, a, b) for(int i = a; i < b ; ++i) #define FORD(i, a, b) for(int i = a; i >= b; --i) using namespace std; template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; } int main() { int n; cin ...
416
E
President's Path
Good old Berland has $n$ cities and $m$ roads. Each road connects a pair of distinct cities and is bidirectional. Between any pair of cities, there is at most one road. For each road, we know its length. We also know that the President will soon ride along the Berland roads from city $s$ to city $t$. Naturally, he wil...
Let's look at the graph given to us in the example: We need to count the count of the edges on all the shortest paths between each pair of vertices. Let's do something easier first - instead of counting all the edges we will count only those which have the destination vertex on its side. For example here are the edges ...
[ "dp", "graphs", "shortest paths" ]
2,500
#include <iostream> #include <vector> int IntMaxVal = (int) 1e20; #define minimize(a, b) { a = min(a, b); } using namespace std; template <typename T> vector<T> readVector(int n) { vector<T> res(n); for (int i = 0 ; i < n ; i++) cin >> res[i]; return res; } const int MAXN = 500; vector<int> allVertices; // ...
417
A
Elimination
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of $c$ problems, the winners of the round are the first $n$ people in the rating list....
The first thing, that you need to mention, is that if $k \le n \cdot m$, then the answer is equal to 0. After that you need to take at least $n \cdot m - k$ people. There's three possibilities to do that: Also in this problem it is possible to write the solution, which check every possible combinations of the numbers...
[ "dp", "implementation", "math" ]
1,500
null
417
B
Crash
During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check. Each participant is identified by some unique positive i...
Let us create array $a$ with $10^{5}$ elements, which is filled with $- 1$. In the cell $a[k]$ we will contain the maximal number of the submissions of the participant with identifier $k$. We will process submissions in the given order. Let us process submission $x$ $k$. If $a[k] < x - 1$, then the answer is NO, else w...
[ "implementation" ]
1,400
null
417
C
Football
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into $n$ teams and played several matches, two teams could not play against each other more than once. The appointed Judge was the most experienced member — Pavel. But since he was the ...
Let's consider this tournir as graph. Each vertex should have out-degree $k$. Then the graph should contain exactly $nk$ edges. But the full-graph contains $\textstyle{\frac{n(n-1)}{2}}$, because of that if $n < 2k + 1$ then the answer is $- 1$, otherwise we will connect the $i$-th vertex with $i + 1, ..., i + k$, taki...
[ "constructive algorithms", "graphs", "implementation" ]
1,400
null
417
D
Cunning Gena
A boy named Gena really wants to get to the "Russian Code Cup" finals, or at least get a t-shirt. But the offered problems are too complex, so he made an arrangement with his $n$ friends that they will solve the problems for him. The participants are offered $m$ problems on the contest. For each friend, Gena knows wha...
Let us sort the friends by the number of the monitors in the increasing order. Afterwards we will calculate the dp on the masks: the minimal amount of money Gena should spend to solve some subset of problems, if we take first $n$ friends. Then the answer we should compare with the answer for first $i$ friends plus the ...
[ "bitmasks", "dp", "greedy", "sortings" ]
1,900
null
417
E
Square Table
While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size $n × m$, consisting of positive integers such that the sum of the squares of numbers for each row and each colu...
Let's build array of the length $n$ for each $n$, that the sum of the squares of its elements is the square: We are given two numbers $n$ and $m$. Let array $a$ corresponds to $n$, and array $b$ corresponds to $m$. The we will build the answer array $c$ as follows $c_{ij} = a_{i} \cdot b_{j}$.
[ "constructive algorithms", "math", "probabilities" ]
2,400
null
418
D
Big Problems for Organizers
The Finals of the "Russian Code Cup" 2214 will be held in $n$ hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by $n - 1$ roads, you can get from any hotel to any other one. The organizer...
This problem has two solutions. The first one. Let's hang the tree on some vertex. Afterwards, let us calculate for eah vertex it's height and $3$ most distant vertices in its subtree. Also let's calculate arrays for the lowest common ancestors problem. For each vertex $i$ and the power of two $2^{j}$ we have $p[i][j]$...
[ "data structures", "graphs", "trees" ]
2,800
null
418
E
Tricky Password
In order to ensure confidentiality, the access to the "Russian Code Cup" problems is password protected during the problem development process. To select a password, the jury can generate a special table that contains $n$ columns and the infinite number of rows. To construct a table, the first row is fixed, and all th...
The key theoretical idea of this problem is that the $2$nd row is exactly the same as the $4$th row, $3$rd row is exactly the same as $5$th row and so on. Because of that we need only to answer queries on the first three rows. Let's move on to the practical part. In the first place we will compress coordinates, that an...
[ "data structures" ]
3,100
null
420
A
Start Up
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it? The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out...
One should firstly recognize that the required string should be palindrome and each character of the string should be symmetric. All the symmetric characters are - $AHIMOTUVWXY$.
[ "implementation" ]
1,000
null
420
B
Online Meeting
Nearly each project of the F company has a whole team of developers working on it. They often are in different rooms of the office in different cities and even countries. To keep in touch and track the results of the project, the F company conducts shared online meetings in a Spyke chat. One day the director of the F ...
Firstly lets add to the answer all the persons, that didn't appear in the log messages. Then we should consider two cases: 1) If there is a person (with number $i$), that the first log message with him is in form $- i$. We will call such persons X-persons. Consider all X-persons. Pick the one from them that has the las...
[ "implementation" ]
1,800
null
420
C
Bug in Code
Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the $n$ coders on the meeting said: 'I know for sure that either $x$ or $y$ did it!' The head of the com...
Lets construct an undirected graph, the vertices of the graph are the persons, there is an edge between two persons if there are claim of some person about these two persons. Now we can describe the problem on this graph. We need to find the number of such pairs of vertices that at least $p$ edges are adjacent to them....
[ "data structures", "graphs", "implementation", "two pointers" ]
1,900
null
420
D
Cup Trick
The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble. The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of $n$ plastic cups. Then the magician places a small marb...
The solution consists of two parts. 1) Find the valid permutation. Let's go through the given queries. Suppose the current query tells us that the number $a$ is placed on $b$-th position. If we already met $a$ then we are going to skip this query. Otherwise let's find the position of $a$ in the sought permutation. Supp...
[ "data structures" ]
2,200
null
420
E
Playing the ball
A coder cannot sit and code all day. Sometimes it is a good idea to rise from the desk, have a rest, have small talk with colleagues and even play. The coders of the F company have their favorite ball game. Let's imagine the game on the plane with a cartesian coordinate system. The point (0, 0) contains the player who...
Let's claim that we have ray and the infinite number of balls on it in this problem. The $k$-th ball is placed on the distance $k \cdot d$ from the begging of the ray. Let's note that in the answer must be the ball which is placed on the border of some cirlce. The second observation is the following. Let's consider any...
[ "geometry" ]
2,600
null
421
A
Pasha and Hamsters
Pasha has two hamsters: Arthur and Alexander. Pasha put $n$ apples in front of them. Pasha knows which apples Arthur likes. Similarly, Pasha knows which apples Alexander likes. Pasha doesn't want any conflict between the hamsters (as they may like the same apple), so he decided to distribute the apples between the hams...
For each apple you just need to determine who like it. If Alexander likes apple, then he should eat it, if Artur likes the apple, then he should eat it. If they both like the apply anyone can eat the apple.
[ "constructive algorithms", "implementation" ]
800
null
424
A
Squats
Pasha has many hamsters and he makes them work out. Today, $n$ hamsters ($n$ is even) came to work out. The hamsters lined up and each hamster either sat down or stood up. For another exercise, Pasha needs exactly $\frac{n t}{2}$ hamsters to stand up and the other hamsters to sit down. In one minute, Pasha can make so...
The problem is to find the number of standing hamsters. If it is less than half, we should make the required number of hamsters standing. Otherwise we should make some hamsters sitting.
[ "implementation" ]
900
null
424
B
Megacity
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
We can sort all the cities by their distance to the Tomsk city $d_{i}$. After that we are to find the smallest index $t$ for which the total population $p_{0} + p_{1} + ... + p_{t} > = 10^{6}$. In such case the answer is $d_{t}$. We can sort all cities in $O(NlogN)$ and find the value of $t$ in $O(N)$. Limits for $N$ a...
[ "binary search", "greedy", "implementation", "sortings" ]
1,200
null
424
C
Magic Formulas
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers $p_{1}$, $p_{2}$, ..., $p_{n}$. Lets write down some magic formulas: \[ q_{i}=p_{i}\oplus(i\;m o d\;1)\oplus(i\;m o d\;2)\oplus\cdot\cdot\cdot\oplus(i\;m o d\;n); \...
Consider the following formulas: $\ell_{i}=p_{i}\varpi\left(1\;\;\mathrm{mod}\;{\dot{\imath}}\right)\varpi\left({\dot{2}}\;\;\mathrm{mod}\;{\dot{\imath}}\right)\varpi\cdot\cdot\cdot\varpi\left(\eta\;\;\mathrm{mod}\;{\dot{\imath}}\right)},$ $Q=\mathbf{c}_{1}\oplus\mathbf{c}_{2}\oplus\cdot\cdot\oplus\mathbf{c}_{n}.$ Let ...
[ "math" ]
1,600
null
424
D
Biathlon Track
Recently an official statement of the world Olympic Committee said that the Olympic Winter Games 2030 will be held in Tomsk. The city officials decided to prepare for the Olympics thoroughly and to build all the necessary Olympic facilities as early as possible. First, a biathlon track will be built. To construct a bi...
Due to the time limit for Java some of $O(N^{4})$ solution got Accepted. The authors solution has complexity $O(N^{3} \cdot logN)$. The main idea is to fix the top-border and bottom-border. Then, using some abstract data type, for each right-border we can find the most suitable left-border in $O(logN)$ time. For exampl...
[ "binary search", "brute force", "constructive algorithms", "data structures", "dp" ]
2,300
null
424
E
Colored Jenga
Cold winter evenings in Tomsk are very boring — nobody wants be on the streets at such a time. Residents of Tomsk while away the time sitting in warm apartments, inventing a lot of different games. One of such games is 'Colored Jenga'. This game requires wooden blocks of three colors: red, green and blue. A tower of $...
A classical DP-problem on finding expected number. Lets define some function $F(S)$ for some state - the expected number of minutes to finish the game from this state. For each color we can compute the probability of showing this color by the simple formula $\frac{C}{6}$, where $c$ - the number of dice's faces of this ...
[ "dfs and similar", "dp", "probabilities" ]
2,500
null
425
A
Sereja and Swaps
As usual, Sereja has array $a$, its elements are integers: $a[1], a[2], ..., a[n]$. Let's introduce notation: \[ f(a,l,r)=\sum_{i=l}^{r}a[i];\;m(a)=\operatorname*{max}_{1\leq l\leq r\leq n}f(a,l,r). \] A swap operation is the following sequence of actions: - choose two indexes $i, j$ $(i ≠ j)$; - perform assignments...
Lets backtrack interval on which will contain maximal sum. To improve our sum we can swap not more then $k$ minimal elements from the interval to $k$ maximal elements that don't belong to interval. As $n$ isn't big we can do it in any way. Author solution sort all elemets from interval in increasing order and all eleme...
[ "brute force", "sortings" ]
1,500
null
425
B
Sereja and Table
Sereja has an $n × m$ rectangular table $a$, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if ...
Note, that if we have two arrays $x[1..n], 0 \le x_{i} \le 1$ and $y[1..m], 0 \le y_{i} \le 1$, then described matrix can be showed as next one: $a_{i, j} = x_{i} xor y_{j}$. If $n \le k$, then we can backtrack array $x$ and using greedy find best $y$. Otherwise there will be atleast one $i$, such that we wil...
[ "bitmasks", "greedy" ]
2,200
null
425
C
Sereja and Two Sequences
Sereja has two sequences $a_{1}, a_{2}, ..., a_{n}$ and $b_{1}, b_{2}, ..., b_{m}$, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions: - Choose several (at least ...
In thgis problem we will use dynamic programming: $dp_{i, j}$ - minimal pozition of deleted element in second array, such that we have made first operation $j$ times and have deleted not more then $i$ elements from first array. Lets decided how to calculate transfers. Standing in pozition $dp_{i, j}$ we can change noth...
[ "data structures", "dp" ]
2,300
null
425
D
Sereja and Squares
Sereja has painted $n$ distinct points on the plane. The coordinates of each point are integers. Now he is wondering: how many squares are there with sides parallel to the coordinate axes and with points painted in all its four vertexes? Help him, calculate this number.
Lets line $x = k$ contain not more then $\sqrt{n}$ points. Then for each pair of points on this line (lets it be $(k, y_{1})$ and $(k, y_{2})$) check: is there squere that contain them as vertexes. So we should check: is there(in input) pair of points $(k - |y_{2} - y_{1}|, y_{1})$ and $(k - |y_{2} - y_{1}|, y_{2})$, o...
[ "binary search", "data structures", "hashing" ]
2,300
null
425
E
Sereja and Sets
Let's assume that set $S$ consists of $m$ distinct intervals $[l_{1}, r_{1}]$, $[l_{2}, r_{2}]$, $...$, $[l_{m}, r_{m}]$ ($1 ≤ l_{i} ≤ r_{i} ≤ n$; $l_{i}, r_{i}$ are integers). Let's assume that $f(S)$ is the maximum number of intervals that you can choose from the set $S$, such that every two of them do not intersect...
First, lets look at $F(S)$. First, we sort all intervals by second coordinte and then go by them in sorted order. And if current interval don't intersected with last taken to the optimal set, we get our current to the set. Our solution will be based on this greedy. Solution of the problem is next dynamic: 1). number of...
[ "dp" ]
2,500
null
426
A
Sereja and Mugs
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and $n$ water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume th...
Lets count the sum of all elements $Sum$ and value of the maximal element $M$. If $Sum - M \le S$ then answer is yes, otherwise - no.
[ "implementation" ]
800
null
426
B
Sereja and Mirroring
Let's assume that we are given a matrix $b$ of size $x × y$, let's determine the operation of mirroring matrix $b$. The mirroring of matrix $b$ is a $2x × y$ matrix $c$ which has the following properties: - the upper half of matrix $c$ (rows with numbers from $1$ to $x$) exactly matches $b$; - the lower half of matrix...
Lets solve problem from another side. We will try to cut of matix as many times as we can. Cut means operation, reversed to operation described in statement. To check, can we cut matrix we need to check following conditions: 1). $n mod 2 = 0$ 2). $a_{i, j} = a_{n - i + 1, j}$ for all $1 \le i \le n, 1 \le j \le ...
[ "implementation" ]
1,300
null
427
A
Police Recruits
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
Maintain a variable, $sum$. Initially $sum$=0, it keeps the number of currently free police officers. With every recruitment operation, add the number of officers recruited at that time to $sum$. When a crime occurs, if $sum > 0$ then decrease the number of free officers by one, otherwise no officers are free so the cr...
[ "implementation" ]
800
null
427
B
Prison Transfer
The prison of your city has $n$ prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer $c$ of the prisoners to a prison located in another city. For this reason, he made the $n$ prisoners to stand in a line, with a number written on their chests. The number is the severity of th...
The severity of crimes form an integer sequence. Find all the contiguous sequences without any integer greater than $t$. If the length of any sequence is $L$, then we can choose $c$ prisoners from them in $L - c + 1$ ways.
[ "data structures", "implementation" ]
1,100
null
427
C
Checkposts
Your city has $n$ junctions. There are $m$ \textbf{one-way} roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions. To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction $i$ can protect ju...
Find the strongly connected components of the graph. From each component we need to choose a node with the lowest cost. If there are more than one nodes with lowest cost, then there are more than one way to choose node from this component.
[ "dfs and similar", "graphs", "two pointers" ]
1,700
null
427
D
Match & Catch
Police headquarter is monitoring signal on different frequency levels. They have got two suspiciously encoded strings $s_{1}$ and $s_{2}$ from two different frequencies as signals. They are suspecting that these two strings are from two different criminals and they are planning to do some evil task. Now they are tryin...
$O(n^{2})$ dynamic programming solution : Calculate the longest common prefix ( LCP ) for each index of $s1$ with each index of $s2$. Then, calculate LCP for each index of $s1$ with all the other indexes of it's own ( $s1$ ). Do the same for $s2$. Now from precalculated values, you can easily check the length of the sh...
[ "dp", "string suffix structures", "strings" ]
2,200
null
427
E
Police Patrol
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the $x$-axis. Currently, there are $n$ criminals along the road. No police station has been built on this road yet, so the mayor wants to build one. As you are going to be in charge of this new...
Trying to place the police station on existing criminal locations is the best strategy. Calculate the cost from the leftmost criminal location, then sweep over the next locations. By doing some adjustments on the cost of the previous location will yield the cost of the current location.
[ "greedy", "implementation", "math", "ternary search" ]
2,000
null
429
A
Xor-tree
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having $n$ nodes, numbered from $1$ to $n$. Each node $i$ has an initial value $init...
There is something to learn from "propagating tree" problem, used in round #225. It's how the special operation works. I'll copy paste the explanation from there (with some modification, corresponding to the problem): Let's define level of a node the number of edges in the path from root to the node. Root (node 1) is a...
[ "dfs and similar", "trees" ]
1,300
null
429
B
Working out
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix $a$ with $n$ lines and $m$ columns. Let number $a[i][j]$ represents the calories burned by performing workout at the cell of gym in the $i$-th line and the $j$-th column. Iahub ...
The particularity of this problem which makes it different by other problem of this kind is that paths need to cross exactly one cell and Iahub can go only right and down, Iahubina can go only right and up. Let's try to come up with a solution based on these facts. A good start is to analyze configurations possible for...
[ "dp" ]
1,600
null
429
C
Guess the Tree
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that - each int...
The constrain n <= 24 immediately suggest us an exponential solution. 24 numbers seems to be not too big, but also not too small. What if we can reduce it by half? We can do this, by analyzing problem's restriction more carefully. The problem states that each internal node has at least two sons. After drawing some tree...
[ "bitmasks", "constructive algorithms", "dp", "greedy", "trees" ]
2,300
null
429
D
Tricky Function
Iahub and Sorin are the best competitive programmers in their town. However, they can't both qualify to an important contest. The selection will be made with the help of a single problem. Blatnatalag, a friend of Iahub, managed to get hold of the problem before the contest. Because he wants to make sure Iahub will be t...
Let's define S[i] = a[1] + a[2] + ... + a[i]. Then, f(i, j) = (i - j) ^ 2 + (S[i] - S[j]) ^ 2. Trying to minimize this function seems complicated, so we need to manipulate the formula more. We know from the maths that if f(i, j) is minimized, then also f'(i, j) = sqrt ( (i - j) ^ 2 + (S[i] - S[j]) ^ 2) is also minimize...
[ "data structures", "divide and conquer", "geometry" ]
2,200
null
429
E
Points and Segments
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw $n$ distinct segments $[l_{i}...
The problem asks you to check the property for an infinity of points. Obviously, we can't do that. However, we can observe that some contiguous ranges on OX axis have the same rx and bx values. Like a sweep line algorithm, a possible change may appear only when a new segment begins or when an old one ends. So let's con...
[ "graphs" ]
3,000
null
430
A
Points and Segments (easy)
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw $n$ distinct points and $m$ s...
The problem asks you to output "-1" if there is no solution. A natural question is now: "when there is no solution"? Try to come up with a test like this! After some analysis, you'll see anyhow we draw the points and the lines, there will always be a solution. By manually solving small cases, you might already have fou...
[ "constructive algorithms", "sortings" ]
1,600
null
430
B
Balls Game
Iahub is training for the IOI. What is a better way to train than playing a Zuma-like game? There are $n$ balls put in a row. Each ball is colored in one of $k$ colors. Initially the row doesn't contain three or more contiguous balls with the same color. Iahub has a single ball of color $x$. He can insert his ball at ...
This is an implementation problem. There is not so much to explain. Perhaps the trick at implementation problems is to divide code into smaller subproblems, easy to code and then put them together. I don't know if this is the universally truth, but this is how I approach them. Here, there are two main parts: the part w...
[ "brute force", "two pointers" ]
1,400
null
431
A
Black Square
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
To solve this problem, you must only do the process described in statement. Complexity: $O(N)$
[ "implementation" ]
800
#include<iostream> using namespace std; int main(){ int a[5]; for (int i = 1; i <= 4; i ++) cin >> a[i]; string s; cin >> s; int sum = 0; for (int i = 0 ;i < s.size(); i ++) sum += a[s[i]-'0']; cout << sum << endl; return 0; }
431
B
Shower Line
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory ...
In this problem, according to the small limits, we can brute all permutations and choose the best answer of all. The easeast way to do this - use standart C++ function next_permutation, or simply write 5 for. For each permutation we can simulate the process, which was described in a statement, or notice that first with...
[ "brute force", "implementation" ]
1,200
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int g[6][6]; int main() { int n = 5; for(int i = 0 ; i < n ; ++i) for(int j = 0 ; j < n ; ++j) cin >> g[i][j]; int p[6], pans[6], ans = -1, tmp; for(int i = 0 ; i < n ; ++i) p[i] = i; ...
431
C
k-Tree
Quite recently a creative student Lesha had a lecture on trees. After the lecture Lesha was inspired and came up with the tree of his own which he called a $k$-tree. A $k$-tree is an infinite rooted tree where: - each vertex has exactly $k$ children; - each edge has some weight; - if we look at the edges that goes fr...
This problem can be solved by dinamic programming. Let's Dp[n][is] - number of ways with length equals to $n$ in k-tree, where if $is = 1$ - there is exists edge with length at least $d$, $is = 0$ - lengths of all edges less then $d$. Initial state Dp[0][0] = 1. Transition - iterate all edges which can be first on the ...
[ "dp", "implementation", "trees" ]
1,600
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; const int mod = 1e9 + 7; int dp[100][2]; void add(int &a, int b) { a += b; if(a >= mod) a -= mod; } int main(int argc, char ** argv) { int n, k, d; cin >> n >> k >> d; dp[0][0] = 1; dp[0][1] = 0; ...
431
D
Random Task
One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer $n$, that among numbers $n + 1$, $n + 2$, ..., $2·n$ there are exactly $m$ numbers which binary representation contains exactly $k$ digits one". The girl got interes...
We will search $n$ by binary search. Such function is monotone, because the amount of numbers with exactly $k$ 1-bits on a segment $n + 2$ ... $2 \cdot (n + 1)$ more or equal than amount of such numbers on segment $n + 1$ ... $2 \cdot n$. Last statement is correct, because of $n + 1$ and $2 \cdot (n + 1)$ have equals n...
[ "binary search", "bitmasks", "combinatorics", "dp", "math" ]
2,100
#include<cstdio> #include<cassert> using namespace std; #define linf 2000000000000000000LL #define bit(mask,i) ((mask>>i)&1) const int Max_Bit = 63; long long C[Max_Bit+1][Max_Bit+1]; int bcount(long long x){ int Res = 0; for (;x;x&=(x-1)) Res++; return Res; } long long Solve(long long x,int k){ ...
431
E
Chemistry Experiment
One day two students, Grisha and Diana, found themselves in the university chemistry lab. In the lab the students found $n$ test tubes with mercury numbered from $1$ to $n$ and decided to conduct an experiment. The experiment consists of $q$ steps. On each step, one of the following actions occurs: - Diana pours all ...
First of all let's understand the statement. We have $n$ tubes. At the beginning of each of them there are a few amount of mercury is poured. We want be able to perform two types of queries: Make the amount of mercury in $p$-th tube equals to $x$. Given the number $v$ - the amount of water that must be optimally pour t...
[ "binary search", "data structures", "ternary search" ]
2,200
#include <iostream> #include <string> #include <cstdlib> #include <map> using namespace std; const int maxn = 200001; int h[maxn]; int T[maxn]; int P[maxn]; long long V[maxn]; int X[maxn]; long long max_h; int n; long long a[maxn], b[maxn]; int mas[maxn]; void add(long long t[], int i, long long value) { ...
432
A
Choosing Teams
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has $n$ students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. Th...
In this problem you should count number of students who can participate in ACM, divide it by 3 and round down. It could be done like this:
[ "greedy", "implementation", "sortings" ]
800
null
432
B
Football Kit
Consider a football tournament where $n$ teams participate. Each team has two football kits: for home games, and for away games. The kit for home games of the $i$-th team has color $x_{i}$ and the kit for away games of this team has color $y_{i}$ $(x_{i} ≠ y_{i})$. In the tournament, each team plays exactly one home g...
Count for every team number of games in home kit. For team $i$ it equals to sum of $n - 1$ games at home and some away games with such teams which home kit color equals away kit color of team $i$. To count number of such away games you could calc array $cnt[j]$ - number of teams with home color kit $j$. The solution co...
[ "brute force", "greedy", "implementation" ]
1,200
null
432
C
Prime Swaps
You have an array $a[1], a[2], ..., a[n]$, containing distinct integers from $1$ to $n$. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times): - choose two indexes, $i$ and $j$ ($1 ≤ i < j ≤ n$; $(j - i + 1)$ is a prime number); - swap the elements ...
The solution can be described by pseudo-code: Consider elements of permutation from $1$ to $n$ While current element $i$ is not sutiated on position $i$ Let the position of element $i$ equals $pos$ Find maximum prime integer $p$ which is less or equal than $pos - i + 1 Swap element in positions $pos$ and $pos - p + 1$ ...
[ "greedy", "sortings" ]
1,800
null
432
D
Prefixes and Suffixes
You have a string $s = s_{1}s_{2}...s_{|s|}$, where $|s|$ is the length of string $s$, and $s_{i}$ its $i$-th character. Let's introduce several definitions: - A substring $s[i..j]$ $(1 ≤ i ≤ j ≤ |s|)$ of string $s$ is string $s_{i}s_{i + 1}...s_{j}$. - The prefix of string $s$ of length $l$ $(1 ≤ l ≤ |s|)$ is string...
The problem could be solved using different algorithms with z and prefix functions. Let's describe the solution with prefix function $p$ of string $s$. Calc prefix function and create a tree where vertices - integers from $0$ to $|s|$, edges - from $p[i]$ to $i$ for every $i$. The root of the tree is $0$. For every ver...
[ "dp", "string suffix structures", "strings", "two pointers" ]
2,000
null
432
E
Square Tiling
You have an $n × m$ rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: - each cell must be painted some color (the colors are marked by uppercase Latin letters); - we will assume that two...
The problem could be solved in a standard way - try to fill the table from the first cell to the last and try to put the miminum letter. Consider the first row. Obviously it begins from some letters A (to be exact $min(n, m)$ letters A). When we put some letters A in the first row, we should put several letters A in so...
[ "constructive algorithms", "greedy" ]
2,300
null
433
A
Kitahara Haruki's Gift
Kitahara Haruki has bought $n$ apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equa...
Denote $G$ as the sum of the weight of the apples. If $G / 100$ is not an even number, then the answer is obviously "NO". Otherwise, we need to check if there is a way of choosing apples, so that the sum of the weight of the chosen apples is exactly $\frac{G}{2}$. A simple $O(n)$ approach would be to enumerate how many...
[ "brute force", "implementation" ]
1,100
//Template #include <cstdio> #include <iostream> using namespace std; int n, a = 0, b = 0; int main(int argc, char *argv[]) { #ifdef KANARI freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cin >> n; for (int i = 1, x; i <= n; ++i) { cin >> x; if (x ==...
433
B
Kuriyama Mirai's Stones
Kuriyama Mirai has killed many monsters and got many (namely $n$) stones. She numbers the stones from $1$ to $n$. The cost of the $i$-th stone is $v_{i}$. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: - She will tell you two numbers, $l$ and $r (1 ≤ l ≤ r ≤ n)$, ...
Sort sequence $v$ to obtain sequence $u$. Sorting can be done in $O(n\log n)$ using quicksort. Now we are interested in the sum of a interval of a given sequence. This can be done by calculating the prefix sum of the sequence beforehand. That is, let $s v_{i}=\sum_{j=1}^{t}v_{j}$. The sum of numbers in the interval $[l...
[ "dp", "implementation", "sortings" ]
1,200
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define LL "%I64d" const int maxn=100010; int n,m; long long y[maxn],z[maxn]; int main() { scanf("%d",&n); for (int a=1;a<=n;a++) { int v; scanf("%d",&v); y[a]=z[a]=v; } sort(y+1,y+n+1); for (int a=1;a<...
433
C
Ryouko's Memory Note
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
Suppose we're merging page $x$ to page $y$. Obviously page $x$ should be an element of sequence $a$, otherwise merging would have no effect. Enumerate all possible values of $x$, and denote sequence $b$ as the elements of $a$ that are adjacent to an element with value $x$. If one element is adjacent to two elements wit...
[ "implementation", "math", "sortings" ]
1,800
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxn=100010; int n,m,cnt,z[maxn]; pair<int,int> y[maxn<<1]; int main() { scanf("%d%d",&n,&m); for (int a=1;a<=m;a++) scanf("%d",&z[a]); long long sum=0; for (int a=2;a<=m;a++) { sum+=abs(z[a]-z[a-1...
433
D
Nanami's Digital Board
Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital ...
Consider a similar problem: find the maximum light-block of the whole board. Constraints to this problem are the same as the original problem, but with no further operations. A brute-force idea would be to enumerate all four edges of the block, checking can be done with two-dimensional prefix sums, so the time complexi...
[ "dsu", "implementation" ]
2,000
#include<cstdio> #include<cstdlib> #include<cstring> #include<cctype> #include<algorithm> using namespace std; const int BUF_SIZE = 30; char buf[BUF_SIZE], *buf_s = buf, *buf_t = buf + 1; #define PTR_NEXT() \ { \ buf_s ++; \ if (buf_s == buf_t) \ { \ buf_s = buf; \ ...
433
E
Tachibana Kanade's Tofu
Tachibana Kanade likes Mapo Tofu very much. One day, the canteen cooked all kinds of tofu to sell, but not all tofu is Mapo Tofu, only those spicy enough can be called Mapo Tofu. Each piece of tofu in the canteen is given a $m$-based number, all numbers are in the range $[l, r]$ ($l$ and $r$ being $m$-based numbers), ...
A straightforward brute-force idea would be to enumerate all numbers in the interval $[l, r]$, and count how many of them have a value greater than $k$. This approach is way too slow, but nevertheless let's try optimizing it first. The enumeration part seems hard to optimize, so let's consider what is the fastest way o...
[ "dp" ]
2,500
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define inc(a,b) {a+=b;if (a>=mo) a-=mo;} #define newnode ++wmt const int maxn=210; const int maxm=22; const int maxk=510; const int maxp=210; const int mo=1000000007; int n,m,k,llen,rlen,wmt,root,f[maxn][maxp][maxk][2...
434
D
Nanami's Power Plant
Nanami likes playing games, and is also really good at it. This day she was playing a new game which involved operating a power plant. Nanami's job is to control the generators in the plant and produce maximum output. There are $n$ generators in the plant. Each generator should be set to a generating level. Generating...
We can use a flow network to solve the problem. For each variable $x_{i}$, create $r_{i} - l_{i} + 2$ points, and denote them as $node(i, l_{i} - 1)$ to $node(i, r_{i})$. Edges are as follows: Let $C$ be the value of the minimum cut of this network. If there are no further restrictions, it is obvious that $MAX \cdot n ...
[ "flows" ]
2,900
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define node(a,b) (b-l[a]+start[a]) const int maxn=50*201+10; const int maxm=(60*210+100)*2; const int INF=0x3f3f3f3f; int n,m,en,q[maxn],depth[maxn],l[60],r[60],start[60],A[60],B[60],C[60],s,t; struct edge { int e,...
434
E
Furukawa Nagisa's Tree
One day, Okazaki Tomoya has bought a tree for Furukawa Nagisa's birthday. The tree is so strange that every node of the tree has a value. The value of the $i$-th node is $v_{i}$. Now Furukawa Nagisa and Okazaki Tomoya want to play a game on the tree. Let $(s, e)$ be the path from node $s$ to node $e$, we can write dow...
In order not to mess things up, we use capital letters $X$, $Y$ and $K$ to denote the values in the original problem. First, we can build a directed graph with $n^{2}$ edges. Let $E(i, j)$ be the edge from node $i$ to node $j$. If path $(i, j)$ is good, the color of $E(i, j)$ is $0$, otherwise it is $1$. We want to cal...
[ "binary search", "divide and conquer", "sortings", "trees" ]
3,000
//Template #include <cstdio> #include <iostream> #include <algorithm> #include <climits> #include <map> #include <vector> using namespace std; typedef long long ll; #define N 100000 struct edge { int next, node; } e[N << 1 | 1]; int head[N + 1], tot = 0; inline void addedge(int a, int b) { e[++tot].next =...
435
A
Queue on Bus Stop
It's that time of the year when the Russians flood their countryside summer cottages (dachas) and the bus stop has a lot of people. People rarely go to the dacha on their own, it's usually a group, so the people stand in queue by groups. The bus stop queue has $n$ groups of people. The $i$-th group from the beginning ...
The problem could be solved in one cycle by groups. The solution could be implemented in this way:
[ "implementation" ]
1,000
null
435
B
Pasha Maximizes
Pasha has a positive integer $a$ without leading zeroes. Today he decided that the number is too small and he should make it larger. Unfortunately, the only operation Pasha can do is to swap two adjacent decimal digits of the integer. Help Pasha count the maximum number he can get if he has the time to make at most $k...
The problem could solved by greedy algorithm. We will try to pull maximum digits to the beginning. The algorithm could be described in this way: 1) Consider every position in the number from the first, assume that the current position is $i$ 2) Find the nearest maximum digit from the next $k$ digits of the number, assu...
[ "greedy" ]
1,400
null
435
C
Cardiogram
In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners: \[ (0;0),(a_{1};a_{1}),(a_{1}+a_{2};a_{1}-a_{2}),(a_{1}+a_{2}+a_{3};a_{1}-a_{2}+a_{3}),\ldots,(\sum_{i=1}^{n}a_{i};\sum_{i=1}^{n}(-1)^{i+1}a_{i}). \] That is, a cardiogram is fully define...
This problem is technical, you should implement what is written in the statement. First, you need to calc coordinates of all points of the polyline. Also create matrix for the answer. Coordinate $y$ could become negative, so it is useful to double the sizes of the matrix and move the picture up to $1000$. In the end yo...
[ "implementation" ]
1,600
null
435
D
Special Grid
You are given an $n × m$ grid, some of its nodes are black, the others are white. Moreover, it's not an ordinary grid — each unit square of the grid has painted diagonals. The figure below is an example of such grid of size $3 × 5$. Four nodes of this grid are black, the other $11$ nodes are white. Your task is to co...
Values $n$ and $m$ are not so large, so the solution with complexity $O(max(n, m)^{3})$ should pass. It means that you should consider all triangles and check all conditions in $O(1)$. To make this check you should precalc arrays of partial sums on all diagonals, rows and columns. After that you could check, that there...
[ "brute force", "dp", "greedy" ]
2,000
null
435
E
Special Graph
In this problem you will need to deal with an $n × m$ grid graph. The graph's vertices are the nodes of the $n × m$ grid. The graph's edges are all the sides and diagonals of the grid's unit squares. The figure below shows a $3 × 5$ graph. The black lines are the graph's edges, the colored circles are the graph's vert...
To solve this problem you have to paint different correct colorings on the paper. After it you could observe that there are two types of them: vertical and horizontal. Vertical colorings looks like this: acbcbd... bdadac... acbcbd... bdadac... acbcbd... bdadac... ...... In other words, each vertical has only two colors...
[]
2,500
null
436
A
Feed with Candy
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. One day, Om Nom visited his friend Evan. Evan has $n$ candies of two types (fruit drops and caramel drops), the $i$-th candy hangs at the height of $h_{i}$ centimeters a...
In this problem types of eaten candies must alternate. It means that the type of first eaten candy dictated the types of all the following candies. There are only two possible types so we should consider each type as a type of first eaten candy separatelly and then pick the most optimal. So, what if Om Nom wants to eat...
[ "greedy" ]
1,500
null
436
B
Om Nom and Spiders
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. The park can be represented as a rectangular $n × m$ field. The park has $k$ spiders, each spider at time ...
Let us number columns with integers from $0$ from left to right and rows from $0$ from top to bottom. In the cell $(x, y)$ at the time $t$ only four spiders can be at this cell: Spider, which is moving left and started at $(x, y + t)$. Spider, which is moving right and started at $(x, y - t)$. Spider, which is moving u...
[ "implementation", "math" ]
1,400
null
436
C
Dungeons and Candies
During the loading of the game "Dungeons and Candies" you are required to get descriptions of $k$ levels from the server. Each description is a map of an $n × m$ checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a c...
Let's consider a weighted undirected graph with $k + 1$ vertex. Label the vertices with numbers from $0$ to $k$. Vertices from $1$ to $k$ correspond to levels. For each pair of levels $i$ and $j$ add an edge between vertices $i$ and $j$ with weight equal to the cost of transferring one level as a difference from the ot...
[ "dsu", "graphs", "greedy", "trees" ]
1,800
null
436
D
Pudding Monsters
Have you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used. Imagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pudding, so...
This problem can be solved using dynamic programming. Let's introduce some designations: $sum(l, r)$ - number of special cells on the segment $[l, r]$, $z_{i}$ - maximal number of covered special cells using only first $i$ monsters, $d_{i}$ - maximal number of covered special cells using only first $i$ monsters and wit...
[ "dp" ]
2,800
null
436
E
Cardboard Box
Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for...
In this task you have to come with the proper greedy algorithms. Several algorithms will fit, let's describe one of them: From that point we will consider that the levels are sorted by increasing value of $b$. Let's look at some optimal solution (a set of completed levels). From levels that we completed for two stars, ...
[ "data structures", "greedy" ]
2,600
null
436
F
Banners
All modern mobile applications are divided into free and paid. Even a single application developers often release two versions: a paid version without ads and a free version with ads. Suppose that a paid version of the app costs $p$ ($p$ is an integer) rubles, and the free version of the application contains $c$ ad ba...
Task F was the hardest one in the problemset. To better understand the solution, let's look at the task from the geometrical point of view. Imagine that people are point in the $Opc$ plane (value of $p$ and $q$ are points' coordinates). Then for each line horizontal $c = i$ we have to find such vertical line $p = j$ th...
[ "brute force", "data structures", "dp" ]
3,000
null
437
A
The Child and Homework
Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: A, B, C and D. Each choice has a description, and the child should find out the only one that is correct. Fortunately the child knows how to solve such complicated test. The chi...
We enumerate each choice $i$, and then enumerate another choice $j$ $(j \neq i)$, let $cnt = 0$ at first, if choice $j$ is twice longer than $i$ let $cnt = cnt + 1$, if choice $j$ is twice shorter than $i$ let $cnt = cnt - 1$. So $i$ is great if and only if $cnt = 3$ or $cnt = - 3$. If there is exactly one great choi...
[ "implementation" ]
1,300
null
437
B
The Child and Set
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks. Fortunately, Picks remembers something about his set $S$: - its elements were distinct integers from $1$ to $limit$; - the value of $\t...
We could deal with this by digits. Because $lowbit(x)$ is taking out the lowest $1$ of the number $x$, we can enumerate the number of the lowest zero. Then, if we enumerate $x$ as the number of zero, we enumerate $a$ as well, which $a \times 2^{x}$ is no more than $limit$ and $a$ is odd. We can find out that $lowbit(...
[ "bitmasks", "greedy", "implementation", "sortings" ]
1,500
null
437
C
The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of $n$ parts and $m$ ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts....
The best way to delete all n nodes is deleting them in decreasing order of their value. Proof: Consider each edge $(x, y)$, it will contribute to the total cost $v_{x}$ or $v_{y}$ when it is deleted. If we delete the vertices in decreasing order, then it will contribute only $min(v_{x}, v_{y})$, so the total costs is t...
[ "graphs", "greedy", "sortings" ]
1,400
null
437
D
The Child and Zoo
Of course our child likes walking in a zoo. The zoo has $n$ areas, that are numbered from $1$ to $n$. The $i$-th area contains $a_{i}$ animals in it. Also there are $m$ roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area u...
First, there is nothing in the graph. We sort all the areas of the original graph by their animal numbers in decreasing order, and then add them one by one. When we add area $i$, we add all the roads $(i, j)$, where $j$ is some area that has been added. After doing so, we have merged some connected components. If $p$ a...
[ "dsu", "sortings" ]
1,900
null
437
E
The Child and Polygon
This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements: - each vertex of each triangle is one of the polygon vertex; - each side of the polygon must be the side of exactly one triangle; - the area ...
In this problem, you are asked to count the triangulations of a simple polygon. First we label the vertex of polygon from $0$ to $n - 1$. Then we let $f[i][j]$ be the number of triangulations from vertex $i$ to vertex $j$. (Suppose there is no other vertices and there is an edge between $i$ and $j$) If the line segment...
[ "dp", "geometry" ]
2,500
null
438
D
The Child and Sequence
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks. Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array $a[1], a[2], ..., a[n]$. Then ...
The important idea of this problem is the property of $\mathrm{mod}$. Let $r=x{\mathrm{~mod~}}p$. So, $x=k\times p+r,k\in\mathbb{N}$. If $k = 0$, $x\ {\mathrm{mod}}\ p$ remains to be $x$. If $k \neq 0$, $x\;\mathrm{mod}\;p=r={\frac{2r}{2}}<{\frac{p+r}{2}}\leq{\frac{k\times p+r}{2}}\leq{\frac{x}{2}}$. We realize every...
[ "data structures", "math" ]
2,300
null
438
E
The Child and Binary Tree
Our child likes computer science very much, especially he likes binary trees. Consider the sequence of $n$ distinct positive integers: $c_{1}, c_{2}, ..., c_{n}$. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex $v$, the weight of $v$ is in the set ${c_{1}, c_{2}, ..., c_{n}}$....
Let $f[s]$ be the number of good vertex-weighted rooted binary trees whose weight exactly equal to $s$, then we have: $f[0] = 1$ $f[s]=\sum_{w\in\{c_{1},\ldots,c_{n}\}}\sum_{i}f[i]\times f[s-w-i]$ Let F(z) be the generating function of f. That is, $F(z)=\sum_{k>0}f[k]z^{k}$ And then let $C(z)=\sum_{k=1}^{n}z^{c_{k}}$ S...
[ "combinatorics", "divide and conquer", "fft", "number theory" ]
3,100
#include <iostream> #include <cstdio> #include <cstdio> #include <algorithm> using namespace std; typedef long long s64; const int Mod = 998244353; const int Mod_G = 3; const int MaxCN = 100000; const int MaxS = 100000; struct modint { int a; modint(){} modint(int _a) { a = _a % Mod; if (a < 0) a += Mod...
439
A
Devu, the Singer and Churu, the Joker
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing $n$ songs, $i^{th}$ ...
For checking whether there is a way to conduct all the songs of the singer, you can conduct the event in the following way. First singer will sing a song. Then during $10$ minutes rest of the singer, the joker will crack $2$ jokes(each of $5$ minutes) Then singer will again sing a song, then joker, etc. After the singe...
[ "greedy", "implementation" ]
900
null
439
B
Devu, the Dumb Guy
Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him $n$ subjects, the $i^{th}$ subject has $c_{i}$ chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously. Let us say that his initial per chapter learning power of a subject is $x$ hours. In othe...
You can formulate the problem in following way. Given two arrays $a$ and $b$. Find minimum cost of matching the elements of array $a$ to $b$. For our problem the array $a$ will be same as $b$. The array $b$ will have content $x$, $x$ - 1, , 1, 1. For a general version of this problem, we can use min cost max flow(min c...
[ "implementation", "sortings" ]
1,200
null
439
C
Devu and Partitioning of the Array
Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him? Given an array consisting of distinct integers. Is it possible to partition the whole array into $k$ disjoint non-empty pa...
Let us first try to find the condition required to make sure the existence of the partitions. Notice the following points. If the parity of sum does not match with parity of number of odd partitions ($k - p$) , then we can't create the required partitions. eg. $a = [1;2]$, $k = 2$, $p = 0$, Then you can not create two ...
[ "brute force", "constructive algorithms", "implementation", "number theory" ]
1,700
null
439
D
Devu and his Brother
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays $a$ and $b$ by their father. The array $a$ is given to Devu and $b$ to his brother. As Devu is really a naughty kid, he wants the minimum value of his array $a$ should be at least as much ...
You can solve the problem in two ways. By using ternary search Let us define a function f. Function f(k) = cost needed to make array a elements $ \ge $ k + cost needed to make array b elements $ \le $ k Instead of proving it formally, try checking the property on many random test cases. You will realize that f is conve...
[ "binary search", "sortings", "ternary search", "two pointers" ]
1,700
null
439
E
Devu and Birthday Celebration
Today is Devu's birthday. For celebrating the occasion, he bought $n$ sweets from the nearby market. He has invited his $f$ friends. He would like to distribute the sweets among them. As he is a nice guy and the occasion is great, he doesn't want any friend to be sad, so he would ensure to give at least one sweet to ea...
There are two possible solutions. dp solution Let $P(n, f)$ be total number of ways of partitioning $n$ into $f$ segments such that each $a_{i}$ is positive. With some manipulations of the generating function, you can find that this is equal to $\textstyle{\binom{n-1}{f-1}}$. So $P(n,f)=\left(\O_{f-1}^{n-1}\right)$ Let...
[ "combinatorics", "dp", "math" ]
2,100
null
441
A
Valera and Antique Items
Valera is a collector. Once he wanted to expand his collection with exactly one antique item. Valera knows $n$ sellers of antiques, the $i$-th of them auctioned $k_{i}$ items. Currently the auction price of the $j$-th object of the $i$-th seller is $s_{ij}$. Valera gets on well with each of the $n$ sellers. He is perf...
You need to implement what written in statement. You could act like that: let's calculate $q_{i}$ - minimum item price from seller $i$. Then if $q_{i} < v$, we can make a deal with seller $i$, otherwise we can't.
[ "implementation" ]
1,000
#include <iostream> #include <vector> #define forn(i,n) for(int i = 0; i < int(n); ++i) using namespace std; int main() { int n, v; cin >> n >> v; vector <int> ans; forn(i, n) { bool u = false; int k, s; cin >> k; forn(j, k) { cin >> s; if (!u && v > s) { u = true; ans.push_back(...
441
B
Valera and Fruits
Valera loves his garden, where $n$ fruit trees grow. This year he will enjoy a great harvest! On the $i$-th tree $b_{i}$ fruit grow, they will ripen on a day number $a_{i}$. Unfortunately, the fruit on the tree get withered, so they can only be collected on day $a_{i}$ and day $a_{i} + 1$ (all fruits that are not coll...
Let's start counting days from 1 to 3001. Let current day be $i$. Additionally, we'll have $cur$ variable - number of fruit we didn't collect previous days. Suppose $now$ fruit is ripen current day. If $now + cur \le v$, we need to add $now + cur$ to answer and update $cur$ value ($cur = 0$). Otherwise we add $v$ to ...
[ "greedy", "implementation" ]
1,400
#undef NDEBUG #ifdef gridnevvvit #define _GLIBCXX_DEBUG #endif #include <iostream> #include <fstream> #include <iomanip> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <list> #include <vector> #include <string> #include <deque> #include <bitset> #include <algorithm> #inc...