contestId
int64
0
1.01k
name
stringlengths
2
58
tags
listlengths
0
11
title
stringclasses
523 values
time-limit
stringclasses
8 values
memory-limit
stringclasses
8 values
problem-description
stringlengths
0
7.15k
input-specification
stringlengths
0
2.05k
output-specification
stringlengths
0
1.5k
demo-input
listlengths
0
7
demo-output
listlengths
0
7
note
stringlengths
0
5.24k
test_cases
listlengths
0
402
timeConsumedMillis
int64
0
8k
memoryConsumedBytes
int64
0
537M
score
float64
-1
3.99
__index_level_0__
int64
0
621k
959
Mahmoud and Ehab and the xor-MST
[ "bitmasks", "dp", "graphs", "implementation", "math" ]
null
null
Ehab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of *n* vertices numbered from 0 to *n*<=-<=1. For all 0<=≤<=*u*<=&lt;<=*v*<=&lt;<=*n*, vertex *u* and vertex *v* are connected with an undirected edge that has weight (where is the [bitwise-xor operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)). Can you find the weight of the minimum spanning tree of that graph? You can read about complete graphs in [https://en.wikipedia.org/wiki/Complete_graph](https://en.wikipedia.org/wiki/Complete_graph) You can read about the minimum spanning tree in [https://en.wikipedia.org/wiki/Minimum_spanning_tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree) The weight of the minimum spanning tree is the sum of the weights on the edges included in it.
The only line contains an integer *n* (2<=≤<=*n*<=≤<=1012), the number of vertices in the graph.
The only line contains an integer *x*, the weight of the graph's minimum spanning tree.
[ "4\n" ]
[ "4" ]
In the first sample: <img class="tex-graphics" src="https://espresso.codeforces.com/20e1655a0ec8e8d788bd2f5af92f93c968c65f3c.png" style="max-width: 100.0%;max-height: 100.0%;"/> The weight of the minimum spanning tree is 1+2+1=4.
[ { "input": "4", "output": "4" }, { "input": "10", "output": "21" }, { "input": "2", "output": "1" }, { "input": "1000000000000", "output": "20140978692096" }, { "input": "999999999999", "output": "20140978692095" }, { "input": "23131234", "output":...
61
0
0
20,537
400
Dima and Bacteria
[ "dsu", "graphs", "shortest paths" ]
null
null
Dima took up the biology of bacteria, as a result of his experiments, he invented *k* types of bacteria. Overall, there are *n* bacteria at his laboratory right now, and the number of bacteria of type *i* equals *c**i*. For convenience, we will assume that all the bacteria are numbered from 1 to *n*. The bacteria of type *c**i* are numbered from to . With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows *m* ways to move energy from some bacteria to another one. The way with number *i* can be described with integers *u**i*, *v**i* and *x**i* mean that this way allows moving energy from bacteria with number *u**i* to bacteria with number *v**i* or vice versa for *x**i* dollars. Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost. As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix *d* with size *k*<=×<=*k*. Cell *d*[*i*][*j*] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type *i* to bacteria with type *j*.
The first line contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*<=≤<=105; 0<=≤<=*m*<=≤<=105; 1<=≤<=*k*<=≤<=500). The next line contains *k* integers *c*1,<=*c*2,<=...,<=*c**k* (1<=≤<=*c**i*<=≤<=*n*). Each of the next *m* lines contains three integers *u**i*,<=*v**i*,<=*x**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=105; 0<=≤<=*x**i*<=≤<=104). It is guaranteed that .
If Dima's type-distribution is correct, print string «Yes», and then *k* lines: in the *i*-th line print integers *d*[*i*][1],<=*d*[*i*][2],<=...,<=*d*[*i*][*k*] (*d*[*i*][*i*]<==<=0). If there is no way to move energy from bacteria *i* to bacteria *j* appropriate *d*[*i*][*j*] must equal to -1. If the type-distribution isn't correct print «No».
[ "4 4 2\n1 3\n2 3 0\n3 4 0\n2 4 1\n2 1 2\n", "3 1 2\n2 1\n1 2 0\n", "3 2 2\n2 1\n1 2 0\n2 3 1\n", "3 0 2\n1 2\n" ]
[ "Yes\n0 2\n2 0\n", "Yes\n0 -1\n-1 0\n", "Yes\n0 1\n1 0\n", "No\n" ]
none
[ { "input": "4 4 2\n1 3\n2 3 0\n3 4 0\n2 4 1\n2 1 2", "output": "Yes\n0 2\n2 0" }, { "input": "3 1 2\n2 1\n1 2 0", "output": "Yes\n0 -1\n-1 0" }, { "input": "3 2 2\n2 1\n1 2 0\n2 3 1", "output": "Yes\n0 1\n1 0" }, { "input": "3 0 2\n1 2", "output": "No" }, { "input...
1,700
75,161,600
0
20,561
978
Mentors
[ "binary search", "data structures", "implementation" ]
null
null
In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$. A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a &gt; r_b)$ and programmers $a$ and $b$ are not in a quarrel. You are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor.
The first line contains two integers $n$ and $k$ $(2 \le n \le 2 \cdot 10^5$, $0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$ — total number of programmers and number of pairs of programmers which are in a quarrel. The second line contains a sequence of integers $r_1, r_2, \dots, r_n$ $(1 \le r_i \le 10^{9})$, where $r_i$ equals to the skill of the $i$-th programmer. Each of the following $k$ lines contains two distinct integers $x$, $y$ $(1 \le x, y \le n$, $x \ne y)$ — pair of programmers in a quarrel. The pairs are unordered, it means that if $x$ is in a quarrel with $y$ then $y$ is in a quarrel with $x$. Guaranteed, that for each pair $(x, y)$ there are no other pairs $(x, y)$ and $(y, x)$ in the input.
Print $n$ integers, the $i$-th number should be equal to the number of programmers, for which the $i$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.
[ "4 2\n10 4 10 15\n1 2\n4 3\n", "10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5\n" ]
[ "0 0 1 2 \n", "5 4 0 5 3 3 9 0 2 5 \n" ]
In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel.
[ { "input": "4 2\n10 4 10 15\n1 2\n4 3", "output": "0 0 1 2 " }, { "input": "10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5", "output": "5 4 0 5 3 3 9 0 2 5 " }, { "input": "2 0\n3 1", "output": "1 0 " }, { "input": "2 0\n1 1", "output": "0 0 " }, { "input": "10 35...
872
56,934,400
3
20,562
725
Hidden Word
[ "brute force", "constructive algorithms", "implementation", "strings" ]
null
null
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: We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself. A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself). You’re given a string *s* which consists of 27 upper-case English letters. Each English letter occurs at least once in *s*. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string *s*. If there’s no solution, print "Impossible" (without the quotes).
The only line of the input contains the string *s*, consisting of 27 upper-case English letters. Each English letter occurs at least once in *s*.
Output two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible".
[ "ABCDEFGHIJKLMNOPQRSGTUVWXYZ\n", "BUVTYZFQSNRIWOXXGJLKACPEMDH\n" ]
[ "YXWVUTGHIJKLM\nZABCDEFSRQPON\n", "Impossible\n" ]
none
[ { "input": "ABCDEFGHIJKLMNOPQRSGTUVWXYZ", "output": "YXWVUTGHIJKLM\nZABCDEFSRQPON" }, { "input": "BUVTYZFQSNRIWOXXGJLKACPEMDH", "output": "Impossible" }, { "input": "DYCEUXXKMGZOINVPHWQSRTABLJF", "output": "Impossible" }, { "input": "UTEDBZRVWLOFUASHCYIPXGJMKNQ", "output"...
46
307,200
-1
20,692
356
Bags and Coins
[ "bitmasks", "constructive algorithms", "dp", "greedy" ]
null
null
When you were a child you must have been told a puzzle of bags and coins. Anyway, here's one of its versions: A horse has three bags. The first bag has one coin, the second bag has one coin and the third bag has three coins. In total, the horse has three coins in the bags. How is that possible? The answer is quite simple. The third bag contains a coin and two other bags. This problem is a generalization of the childhood puzzle. You have *n* bags. You know that the first bag contains *a*1 coins, the second bag contains *a*2 coins, ..., the *n*-th bag contains *a**n* coins. In total, there are *s* coins. Find the way to arrange the bags and coins so that they match the described scenario or else state that it is impossible to do.
The first line contains two integers *n* and *s* (1<=≤<=*n*,<=*s*<=≤<=70000) — the number of bags and the total number of coins. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=70000), where *a**i* shows the number of coins in the *i*-th bag.
If the answer doesn't exist, print -1. Otherwise, print *n* lines, on the *i*-th line print the contents of the *i*-th bag. The first number in the line, *c**i* (0<=≤<=*c**i*<=≤<=*a**i*), must represent the number of coins lying directly in the *i*-th bag (the coins in the bags that are in the *i*-th bag are not taken into consideration). The second number in the line, *k**i* (0<=≤<=*k**i*<=&lt;<=*n*) must represent the number of bags that lie directly in the *i*-th bag (the bags that are inside the bags lying in the *i*-th bag are not taken into consideration). Next, the line must contain *k**i* integers — the numbers of the bags that are lying directly in the *i*-th bag. The total number of coins in the solution must equal *s*. If we count the total number of coins the *i*-th bag in the solution has, we should get *a**i*. No bag can directly lie in more than one bag. The bags can be nested in more than one level (see the second test case). If there are multiple correct answers, you can print any of them.
[ "3 3\n1 3 1\n", "3 3\n1 3 1\n", "1 2\n1\n", "8 10\n2 7 3 4 1 3 1 2\n" ]
[ "1 0\n1 2 3 1\n1 0\n", "1 0\n2 1 3\n0 1 1\n", "-1\n", "2 0\n1 2 1 4\n0 2 7 8\n0 2 5 6\n1 0\n3 0\n1 0\n2 0\n" ]
The pictures below show two possible ways to solve one test case from the statement. The left picture corresponds to the first test case, the right picture corresponds to the second one.
[]
30
0
0
20,705
645
Intellectual Inquiry
[ "dp", "greedy", "strings" ]
null
null
After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first *k* English letters. Each morning, Bessie travels to school along a sidewalk consisting of *m*<=+<=*n* tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first *m* sidewalk tiles with one of the first *k* lowercase English letters, spelling out a string *t*. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last *n* tiles of the sidewalk by herself. Consider the resulting string *s* (|*s*|<==<=*m*<=+<=*n*) consisting of letters labeled on tiles in order from home to school. For any sequence of indices *p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**q* we can define subsequence of the string *s* as string *s**p*1*s**p*2... *s**p**q*. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help! Note that empty subsequence also counts.
The first line of the input contains two integers *n* and *k* (0<=≤<=*n*<=≤<=1<=000<=000, 1<=≤<=*k*<=≤<=26). The second line contains a string *t* (|*t*|<==<=*m*,<=1<=≤<=*m*<=≤<=1<=000<=000) consisting of only first *k* lowercase English letters.
Determine the maximum number of distinct subsequences Bessie can form after labeling the last *n* sidewalk tiles each with one of the first *k* lowercase English letters. Since this number can be rather large, you should print it modulo 109<=+<=7. Please note, that you are not asked to maximize the remainder modulo 109<=+<=7! The goal is to maximize the initial value and then print the remainder.
[ "1 3\nac\n", "0 2\naaba\n" ]
[ "8\n", "10\n" ]
In the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb". In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.
[]
2,000
3,072,000
0
20,708
0
none
[ "none" ]
null
null
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string *s*. String *p* is called a substring of string *s* if you can read it starting from some position in the string *s*. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string *s* and cut out some substring from it, let's call it *t*. Then he needs to change the substring *t* zero or more times. As a result, he should obtain a fixed string *u* (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions: - Insert one letter to any end of the string. - Delete one letter from any end of the string. - Change one letter into any other one. Moriarty is very smart and after he chooses some substring *t*, he always makes the minimal number of changes to obtain *u*. Help Moriarty choose the best substring *t* from all substrings of the string *s*. The substring *t* should minimize the number of changes Moriarty should make to obtain the string *u* from it.
The first line contains a non-empty string *s*, consisting of lowercase Latin letters. The second line contains a non-empty string *u*, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.
Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.
[ "aaaaa\naaa\n", "abcabc\nbcd\n", "abcdef\nklmnopq\n" ]
[ "0\n", "1\n", "7\n" ]
In the first sample Moriarty can take any substring of length 3, and it will be equal to the required message *u*, so Moriarty won't have to make any changes. In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character. In the third sample the initial string *s* doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.
[ { "input": "aaaaa\naaa", "output": "0" }, { "input": "abcabc\nbcd", "output": "1" }, { "input": "abcdef\nklmnopq", "output": "7" }, { "input": "aaabbbaaa\naba", "output": "1" }, { "input": "a\na", "output": "0" }, { "input": "z\nz", "output": "0" ...
2,000
4,608,000
0
20,716
729
Road to Cinema
[ "binary search", "greedy", "sortings" ]
null
null
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 point *s*. There are *k* gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly. There are *n* cars in the rental service, *i*-th of them is characterized with two integers *c**i* and *v**i* — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity *v**i*. All cars are completely fueled at the car rental service. Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times. Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in *t* minutes. Assume that all cars are completely fueled initially.
The first line contains four positive integers *n*, *k*, *s* and *t* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*k*<=≤<=2·105, 2<=≤<=*s*<=≤<=109, 1<=≤<=*t*<=≤<=2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next *n* lines contains two positive integers *c**i* and *v**i* (1<=≤<=*c**i*,<=*v**i*<=≤<=109) — the price of the *i*-th car and its fuel tank capacity. The next line contains *k* distinct integers *g*1,<=*g*2,<=...,<=*g**k* (1<=≤<=*g**i*<=≤<=*s*<=-<=1) — the positions of the gas stations on the road in arbitrary order.
Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in *t* minutes). If there is no appropriate car, print -1.
[ "3 1 8 10\n10 8\n5 7\n11 9\n3\n", "2 2 10 18\n10 4\n20 6\n5 3\n" ]
[ "10\n", "20\n" ]
In the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.
[ { "input": "3 1 8 10\n10 8\n5 7\n11 9\n3", "output": "10" }, { "input": "2 2 10 18\n10 4\n20 6\n5 3", "output": "20" }, { "input": "2 1 1000000000 2000000000\n111 1000000000\n101 1000000000\n5", "output": "101" }, { "input": "2 1 1000000000 2000000000\n111 999999998\n101 9999...
46
204,800
0
20,732
125
MST Company
[ "binary search", "graphs" ]
null
null
The MST (Meaningless State Team) company won another tender for an important state reform in Berland. There are *n* cities in Berland, some pairs of the cities are connected by roads. Each road has its price. One can move along any road in any direction. The MST team should carry out the repair works on some set of roads such that one can get from any city to any other one moving only along the repaired roads. Moreover, this set should contain exactly *k* capital roads (that is, the roads that start or finish in the capital). The number of the capital is 1. As the budget has already been approved, the MST Company will profit by finding the set with minimum lengths of roads.
The first input line contains three integers *n*,<=*m*,<=*k* (1<=≤<=*n*<=≤<=5000;0<=≤<=*m*<=≤<=105;0<=≤<=*k*<=&lt;<=5000), where *n* is the number of cities in the country, *m* is the number of roads in the country, *k* is the number of capital roads in the required set. Then *m* lines enumerate the roads in question. Each road is specified by three numbers *a**i*,<=*b**i*,<=*w**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; 1<=≤<=*w*<=≤<=105), where *a**i*,<=*b**i* are the numbers of cities linked by a road and *w**i* is its length. Between each pair of cities no more than one road exists. There are no roads that start and finish in one city. The capital's number is 1.
In the first line print the number of roads in the required set. The second line should contain the numbers of roads included in the sought set. If the sought set does not exist, print -1.
[ "4 5 2\n1 2 1\n2 3 1\n3 4 1\n1 3 3\n1 4 2\n" ]
[ "3\n1 5 2 " ]
none
[]
62
0
-1
20,746
58
Expression
[ "dp" ]
E. Expression
2
256
One day Vasya was solving arithmetical problems. He wrote down an expression *a*<=+<=*b*<==<=*c* in his notebook. When the teacher checked Vasya's work it turned out that Vasya had solved the problem incorrectly. Now Vasya tries to find excuses. He says that he simply forgot to write down several digits in numbers *a*, *b* and *c*, but he can't remember what numbers they actually were. Help Vasya, find such numbers *x*, *y* and *z*, with which the following conditions are met: - *x*<=+<=*y*<==<=*z*, - from the expression *x*<=+<=*y*<==<=*z* several digits can be erased in such a way that the result will be *a*<=+<=*b*<==<=*c*, - the expression *x*<=+<=*y*<==<=*z* should have the minimal length.
The first and only input line contains the expression *a*<=+<=*b*<==<=*c* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=106, *a*, *b* and *c* don't contain leading zeroes) which is the expression Vasya wrote down.
Print the correct expression *x*<=+<=*y*<==<=*z* (*x*, *y* and *z* are non-negative numbers without leading zeroes). The expression *a*<=+<=*b*<==<=*c* must be met in *x*<=+<=*y*<==<=*z* as a subsequence. The printed solution should have the minimal possible number of characters. If there are several such solutions, you can print any of them.
[ "2+4=5\n", "1+1=3\n", "1+1=2\n" ]
[ "21+4=25\n", "1+31=32\n", "1+1=2\n" ]
none
[ { "input": "2+4=5", "output": "21+4=25" }, { "input": "1+1=3", "output": "1+31=32" }, { "input": "1+1=2", "output": "1+1=2" }, { "input": "323+123=287", "output": "323+12553=12876" }, { "input": "878347+637216=542650", "output": "847834370+6372160=854206530" ...
278
8,294,400
0
20,773
309
Sheep
[ "binary search", "greedy" ]
null
null
Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming! A large farm has a meadow with grazing sheep. Overall there are *n* sheep and each of them contains a unique number from 1 to *n* — because the sheep need to be distinguished and you need to remember information about each one, and they are so much alike! The meadow consists of infinite number of regions numbered from 1 to infinity. It's known that sheep *i* likes regions from *l**i* to *r**i*. There are two shepherds taking care of the sheep: First and Second. First wakes up early in the morning and leads the sheep graze on the lawn. Second comes in the evening and collects all the sheep. One morning, First woke up a little later than usual, and had no time to lead the sheep graze on the lawn. So he tied together every two sheep if there is a region they both like. First thought that it would be better — Second would have less work in the evening, because sheep won't scatter too much, being tied to each other! In the evening Second came on the lawn, gathered the sheep and tried to line them up in a row. But try as he might, the sheep wouldn't line up as Second want! Second had neither the strength nor the ability to untie the sheep so he left them as they are, but with one condition: he wanted to line up the sheep so that the maximum distance between two tied sheep was as small as possible. The distance between the sheep is the number of sheep in the ranks that are between these two. Help Second find the right arrangement.
The first input line contains one integer *n* (1<=≤<=*n*<=≤<=2000). Each of the following *n* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*,<=*r**i*<=≤<=109; *l**i*<=≤<=*r**i*).
In the single output line print *n* space-separated numbers — the sought arrangement of the sheep. The *i*-th value in the line must represent the number of the sheep that took the *i*-th place from left in the optimal arrangement line. If there are multiple optimal arrangements, print any of them.
[ "3\n1 3\n5 7\n2 4\n", "5\n1 5\n2 4\n3 6\n1 7\n2 6\n", "4\n1 3\n4 6\n5 7\n2 3\n" ]
[ "1 3 2", "2 1 3 5 4", "1 4 2 3" ]
none
[]
31
6,656,000
0
20,785
543
Road Improvement
[ "dp", "trees" ]
null
null
The country has *n* cities and *n*<=-<=1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to *n* inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city *x* to any other city contains at most one bad road. Your task is — for every possible *x* determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1<=000<=000<=007 (109<=+<=7).
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of cities in the country. Next line contains *n*<=-<=1 positive integers *p*2,<=*p*3,<=*p*4,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*i*<=-<=1) — the description of the roads in the country. Number *p**i* means that the country has a road connecting city *p**i* and city *i*.
Print *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sought number of ways to improve the quality of the roads modulo 1<=000<=000<=007 (109<=+<=7), if the capital of the country is at city number *i*.
[ "3\n1 1\n", "5\n1 2 3 4\n" ]
[ "4 3 3", "5 8 9 8 5" ]
none
[ { "input": "3\n1 1", "output": "4 3 3" }, { "input": "5\n1 2 3 4", "output": "5 8 9 8 5" }, { "input": "31\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "73741817 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 5368...
452
21,913,600
3
20,900
68
Contact
[ "geometry" ]
E. Contact
3
256
Little Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing. Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships.
Each of 4 lines will contain 6 integers *x*1 *y*1 *x*2 *y*2 *x*3 *y*3 (0<=≤<=*x*1,<=*y*1,<=*x*2,<=*y*2,<=*x*3,<=*y*3<=≤<=20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.
First line should contain minimum number of columns enough to land all spaceships.
[ "0 0 1 0 1 2\n0 0 0 2 2 2\n0 0 3 0 1 2\n0 0 3 0 2 2\n", "0 0 0 1 1 1\n0 0 0 2 2 2\n0 0 0 5 5 5\n0 0 0 17 17 17\n" ]
[ "4\n", "9\n" ]
In the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns. In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns.
[]
62
0
0
20,949
955
Scissors
[ "brute force", "strings" ]
null
null
Jenya has recently acquired quite a useful tool — *k*-scissors for cutting strings. They are generally used for cutting out two non-intersecting substrings of length *k* from an arbitrary string *s* (its length should be at least 2·*k* in order to perform this operation) and concatenating them afterwards (preserving the initial order). For example, with the help of 2-scissors you can cut *ab* and *de* out of *abcde* and concatenate them into *abde*, but not *ab* and *bc* since they're intersecting. It's a nice idea to test this tool before using it in practice. After looking through the papers, Jenya came up with two strings *s* and *t*. His question is whether it is possible to apply his scissors to string *s* such that the resulting concatenation contains *t* as a substring?
The first line contains three integers *n*, *m*, *k* (2<=≤<=*m*<=≤<=2·*k*<=≤<=*n*<=≤<=5·105) — length of *s*, length of *t* and the aforementioned scissors' parameter correspondingly. The next two lines feature *s* and *t* consisting of lowercase latin letters.
If there is no answer, print «No». Otherwise print «Yes» and two integers *L* and *R* denoting the indexes where cutted substrings start (1-indexed). If there are several possible answers, output any.
[ "7 4 3\nbaabaab\naaaa\n", "6 3 2\ncbcbcb\nbcc\n", "7 5 3\naabbaaa\naaaaa\n" ]
[ "Yes\n1 5\n", "Yes\n2 5\n", "No\n" ]
In the first sample case you can cut out two substrings starting at 1 and 5. The resulting string baaaab contains aaaa as a substring. In the second sample case the resulting string is bccb.
[ { "input": "7 4 3\nbaabaab\naaaa", "output": "Yes\n1 5" }, { "input": "6 3 2\ncbcbcb\nbcc", "output": "Yes\n2 5" }, { "input": "7 5 3\naabbaaa\naaaaa", "output": "No" }, { "input": "16 6 4\nabcdcadbbbcacdca\ndcadbc", "output": "Yes\n4 10" }, { "input": "81 5 3\nac...
62
7,065,600
0
20,960
500
New Year Permutation
[ "dfs and similar", "dsu", "graphs", "greedy", "math", "sortings" ]
null
null
User ainta has a permutation *p*1,<=*p*2,<=...,<=*p**n*. As the New Year is coming, he wants to make his permutation as pretty as possible. Permutation *a*1,<=*a*2,<=...,<=*a**n* is prettier than permutation *b*1,<=*b*2,<=...,<=*b**n*, if and only if there exists an integer *k* (1<=≤<=*k*<=≤<=*n*) where *a*1<==<=*b*1,<=*a*2<==<=*b*2,<=...,<=*a**k*<=-<=1<==<=*b**k*<=-<=1 and *a**k*<=&lt;<=*b**k* all holds. As known, permutation *p* is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an *n*<=×<=*n* binary matrix *A*, user ainta can swap the values of *p**i* and *p**j* (1<=≤<=*i*,<=*j*<=≤<=*n*, *i*<=≠<=*j*) if and only if *A**i*,<=*j*<==<=1. Given the permutation *p* and the matrix *A*, user ainta wants to know the prettiest permutation that he can obtain.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=300) — the size of the permutation *p*. The second line contains *n* space-separated integers *p*1,<=*p*2,<=...,<=*p**n* — the permutation *p* that user ainta has. Each integer between 1 and *n* occurs exactly once in the given permutation. Next *n* lines describe the matrix *A*. The *i*-th line contains *n* characters '0' or '1' and describes the *i*-th row of *A*. The *j*-th character of the *i*-th line *A**i*,<=*j* is the element on the intersection of the *i*-th row and the *j*-th column of A. It is guaranteed that, for all integers *i*,<=*j* where 1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*, *A**i*,<=*j*<==<=*A**j*,<=*i* holds. Also, for all integers *i* where 1<=≤<=*i*<=≤<=*n*, *A**i*,<=*i*<==<=0 holds.
In the first and only line, print *n* space-separated integers, describing the prettiest permutation that can be obtained.
[ "7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000\n", "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010\n" ]
[ "1 2 4 3 6 7 5\n", "1 2 3 4 5\n" ]
In the first sample, the swap needed to obtain the prettiest permutation is: (*p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">7</sub>). In the second sample, the swaps needed to obtain the prettiest permutation is (*p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">3</sub>), (*p*<sub class="lower-index">4</sub>, *p*<sub class="lower-index">5</sub>), (*p*<sub class="lower-index">3</sub>, *p*<sub class="lower-index">4</sub>). A permutation *p* is a sequence of integers *p*<sub class="lower-index">1</sub>, *p*<sub class="lower-index">2</sub>, ..., *p*<sub class="lower-index">*n*</sub>, consisting of *n* distinct positive integers, each of them doesn't exceed *n*. The *i*-th element of the permutation *p* is denoted as *p*<sub class="lower-index">*i*</sub>. The size of the permutation *p* is denoted as *n*.
[ { "input": "7\n5 2 4 3 6 7 1\n0001001\n0000000\n0000010\n1000001\n0000000\n0010000\n1001000", "output": "1 2 4 3 6 7 5" }, { "input": "5\n4 2 1 5 3\n00100\n00011\n10010\n01101\n01010", "output": "1 2 3 4 5" }, { "input": "7\n1 7 6 4 2 3 5\n0000100\n0000010\n0000001\n0000000\n1000000\n010...
46
0
0
20,986
235
Let's Play Osu!
[ "dp", "math", "probabilities" ]
null
null
You're playing a game called Osu! Here's a simplified version of it. There are *n* clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of *n* characters "O" and "X". Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22<=+<=32<=+<=22<==<=17. If there are no correct clicks in a play then the score for the play equals to 0. You know that the probability to click the *i*-th (1<=≤<=*i*<=≤<=*n*) click correctly is *p**i*. In other words, the *i*-th character in the play sequence has *p**i* probability to be "O", 1<=-<=*p**i* to be "X". You task is to calculate the expected score for your play.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of clicks. The second line contains *n* space-separated real numbers *p*1,<=*p*2,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=1). There will be at most six digits after the decimal point in the given *p**i*.
Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
[ "3\n0.5 0.5 0.5\n", "4\n0.7 0.2 0.1 0.9\n", "5\n1 1 1 1 1\n" ]
[ "2.750000000000000\n", "2.489200000000000\n", "25.000000000000000\n" ]
For the first example. There are 8 possible outcomes. Each has a probability of 0.125. - "OOO"  →  3<sup class="upper-index">2</sup> = 9; - "OOX"  →  2<sup class="upper-index">2</sup> = 4; - "OXO"  →  1<sup class="upper-index">2</sup> + 1<sup class="upper-index">2</sup> = 2; - "OXX"  →  1<sup class="upper-index">2</sup> = 1; - "XOO"  →  2<sup class="upper-index">2</sup> = 4; - "XOX"  →  1<sup class="upper-index">2</sup> = 1; - "XXO"  →  1<sup class="upper-index">2</sup> = 1; - "XXX"  →  0. So the expected score is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9aa477286058d4dd02d6f78cad11a658e4f37440.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "3\n0.5 0.5 0.5", "output": "2.750000000000000" }, { "input": "4\n0.7 0.2 0.1 0.9", "output": "2.489200000000000" }, { "input": "5\n1 1 1 1 1", "output": "25.000000000000000" }, { "input": "10\n0.684846 0.156794 0.153696 0.714526 0.281868 0.628256 0.745339 0.123854...
342
11,776,000
3
21,000
132
Constants in the language of Shakespeare
[ "constructive algorithms", "dp", "greedy" ]
null
null
Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare. Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations. You are given an integer *n*. You have to represent it as *n*<==<=*a*1<=+<=*a*2<=+<=...<=+<=*a**m*, where each of *a**i* is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of *m*.
The only line of input contains a positive integer *n*, written as its binary notation. The length of the notation is at most 106. The first digit of the notation is guaranteed to be 1.
Output the required minimal *m*. After it output *m* lines. Each line has to be formatted as "+2^x" or "-2^x", where *x* is the power coefficient of the corresponding term. The order of the lines doesn't matter.
[ "1111\n", "1010011\n" ]
[ "2\n+2^4\n-2^0\n", "4\n+2^0\n+2^1\n+2^4\n+2^6\n" ]
none
[ { "input": "1111", "output": "2\n+2^4\n-2^0" }, { "input": "1010011", "output": "4\n+2^0\n+2^1\n+2^4\n+2^6" }, { "input": "1", "output": "1\n+2^0" }, { "input": "10110111", "output": "4\n+2^8\n-2^6\n-2^3\n-2^0" }, { "input": "10101110", "output": "4\n+2^8\n-2^...
46
0
0
21,040
0
none
[ "none" ]
null
null
На тренировку по подготовке к соревнованиям по программированию пришли *n* команд. Тренер для каждой команды подобрал тренировку, комплект задач для *i*-й команды занимает *a**i* страниц. В распоряжении тренера есть *x* листов бумаги, у которых обе стороны чистые, и *y* листов, у которых только одна сторона чистая. При печати условия на листе первого типа можно напечатать две страницы из условий задач, а при печати на листе второго типа — только одну. Конечно, на листе нельзя печатать условия из двух разных комплектов задач. Обратите внимание, что при использовании листов, у которых обе стороны чистые, не обязательно печатать условие на обеих сторонах, одна из них может остаться чистой. Вам предстоит определить максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.
В первой строке входных данных следуют три целых числа *n*, *x* и *y* (1<=≤<=*n*<=≤<=200<=000, 0<=≤<=*x*,<=*y*<=≤<=109) — количество команд, количество листов бумаги с двумя чистыми сторонами и количество листов бумаги с одной чистой стороной. Во второй строке входных данных следует последовательность из *n* целых чисел *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=10<=000), где *i*-е число равно количеству страниц в комплекте задач для *i*-й команды.
Выведите единственное целое число — максимальное количество команд, которым тренер сможет напечатать комплекты задач целиком.
[ "2 3 5\n4 6\n", "2 3 5\n4 7\n", "6 3 5\n12 11 12 11 12 11\n" ]
[ "2\n", "2\n", "1\n" ]
В первом тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать весь первый комплект задач на листах с одной чистой стороной (после этого останется 3 листа с двумя чистыми сторонами и 1 лист с одной чистой стороной), а второй комплект напечатать на трех листах с двумя чистыми сторонами. Во втором тестовом примере можно напечатать оба комплекта задач. Один из возможных ответов — напечатать первый комплект задач на двух листах с двумя чистыми сторонами (после этого останется 1 лист с двумя чистыми сторонами и 5 листов с одной чистой стороной), а второй комплект напечатать на одном листе с двумя чистыми сторонами и на пяти листах с одной чистой стороной. Таким образом, тренер использует все листы для печати. В третьем тестовом примере можно напечатать только один комплект задач (любой из трёх 11-страничных). Для печати 11-страничного комплекта задач будет израсходована вся бумага.
[ { "input": "2 3 5\n4 6", "output": "2" }, { "input": "2 3 5\n4 7", "output": "2" }, { "input": "6 3 5\n12 11 12 11 12 11", "output": "1" }, { "input": "1 4 3\n12", "output": "0" }, { "input": "10 1 17\n3 1 1 2 1 3 4 4 1 4", "output": "8" }, { "input": ...
61
4,608,000
0
21,044
236
Easy Number Challenge
[ "implementation", "number theory" ]
null
null
Let's denote *d*(*n*) as the number of divisors of a positive integer *n*. You are given three integers *a*, *b* and *c*. Your task is to calculate the following sum: Find the sum modulo 1073741824 (230).
The first line contains three space-separated integers *a*, *b* and *c* (1<=≤<=*a*,<=*b*,<=*c*<=≤<=100).
Print a single integer — the required sum modulo 1073741824 (230).
[ "2 2 2\n", "5 6 7\n" ]
[ "20\n", "1520\n" ]
For the first example. - *d*(1·1·1) = *d*(1) = 1; - *d*(1·1·2) = *d*(2) = 2; - *d*(1·2·1) = *d*(2) = 2; - *d*(1·2·2) = *d*(4) = 3; - *d*(2·1·1) = *d*(2) = 2; - *d*(2·1·2) = *d*(4) = 3; - *d*(2·2·1) = *d*(4) = 3; - *d*(2·2·2) = *d*(8) = 4. So the result is 1 + 2 + 2 + 3 + 2 + 3 + 3 + 4 = 20.
[ { "input": "2 2 2", "output": "20" }, { "input": "5 6 7", "output": "1520" }, { "input": "91 42 25", "output": "3076687" }, { "input": "38 47 5", "output": "160665" }, { "input": "82 29 45", "output": "3504808" }, { "input": "40 15 33", "output": "...
2,000
0
0
21,139
183
Candy Shop
[ "greedy" ]
null
null
The prestigious Codeforces kindergarten consists of *n* kids, numbered 1 through *n*. Each of them are given allowance in rubles by their parents. Today, they are going to the most famous candy shop in the town. The shop sells candies in packages: for all *i* between 1 and *m*, inclusive, it sells a package containing exactly *i* candies. A candy costs one ruble, so a package containing *x* candies costs *x* rubles. The kids will purchase candies in turns, starting from kid 1. In a single turn, kid *i* will purchase one candy package. Due to the highly competitive nature of Codeforces kindergarten, during a turn, the number of candies contained in the package purchased by the kid will always be strictly greater than the number of candies contained in the package purchased by the kid in the preceding turn (an exception is in the first turn: the first kid may purchase any package). Then, the turn proceeds to kid *i*<=+<=1, or to kid 1 if it was kid *n*'s turn. This process can be ended at any time, but at the end of the purchase process, all the kids must have the same number of candy packages. Of course, the amount spent by each kid on the candies cannot exceed their allowance. You work at the candy shop and would like to prepare the candies for the kids. Print the maximum number of candies that can be sold by the candy shop to the kids. If the kids cannot purchase any candy (due to insufficient allowance), print 0.
The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=2·105,<=2<=≤<=*m*<=≤<=5·106,<=*n*<=≤<=*m*), denoting the number of kids and the maximum number of candies in a package sold by the candy shop, respectively. Then *n* lines follow, each line will contain a single positive integer not exceeding denoting the allowance of a kid in rubles. The allowances are given in order from kid 1 to kid *n*. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is recommended to use cin, cout streams (also you may use %I64d specificator).
Print a single integer denoting the maximum number of candies that can be sold by the candy shop.
[ "2 5\n5\n10\n", "3 8\n8\n16\n13\n", "2 5000000\n12500002500000\n12500002500000\n" ]
[ "13\n", "32\n", "12500002500000\n" ]
For the first example, one of the scenarios that will result in 13 purchased candies is as follows. - Turn 1. Kid 1 purchases 1 candy. - Turn 2. Kid 2 purchases 3 candies. - Turn 3. Kid 1 purchases 4 candies. - Turn 4. Kid 2 purchases 5 candies.
[]
92
0
0
21,218
375
Tree and Queries
[ "data structures", "dfs and similar", "trees" ]
null
null
You have a rooted tree consisting of *n* vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to *n*. Then we represent the color of vertex *v* as *c**v*. The tree root is a vertex with number 1. In this problem you need to answer to *m* queries. Each query is described by two integers *v**j*,<=*k**j*. The answer to query *v**j*,<=*k**j* is the number of such colors of vertices *x*, that the subtree of vertex *v**j* contains at least *k**j* vertices of color *x*. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=105). The next line contains a sequence of integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=105). The next *n*<=-<=1 lines contain the edges of the tree. The *i*-th line contains the numbers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*) — the vertices connected by an edge of the tree. Next *m* lines contain the queries. The *j*-th line contains two integers *v**j*,<=*k**j* (1<=≤<=*v**j*<=≤<=*n*; 1<=≤<=*k**j*<=≤<=105).
Print *m* integers — the answers to the queries in the order the queries appear in the input.
[ "8 5\n1 2 2 3 3 2 3 3\n1 2\n1 5\n2 3\n2 4\n5 6\n5 7\n5 8\n1 2\n1 3\n1 4\n2 3\n5 3\n", "4 1\n1 2 3 4\n1 2\n2 3\n3 4\n1 1\n" ]
[ "2\n2\n1\n0\n1\n", "4\n" ]
A subtree of vertex *v* in a rooted tree with root *r* is a set of vertices {*u* : *dist*(*r*, *v*) + *dist*(*v*, *u*) = *dist*(*r*, *u*)}. Where *dist*(*x*, *y*) is the length (in edges) of the shortest path between vertices *x* and *y*.
[ { "input": "8 5\n1 2 2 3 3 2 3 3\n1 2\n1 5\n2 3\n2 4\n5 6\n5 7\n5 8\n1 2\n1 3\n1 4\n2 3\n5 3", "output": "2\n2\n1\n0\n1" }, { "input": "4 1\n1 2 3 4\n1 2\n2 3\n3 4\n1 1", "output": "4" } ]
1,000
102,400
0
21,223
838
Binary Blocks
[ "brute force" ]
null
null
You are given an image, that can be represented with a 2-d *n* by *m* grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer *k*<=&gt;<=1 and split the image into *k* by *k* blocks. If *n* and *m* are not divisible by *k*, the image is padded with only zeros on the right and bottom so that they are divisible by *k*. Each pixel in each individual block must have the same value. The given image may not be compressible in its current state. Find the minimum number of pixels you need to toggle (after padding) in order for the image to be compressible for some *k*. More specifically, the steps are to first choose *k*, then the image is padded with zeros, then, we can toggle the pixels so it is compressible for this *k*. The image must be compressible in that state.
The first line of input will contain two integers *n*,<=*m* (2<=≤<=*n*,<=*m*<=≤<=2<=500), the dimensions of the image. The next *n* lines of input will contain a binary string with exactly *m* characters, representing the image.
Print a single integer, the minimum number of pixels needed to toggle to make the image compressible.
[ "3 5\n00100\n10110\n11001\n" ]
[ "5\n" ]
We first choose *k* = 2. The image is padded as follows: We can toggle the image to look as follows: We can see that this image is compressible for *k* = 2.
[ { "input": "3 5\n00100\n10110\n11001", "output": "5" } ]
2,000
29,491,200
0
21,235
0
none
[ "none" ]
null
null
Leha plays a computer game, where is on each level is given a connected graph with *n* vertices and *m* edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer *d**i*, which can be equal to 0, 1 or <=-<=1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, *d**i*<==<=<=-<=1 or it's degree modulo 2 is equal to *d**i*. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them.
The first line contains two integers *n*, *m* (1<=≤<=*n*<=≤<=3·105, *n*<=-<=1<=≤<=*m*<=≤<=3·105) — number of vertices and edges. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (<=-<=1<=≤<=*d**i*<=≤<=1) — numbers on the vertices. Each of the next *m* lines contains two integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*n*) — edges. It's guaranteed, that graph in the input is connected.
Print <=-<=1 in a single line, if solution doesn't exist. Otherwise in the first line *k* — number of edges in a subset. In the next *k* lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1.
[ "1 0\n1\n", "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4\n", "2 1\n1 1\n1 2\n", "3 3\n0 -1 1\n1 2\n2 3\n1 3\n" ]
[ "-1\n", "0\n", "1\n1\n", "1\n2\n" ]
In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
[ { "input": "1 0\n1", "output": "-1" }, { "input": "4 5\n0 0 0 -1\n1 2\n2 3\n3 4\n1 4\n2 4", "output": "0" }, { "input": "2 1\n1 1\n1 2", "output": "1\n1" }, { "input": "3 3\n0 -1 1\n1 2\n2 3\n1 3", "output": "1\n2" }, { "input": "10 10\n-1 -1 -1 -1 -1 -1 -1 -1 -1 ...
280
15,872,000
0
21,283
632
Alice, Bob, Two Teams
[ "brute force", "constructive algorithms" ]
null
null
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are *n* pieces, and the *i*-th piece has a strength *p**i*. The way to split up game pieces is split into several steps: 1. First, Alice will split the pieces into two different groups *A* and *B*. This can be seen as writing the assignment of teams of a piece in an *n* character string, where each character is *A* or *B*. 1. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change *A* to *B* and *B* to *A*). He can do this step at most once. 1. Alice will get all the pieces marked *A* and Bob will get all the pieces marked *B*. The strength of a player is then the sum of strengths of the pieces in the group. Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
The first line contains integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of game pieces. The second line contains *n* integers *p**i* (1<=≤<=*p**i*<=≤<=109) — the strength of the *i*-th piece. The third line contains *n* characters *A* or *B* — the assignment of teams after the first step (after Alice's step).
Print the only integer *a* — the maximum strength Bob can achieve.
[ "5\n1 2 3 4 5\nABABA\n", "5\n1 2 3 4 5\nAAAAA\n", "1\n1\nB\n" ]
[ "11\n", "15\n", "1\n" ]
In the first sample Bob should flip the suffix of length one. In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5. In the third sample Bob should do nothing.
[ { "input": "5\n1 2 3 4 5\nABABA", "output": "11" }, { "input": "5\n1 2 3 4 5\nAAAAA", "output": "15" }, { "input": "1\n1\nB", "output": "1" }, { "input": "10\n1 9 7 6 2 4 7 8 1 3\nABBABAABBB", "output": "33" }, { "input": "100\n591 417 888 251 792 847 685 3 182 46...
1,356
43,315,200
3
21,305
39
C*++ Calculations
[ "expression parsing", "greedy" ]
A. C*++ Calculations
2
64
C*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (*expression* is the main term): - *expression* ::= *summand* | *expression*<=+<=*summand* | *expression*<=-<=*summand* - *summand* ::= *increment* | *coefficient***increment* - *increment* ::= a++ | ++a - *coefficient* ::= 0|1|2|...|1000 For example, "5*a++-3*++a+a++" is a valid expression in C*++. Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1. The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then — multiplied by the coefficient. The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.
The first input line contains an integer *a* (<=-<=1000<=≤<=*a*<=≤<=1000) — the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation.
Output a single number — the maximal possible value of the expression.
[ "1\n5*a++-3*++a+a++\n", "3\na+++++a\n" ]
[ "11\n", "8\n" ]
Consider the second example. Initially *a* = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of *a* is increased by 1. At the calculation of the second summand *a* is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
[ { "input": "1\n5*a++-3*++a+a++", "output": "11" }, { "input": "3\na+++++a", "output": "8" }, { "input": "-668\n820*a+++402*++a-482*++a", "output": "-492358" }, { "input": "902\n600*++a+411*a+++20*a++-340*++a-306*++a+485*a++-776*a+++417*a+++70*a++-703*a++", "output": "-972...
0
0
-1
21,456
743
Chloe and pleasant prizes
[ "dfs and similar", "dp", "graphs", "trees" ]
null
null
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 from 1 to *n*). A gift *i* is characterized by integer *a**i* — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with *n* vertices. The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts. Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible. Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=2·105) — the number of gifts. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the pleasantness of the gifts. The next (*n*<=-<=1) lines contain two numbers each. The *i*-th of these lines contains integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*) — the description of the tree's edges. It means that gifts with numbers *u**i* and *v**i* are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: *v**i* hangs on *u**i* or *u**i* hangs on *v**i*. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.
If it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together. Otherwise print Impossible.
[ "8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8\n", "4\n1 -5 1 1\n1 2\n1 4\n2 3\n", "1\n-1\n" ]
[ "25", "2", "Impossible" ]
none
[ { "input": "8\n0 5 -1 4 3 2 6 5\n1 2\n2 4\n2 5\n1 3\n3 6\n6 7\n6 8", "output": "25" }, { "input": "4\n1 -5 1 1\n1 2\n1 4\n2 3", "output": "2" }, { "input": "1\n-1", "output": "Impossible" }, { "input": "10\n3 2 -4 2 0 3 3 3 3 4\n10 8\n4 2\n4 9\n3 5\n5 2\n7 4\n2 6\n1 8\n10 9",...
31
0
0
21,461
49
Game
[ "brute force", "dp", "implementation" ]
D. Game
2
256
Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1<=×<=*n* square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.
The first line contains number *n* (1<=≤<=*n*<=≤<=1000) which represents the stripe’s length. The second line contains exactly *n* symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.
If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.
[ "6\n111010\n", "5\n10001\n", "7\n1100010\n", "5\n00100\n" ]
[ "1\n", "1\n", "2\n", "2\n" ]
In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white. In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black.
[ { "input": "6\n111010", "output": "1" }, { "input": "5\n10001", "output": "1" }, { "input": "7\n1100010", "output": "2" }, { "input": "5\n00100", "output": "2" }, { "input": "3\n101", "output": "0" }, { "input": "6\n111111", "output": "3" }, { ...
124
4,608,000
3.960417
21,619
592
BCPC
[ "binary search", "geometry", "two pointers" ]
null
null
BCPC stands for Byteforces Collegiate Programming Contest, and is the most famous competition in Byteforces. BCPC is a team competition. Each team is composed by a coach and three contestants. Blenda is the coach of the Bit State University(BSU), and she is very strict selecting the members of her team. In BSU there are *n* students numbered from 1 to *n*. Since all BSU students are infinitely smart, the only important parameters for Blenda are their reading and writing speed. After a careful measuring, Blenda have found that the *i*-th student have a reading speed equal to *r**i* (words per minute), and a writing speed of *w**i* (symbols per minute). Since BSU students are very smart, the measured speeds are sometimes very big and Blenda have decided to subtract some constant value *c* from all the values of reading speed and some value *d* from all the values of writing speed. Therefore she considers *r**i*'<==<=*r**i*<=-<=*c* and *w**i*'<==<=*w**i*<=-<=*d*. The student *i* is said to overwhelm the student *j* if and only if *r**i*'·*w**j*'<=&gt;<=*r**j*'·*w**i*'. Blenda doesn’t like fights in teams, so she thinks that a team consisting of three distinct students *i*,<=*j* and *k* is good if *i* overwhelms *j*, *j* overwhelms *k*, and *k* overwhelms *i*. Yes, the relation of overwhelming is not transitive as it often happens in real life. Since Blenda is busy preparing a training camp in Codeforces, you are given a task to calculate the number of different good teams in BSU. Two teams are considered to be different if there is at least one student that is present in one team but is not present in the other. In other words, two teams are different if the sets of students that form these teams are different.
In the first line of the input three integers *n*, *c* and *d* (3<=≤<=*n*<=≤<=345678,<=1<=≤<=*c*,<=*d*<=≤<=109) are written. They denote the number of students Blenda can use to form teams, the value subtracted from all reading speeds and the value subtracted from all writing speeds respectively. Each of the next *n* lines contains two integers *r**i* and *w**i* (0<=&lt;<=*r**i*,<=*w**i*<=≤<=109,<=|*r**i*<=-<=*c*|<=+<=|*w**i*<=-<=*d*|<=&gt;<=0). There are no two students, such that both their reading and writing speeds coincide, i.e. for every *i*<=≠<=*j* condition |*r**i*<=-<=*r**j*|<=+<=|*w**i*<=-<=*w**j*|<=&gt;<=0 holds.
Print the number of different teams in BSU, that are good according to Blenda's definition.
[ "5 2 2\n1 1\n4 1\n2 3\n3 2\n3 4\n", "7 6 6\n3 2\n1 7\n5 7\n3 7\n6 4\n8 9\n8 5\n" ]
[ "4\n", "11\n" ]
In the first sample the following teams are good: (*i* = 1, *j* = 2, *k* = 3), (*i* = 2, *j* = 5, *k* = 1), (*i* = 1, *j* = 4, *k* = 3), (*i* = 5, *j* = 1, *k* = 4). Note, that for example the team (*i* = 3, *j* = 1, *k* = 2) is also good, but is considered to be the same as the team (*i* = 1, *j* = 2, *k* = 3).
[]
30
204,800
-1
21,646
0
none
[ "none" ]
null
null
All Berland residents are waiting for an unprecedented tour of wizard in his Blue Helicopter over the cities of Berland! It is well-known that there are *n* cities in Berland, some pairs of which are connected by bidirectional roads. Each pair of cities is connected by no more than one road. It is not guaranteed that the road network is connected, i.e. it is possible that you can't reach some city from some other. The tour will contain several episodes. In each of the episodes: - the wizard will disembark at some city *x* from the Helicopter; - he will give a performance and show a movie for free at the city *x*; - he will drive to some neighboring city *y* using a road; - he will give a performance and show a movie for free at the city *y*; - he will drive to some neighboring to *y* city *z*; - he will give a performance and show a movie for free at the city *z*; - he will embark the Helicopter and fly away from the city *z*. It is known that the wizard doesn't like to use roads, so he agrees to use each road at most once (regardless of direction). In other words, for road between *a* and *b* he only can drive once from *a* to *b*, or drive once from *b* to *a*, or do not use this road at all. The wizards wants to plan as many episodes as possible without violation the above rules. Help the wizard! Please note that the wizard can visit the same city multiple times, the restriction is on roads only.
The first line contains two integers *n*, *m* (1<=≤<=*n*<=≤<=2·105, 0<=≤<=*m*<=≤<=2·105) — the number of cities and the number of roads in Berland, respectively. The roads description follow, one in each line. Each description is a pair of two integers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*), where *a**i* and *b**i* are the ids of the cities connected by the *i*-th road. It is guaranteed that there are no two roads connecting the same pair of cities. Every road is bidirectional. The cities are numbered from 1 to *n*. It is possible that the road network in Berland is not connected.
In the first line print *w* — the maximum possible number of episodes. The next *w* lines should contain the episodes in format *x*, *y*, *z* — the three integers denoting the ids of the cities in the order of the wizard's visits.
[ "4 5\n1 2\n3 2\n2 4\n3 4\n4 1\n", "5 8\n5 3\n1 2\n4 5\n5 1\n2 5\n4 3\n1 4\n3 2\n" ]
[ "2\n1 4 2\n4 3 2\n", "4\n1 4 5\n2 3 4\n1 5 3\n5 2 1\n" ]
none
[ { "input": "4 5\n1 2\n3 2\n2 4\n3 4\n4 1", "output": "2\n1 4 2\n4 3 2" }, { "input": "5 8\n5 3\n1 2\n4 5\n5 1\n2 5\n4 3\n1 4\n3 2", "output": "4\n1 4 5\n2 3 4\n1 5 3\n5 2 1" }, { "input": "1 0", "output": "0" }, { "input": "2 1\n1 2", "output": "0" }, { "input": "...
1,684
133,632,000
-1
21,706
370
Summer Reading
[ "dp", "greedy" ]
null
null
At school Vasya got an impressive list of summer reading books. Unlike other modern schoolchildren, Vasya loves reading, so he read some book each day of the summer. As Vasya was reading books, he was making notes in the Reader's Diary. Each day he wrote the orderal number of the book he was reading. The books in the list are numbered starting from 1 and Vasya was reading them in the order they go in the list. Vasya never reads a new book until he finishes reading the previous one. Unfortunately, Vasya wasn't accurate and some days he forgot to note the number of the book and the notes for those days remained empty. As Vasya knows that the literature teacher will want to check the Reader's Diary, so he needs to restore the lost records. Help him do it and fill all the blanks. Vasya is sure that he spends at least two and at most five days for each book. Vasya finished reading all the books he had started. Assume that the reading list contained many books. So many, in fact, that it is impossible to read all of them in a summer. If there are multiple valid ways to restore the diary records, Vasya prefers the one that shows the maximum number of read books.
The first line contains integer *n* — the number of summer days (2<=≤<=*n*<=≤<=2·105). The second line contains *n* integers *a*1,<=*a*2,<=... *a**n* — the records in the diary in the order they were written (0<=≤<=*a**i*<=≤<=105). If Vasya forgot to write the number of the book on the *i*-th day, then *a**i* equals 0.
If it is impossible to correctly fill the blanks in the diary (the diary may contain mistakes initially), print "-1". Otherwise, print in the first line the maximum number of books Vasya could have read in the summer if we stick to the diary. In the second line print *n* integers — the diary with correctly inserted records. If there are multiple optimal solutions, you can print any of them.
[ "7\n0 1 0 0 0 3 0\n", "8\n0 0 0 0 0 0 0 0\n", "4\n0 0 1 0\n", "4\n0 0 0 3\n" ]
[ "3\n1 1 2 2 3 3 3 \n", "4\n1 1 2 2 3 3 4 4 \n", "1\n1 1 1 1 \n", "-1\n" ]
none
[]
31
0
0
21,731
0
none
[ "none" ]
null
null
Old MacDonald has a farm and a large potato field, (1010<=+<=1)<=×<=(1010<=+<=1) square meters in size. The field is divided into square garden beds, each bed takes up one square meter. Old McDonald knows that the Colorado potato beetle is about to invade his farm and can destroy the entire harvest. To fight the insects, Old McDonald wants to spray some beds with insecticides. So Old McDonald went to the field, stood at the center of the central field bed and sprayed this bed with insecticides. Now he's going to make a series of movements and spray a few more beds. During each movement Old McDonald moves left, right, up or down the field some integer number of meters. As Old McDonald moves, he sprays all the beds he steps on. In other words, the beds that have any intersection at all with Old McDonald's trajectory, are sprayed with insecticides. When Old McDonald finished spraying, he wrote out all his movements on a piece of paper. Now he wants to know how many beds won't be infected after the invasion of the Colorado beetles. It is known that the invasion of the Colorado beetles goes as follows. First some bed on the field border gets infected. Than any bed that hasn't been infected, hasn't been sprayed with insecticides and has a common side with an infected bed, gets infected as well. Help Old McDonald and determine the number of beds that won't be infected by the Colorado potato beetle.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=1000) — the number of Old McDonald's movements. Next *n* lines contain the description of Old McDonald's movements. The *i*-th of these lines describes the *i*-th movement. Each movement is given in the format "*d**i* *x**i*", where *d**i* is the character that determines the direction of the movement ("L", "R", "U" or "D" for directions "left", "right", "up" and "down", correspondingly), and *x**i* (1<=≤<=*x**i*<=≤<=106) is an integer that determines the number of meters in the movement.
Print a single integer — the number of beds that won't be infected by the Colorado potato beetle. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "5\nR 8\nU 9\nL 9\nD 8\nL 2\n", "7\nR 10\nD 2\nL 7\nU 9\nD 2\nR 3\nD 10\n" ]
[ "101", "52" ]
none
[]
60
0
0
21,735
335
Buy One, Get One Free
[ "dp", "greedy" ]
null
null
A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input will begin with an integer *n* (1<=≤<=*n*<=≤<=500000), the number of pies you wish to acquire. Following this is a line with *n* integers, each indicating the cost of a pie. All costs are positive integers not exceeding 109.
Print the minimum cost to acquire all the pies. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "6\n3 4 5 3 4 5\n", "5\n5 5 5 5 5\n", "4\n309999 6000 2080 2080\n" ]
[ "14\n", "25\n", "314159\n" ]
In the first test case you can pay for a pie with cost 5 and get a pie with cost 4 for free, then pay for a pie with cost 5 and get a pie with cost 3 for free, then pay for a pie with cost 4 and get a pie with cost 3 for free. In the second test case you have to pay full price for every pie.
[ { "input": "6\n3 4 5 3 4 5", "output": "14" }, { "input": "5\n5 5 5 5 5", "output": "25" }, { "input": "4\n309999 6000 2080 2080", "output": "314159" }, { "input": "10\n1 1 1 1 1 2 3 4 5 6", "output": "16" }, { "input": "1\n1", "output": "1" }, { "inpu...
124
307,200
0
21,822
507
Guess Your Way Out!
[ "implementation", "math", "trees" ]
null
null
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height *h*. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2*h*. The exit is located at some node *n* where 1<=≤<=*n*<=≤<=2*h*, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: - Character 'L' means "go to the left child of the current node"; - Character 'R' means "go to the right child of the current node"; - If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; - If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; - If he reached a leaf node that is not the exit, he returns to the parent of the current node; - If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?
Input consists of two integers *h*,<=*n* (1<=≤<=*h*<=≤<=50, 1<=≤<=*n*<=≤<=2*h*).
Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.
[ "1 2\n", "2 3\n", "3 6\n", "10 1024\n" ]
[ "2", "5", "10", "2046" ]
A perfect binary tree of height *h* is a binary tree consisting of *h* + 1 levels. Level 0 consists of a single node called root, level *h* consists of 2<sup class="upper-index">*h*</sup> nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <img class="tex-graphics" src="https://espresso.codeforces.com/e9d0715dc8cd9b4f6ac7a0fb137563f857660adc.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "1 2", "output": "2" }, { "input": "2 3", "output": "5" }, { "input": "3 6", "output": "10" }, { "input": "10 1024", "output": "2046" }, { "input": "10 577", "output": "1345" }, { "input": "11 550", "output": "408" }, { "input": ...
1,000
1,228,800
0
21,837
922
Robot Vacuum Cleaner
[ "greedy", "sortings" ]
null
null
Pushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string *t* consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string *t* as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (*i*,<=*j*), that *i*<=&lt;<=*j* and and . The robot is off at the moment. Imp knows that it has a sequence of strings *t**i* in its memory, and he can arbitrary change their order. When the robot is started, it generates the string *t* as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation. Help Imp to find the maximum noise he can achieve by changing the order of the strings.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the number of strings in robot's memory. Next *n* lines contain the strings *t*1,<=*t*2,<=...,<=*t**n*, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.
Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.
[ "4\nssh\nhs\ns\nhhhs\n", "2\nh\ns\n" ]
[ "18\n", "1\n" ]
The optimal concatenation in the first sample is *ssshhshhhs*.
[ { "input": "4\nssh\nhs\ns\nhhhs", "output": "18" }, { "input": "2\nh\ns", "output": "1" }, { "input": "6\nh\ns\nhhh\nh\nssssss\ns", "output": "40" }, { "input": "1\ns", "output": "0" }, { "input": "10\nsshshss\nhssssssssh\nhhhhhh\nhhhs\nhshhh\nhhhhshsh\nhh\nh\nshs...
46
0
0
21,859
763
Timofey and remoduling
[ "brute force", "implementation", "math", "number theory" ]
null
null
Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime *m*. Also, Timofey likes to look for arithmetical progressions everywhere. One of his birthday presents was a sequence of distinct integers *a*1,<=*a*2,<=...,<=*a**n*. Timofey wants to know whether he can rearrange the elements of the sequence so that is will be an arithmetical progression modulo *m*, or not. Arithmetical progression modulo *m* of length *n* with first element *x* and difference *d* is sequence of integers *x*,<=*x*<=+<=*d*,<=*x*<=+<=2*d*,<=...,<=*x*<=+<=(*n*<=-<=1)·*d*, each taken modulo *m*.
The first line contains two integers *m* and *n* (2<=≤<=*m*<=≤<=109<=+<=7, 1<=≤<=*n*<=≤<=105, *m* is prime) — Timofey's favorite prime module and the length of the sequence. The second line contains *n* distinct integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=&lt;<=*m*) — the elements of the sequence.
Print -1 if it is not possible to rearrange the elements of the sequence so that is will be an arithmetical progression modulo *m*. Otherwise, print two integers — the first element of the obtained progression *x* (0<=≤<=*x*<=&lt;<=*m*) and its difference *d* (0<=≤<=*d*<=&lt;<=*m*). If there are multiple answers, print any of them.
[ "17 5\n0 2 4 13 15\n", "17 5\n0 2 4 13 14\n", "5 3\n1 2 3\n" ]
[ "13 2\n", "-1\n", "3 4\n" ]
none
[ { "input": "17 5\n0 2 4 13 15", "output": "13 2" }, { "input": "17 5\n0 2 4 13 14", "output": "-1" }, { "input": "5 3\n1 2 3", "output": "3 4" }, { "input": "17 8\n7 9 11 13 15 1 3 5", "output": "1 2" }, { "input": "13 2\n0 11", "output": "0 11" }, { "...
31
0
0
21,897
754
Fedor and coupons
[ "binary search", "data structures", "greedy", "sortings" ]
null
null
All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has *n* discount coupons, the *i*-th of them can be used with products with ids ranging from *l**i* to *r**i*, inclusive. Today Fedor wants to take exactly *k* coupons with him. Fedor wants to choose the *k* coupons in such a way that the number of such products *x* that all coupons can be used with this product *x* is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=3·105) — the number of coupons Fedor has, and the number of coupons he wants to choose. Each of the next *n* lines contains two integers *l**i* and *r**i* (<=-<=109<=≤<=*l**i*<=≤<=*r**i*<=≤<=109) — the description of the *i*-th coupon. The coupons can be equal.
In the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted. In the second line print *k* distinct integers *p*1,<=*p*2,<=...,<=*p**k* (1<=≤<=*p**i*<=≤<=*n*) — the ids of the coupons which Fedor should choose. If there are multiple answers, print any of them.
[ "4 2\n1 100\n40 70\n120 130\n125 180\n", "3 2\n1 12\n15 20\n25 30\n", "5 2\n1 10\n5 15\n14 50\n30 70\n99 100\n" ]
[ "31\n1 2 \n", "0\n1 2 \n", "21\n3 4 \n" ]
In the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total. In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.
[ { "input": "4 2\n1 100\n40 70\n120 130\n125 180", "output": "31\n1 2 " }, { "input": "3 2\n1 12\n15 20\n25 30", "output": "0\n1 2 " }, { "input": "5 2\n1 10\n5 15\n14 50\n30 70\n99 100", "output": "21\n3 4 " }, { "input": "7 6\n-8 6\n7 9\n-10 -5\n-6 10\n-7 -3\n5 8\n4 10", ...
46
102,400
0
21,909
150
Quantity of Strings
[ "combinatorics", "dfs and similar", "graphs", "math" ]
null
null
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly *n*, based on the alphabet of size *m*. Any its substring with length equal to *k* is a palindrome. How many such strings exist? Your task is to find their quantity modulo 1000000007 (109<=+<=7). Be careful and don't miss a string or two! Let us remind you that a string is a palindrome if it can be read the same way in either direction, from the left to the right and from the right to the left.
The first and only line contains three integers: *n*, *m* and *k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=2000).
Print a single integer — the number of strings of the described type modulo 1000000007 (109<=+<=7).
[ "1 1 1\n", "5 2 4\n" ]
[ "1\n", "2\n" ]
In the first sample only one string is valid: "a" (let's denote the only letter of our alphabet as "a"). In the second sample (if we denote the alphabet letters as "a" and "b") the following strings are valid: "aaaaa" and "bbbbb".
[ { "input": "1 1 1", "output": "1" }, { "input": "5 2 4", "output": "2" }, { "input": "7 4 20", "output": "16384" }, { "input": "8 13 9", "output": "815730721" }, { "input": "10 23 9", "output": "529" }, { "input": "10 25 8", "output": "25" }, {...
15
0
0
21,913
515
Drazil and His Happy Friends
[ "brute force", "dsu", "meet-in-the-middle", "number theory" ]
null
null
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan. There are *n* boys and *m* girls among his friends. Let's number them from 0 to *n*<=-<=1 and 0 to *m*<=-<=1 separately. In *i*-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, *i* starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever. Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.
The first line contains two integer *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). The second line contains integer *b* (0<=≤<=*b*<=≤<=*n*), denoting the number of happy boys among friends of Drazil, and then follow *b* distinct integers *x*1,<=*x*2,<=...,<=*x**b* (0<=≤<=*x**i*<=&lt;<=*n*), denoting the list of indices of happy boys. The third line conatins integer *g* (0<=≤<=*g*<=≤<=*m*), denoting the number of happy girls among friends of Drazil, and then follow *g* distinct integers *y*1,<=*y*2,<=... ,<=*y**g* (0<=≤<=*y**j*<=&lt;<=*m*), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.
If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".
[ "2 3\n0\n1 0\n", "2 4\n1 0\n1 2\n", "2 3\n1 0\n1 1\n" ]
[ "Yes\n", "No\n", "Yes\n" ]
By <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/169ade208e6eb4f9263c57aaff716529d59c3288.png" style="max-width: 100.0%;max-height: 100.0%;"/> we define the remainder of integer division of *i* by *k*. In first sample case: - On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. - On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. - On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. - On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. - On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.
[ { "input": "2 3\n0\n1 0", "output": "Yes" }, { "input": "2 4\n1 0\n1 2", "output": "No" }, { "input": "2 3\n1 0\n1 1", "output": "Yes" }, { "input": "16 88\n6 5 14 2 0 12 7\n30 21 64 35 79 74 39 63 44 81 73 0 27 33 69 12 86 46 20 25 55 52 7 58 23 5 60 32 41 50 82", "outpu...
77
6,963,200
0
21,922
251
Two Sets
[ "bitmasks", "math" ]
null
null
Little Petya likes numbers a lot. Recently his mother has presented him a collection of *n* non-negative integers. There's only one thing Petya likes more than numbers: playing with little Masha. He immediately decided to give a part of his new collection to her. To make the game even more interesting, Petya decided to give Masha such collection of numbers for which the following conditions fulfill: - Let's introduce *x*1 to denote the *xor* of all numbers Petya has got left; and let's introduce *x*2 to denote the *xor* of all numbers he gave to Masha. Value (*x*1<=+<=*x*2) must be as large as possible. - If there are multiple ways to divide the collection so that the previous condition fulfilled, then Petya minimizes the value *x*1. The *xor* operation is a bitwise excluding "OR", that is denoted as "xor" in the Pascal language and "^" in C/C++/Java. Help Petya divide the collection as described above. If there are multiple suitable ways to divide it, find any of them. Please note that after Petya gives a part of his numbers to Masha, he may have no numbers left. The reverse situation is also possible, when Petya gives nothing to Masha. In both cases we must assume that the *xor* of an empty set of numbers equals 0.
The first line contains integer *n* (1<=≤<=*n*<=≤<=105), showing how many numbers Petya's mother gave him. The second line contains the actual space-separated numbers. They are all integer, non-negative and do not exceed 1018.
Print *n* space-separated integers, the *i*-th of them should equal either 1, if Petya keeps the number that follows *i*-th in his collection, or it should equal 2, if Petya gives the corresponding number to Masha. The numbers are indexed in the order in which they are given in the input.
[ "6\n1 2 3 4 5 6\n", "3\n1000000000000 1000000000000 1000000000000\n", "8\n1 1 2 2 3 3 4 4\n" ]
[ "2 2 2 2 2 2\n", "2 2 2\n", "1 2 1 2 2 2 1 2\n" ]
none
[]
30
0
0
22,073
852
Casinos and travel
[ "dp" ]
null
null
John has just bought a new car and is planning a journey around the country. Country has *N* cities, some of which are connected by bidirectional roads. There are *N*<=-<=1 roads and every city is reachable from any other city. Cities are labeled from 1 to *N*. John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules. To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey. He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey. In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109<=+<=7.
In the first line, a positive integer *N* (1<=≤<=*N*<=≤<=100000), the number of cities. In the next *N*<=-<=1 lines, two numbers *a*,<= *b* (1<=≤<=*a*,<=*b*<=≤<=*N*) separated by a single space meaning that cities *a* and *b* are connected by a bidirectional road.
Output one number, the answer to the problem modulo 109<=+<=7.
[ "2\n1 2\n", "3\n1 2\n2 3\n" ]
[ "4\n", "10\n" ]
Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4. Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4 + 2 + 4 = 10 options.
[ { "input": "2\n1 2", "output": "4" }, { "input": "3\n1 2\n2 3", "output": "10" }, { "input": "4\n1 2\n2 3\n3 4", "output": "24" } ]
78
0
0
22,217
995
Number Clicker
[ "divide and conquer", "graphs", "meet-in-the-middle", "number theory" ]
null
null
Allen is playing Number Clicker on his phone. He starts with an integer $u$ on the screen. Every second, he can press one of 3 buttons. 1. Turn $u \to u+1 \pmod{p}$. 1. Turn $u \to u+p-1 \pmod{p}$. 1. Turn $u \to u^{p-2} \pmod{p}$. Allen wants to press at most 200 buttons and end up with $v$ on the screen. Help him!
The first line of the input contains 3 positive integers: $u, v, p$ ($0 \le u, v \le p-1$, $3 \le p \le 10^9 + 9$). $p$ is guaranteed to be prime.
On the first line, print a single integer $\ell$, the number of button presses. On the second line, print integers $c_1, \dots, c_\ell$, the button presses. For $1 \le i \le \ell$, $1 \le c_i \le 3$. We can show that the answer always exists.
[ "1 3 5\n", "3 2 5\n" ]
[ "2\n1 1\n", "1\n3\n" ]
In the first example the integer on the screen changes as $1 \to 2 \to 3$. In the second example the integer on the screen changes as $3 \to 2$.
[ { "input": "1 3 5", "output": "2\n1 1 " }, { "input": "3 2 5", "output": "1\n2 " }, { "input": "9382509 19872987 1000000007", "output": "38\n3 2 2 3 2 2 2 3 2 2 2 2 2 2 3 2 2 2 2 2 2 3 2 3 2 3 2 2 2 3 2 2 2 3 1 1 1 1 " }, { "input": "1 1 3", "output": "0" }, { "in...
92
0
0
22,231
22
Segments
[ "greedy", "sortings" ]
D. Segments
1
256
You are given *n* segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?
The first line of the input contains single integer number *n* (1<=≤<=*n*<=≤<=1000) — amount of segments. Following *n* lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.
The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.
[ "2\n0 2\n2 5\n", "5\n0 3\n4 2\n4 8\n8 10\n7 7\n" ]
[ "1\n2 ", "3\n7 10 3\n" ]
none
[ { "input": "2\n0 2\n2 5", "output": "1\n2 " }, { "input": "5\n0 3\n4 2\n4 8\n8 10\n7 7", "output": "3\n3 7 10 " }, { "input": "3\n40 -83\n52 -80\n-21 -4", "output": "1\n-4 " }, { "input": "4\n67 -88\n37 -62\n-26 91\n-99 -50", "output": "2\n-50 91 " }, { "input": "...
155
1,638,400
3.919448
22,239
367
Sereja and Algorithm
[ "data structures", "implementation" ]
null
null
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as *q*<==<=*q*1*q*2... *q**k*. The algorithm consists of two steps: 1. Find any continuous subsequence (substring) of three characters of string *q*, which doesn't equal to either string "zyx", "xzy", "yxz". If *q* doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2. 1. Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string *q* if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string. Sereja wants to test his algorithm. For that, he has string *s*<==<=*s*1*s*2... *s**n*, consisting of *n* characters. The boy conducts a series of *m* tests. As the *i*-th test, he sends substring *s**l**i**s**l**i*<=+<=1... *s**r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (*l**i*,<=*r**i*) determine if the algorithm works correctly on this test or not.
The first line contains non-empty string *s*, its length (*n*) doesn't exceed 105. It is guaranteed that string *s* only contains characters: 'x', 'y', 'z'. The second line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of tests. Next *m* lines contain the tests. The *i*-th line contains a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.
[ "zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6\n" ]
[ "YES\nYES\nNO\nYES\nNO\n" ]
In the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.
[ { "input": "zyxxxxxxyyz\n5\n5 5\n1 3\n1 11\n1 4\n3 6", "output": "YES\nYES\nNO\nYES\nNO" }, { "input": "yxzyzxzzxyyzzxxxzyyzzyzxxzxyzyyzxyzxyxxyzxyxzyzxyzxyyxzzzyzxyyxyzxxy\n10\n17 67\n6 35\n12 45\n56 56\n14 30\n25 54\n1 1\n46 54\n3 33\n19 40", "output": "NO\nNO\nNO\nYES\nYES\nNO\nYES\nNO\nNO\nY...
93
0
-1
22,291
958
Encryption (easy)
[ "brute force" ]
null
null
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks. Heidi is presented with a screen that shows her a sequence of integers *A* and a positive integer *p*. She knows that the encryption code is a single number *S*, which is defined as follows: Define the score of *X* to be the sum of the elements of *X* modulo *p*. Heidi is given a sequence *A* that consists of *N* integers, and also given an integer *p*. She needs to split *A* into 2 parts such that: - Each part contains at least 1 element of *A*, and each part consists of contiguous elements of *A*. - The two parts do not overlap. - The total sum *S* of the scores of those two parts is maximized. This is the encryption code. Output the sum *S*, which is the encryption code.
The first line of the input contains two space-separated integer *N* and *p* (2<=≤<=*N*<=≤<=100<=000, 2<=≤<=*p*<=≤<=10<=000) – the number of elements in *A*, and the modulo for computing scores, respectively. The second line contains *N* space-separated integers which are the elements of *A*. Each integer is from the interval [1,<=1<=000<=000].
Output the number *S* as described in the problem statement.
[ "4 10\n3 4 7 2\n", "10 12\n16 3 24 13 9 8 7 5 12 12\n" ]
[ "16\n", "13\n" ]
In the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fc1f9aecea625f3be9a56917d3ba448d669ff278.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ffd0a0f4c65b0578601ae2fe11a80aec5192f53d.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "4 10\n3 4 7 2", "output": "16" }, { "input": "10 12\n16 3 24 13 9 8 7 5 12 12", "output": "13" }, { "input": "2 2\n9 9", "output": "2" }, { "input": "2 2\n8 8", "output": "0" }, { "input": "5 50\n1 1 1 1 1", "output": "5" }, { "input": "5 5...
46
3,379,200
-1
22,300
960
Alternating Tree
[ "combinatorics", "dfs and similar", "divide and conquer", "dp", "probabilities", "trees" ]
null
null
Given a tree with $n$ nodes numbered from $1$ to $n$. Each node $i$ has an associated value $V_i$. If the simple path from $u_1$ to $u_m$ consists of $m$ nodes namely $u_1 \rightarrow u_2 \rightarrow u_3 \rightarrow \dots u_{m-1} \rightarrow u_{m}$, then its alternating function $A(u_{1},u_{m})$ is defined as $A(u_{1},u_{m}) = \sum\limits_{i=1}^{m} (-1)^{i+1} \cdot V_{u_{i}}$. A path can also have $0$ edges, i.e. $u_{1}=u_{m}$. Compute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo $10^{9}+7$.
The first line contains an integer $n$ $(2 \leq n \leq 2\cdot10^{5} )$ — the number of vertices in the tree. The second line contains $n$ space-separated integers $V_1, V_2, \ldots, V_n$ ($-10^9\leq V_i \leq 10^9$) — values of the nodes. The next $n-1$ lines each contain two space-separated integers $u$ and $v$ $(1\leq u, v\leq<=n, u \neq v)$ denoting an edge between vertices $u$ and $v$. It is guaranteed that the given graph is a tree.
Print the total sum of alternating functions of all unique simple paths modulo $10^{9}+7$.
[ "4\n-4 1 5 -2\n1 2\n1 3\n1 4\n", "8\n-2 6 -4 -4 -9 -3 -7 23\n8 2\n2 3\n1 4\n6 5\n7 6\n4 7\n5 8\n" ]
[ "40\n", "4\n" ]
Consider the first example. A simple path from node $1$ to node $2$: $1 \rightarrow 2$ has alternating function equal to $A(1,2) = 1 \cdot (-4)+(-1) \cdot 1 = -5$. A simple path from node $1$ to node $3$: $1 \rightarrow 3$ has alternating function equal to $A(1,3) = 1 \cdot (-4)+(-1) \cdot 5 = -9$. A simple path from node $2$ to node $4$: $2 \rightarrow 1 \rightarrow 4$ has alternating function $A(2,4) = 1 \cdot (1)+(-1) \cdot (-4)+1 \cdot (-2) = 3$. A simple path from node $1$ to node $1$ has a single node $1$, so $A(1,1) = 1 \cdot (-4) = -4$. Similarly, $A(2, 1) = 5$, $A(3, 1) = 9$, $A(4, 2) = 3$, $A(1, 4) = -2$, $A(4, 1) = 2$, $A(2, 2) = 1$, $A(3, 3) = 5$, $A(4, 4) = -2$, $A(3, 4) = 7$, $A(4, 3) = 7$, $A(2, 3) = 10$, $A(3, 2) = 10$. So the answer is $(-5) + (-9) + 3 + (-4) + 5 + 9 + 3 + (-2) + 2 + 1 + 5 + (-2) + 7 + 7 + 10 + 10 = 40$. Similarly $A(1,4)=-2, A(2,2)=1, A(2,1)=5, A(2,3)=10, A(3,3)=5, A(3,1)=9, A(3,2)=10, A(3,4)=7, A(4,4)=-2, A(4,1)=2, A(4,2)=3 , A(4,3)=7$ which sums upto 40.
[ { "input": "4\n-4 1 5 -2\n1 2\n1 3\n1 4", "output": "40" }, { "input": "8\n-2 6 -4 -4 -9 -3 -7 23\n8 2\n2 3\n1 4\n6 5\n7 6\n4 7\n5 8", "output": "4" }, { "input": "15\n-4 6 1 6 -9 -8 -10 9 -2 -9 7 2 -3 1 13\n11 2\n10 3\n15 4\n7 5\n2 6\n9 7\n6 8\n12 9\n4 10\n1 11\n3 12\n8 13\n5 14\n13 15"...
421
23,961,600
0
22,319
115
Lawnmower
[ "greedy", "sortings" ]
null
null
You have a garden consisting entirely of grass and weeds. Your garden is described by an *n*<=×<=*m* grid, with rows numbered 1 to *n* from top to bottom, and columns 1 to *m* from left to right. Each cell is identified by a pair (*r*,<=*c*) which means that the cell is located at row *r* and column *c*. Each cell may contain either grass or weeds. For example, a 4<=×<=5 garden may look as follows (empty cells denote grass): You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1,<=1). At any moment of time you are facing a certain direction — either left or right. And initially, you face right. In one move you can do either one of these: 1) Move one cell in the direction that you are facing. - if you are facing right: move from cell (*r*,<=*c*) to cell (*r*,<=*c*<=+<=1) - if you are facing left: move from cell (*r*,<=*c*) to cell (*r*,<=*c*<=-<=1) - if you were facing right previously, you will face left - if you were facing left previously, you will face right You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move. What is the minimum number of moves required to mow all the weeds?
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=150) — the number of rows and columns respectively. Then follow *n* lines containing *m* characters each — the content of the grid. "G" means that this cell contains grass. "W" means that this cell contains weeds. It is guaranteed that the top-left corner of the grid will contain grass.
Print a single number — the minimum number of moves required to mow all the weeds.
[ "4 5\nGWGGW\nGGWGG\nGWGGG\nWGGGG\n", "3 3\nGWW\nWWW\nWWG\n", "1 1\nG\n" ]
[ "11\n", "7\n", "0\n" ]
For the first example, this is the picture of the initial state of the grid: A possible solution is by mowing the weeds as illustrated below:
[ { "input": "4 5\nGWGGW\nGGWGG\nGWGGG\nWGGGG", "output": "11" }, { "input": "3 3\nGWW\nWWW\nWWG", "output": "7" }, { "input": "1 1\nG", "output": "0" }, { "input": "4 3\nGWW\nWWW\nWWW\nWWG", "output": "11" }, { "input": "6 5\nGWWWW\nWWWWW\nWWWWW\nWWWWW\nWWWWW\nWWWW...
31
0
0
22,354
367
Sereja ans Anagrams
[ "binary search", "data structures" ]
null
null
Sereja has two sequences *a* and *b* and number *p*. Sequence *a* consists of *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Similarly, sequence *b* consists of *m* integers *b*1,<=*b*2,<=...,<=*b**m*. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions *q* (*q*<=+<=(*m*<=-<=1)·*p*<=≤<=*n*; *q*<=≥<=1), such that sequence *b* can be obtained from sequence *a**q*,<=*a**q*<=+<=*p*,<=*a**q*<=+<=2*p*,<=...,<=*a**q*<=+<=(*m*<=-<=1)*p* by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of *q*.
The first line contains three integers *n*, *m* and *p* (1<=≤<=*n*,<=*m*<=≤<=2·105,<=1<=≤<=*p*<=≤<=2·105). The next line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=109). The next line contains *m* integers *b*1, *b*2, ..., *b**m* (1<=≤<=*b**i*<=≤<=109).
In the first line print the number of valid *q*s. In the second line, print the valid values in the increasing order.
[ "5 3 1\n1 2 3 2 1\n1 2 3\n", "6 3 2\n1 3 2 2 3 1\n1 2 3\n" ]
[ "2\n1 3\n", "2\n1 2\n" ]
none
[ { "input": "5 3 1\n1 2 3 2 1\n1 2 3", "output": "2\n1 3" }, { "input": "6 3 2\n1 3 2 2 3 1\n1 2 3", "output": "2\n1 2" }, { "input": "68 16 3\n5 3 4 3 3 3 2 2 2 3 2 4 2 2 2 2 4 3 5 1 1 2 2 2 3 1 5 1 2 2 1 5 1 5 3 2 3 5 2 1 1 4 2 3 4 3 4 3 3 1 3 4 1 5 2 5 3 4 4 1 4 5 5 1 1 2 2 2\n5 4 4 3 ...
61
2,867,200
-1
22,390
919
Seat Arrangements
[ "brute force", "implementation" ]
null
null
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied. The classroom contains $n$ rows of seats and there are $m$ seats in each row. Then the classroom can be represented as an $n \times m$ matrix. The character '.' represents an empty seat, while '*' means that the seat is occupied. You need to find $k$ consecutive empty seats in the same row or column and arrange those seats for you and your friends. Your task is to find the number of ways to arrange the seats. Two ways are considered different if sets of places that students occupy differs.
The first line contains three positive integers $n,m,k$ ($1 \leq n, m, k \leq 2\,000$), where $n,m$ represent the sizes of the classroom and $k$ is the number of consecutive seats you need to find. Each of the next $n$ lines contains $m$ characters '.' or '*'. They form a matrix representing the classroom, '.' denotes an empty seat, and '*' denotes an occupied seat.
A single number, denoting the number of ways to find $k$ empty seats in the same row or column.
[ "2 3 2\n**.\n...\n", "1 2 2\n..\n", "3 3 4\n.*.\n*.*\n.*.\n" ]
[ "3\n", "1\n", "0\n" ]
In the first sample, there are three ways to arrange those seats. You can take the following seats for your arrangement. - $(1,3)$, $(2,3)$ - $(2,2)$, $(2,3)$ - $(2,1)$, $(2,2)$
[ { "input": "1 2 2\n..", "output": "1" }, { "input": "3 3 4\n.*.\n*.*\n.*.", "output": "0" }, { "input": "1 1 1\n.", "output": "1" }, { "input": "1 1 1\n*", "output": "0" }, { "input": "2 2 2\n.*\n*.", "output": "0" }, { "input": "1 1 1000\n.", "out...
1,000
9,728,000
0
22,423
0
none
[ "none" ]
null
null
You are given a rectangular parallelepiped with sides of positive integer lengths $A$, $B$ and $C$. Find the number of different groups of three integers ($a$, $b$, $c$) such that $1\leq a\leq b\leq c$ and parallelepiped $A\times B\times C$ can be paved with parallelepipeds $a\times b\times c$. Note, that all small parallelepipeds have to be rotated in the same direction. For example, parallelepiped $1\times 5\times 6$ can be divided into parallelepipeds $1\times 3\times 5$, but can not be divided into parallelepipeds $1\times 2\times 3$.
The first line contains a single integer $t$ ($1 \leq t \leq 10^5$) — the number of test cases. Each of the next $t$ lines contains three integers $A$, $B$ and $C$ ($1 \leq A, B, C \leq 10^5$) — the sizes of the parallelepiped.
For each test case, print the number of different groups of three points that satisfy all given conditions.
[ "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100\n" ]
[ "1\n4\n4\n165\n" ]
In the first test case, rectangular parallelepiped $(1, 1, 1)$ can be only divided into rectangular parallelepiped with sizes $(1, 1, 1)$. In the second test case, rectangular parallelepiped $(1, 6, 1)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 1, 3)$ and $(1, 1, 6)$. In the third test case, rectangular parallelepiped $(2, 2, 2)$ can be divided into rectangular parallelepipeds with sizes $(1, 1, 1)$, $(1, 1, 2)$, $(1, 2, 2)$ and $(2, 2, 2)$.
[ { "input": "4\n1 1 1\n1 6 1\n2 2 2\n100 100 100", "output": "1\n4\n4\n165" }, { "input": "10\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1", "output": "1\n1\n1\n1\n1\n1\n1\n1\n1\n1" }, { "input": "10\n9 6 8\n5 5 2\n8 9 2\n2 7 9\n6 4 10\n1 1 8\n2 8 1\n10 6 3\n7 5 2...
46
0
0
22,429
379
New Year Present
[ "constructive algorithms", "implementation" ]
null
null
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put *n* empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided to put *a**i* coins to the *i*-th wallet from the left. Vasily is a very busy man, so the money are sorted into the bags by his robot. Initially, the robot stands by the leftmost wallet in the row. The robot can follow instructions of three types: go to the wallet that is to the left of the current one (if such wallet exists), go to the wallet that is to the right of the current one (if such wallet exists), put a coin to the current wallet. Due to some technical malfunctions the robot cannot follow two "put a coin" instructions in a row. Vasily doesn't want to wait for long, so he wants to write a program for the robot that contains at most 106 operations (not necessarily minimum in length) the robot can use to put coins into the wallets. Help him.
The first line contains integer *n* (2<=≤<=*n*<=≤<=300) — the number of wallets. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=300). It is guaranteed that at least one *a**i* is positive.
Print the sequence that consists of *k* (1<=≤<=*k*<=≤<=106) characters, each of them equals: "L", "R" or "P". Each character of the sequence is an instruction to the robot. Character "L" orders to move to the left, character "R" orders to move to the right, character "P" orders the robot to put a coin in the wallet. The robot is not allowed to go beyond the wallet line. In other words, you cannot give instructions "L" if the robot is at wallet 1, or "R" at wallet *n*. As a result of the performed operations, the *i*-th wallet from the left must contain exactly *a**i* coins. If there are multiple answers, you can print any of them.
[ "2\n1 2\n", "4\n0 2 0 2\n" ]
[ "PRPLRP", "RPRRPLLPLRRRP" ]
none
[ { "input": "2\n1 2", "output": "PRPLRP" }, { "input": "4\n0 2 0 2", "output": "RPRRPLLPLRRRP" }, { "input": "10\n2 3 4 0 0 1 1 3 4 2", "output": "PRPRPRRRPRPRPRPRPLPLPLLLLLPLPLPRPRPRRRRRPRPRPLPLLLLLLPLL" }, { "input": "10\n0 0 0 0 0 0 0 0 1 0", "output": "RRRRRRRRPR" },...
77
3,072,000
-1
22,525
0
none
[ "none" ]
null
null
One day Polycarpus got hold of two non-empty strings *s* and *t*, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "*x* *y*" are there, such that *x* is a substring of string *s*, *y* is a subsequence of string *t*, and the content of *x* and *y* is the same. Two pairs are considered different, if they contain different substrings of string *s* or different subsequences of string *t*. Read the whole statement to understand the definition of different substrings and subsequences. The length of string *s* is the number of characters in it. If we denote the length of the string *s* as |*s*|, we can write the string as *s*<==<=*s*1*s*2... *s*|*s*|. A substring of *s* is a non-empty string *x*<==<=*s*[*a*... *b*]<==<=*s**a**s**a*<=+<=1... *s**b* (1<=≤<=*a*<=≤<=*b*<=≤<=|*s*|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings *s*[*a*... *b*] and *s*[*c*... *d*] are considered to be different if *a*<=≠<=*c* or *b*<=≠<=*d*. For example, if *s*="codeforces", *s*[2...2] and *s*[6...6] are different, though their content is the same. A subsequence of *s* is a non-empty string *y*<==<=*s*[*p*1*p*2... *p*|*y*|]<==<=*s**p*1*s**p*2... *s**p*|*y*| (1<=≤<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p*|*y*|<=≤<=|*s*|). For example, "coders" is a subsequence of "codeforces". Two subsequences *u*<==<=*s*[*p*1*p*2... *p*|*u*|] and *v*<==<=*s*[*q*1*q*2... *q*|*v*|] are considered different if the sequences *p* and *q* are different.
The input consists of two lines. The first of them contains *s* (1<=≤<=|*s*|<=≤<=5000), and the second one contains *t* (1<=≤<=|*t*|<=≤<=5000). Both strings consist of lowercase Latin letters.
Print a single number — the number of different pairs "*x* *y*" such that *x* is a substring of string *s*, *y* is a subsequence of string *t*, and the content of *x* and *y* is the same. As the answer can be rather large, print it modulo 1000000007 (109<=+<=7).
[ "aa\naa\n", "codeforces\nforceofcode\n" ]
[ "5\n", "60\n" ]
Let's write down all pairs "*x* *y*" that form the answer in the first sample: "*s*[1...1] *t*[1]", "*s*[2...2] *t*[1]", "*s*[1...1] *t*[2]","*s*[2...2] *t*[2]", "*s*[1...2] *t*[1 2]".
[]
62
0
0
22,539
332
Theft of Blueprints
[ "graphs", "math" ]
null
null
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of *n* missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos *i* and *j* is patrolled by *c**i*,<=*j* war droids. The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any *k*-element set of silos *S* there is exactly one silo that is directly connected by a passage with each silo from *S* (we'll call this silo adjacent with *S*). Having considered that, the insurgents decided to act as follows: 1. they choose a *k*-element set of silos *S*; 1. a group of scouts lands from the air into each silo from *S*; 1. each group moves along the corresponding passage to the silo, adjacent with *S* (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); 1. in the silo, adjacent with *S*, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set *S*. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set *S*. Solve this problem to help the insurgents protect the ideals of the Republic!
The first line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=2000, 1<=≤<=*k*<=≤<=*n*<=-<=1) — the number of silos and the number of scout groups, correspondingly. The next *n*<=-<=1 lines describe the polygon plan: the *i*-th of these lines contains *n*<=-<=*i* integers *c**i*,<=*i*<=+<=1,<=*c**i*,<=*i*<=+<=2,<=...,<=*c**i*,<=*n* — the number of droids that patrol the corresponding passages (-1<=≤<=*c**i*,<=*j*<=≤<=109; if *c**i*,<=*j*<==<= -1, then silos *i* and *j* don't have a passage between them). All passages are bidirectional, that is, we can assume that *c**i*,<=*j*<==<=*c**j*,<=*i*. No passages connect a silo with itself. It is guaranteed that the polygon plan meets the conditions of the problem statement.
Print the average danger of the scouting operation, rounded down to an integer. Note that at the given limits the answer to the problem always fits into the standard integer 64-bit data type. Please do not use the %lld specifier to write 64-bit integers in С++. It is preferred to use the cout stream or the %I64d specifier.
[ "6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1\n", "3 2\n10 0\n11\n" ]
[ "5\n", "14\n" ]
In the first sample there are 6 one-element sets of silos. For sets {1}, {5} the operation danger will equal 8, for sets {3}, {6} — 3, for sets {2}, {4} — 5. The mathematical average equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/3bc833659595c25e73150ed7f23907011961ceca.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample there are 3 two-elements sets of silos: {1, 3} (danger equals 21), {1, 2} (danger equals 11), {2, 3} (danger equals 10). The average operation danger equals <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/02946ba8c525c97041629189ab4acc976074d8d1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "6 1\n-1 -1 -1 8 -1\n-1 5 -1 -1\n-1 -1 3\n-1 -1\n-1", "output": "5" }, { "input": "3 2\n10 0\n11", "output": "14" }, { "input": "4 3\n15 1 3\n5 8\n9", "output": "20" }, { "input": "5 2\n-1 -1 14 3\n19 -1 1\n-1 6\n0", "output": "10" }, { "input": "10 9\n...
92
0
0
22,540
14
Camels
[ "dp" ]
E. Camels
2
64
Bob likes to draw camels: with a single hump, two humps, three humps, etc. He draws a camel by connecting points on a coordinate plane. Now he's drawing camels with *t* humps, representing them as polylines in the plane. Each polyline consists of *n* vertices with coordinates (*x*1,<=*y*1), (*x*2,<=*y*2), ..., (*x**n*,<=*y**n*). The first vertex has a coordinate *x*1<==<=1, the second — *x*2<==<=2, etc. Coordinates *y**i* might be any, but should satisfy the following conditions: - there should be *t* humps precisely, i.e. such indexes *j* (2<=≤<=*j*<=≤<=*n*<=-<=1), so that *y**j*<=-<=1<=&lt;<=*y**j*<=&gt;<=*y**j*<=+<=1, - there should be precisely *t*<=-<=1 such indexes *j* (2<=≤<=*j*<=≤<=*n*<=-<=1), so that *y**j*<=-<=1<=&gt;<=*y**j*<=&lt;<=*y**j*<=+<=1, - no segment of a polyline should be parallel to the *Ox*-axis, - all *y**i* are integers between 1 and 4. For a series of his drawings of camels with *t* humps Bob wants to buy a notebook, but he doesn't know how many pages he will need. Output the amount of different polylines that can be drawn to represent camels with *t* humps for a given number *n*.
The first line contains a pair of integers *n* and *t* (3<=≤<=*n*<=≤<=20, 1<=≤<=*t*<=≤<=10).
Output the required amount of camels with *t* humps.
[ "6 1\n", "4 2\n" ]
[ "6\n", "0\n" ]
In the first sample test sequences of *y*-coordinates for six camels are: 123421, 123431, 123432, 124321, 134321 и 234321 (each digit corresponds to one value of *y*<sub class="lower-index">*i*</sub>).
[ { "input": "6 1", "output": "6" }, { "input": "4 2", "output": "0" }, { "input": "3 1", "output": "14" }, { "input": "3 2", "output": "0" }, { "input": "3 3", "output": "0" }, { "input": "3 10", "output": "0" }, { "input": "4 1", "outpu...
60
0
0
22,548
311
Cats Transport
[ "data structures", "dp" ]
null
null
Zxr960115 is owner of a large farm. He feeds *m* cute cats and employs *p* feeders. There's a straight road across the farm and *n* hills along the road, numbered from 1 to *n* from left to right. The distance between hill *i* and (*i*<=-<=1) is *d**i* meters. The feeders live in hill 1. One day, the cats went out to play. Cat *i* went on a trip to hill *h**i*, finished its trip at time *t**i*, and then waited at hill *h**i* for a feeder. The feeders must take all the cats. Each feeder goes straightly from hill 1 to *n* without waiting at a hill and takes all the waiting cats at each hill away. Feeders walk at a speed of 1 meter per unit time and are strong enough to take as many cats as they want. For example, suppose we have two hills (*d*2<==<=1) and one cat that finished its trip at time 3 at hill 2 (*h*1<==<=2). Then if the feeder leaves hill 1 at time 2 or at time 3, he can take this cat, but if he leaves hill 1 at time 1 he can't take it. If the feeder leaves hill 1 at time 2, the cat waits him for 0 time units, if the feeder leaves hill 1 at time 3, the cat waits him for 1 time units. Your task is to schedule the time leaving from hill 1 for each feeder so that the sum of the waiting time of all cats is minimized.
The first line of the input contains three integers *n*,<=*m*,<=*p* (2<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=105,<=1<=≤<=*p*<=≤<=100). The second line contains *n*<=-<=1 positive integers *d*2,<=*d*3,<=...,<=*d**n* (1<=≤<=*d**i*<=&lt;<=104). Each of the next *m* lines contains two integers *h**i* and *t**i* (1<=≤<=*h**i*<=≤<=*n*,<=0<=≤<=*t**i*<=≤<=109).
Output an integer, the minimum sum of waiting time of all cats. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "4 6 2\n1 3 5\n1 0\n2 1\n4 9\n1 10\n2 10\n3 12\n" ]
[ "3\n" ]
none
[ { "input": "4 6 2\n1 3 5\n1 0\n2 1\n4 9\n1 10\n2 10\n3 12", "output": "3" } ]
78
409,600
0
22,582
796
Police Stations
[ "constructive algorithms", "dfs and similar", "dp", "graphs", "shortest paths", "trees" ]
null
null
Inzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own. Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most *d* kilometers along the roads. There are *n* cities in the country, numbered from 1 to *n*, connected only by exactly *n*<=-<=1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has *k* police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city. However, Zane feels like having as many as *n*<=-<=1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible. Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.
The first line contains three integers *n*, *k*, and *d* (2<=≤<=*n*<=≤<=3·105, 1<=≤<=*k*<=≤<=3·105, 0<=≤<=*d*<=≤<=*n*<=-<=1) — the number of cities, the number of police stations, and the distance limitation in kilometers, respectively. The second line contains *k* integers *p*1,<=*p*2,<=...,<=*p**k* (1<=≤<=*p**i*<=≤<=*n*) — each denoting the city each police station is located in. The *i*-th of the following *n*<=-<=1 lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*) — the cities directly connected by the road with index *i*. It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within *d* kilometers.
In the first line, print one integer *s* that denotes the maximum number of roads that can be shut down. In the second line, print *s* distinct integers, the indices of such roads, in any order. If there are multiple answers, print any of them.
[ "6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6\n", "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6\n" ]
[ "1\n5\n", "2\n4 5 " ]
In the first sample, if you shut down road 5, all cities can still reach a police station within *k* = 4 kilometers. In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line.
[ { "input": "6 2 4\n1 6\n1 2\n2 3\n3 4\n4 5\n5 6", "output": "1\n3 " }, { "input": "6 3 2\n1 5 6\n1 2\n1 3\n1 4\n1 5\n5 6", "output": "2\n4 5 " }, { "input": "10 1 5\n5\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10", "output": "0" }, { "input": "11 1 5\n6\n1 2\n2 3\n3 4\n4 5\n...
2,000
105,472,000
0
22,587
0
none
[ "none" ]
null
null
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is *t*1, and the hot water's temperature is *t*2. The cold water tap can transmit any integer number of water units per second from 0 to *x*1, inclusive. Similarly, the hot water tap can transmit from 0 to *x*2 water units per second. If *y*1 water units per second flow through the first tap and *y*2 water units per second flow through the second tap, then the resulting bath water temperature will be: Bob wants to open both taps so that the bath water temperature was not less than *t*0. However, the temperature should be as close as possible to this value. If there are several optimal variants, Bob chooses the one that lets fill the bath in the quickest way possible. Determine how much each tap should be opened so that Bob was pleased with the result in the end.
You are given five integers *t*1, *t*2, *x*1, *x*2 and *t*0 (1<=≤<=*t*1<=≤<=*t*0<=≤<=*t*2<=≤<=106, 1<=≤<=*x*1,<=*x*2<=≤<=106).
Print two space-separated integers *y*1 and *y*2 (0<=≤<=*y*1<=≤<=*x*1, 0<=≤<=*y*2<=≤<=*x*2).
[ "10 70 100 100 25\n", "300 500 1000 1000 300\n", "143 456 110 117 273\n" ]
[ "99 33", "1000 0", "76 54" ]
In the second sample the hot water tap shouldn't be opened, but the cold water tap should be opened at full capacity in order to fill the bath in the quickest way possible.
[ { "input": "10 70 100 100 25", "output": "99 33" }, { "input": "300 500 1000 1000 300", "output": "1000 0" }, { "input": "143 456 110 117 273", "output": "76 54" }, { "input": "10 20 5 5 13", "output": "4 2" }, { "input": "1 3 1999 3444 2", "output": "1999 199...
216
2,867,200
0
22,609
4
Mysterious Present
[ "dp", "sortings" ]
D. Mysterious Present
1
64
Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes *A*<==<={*a*1,<=<=*a*2,<=<=...,<=<=*a**n*}, where the width and the height of the *i*-th envelope is strictly higher than the width and the height of the (*i*<=<=-<=<=1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.
The first line contains integers *n*, *w*, *h* (1<=<=≤<=*n*<=≤<=5000, 1<=≤<=*w*,<=<=*h*<=<=≤<=106) — amount of envelopes Peter has, the card width and height respectively. Then there follow *n* lines, each of them contains two integer numbers *w**i* and *h**i* — width and height of the *i*-th envelope (1<=≤<=*w**i*,<=<=*h**i*<=≤<=106).
In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.
[ "2 1 1\n2 2\n2 2\n", "3 3 3\n5 4\n12 11\n9 8\n" ]
[ "1\n1 \n", "3\n1 3 2 \n" ]
none
[ { "input": "2 1 1\n2 2\n2 2", "output": "1\n1 " }, { "input": "3 3 3\n5 4\n12 11\n9 8", "output": "3\n1 3 2 " }, { "input": "5 10 10\n22 23\n17 19\n13 17\n8 12\n2 6", "output": "3\n3 2 1 " }, { "input": "5 13 13\n4 4\n10 10\n7 7\n1 1\n13 13", "output": "0" }, { "i...
46
0
0
22,624
118
Caesar's Legions
[ "dp" ]
null
null
Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had *n*1 footmen and *n*2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that *k*1 footmen standing successively one after another, or there are strictly more than *k*2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers. Note that all *n*1<=+<=*n*2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
The only line contains four space-separated integers *n*1, *n*2, *k*1, *k*2 (1<=≤<=*n*1,<=*n*2<=≤<=100,<=1<=≤<=*k*1,<=*k*2<=≤<=10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.
Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than *k*1 footmen stand successively, and no more than *k*2 horsemen stand successively.
[ "2 1 1 10\n", "2 3 1 2\n", "2 4 1 1\n" ]
[ "1\n", "5\n", "0\n" ]
Let's mark a footman as 1, and a horseman as 2. In the first sample the only beautiful line-up is: 121 In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
[ { "input": "2 1 1 10", "output": "1" }, { "input": "2 3 1 2", "output": "5" }, { "input": "2 4 1 1", "output": "0" }, { "input": "10 10 5 7", "output": "173349" }, { "input": "12 15 7 2", "output": "171106" }, { "input": "20 8 4 8", "output": "1625...
154
2,252,800
-1
22,643
756
Nikita and stack
[ "data structures" ]
null
null
Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer *x* on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing. Nikita made *m* operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the *i*-th step he remembers an operation he made *p**i*-th. In other words, he remembers the operations in order of some permutation *p*1,<=*p*2,<=...,<=*p**m*. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!
The first line contains the integer *m* (1<=≤<=*m*<=≤<=105) — the number of operations Nikita made. The next *m* lines contain the operations Nikita remembers. The *i*-th line starts with two integers *p**i* and *t**i* (1<=≤<=*p**i*<=≤<=*m*, *t**i*<==<=0 or *t**i*<==<=1) — the index of operation he remembers on the step *i*, and the type of the operation. *t**i* equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer *x**i* (1<=≤<=*x**i*<=≤<=106) — the integer added to the stack. It is guaranteed that each integer from 1 to *m* is present exactly once among integers *p**i*.
Print *m* integers. The integer *i* should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to *i*. If the stack is empty after performing all these operations, print -1.
[ "2\n2 1 2\n1 0\n", "3\n1 1 2\n2 1 3\n3 0\n", "5\n5 0\n4 0\n3 1 1\n2 1 1\n1 1 2\n" ]
[ "2\n2\n", "2\n3\n2\n", "-1\n-1\n-1\n-1\n2\n" ]
In the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same. In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed. In the third example Nikita remembers the operations in the reversed order.
[]
46
0
0
22,667
600
Make Palindrome
[ "constructive algorithms", "greedy", "strings" ]
null
null
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string *s* consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in *s*. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
The only line contains string *s* (1<=≤<=|*s*|<=≤<=2·105) consisting of only lowercase Latin letters.
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
[ "aabc\n", "aabcd\n" ]
[ "abba\n", "abcba\n" ]
none
[ { "input": "aabc", "output": "abba" }, { "input": "aabcd", "output": "abcba" }, { "input": "u", "output": "u" }, { "input": "ttttt", "output": "ttttt" }, { "input": "xxxvvvxxvv", "output": "vvvxxxxvvv" }, { "input": "wrwrwfrrfrffrrwwwffffwrfrrwfrrfrwwf...
31
307,200
0
22,680
453
Little Pony and Harmony Chest
[ "bitmasks", "brute force", "dp" ]
null
null
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony. A sequence of positive integers *b**i* is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence *b**i* which minimizes the following expression: You are given sequence *a**i*, help Princess Twilight to find the key.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of elements of the sequences *a* and *b*. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=30).
Output the key — sequence *b**i* that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.
[ "5\n1 1 1 1 1\n", "5\n1 6 4 2 8\n" ]
[ "1 1 1 1 1 ", "1 5 3 1 8 " ]
none
[ { "input": "5\n1 1 1 1 1", "output": "1 1 1 1 1 " }, { "input": "5\n1 6 4 2 8", "output": "1 5 3 1 8 " }, { "input": "10\n16 3 16 10 12 5 14 14 15 27", "output": "19 1 17 7 11 1 16 13 15 29 " }, { "input": "10\n8 7 11 5 17 24 28 18 7 8", "output": "9 7 11 5 17 23 29 19 1 ...
202
6,656,000
0
22,724
522
Chicken or Fish?
[ "greedy" ]
null
null
Polycarp is flying in the airplane. Finally, it is his favorite time — the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat *m*, that means, he will be the *m*-th person to get food. The flight menu has *k* dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values *a*1,<=*a*2,<=...,<=*a**k*, where *a**i* is the number of portions of the *i*-th dish. The stewardess has already given food to *m*<=-<=1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the *m*<=-<=1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the *m*<=-<=1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try. Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.
Each test in this problem consists of one or more input sets. First goes a string that contains a single integer *t* (1<=≤<=*t*<=≤<=100<=000) — the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line. The first line of each set of the input contains integers *m*, *k* (2<=≤<=*m*<=≤<=100<=000, 1<=≤<=*k*<=≤<=100<=000) — the number of Polycarp's seat and the number of dishes, respectively. The second line contains a sequence of *k* integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=100<=000), where *a**i* is the initial number of portions of the *i*-th dish. Then *m*<=-<=1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the *j*-th line contains a pair of integers *t**j*,<=*r**j* (0<=≤<=*t**j*<=≤<=*k*,<=0<=≤<=*r**j*<=≤<=1), where *t**j* is the number of the dish that was given to the *j*-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and *r**j* — a 1 or a 0, depending on whether the *j*-th passenger was or wasn't disappointed, respectively. We know that sum *a**i* equals at least *m*, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent. Sum *m* for all input sets doesn't exceed 100<=000. Sum *k* for all input sets doesn't exceed 100<=000.
For each input set print the answer as a single line. Print a string of *k* letters "Y" or "N". Letter "Y" in position *i* should be printed if they could have run out of the *i*-th dish by the time the stewardess started serving Polycarp.
[ "2\n\n3 4\n2 3 2 1\n1 0\n0 0\n\n5 5\n1 2 1 3 1\n3 0\n0 0\n2 1\n4 0\n" ]
[ "YNNY\nYYYNY\n" ]
In the first input set depending on the choice of the second passenger the situation could develop in different ways: - If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish; - If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish; - Otherwise, Polycarp will be able to choose from any of the four dishes. Thus, the answer is "YNNY". In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish. Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY".
[ { "input": "2\n\n3 4\n2 3 2 1\n1 0\n0 0\n\n5 5\n1 2 1 3 1\n3 0\n0 0\n2 1\n4 0", "output": "YNNY\nYYYNY" }, { "input": "4\n\n2 1\n42\n0 0\n\n2 1\n2\n0 0\n\n2 1\n42\n1 0\n\n2 1\n2\n1 0", "output": "N\nN\nN\nN" }, { "input": "5\n\n3 3\n1 1 1\n0 0\n0 1\n\n3 3\n1 1 1\n1 0\n2 1\n\n3 3\n1 1 1\n...
46
0
-1
22,765
0
none
[ "none" ]
null
null
Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters. Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: 1. the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", 1. or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club *x* the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club *x*. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name. Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of clubs in the league. Each of the next *n* lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.
It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print *n* lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.
[ "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW\n", "2\nDINAMO BYTECITY\nDINAMO BITECITY\n", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP\n", "3\nABC DEF\nABC EFG\nABD OOO\n" ]
[ "YES\nDIN\nFOO\n", "NO\n", "YES\nPLM\nPLS\nGOG\n", "YES\nABD\nABE\nABO\n" ]
In the first sample Innokenty can choose first option for both clubs. In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs. In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club. In the fourth example note that it is possible that the chosen short name for some club *x* is the same as the first option of another club *y* if the first options of *x* and *y* are different.
[ { "input": "2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "output": "YES\nDIN\nFOO" }, { "input": "2\nDINAMO BYTECITY\nDINAMO BITECITY", "output": "NO" }, { "input": "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "output": "YES\nPLM\nPLS\nGOG" }, { "input": "3\nABC DEF...
171
23,654,400
0
22,815
755
PolandBall and Gifts
[ "bitmasks", "dp", "greedy" ]
null
null
It's Christmas time! PolandBall and his friends will be giving themselves gifts. There are *n* Balls overall. Each Ball has someone for whom he should bring a present according to some permutation *p*, *p**i*<=≠<=*i* for all *i*. Unfortunately, Balls are quite clumsy. We know earlier that exactly *k* of them will forget to bring their gift. A Ball number *i* will get his present if the following two constraints will hold: 1. Ball number *i* will bring the present he should give. 1. Ball *x* such that *p**x*<==<=*i* will bring his present. What is minimum and maximum possible number of kids who will not get their present if exactly *k* Balls will forget theirs?
The first line of input contains two integers *n* and *k* (2<=≤<=*n*<=≤<=106, 0<=≤<=*k*<=≤<=*n*), representing the number of Balls and the number of Balls who will forget to bring their presents. The second line contains the permutation *p* of integers from 1 to *n*, where *p**i* is the index of Ball who should get a gift from the *i*-th Ball. For all *i*, *p**i*<=≠<=*i* holds.
You should output two values — minimum and maximum possible number of Balls who will not get their presents, in that order.
[ "5 2\n3 4 1 5 2\n", "10 1\n2 3 4 5 6 7 8 9 10 1\n" ]
[ "2 4", "2 2" ]
In the first sample, if the third and the first balls will forget to bring their presents, they will be th only balls not getting a present. Thus the minimum answer is 2. However, if the first ans the second balls will forget to bring their presents, then only the fifth ball will get a present. So, the maximum answer is 4.
[ { "input": "5 2\n3 4 1 5 2", "output": "2 4" }, { "input": "10 1\n2 3 4 5 6 7 8 9 10 1", "output": "2 2" }, { "input": "5 4\n3 1 4 5 2", "output": "5 5" }, { "input": "3 0\n2 3 1", "output": "0 0" }, { "input": "4 3\n2 3 4 1", "output": "4 4" }, { "inp...
0
0
-1
22,887
55
Pie or die
[ "games" ]
C. Pie or die
2
256
Volodya and Vlad play the following game. There are *k* pies at the cells of *n*<=<=×<=<=*m* board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border of the board of length 1 (between two knots of the board) so that Volodya is not able to move the pie outside the board through this edge anymore. The question is: will Volodya win this game? We suppose both players follow the optimal strategy.
First line contains 3 integers, separated by space: 1<=≤<=*n*,<=*m*<=≤<=100 — dimensions of the board and 0<=≤<=*k*<=≤<=100 — the number of pies. Each of the next *k* lines contains 2 integers, separated by space: 1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=*m* — coordinates of the corresponding pie. There could be more than one pie at a cell.
Output only one word: "YES" — if Volodya wins, "NO" — otherwise.
[ "2 2 1\n1 2\n", "3 4 0\n", "100 50 2\n50 25\n50 25\n" ]
[ "YES", "NO", "NO" ]
none
[ { "input": "2 2 1\n1 2", "output": "YES" }, { "input": "3 4 0", "output": "NO" }, { "input": "100 50 2\n50 25\n50 25", "output": "NO" }, { "input": "20 20 4\n10 10\n10 10\n10 10\n10 10", "output": "NO" }, { "input": "15 15 1\n8 8", "output": "NO" }, { ...
122
0
3.9695
22,899
383
Propagating tree
[ "data structures", "dfs and similar", "trees" ]
null
null
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of *n* nodes numbered from 1 to *n*, each node *i* having an initial value *a**i*. The root of the tree is node 1. This tree has a special property: when a value *val* is added to a value of node *i*, the value -*val* is added to values of all the children of node *i*. Note that when you add value -*val* to a child of node *i*, you also add -(-*val*) to all children of the child of node *i* and so on. Look an example explanation to understand better how it works. This tree supports two types of queries: - "1 *x* *val*" — *val* is added to the value of node *x*; - "2 *x*" — print the current value of node *x*. In order to help Iahub understand the tree better, you must answer *m* queries of the preceding type.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=200000). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=1000). Each of the next *n*–1 lines contains two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*), meaning that there is an edge between nodes *v**i* and *u**i*. Each of the next *m* lines contains a query in the format described above. It is guaranteed that the following constraints hold for all queries: 1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*val*<=≤<=1000.
For each query of type two (print the value of node *x*) you must print the answer to the query on a separate line. The queries must be answered in the order given in the input.
[ "5 5\n1 2 1 1 2\n1 2\n1 3\n2 4\n2 5\n1 2 3\n1 1 2\n2 1\n2 2\n2 4\n" ]
[ "3\n3\n0\n" ]
The values of the nodes are [1, 2, 1, 1, 2] at the beginning. Then value 3 is added to node 2. It propagates and value -3 is added to it's sons, node 4 and node 5. Then it cannot propagate any more. So the values of the nodes are [1, 5, 1,  - 2,  - 1]. Then value 2 is added to node 1. It propagates and value -2 is added to it's sons, node 2 and node 3. From node 2 it propagates again, adding value 2 to it's sons, node 4 and node 5. Node 3 has no sons, so it cannot propagate from there. The values of the nodes are [3, 3,  - 1, 0, 1]. You can see all the definitions about the tree at the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory)
[ { "input": "5 5\n1 2 1 1 2\n1 2\n1 3\n2 4\n2 5\n1 2 3\n1 1 2\n2 1\n2 2\n2 4", "output": "3\n3\n0" }, { "input": "10 10\n137 197 856 768 825 894 86 174 218 326\n7 8\n4 7\n8 9\n7 10\n1 2\n2 4\n3 6\n3 5\n2 3\n1 9 624\n2 1\n2 4\n1 6 505\n1 8 467\n1 3 643\n2 1\n1 8 631\n2 4\n1 7 244", "output": "137\...
1,107
130,252,800
3
22,952
868
El Toll Caves
[ "math" ]
null
null
The prehistoric caves of El Toll are located in Moià (Barcelona). You have heard that there is a treasure hidden in one of *n* possible spots in the caves. You assume that each of the spots has probability 1<=/<=*n* to contain a treasure. You cannot get into the caves yourself, so you have constructed a robot that can search the caves for treasure. Each day you can instruct the robot to visit exactly *k* distinct spots in the caves. If none of these spots contain treasure, then the robot will obviously return with empty hands. However, the caves are dark, and the robot may miss the treasure even when visiting the right spot. Formally, if one of the visited spots does contain a treasure, the robot will obtain it with probability 1<=/<=2, otherwise it will return empty. Each time the robot searches the spot with the treasure, his success probability is independent of all previous tries (that is, the probability to miss the treasure after searching the right spot *x* times is 1<=/<=2*x*). What is the expected number of days it will take to obtain the treasure if you choose optimal scheduling for the robot? Output the answer as a rational number modulo 109<=+<=7. Formally, let the answer be an irreducible fraction *P*<=/<=*Q*, then you have to output . It is guaranteed that *Q* is not divisible by 109<=+<=7.
The first line contains the number of test cases *T* (1<=≤<=*T*<=≤<=1000). Each of the next *T* lines contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=5·108).
For each test case output the answer in a separate line.
[ "3\n1 1\n2 1\n3 2\n" ]
[ "2\n500000007\n777777786\n" ]
In the first case the robot will repeatedly search in the only spot. The expected number of days in this case is 2. Note that in spite of the fact that we know the treasure spot from the start, the robot still has to search there until he succesfully recovers the treasure. In the second case the answer can be shown to be equal to 7 / 2 if we search the two spots alternatively. In the third case the answer is 25 / 9.
[]
2,000
7,065,600
0
23,010
776
The Door Problem
[ "2-sat", "dfs and similar", "dsu", "graphs" ]
null
null
Moriarty has trapped *n* people in *n* distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are *m* switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches. You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked. You need to tell Sherlock, if there exists a way to unlock all doors at the same time.
First line of input contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105, 2<=≤<=*m*<=≤<=105) — the number of rooms and the number of switches. Next line contains *n* space-separated integers *r*1,<=*r*2,<=...,<=*r**n* (0<=≤<=*r**i*<=≤<=1) which tell the status of room doors. The *i*-th room is locked if *r**i*<==<=0, otherwise it is unlocked. The *i*-th of next *m* lines contains an integer *x**i* (0<=≤<=*x**i*<=≤<=*n*) followed by *x**i* distinct integers separated by space, denoting the number of rooms controlled by the *i*-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to *n*. It is guaranteed that each door is controlled by exactly two switches.
Output "YES" without quotes, if it is possible to open all doors at the same time, otherwise output "NO" without quotes.
[ "3 3\n1 0 1\n2 1 3\n2 1 2\n2 2 3\n", "3 3\n1 0 1\n3 1 2 3\n1 2\n2 1 3\n", "3 3\n1 0 1\n3 1 2 3\n2 1 2\n1 3\n" ]
[ "NO", "YES", "NO" ]
In the second example input, the initial statuses of the doors are [1, 0, 1] (0 means locked, 1 — unlocked). After toggling switch 3, we get [0, 0, 0] that means all doors are locked. Then, after toggling switch 1, we get [1, 1, 1] that means all doors are unlocked. It can be seen that for the first and for the third example inputs it is not possible to make all doors unlocked.
[ { "input": "3 3\n1 0 1\n2 1 3\n2 1 2\n2 2 3", "output": "NO" }, { "input": "3 3\n1 0 1\n3 1 2 3\n1 2\n2 1 3", "output": "YES" }, { "input": "3 3\n1 0 1\n3 1 2 3\n2 1 2\n1 3", "output": "NO" }, { "input": "11 10\n0 0 1 0 0 0 0 1 1 0 1\n3 2 3 11\n1 3\n2 6 7\n1 5\n1 11\n1 10\n5 ...
733
38,195,200
-1
23,029
825
Five-In-a-Row
[ "brute force", "implementation" ]
null
null
Alice and Bob play 5-in-a-row game. They have a playing field of size 10<=×<=10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts. In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately. Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.
You are given matrix 10<=×<=10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell. It is guaranteed that in the current arrangement nobody has still won.
Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.
[ "XX.XX.....\n.....OOOO.\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n", "XXOXX.....\nOO.O......\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n" ]
[ "YES\n", "NO\n" ]
none
[ { "input": "O.......O.\n.....O.X..\n......O...\n....X.O...\n.O.O.....X\n.XO.....XX\n...X...X.O\n........O.\n........O.\n.X.X.....X", "output": "NO" }, { "input": "....OX....\n..........\n.O..X...X.\nXXO..XO..O\nO.......X.\n...XX.....\n..O.O...OX\n.........X\n.....X..OO\n........O.", "output": "N...
124
0
0
23,074
691
Couple Cover
[ "brute force", "dp", "number theory" ]
null
null
Couple Cover, a wildly popular luck-based game, is about to begin! Two players must work together to construct a rectangle. A bag with *n* balls, each with an integer written on it, is placed on the table. The first player reaches in and grabs a ball randomly (all balls have equal probability of being chosen) — the number written on this ball is the rectangle's width in meters. This ball is not returned to the bag, and the second player reaches into the bag and grabs another ball — the number written on this ball is the rectangle's height in meters. If the area of the rectangle is greater than or equal some threshold *p* square meters, the players win. Otherwise, they lose. The organizers of the game are trying to select an appropriate value for *p* so that the probability of a couple winning is not too high and not too low, but they are slow at counting, so they have hired you to answer some questions for them. You are given a list of the numbers written on the balls, the organizers would like to know how many winning pairs of balls exist for different values of *p*. Note that two pairs are different if either the first or the second ball is different between the two in pair, and two different balls with the same number are considered different.
The input begins with a single positive integer *n* in its own line (1<=≤<=*n*<=≤<=106). The second line contains *n* positive integers — the *i*-th number in this line is equal to *a**i* (1<=≤<=*a**i*<=≤<=3·106), the number written on the *i*-th ball. The next line contains an integer *m* (1<=≤<=*m*<=≤<=106), the number of questions you are being asked. Then, the following line contains *m* positive integers — the *j*-th number in this line is equal to the value of *p* (1<=≤<=*p*<=≤<=3·106) in the *j*-th question you are being asked.
For each question, print the number of winning pairs of balls that exist for the given value of *p* in the separate line.
[ "5\n4 2 6 1 3\n4\n1 3 5 8\n", "2\n5 6\n2\n30 31\n" ]
[ "20\n18\n14\n10\n", "2\n0\n" ]
none
[ { "input": "5\n4 2 6 1 3\n4\n1 3 5 8", "output": "20\n18\n14\n10" }, { "input": "2\n5 6\n2\n30 31", "output": "2\n0" }, { "input": "2\n2000000 2000000\n1\n2000000", "output": "2" }, { "input": "1\n1\n1\n5", "output": "0" }, { "input": "10\n18 34 3 49 40 50 53 30 2...
46
0
0
23,089
707
Bakery
[ "graphs" ]
null
null
Masha wants to open her own bakery and bake muffins in one of the *n* cities numbered from 1 to *n*. There are *m* bidirectional roads, each of whose connects some pair of cities. To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only *k* storages, located in different cities numbered *a*1,<=*a*2,<=...,<=*a**k*. Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another *n*<=-<=*k* cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble. Formally, Masha will pay *x* roubles, if she will open the bakery in some city *b* (*a**i*<=≠<=*b* for every 1<=≤<=*i*<=≤<=*k*) and choose a storage in some city *s* (*s*<==<=*a**j* for some 1<=≤<=*j*<=≤<=*k*) and *b* and *s* are connected by some path of roads of summary length *x* (if there are more than one path, Masha is able to choose which of them should be used). Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of *k* storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.
The first line of the input contains three integers *n*, *m* and *k* (1<=≤<=*n*,<=*m*<=≤<=105, 0<=≤<=*k*<=≤<=*n*) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then *m* lines follow. Each of them contains three integers *u*, *v* and *l* (1<=≤<=*u*,<=*v*<=≤<=*n*, 1<=≤<=*l*<=≤<=109, *u*<=≠<=*v*) meaning that there is a road between cities *u* and *v* of length of *l* kilometers . If *k*<=&gt;<=0, then the last line of the input contains *k* distinct integers *a*1,<=*a*2,<=...,<=*a**k* (1<=≤<=*a**i*<=≤<=*n*) — the number of cities having flour storage located in. If *k*<==<=0 then this line is not presented in the input.
Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the *n* cities, print <=-<=1 in the only line.
[ "5 4 2\n1 2 5\n1 2 3\n2 3 4\n1 4 10\n1 5\n", "3 1 1\n1 2 3\n3\n" ]
[ "3", "-1" ]
Image illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.
[ { "input": "5 4 2\n1 2 5\n1 2 3\n2 3 4\n1 4 10\n1 5", "output": "3" }, { "input": "3 1 1\n1 2 3\n3", "output": "-1" }, { "input": "2 3 1\n1 2 3\n1 2 18\n1 2 13\n2", "output": "3" }, { "input": "3 7 0\n1 3 9\n1 2 5\n1 2 21\n1 2 12\n1 2 13\n2 3 19\n2 3 8", "output": "-1" ...
46
134,860,800
0
23,141
69
Dot
[ "dp", "games" ]
D. Dot
3
256
Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules: - On the checkered paper a coordinate system is drawn. A dot is initially put in the position (*x*,<=*y*). - A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line *y*<==<=*x*. - Anton and Dasha take turns. Anton goes first. - The player after whose move the distance from the dot to the coordinates' origin exceeds *d*, loses. Help them to determine the winner.
The first line of the input file contains 4 integers *x*, *y*, *n*, *d* (<=-<=200<=≤<=*x*,<=*y*<=≤<=200,<=1<=≤<=*d*<=≤<=200,<=1<=≤<=*n*<=≤<=20) — the initial coordinates of the dot, the distance *d* and the number of vectors. It is guaranteed that the initial dot is at the distance less than *d* from the origin of the coordinates. The following *n* lines each contain two non-negative numbers *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=200) — the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different.
You should print "Anton", if the winner is Anton in case of both players play the game optimally, and "Dasha" otherwise.
[ "0 0 2 3\n1 1\n1 2\n", "0 0 2 4\n1 1\n1 2\n" ]
[ "Anton", "Dasha" ]
In the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move — to reflect relatively to the line *y* = *x*. Dasha will respond to it with the same move and return the dot in position (2;3).
[ { "input": "0 0 2 3\n1 1\n1 2", "output": "Anton" }, { "input": "0 0 2 4\n1 1\n1 2", "output": "Dasha" }, { "input": "0 0 5 100\n12 105\n15 59\n21 1\n27 6\n27 76", "output": "Anton" }, { "input": "0 0 5 100\n16 24\n29 6\n44 24\n66 37\n102 19", "output": "Anton" }, { ...
872
22,220,800
3.813277
23,160
0
none
[ "none" ]
null
null
For each string *s* consisting of characters '0' and '1' one can define four integers *a*00, *a*01, *a*10 and *a*11, where *a**xy* is the number of subsequences of length 2 of the string *s* equal to the sequence {*x*,<=*y*}. In these problem you are given four integers *a*00, *a*01, *a*10, *a*11 and have to find any non-empty string *s* that matches them, or determine that there is no such string. One can prove that if at least one answer exists, there exists an answer of length no more than 1<=000<=000.
The only line of the input contains four non-negative integers *a*00, *a*01, *a*10 and *a*11. Each of them doesn't exceed 109.
If there exists a non-empty string that matches four integers from the input, print it in the only line of the output. Otherwise, print "Impossible". The length of your answer must not exceed 1<=000<=000.
[ "1 2 3 4\n", "1 2 2 1\n" ]
[ "Impossible\n", "0110\n" ]
none
[ { "input": "1 2 3 4", "output": "Impossible" }, { "input": "1 2 2 1", "output": "0110" }, { "input": "10 7 28 21", "output": "011111110000" }, { "input": "0 0 0 0", "output": "0" }, { "input": "499928010 820999488 178951395 499991253", "output": "0000000000000...
31
0
0
23,176
225
Unsolvable
[ "math", "number theory" ]
null
null
Consider the following equation: Let's find all integer *z* (*z*<=&gt;<=0), for which this equation is unsolvable in positive integers. The phrase "unsolvable in positive integers" means that there are no such positive integers *x* and *y* (*x*,<=*y*<=&gt;<=0), for which the given above equation holds. Let's write out all such *z* in the increasing order: *z*1,<=*z*2,<=*z*3, and so on (*z**i*<=&lt;<=*z**i*<=+<=1). Your task is: given the number *n*, find the number *z**n*.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=40).
Print a single integer — the number *z**n* modulo 1000000007 (109<=+<=7). It is guaranteed that the answer exists.
[ "1\n", "2\n", "3\n" ]
[ "1", "3", "15" ]
none
[ { "input": "1", "output": "1" }, { "input": "2", "output": "3" }, { "input": "3", "output": "15" }, { "input": "4", "output": "63" }, { "input": "5", "output": "4095" }, { "input": "6", "output": "65535" }, { "input": "7", "output": "26...
248
0
0
23,197
732
Cormen --- The Best Friend Of a Man
[ "dp", "greedy" ]
null
null
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 for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next *n* days and made a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the number of times Polycarp will walk with the dog on the *i*-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.). Help Polycarp determine the minimum number of walks he needs to do additionaly in the next *n* days so that Cormen will feel good during all the *n* days. You can assume that on the day before the first day and on the day after the *n*-th day Polycarp will go for a walk with Cormen exactly *k* times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers *b*1,<=*b*2,<=...,<=*b**n* (*b**i*<=≥<=*a**i*), where *b**i* means the total number of walks with the dog on the *i*-th day.
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=500) — the number of days and the minimum number of walks with Cormen for any two consecutive days. The second line contains integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=500) — the number of walks with Cormen on the *i*-th day which Polycarp has already planned.
In the first line print the smallest number of additional walks that Polycarp should do during the next *n* days so that Cormen will feel good during all days. In the second line print *n* integers *b*1,<=*b*2,<=...,<=*b**n*, where *b**i* — the total number of walks on the *i*-th day according to the found solutions (*a**i*<=≤<=*b**i* for all *i* from 1 to *n*). If there are multiple solutions, print any of them.
[ "3 5\n2 0 1\n", "3 1\n0 0 0\n", "4 6\n2 4 3 5\n" ]
[ "4\n2 3 2\n", "1\n0 1 0\n", "0\n2 4 3 5\n" ]
none
[ { "input": "3 5\n2 0 1", "output": "4\n2 3 2" }, { "input": "3 1\n0 0 0", "output": "1\n0 1 0" }, { "input": "4 6\n2 4 3 5", "output": "0\n2 4 3 5" }, { "input": "5 1\n0 0 0 0 1", "output": "2\n0 1 0 1 1" }, { "input": "10 500\n164 44 238 205 373 249 87 30 239 90"...
62
0
3
23,202
413
Jeopardy!
[ "greedy", "math" ]
null
null
'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 questions and *n*<=-<=*m* of them are regular questions. Each question has a price. The price of the *i*-th question is *a**i* points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price. The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again. All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100; *m*<=≤<=*min*(*n*,<=30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=107) — the prices of the questions. The third line contains *m* distinct integers *b**i* (1<=≤<=*b**i*<=≤<=*n*) — the numbers of auction questions. Assume that the questions are numbered from 1 to *n*.
In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.
[ "4 1\n1 3 7 5\n3\n", "3 2\n10 3 8\n2 3\n", "2 2\n100 200\n1 2\n" ]
[ "18\n", "40\n", "400\n" ]
none
[ { "input": "4 1\n1 3 7 5\n3", "output": "18" }, { "input": "3 2\n10 3 8\n2 3", "output": "40" }, { "input": "2 2\n100 200\n1 2", "output": "400" }, { "input": "1 1\n1\n1", "output": "1" }, { "input": "2 2\n1 5\n1 2", "output": "10" }, { "input": "5 3\n...
62
0
0
23,214
309
Memory for Arrays
[ "binary search", "bitmasks", "greedy" ]
null
null
You get to work and turn on the computer. You start coding and give little thought to the RAM role in the whole process. In this problem your task is to solve one of the problems you encounter in your computer routine. We'll consider the RAM as a sequence of cells that can contain data. Some cells already contain some data, some are empty. The empty cells form the so-called memory clusters. Thus, a memory cluster is a sequence of some consecutive empty memory cells. You have exactly *n* memory clusters, the *i*-th cluster consists of *a**i* cells. You need to find memory for *m* arrays in your program. The *j*-th array takes 2*b**j* consecutive memory cells. There possibly isn't enough memory for all *m* arrays, so your task is to determine what maximum number of arrays can be located in the available memory clusters. Of course, the arrays cannot be divided between the memory clusters. Also, no cell can belong to two arrays.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=106). The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). The next line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=2*b**i*<=≤<=109).
Print a single integer — the answer to the problem.
[ "5 3\n8 4 3 2 2\n3 2 2\n", "10 6\n1 1 1 1 1 1 1 1 1 1\n0 0 0 0 0 0\n" ]
[ "2\n", "6\n" ]
In the first example you are given memory clusters with sizes 8, 4, 3, 2, 2 and arrays with sizes 8, 4, 4. There are few ways to obtain an answer equals 2: you can locate array with size 8 to the cluster with size 8, and one of the arrays with size 4 to the cluster with size 4. Another way is to locate two arrays with size 4 to the one cluster with size 8. In the second example you are given 10 memory clusters with size 1 and 6 arrays with size 1. You can choose any 6 clusters and locate all given arrays to them.
[ { "input": "5 3\n8 4 3 2 2\n3 2 2", "output": "2" }, { "input": "10 6\n1 1 1 1 1 1 1 1 1 1\n0 0 0 0 0 0", "output": "6" }, { "input": "5 10\n4 4 3 3 3\n0 0 0 0 0 2 0 2 0 0", "output": "10" }, { "input": "5 10\n3 4 5 4 3\n1 2 1 0 1 2 1 0 2 0", "output": "9" }, { "i...
1,154
108,236,800
0
23,282
813
Bipartite Checking
[ "data structures", "dsu", "graphs" ]
null
null
You are given an undirected graph consisting of *n* vertices. Initially there are no edges in the graph. Also you are given *q* queries, each query either adds one undirected edge to the graph or removes it. After each query you have to check if the resulting graph is bipartite (that is, you can paint all vertices of the graph into two colors so that there is no edge connecting two vertices of the same color).
The first line contains two integers *n* and *q* (2<=≤<=*n*,<=*q*<=≤<=100000). Then *q* lines follow. *i*th line contains two numbers *x**i* and *y**i* (1<=≤<=*x**i*<=&lt;<=*y**i*<=≤<=*n*). These numbers describe *i*th query: if there is an edge between vertices *x**i* and *y**i*, then remove it, otherwise add it.
Print *q* lines. *i*th line must contain YES if the graph is bipartite after *i*th query, and NO otherwise.
[ "3 5\n2 3\n1 3\n1 2\n1 2\n1 2\n" ]
[ "YES\nYES\nNO\nYES\nNO\n" ]
none
[ { "input": "3 5\n2 3\n1 3\n1 2\n1 2\n1 2", "output": "YES\nYES\nNO\nYES\nNO" }, { "input": "5 10\n1 5\n2 5\n2 4\n1 4\n4 5\n2 4\n2 5\n1 4\n2 3\n1 2", "output": "YES\nYES\nYES\nYES\nNO\nNO\nNO\nYES\nYES\nYES" }, { "input": "10 20\n1 10\n5 7\n1 2\n3 5\n3 6\n4 9\n3 4\n6 9\n4 8\n6 9\n7 8\n3 8...
46
204,800
-1
23,292
731
Socks
[ "dfs and similar", "dsu", "graphs", "greedy" ]
null
null
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 clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's *n* socks is assigned a unique integer from 1 to *n*. Thus, the only thing his mother had to do was to write down two integers *l**i* and *r**i* for each of the days — the indices of socks to wear on the day *i* (obviously, *l**i* stands for the left foot and *r**i* for the right). Each sock is painted in one of *k* colors. When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses *k* jars with the paint — one for each of *k* colors. Arseniy wants to repaint some of the socks in such a way, that for each of *m* days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now. The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of *m* days.
The first line of input contains three integers *n*, *m* and *k* (2<=≤<=*n*<=≤<=200<=000, 0<=≤<=*m*<=≤<=200<=000, 1<=≤<=*k*<=≤<=200<=000) — the number of socks, the number of days and the number of available colors respectively. The second line contain *n* integers *c*1, *c*2, ..., *c**n* (1<=≤<=*c**i*<=≤<=*k*) — current colors of Arseniy's socks. Each of the following *m* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*,<=*r**i*<=≤<=*n*, *l**i*<=≠<=*r**i*) — indices of socks which Arseniy should wear during the *i*-th day.
Print one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.
[ "3 2 3\n1 2 3\n1 2\n2 3\n", "3 2 2\n1 1 2\n1 2\n2 1\n" ]
[ "2\n", "0\n" ]
In the first sample, Arseniy can repaint the first and the third socks to the second color. In the second sample, there is no need to change any colors.
[ { "input": "3 2 3\n1 2 3\n1 2\n2 3", "output": "2" }, { "input": "3 2 2\n1 1 2\n1 2\n2 1", "output": "0" }, { "input": "3 3 3\n1 2 3\n1 2\n2 3\n3 1", "output": "2" }, { "input": "4 2 4\n1 2 3 4\n1 2\n3 4", "output": "2" }, { "input": "10 3 2\n2 1 1 2 1 1 2 1 2 2\n...
2,000
89,907,200
0
23,325
183
Zoo
[ "brute force", "geometry" ]
null
null
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has *n* observation binoculars located at the *OX* axis. For each *i* between 1 and *n*, inclusive, there exists a single binocular located at the point with coordinates (*i*,<=0). There are *m* flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move. In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line. Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=106,<=1<=≤<=*m*<=≤<=250), denoting the number of binoculars and the number of flamingos, respectively. Then *m* lines follow, the *i*-th line will contain two space-separated integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=109), which means that the *i*-th flamingo is located at point (*x**i*,<=*y**i*). All flamingos will be located at distinct points.
Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.
[ "5 5\n2 1\n4 1\n3 2\n4 3\n4 4\n" ]
[ "11\n" ]
This picture shows the answer to the example test case.
[ { "input": "5 5\n2 1\n4 1\n3 2\n4 3\n4 4", "output": "11" }, { "input": "3 3\n1 1\n2 10\n3 100", "output": "3" }, { "input": "1 2\n450000001 500000000\n900000001 1000000000", "output": "2" }, { "input": "3 6\n1 1\n1 2\n1 3\n2 1\n2 2\n3 1", "output": "7" }, { "inpu...
92
307,200
0
23,355
859
Desk Disorder
[ "combinatorics", "dfs and similar", "dsu", "graphs", "trees" ]
null
null
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement. How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007<==<=109<=+<=7.
Input will begin with a line containing *N* (1<=≤<=*N*<=≤<=100000), the number of engineers. *N* lines follow, each containing exactly two integers. The *i*-th line contains the number of the current desk of the *i*-th engineer and the number of the desk the *i*-th engineer wants to move to. Desks are numbered from 1 to 2·*N*. It is guaranteed that no two engineers sit at the same desk.
Print the number of possible assignments, modulo 1000000007<==<=109<=+<=7.
[ "4\n1 5\n5 2\n3 7\n7 3\n", "5\n1 10\n2 10\n3 10\n4 10\n5 5\n" ]
[ "6\n", "5\n" ]
These are the possible assignments for the first example: - 1 5 3 7 - 1 2 3 7 - 5 2 3 7 - 1 5 7 3 - 1 2 7 3 - 5 2 7 3
[ { "input": "4\n1 5\n5 2\n3 7\n7 3", "output": "6" }, { "input": "5\n1 10\n2 10\n3 10\n4 10\n5 5", "output": "5" }, { "input": "1\n1 2", "output": "2" }, { "input": "30\n22 37\n12 37\n37 58\n29 57\n43 57\n57 58\n58 53\n45 4\n1 4\n4 51\n35 31\n21 31\n31 51\n51 53\n53 48\n60 55\...
93
4,710,400
0
23,503
986
Fair
[ "graphs", "greedy", "number theory", "shortest paths" ]
null
null
Some company is going to hold a fair in Byteland. There are $n$ towns in Byteland and $m$ two-way roads between towns. Of course, you can reach any town from any other town using roads. There are $k$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $s$ different types of goods. It costs $d(u,v)$ coins to bring goods from town $u$ to town $v$ where $d(u,v)$ is the length of the shortest path from $u$ to $v$. Length of a path is the number of roads in this path. The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $n$ towns.
There are $4$ integers $n$, $m$, $k$, $s$ in the first line of input ($1 \le n \le 10^{5}$, $0 \le m \le 10^{5}$, $1 \le s \le k \le min(n, 100)$) — the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair. In the next line there are $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_{i} \le k$), where $a_i$ is the type of goods produced in the $i$-th town. It is guaranteed that all integers between $1$ and $k$ occur at least once among integers $a_{i}$. In the next $m$ lines roads are described. Each road is described by two integers $u$ $v$ ($1 \le u, v \le n$, $u \ne v$) — the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads.
Print $n$ numbers, the $i$-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town $i$. Separate numbers with spaces.
[ "5 5 4 3\n1 2 4 3 2\n1 2\n2 3\n3 4\n4 1\n4 5\n", "7 6 3 2\n1 2 3 3 2 2 1\n1 2\n2 3\n3 4\n2 5\n5 6\n6 7\n" ]
[ "2 2 2 2 3 \n", "1 1 1 2 2 1 1 \n" ]
Let's look at the first sample. To hold a fair in town $1$ you can bring goods from towns $1$ ($0$ coins), $2$ ($1$ coin) and $4$ ($1$ coin). Total numbers of coins is $2$. Town $2$: Goods from towns $2$ ($0$), $1$ ($1$), $3$ ($1$). Sum equals $2$. Town $3$: Goods from towns $3$ ($0$), $2$ ($1$), $4$ ($1$). Sum equals $2$. Town $4$: Goods from towns $4$ ($0$), $1$ ($1$), $5$ ($1$). Sum equals $2$. Town $5$: Goods from towns $5$ ($0$), $4$ ($1$), $3$ ($2$). Sum equals $3$.
[]
2,000
93,900,800
0
23,512
264
Choosing Balls
[ "dp" ]
null
null
There are *n* balls. They are arranged in a row. Each ball has a color (for convenience an integer) and an integer value. The color of the *i*-th ball is *c**i* and the value of the *i*-th ball is *v**i*. Squirrel Liss chooses some balls and makes a new sequence without changing the relative order of the balls. She wants to maximize the value of this sequence. The value of the sequence is defined as the sum of following values for each ball (where *a* and *b* are given constants): - If the ball is not in the beginning of the sequence and the color of the ball is same as previous ball's color, add (the value of the ball) <=×<= *a*. - Otherwise, add (the value of the ball) <=×<= *b*. You are given *q* queries. Each query contains two integers *a**i* and *b**i*. For each query find the maximal value of the sequence she can make when *a*<==<=*a**i* and *b*<==<=*b**i*. Note that the new sequence can be empty, and the value of an empty sequence is defined as zero.
The first line contains two integers *n* and *q* (1<=≤<=*n*<=≤<=105; 1<=≤<=*q*<=≤<=500). The second line contains *n* integers: *v*1,<=*v*2,<=...,<=*v**n* (|*v**i*|<=≤<=105). The third line contains *n* integers: *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=*n*). The following *q* lines contain the values of the constants *a* and *b* for queries. The *i*-th of these lines contains two integers *a**i* and *b**i* (|*a**i*|,<=|*b**i*|<=≤<=105). In each line integers are separated by single spaces.
For each query, output a line containing an integer — the answer to the query. The *i*-th line contains the answer to the *i*-th query in the input order. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "6 3\n1 -2 3 4 0 -1\n1 2 1 2 1 1\n5 1\n-2 1\n1 0\n", "4 1\n-3 6 -1 2\n1 2 3 1\n1 -1\n" ]
[ "20\n9\n4\n", "5\n" ]
In the first example, to achieve the maximal value: - In the first query, you should select 1st, 3rd, and 4th ball. - In the second query, you should select 3rd, 4th, 5th and 6th ball. - In the third query, you should select 2nd and 4th ball. Note that there may be other ways to achieve the maximal value.
[]
124
4,812,800
0
23,513
10
Digital Root
[ "number theory" ]
C. Digital Root
2
256
Not long ago Billy came across such a problem, where there were given three natural numbers *A*, *B* and *C* from the range [1,<=*N*], and it was asked to check whether the equation *AB*<==<=*C* is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root *d*(*x*) of the number *x* is the sum *s*(*x*) of all the digits of this number, if *s*(*x*)<=≤<=9, otherwise it is *d*(*s*(*x*)). For example, a digital root of the number 6543 is calculated as follows: *d*(6543)<==<=*d*(6<=+<=5<=+<=4<=+<=3)<==<=*d*(18)<==<=9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. *d*(*xy*)<==<=*d*(*d*(*x*)*d*(*y*)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.
The first line contains the only number *N* (1<=≤<=*N*<=≤<=106).
Output one number — the amount of required *A*, *B* and *C* from the range [1,<=*N*].
[ "4\n", "5\n" ]
[ "2\n", "6\n" ]
For the first sample the required triples are (3, 4, 3) and (4, 3, 3).
[ { "input": "4", "output": "2" }, { "input": "5", "output": "6" }, { "input": "6", "output": "14" }, { "input": "7", "output": "25" }, { "input": "1", "output": "0" }, { "input": "8", "output": "40" }, { "input": "10", "output": "82" }...
218
1,433,600
3.94283
23,582
388
Fox and Card Game
[ "games", "greedy", "sortings" ]
null
null
Fox Ciel is playing a card game with her friend Fox Jiro. There are *n* piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom of any non-empty pile. Each player wants to maximize the total sum of the cards he took. The game ends when all piles become empty. Suppose Ciel and Jiro play optimally, what is the score of the game?
The first line contain an integer *n* (1<=≤<=*n*<=≤<=100). Each of the next *n* lines contains a description of the pile: the first integer in the line is *s**i* (1<=≤<=*s**i*<=≤<=100) — the number of cards in the *i*-th pile; then follow *s**i* positive integers *c*1, *c*2, ..., *c**k*, ..., *c**s**i* (1<=≤<=*c**k*<=≤<=1000) — the sequence of the numbers on the cards listed from top of the current pile to bottom of the pile.
Print two integers: the sum of Ciel's cards and the sum of Jiro's cards if they play optimally.
[ "2\n1 100\n2 1 10\n", "1\n9 2 8 6 5 9 4 7 1 3\n", "3\n3 1 3 2\n3 5 4 6\n2 8 7\n", "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000\n" ]
[ "101 10\n", "30 15\n", "18 18\n", "7000 7000\n" ]
In the first example, Ciel will take the cards with number 100 and 1, Jiro will take the card with number 10. In the second example, Ciel will take cards with numbers 2, 8, 6, 5, 9 and Jiro will take cards with numbers 4, 7, 1, 3.
[ { "input": "2\n1 100\n2 1 10", "output": "101 10" }, { "input": "1\n9 2 8 6 5 9 4 7 1 3", "output": "30 15" }, { "input": "3\n3 1 3 2\n3 5 4 6\n2 8 7", "output": "18 18" }, { "input": "3\n3 1000 1000 1000\n6 1000 1000 1000 1000 1000 1000\n5 1000 1000 1000 1000 1000", "out...
0
0
-1
23,588
392
Blocked Points
[ "math" ]
null
null
Imagine you have an infinite 2D plane with Cartesian coordinate system. Some of the integral points are blocked, and others are not. Two integral points *A* and *B* on the plane are 4-connected if and only if: - the Euclidean distance between *A* and *B* is one unit and neither *A* nor *B* is blocked; - or there is some integral point *C*, such that *A* is 4-connected with *C*, and *C* is 4-connected with *B*. Let's assume that the plane doesn't contain blocked points. Consider all the integral points of the plane whose Euclidean distance from the origin is no more than *n*, we'll name these points special. Chubby Yang wants to get the following property: no special point is 4-connected to some non-special point. To get the property she can pick some integral points of the plane and make them blocked. What is the minimum number of points she needs to pick?
The first line contains an integer *n* (0<=≤<=*n*<=≤<=4·107).
Print a single integer — the minimum number of points that should be blocked.
[ "1\n", "2\n", "3\n" ]
[ "4\n", "8\n", "16\n" ]
none
[ { "input": "1", "output": "4" }, { "input": "2", "output": "8" }, { "input": "3", "output": "16" }, { "input": "4", "output": "20" }, { "input": "0", "output": "1" }, { "input": "30426905", "output": "172120564" }, { "input": "38450759", ...
109
0
0
23,613
215
Periodical Numbers
[ "combinatorics", "dp", "number theory" ]
null
null
A non-empty string *s* is called binary, if it consists only of characters "0" and "1". Let's number the characters of binary string *s* from 1 to the string's length and let's denote the *i*-th character in string *s* as *s**i*. Binary string *s* with length *n* is periodical, if there is an integer 1<=≤<=*k*<=&lt;<=*n* such that: - *k* is a divisor of number *n* - for all 1<=≤<=*i*<=≤<=*n*<=-<=*k*, the following condition fulfills: *s**i*<==<=*s**i*<=+<=*k* For example, binary strings "101010" and "11" are periodical and "10" and "10010" are not. A positive integer *x* is periodical, if its binary representation (without leading zeroes) is a periodic string. Your task is to calculate, how many periodic numbers are in the interval from *l* to *r* (both ends are included).
The single input line contains two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=1018). The numbers are separated by a space. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Print a single integer, showing how many periodic numbers are in the interval from *l* to *r* (both ends are included).
[ "1 10\n", "25 38\n" ]
[ "3\n", "2\n" ]
In the first sample periodic numbers are 3, 7 and 10. In the second sample periodic numbers are 31 and 36.
[ { "input": "1 10", "output": "3" }, { "input": "25 38", "output": "2" }, { "input": "7 9", "output": "1" }, { "input": "12 20", "output": "1" }, { "input": "7 49", "output": "7" }, { "input": "28 97", "output": "6" }, { "input": "65 72", ...
92
0
-1
23,615
814
An overnight dance in discotheque
[ "dfs and similar", "dp", "geometry", "greedy", "trees" ]
null
null
The crowdedness of the discotheque would never stop our friends from having fun, but a bit more spaciousness won't hurt, will it? The discotheque can be seen as an infinite *xy*-plane, in which there are a total of *n* dancers. Once someone starts moving around, they will move only inside their own movement range, which is a circular area *C**i* described by a center (*x**i*,<=*y**i*) and a radius *r**i*. No two ranges' borders have more than one common point, that is for every pair (*i*,<=*j*) (1<=≤<=*i*<=&lt;<=*j*<=≤<=*n*) either ranges *C**i* and *C**j* are disjoint, or one of them is a subset of the other. Note that it's possible that two ranges' borders share a single common point, but no two dancers have exactly the same ranges. Tsukihi, being one of them, defines the spaciousness to be the area covered by an odd number of movement ranges of dancers who are moving. An example is shown below, with shaded regions representing the spaciousness if everyone moves at the same time. But no one keeps moving for the whole night after all, so the whole night's time is divided into two halves — before midnight and after midnight. Every dancer moves around in one half, while sitting down with friends in the other. The spaciousness of two halves are calculated separately and their sum should, of course, be as large as possible. The following figure shows an optimal solution to the example above. By different plans of who dances in the first half and who does in the other, different sums of spaciousness over two halves are achieved. You are to find the largest achievable value of this sum.
The first line of input contains a positive integer *n* (1<=≤<=*n*<=≤<=1<=000) — the number of dancers. The following *n* lines each describes a dancer: the *i*-th line among them contains three space-separated integers *x**i*, *y**i* and *r**i* (<=-<=106<=≤<=*x**i*,<=*y**i*<=≤<=106, 1<=≤<=*r**i*<=≤<=106), describing a circular movement range centered at (*x**i*,<=*y**i*) with radius *r**i*.
Output one decimal number — the largest achievable sum of spaciousness over two halves of the night. The output is considered correct if it has a relative or absolute error of at most 10<=-<=9. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if .
[ "5\n2 1 6\n0 4 1\n2 -1 3\n1 -2 1\n4 -1 1\n", "8\n0 0 1\n0 0 2\n0 0 3\n0 0 4\n0 0 5\n0 0 6\n0 0 7\n0 0 8\n" ]
[ "138.23007676\n", "289.02652413\n" ]
The first sample corresponds to the illustrations in the legend.
[ { "input": "5\n2 1 6\n0 4 1\n2 -1 3\n1 -2 1\n4 -1 1", "output": "138.23007676" }, { "input": "8\n0 0 1\n0 0 2\n0 0 3\n0 0 4\n0 0 5\n0 0 6\n0 0 7\n0 0 8", "output": "289.02652413" }, { "input": "4\n1000000 -1000000 2\n1000000 -1000000 3\n-1000000 1000000 2\n-1000000 1000000 1000000", ...
920
6,144,000
3
23,684
301
Yaroslav and Divisors
[ "data structures" ]
null
null
Yaroslav has an array *p*<==<=*p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*), consisting of *n* distinct integers. Also, he has *m* queries: - Query number *i* is represented as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The answer to the query *l**i*,<=*r**i* is the number of pairs of integers *q*, *w* (*l**i*<=≤<=*q*,<=*w*<=≤<=*r**i*) such that *p**q* is the divisor of *p**w*. Help Yaroslav, answer all his queries.
The first line contains the integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105). The second line contains *n* distinct integers *p*1,<=*p*2,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*n*). The following *m* lines contain Yaroslav's queries. The *i*-th line contains integers *l**i*,<=*r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*).
Print *m* integers — the answers to Yaroslav's queries in the order they appear in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "1 1\n1\n1 1\n", "10 9\n1 2 3 4 5 6 7 8 9 10\n1 10\n2 9\n3 8\n4 7\n5 6\n2 2\n9 10\n5 10\n4 10\n" ]
[ "1\n", "27\n14\n8\n4\n2\n1\n2\n7\n9\n" ]
none
[]
248
0
0
23,692
190
Counter Attack
[ "data structures", "dsu", "graphs", "hashing", "sortings" ]
null
null
Berland has managed to repel the flatlanders' attack and is now starting the counter attack. Flatland has *n* cities, numbered from 1 to *n*, and some pairs of them are connected by bidirectional roads. The Flatlandian maps show roads between cities if and only if there is in fact no road between this pair of cities (we do not know whether is it a clever spy-proof strategy or just saving ink). In other words, if two cities are connected by a road on a flatland map, then there is in fact no road between them. The opposite situation is also true: if two cities are not connected by a road on a flatland map, then in fact, there is a road between them. The berlanders got hold of a flatland map. Now Vasya the Corporal is commissioned by General Touristov to find all such groups of flatland cities, that in each group of cities you can get from any city to any other one, moving along the actual roads. Also the cities from different groups are unreachable from each other, moving along the actual roads. Indeed, destroying such groups one by one is much easier than surrounding all Flatland at once! Help the corporal complete this task and finally become a sergeant! Don't forget that a flatland map shows a road between cities if and only if there is in fact no road between them.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=5·105,<=0<=≤<=*m*<=≤<=106) — the number of cities and the number of roads marked on the flatland map, correspondingly. Next *m* lines contain descriptions of the cities on the map. The *i*-th line contains two integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*,<=*a**i*<=≠<=*b**i*) — the numbers of cities that are connected by the *i*-th road on the flatland map. It is guaranteed that each pair of cities occurs in the input no more than once.
On the first line print number *k* — the number of groups of cities in Flatland, such that in each group you can get from any city to any other one by flatland roads. At the same time, the cities from different groups should be unreachable by flatland roads. On each of the following *k* lines first print *t**i* (1<=≤<=*t**i*<=≤<=*n*) — the number of vertexes in the *i*-th group. Then print space-separated numbers of cities in the *i*-th group. The order of printing groups and the order of printing numbers in the groups does not matter. The total sum *t**i* for all *k* groups must equal *n*.
[ "4 4\n1 2\n1 3\n4 2\n4 3\n", "3 1\n1 2\n" ]
[ "2\n2 1 4 \n2 2 3 \n", "1\n3 1 2 3 \n" ]
In the first sample there are roads only between pairs of cities 1-4 and 2-3. In the second sample there is no road between cities 1 and 2, but still you can get from one city to the other one through city number 3.
[ { "input": "4 4\n1 2\n1 3\n4 2\n4 3", "output": "2\n2 1 4 \n2 2 3 " }, { "input": "3 1\n1 2", "output": "1\n3 1 2 3 " }, { "input": "8 14\n1 3\n1 4\n1 5\n1 6\n1 7\n1 8\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n5 6\n6 7", "output": "2\n2 1 2 \n6 3 4 5 6 7 8 " }, { "input": "6 9\n1 4\n1 5...
3,000
56,934,400
0
23,697
504
Misha and XOR
[ "bitmasks" ]
null
null
After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number *x* to the basket, Misha should answer the question: is it possible to choose one or multiple numbers that already are in the basket, such that their XOR sum equals *x*? If the answer is positive, you also need to give the indexes of these numbers. If there are multiple options of choosing numbers, you are allowed to choose any correct option. After Misha's answer the robot puts the number to the basket. Initially the basket is empty. Each integer you put in the basket takes some number. The first integer you put into the basket take number 0, the second integer takes number 1 and so on. Misha needs to clean up the place as soon as possible but unfortunately, he isn't that good at mathematics. He asks you to help him.
The first line contains number *m* (1<=≤<=*m*<=≤<=2000), showing how many numbers are scattered around the room. The next *m* lines contain the numbers in the order in which the robot puts them in the basket. Each number is a positive integer strictly less than 10600 that doesn't contain leading zeroes.
For each number either print a 0 on the corresponding line, if the number cannot be represented as a XOR sum of numbers that are in the basket, or print integer *k* showing how many numbers are in the representation and the indexes of these numbers. Separate the numbers by spaces. Each number can occur in the representation at most once.
[ "7\n7\n6\n5\n4\n3\n2\n1\n", "2\n5\n5\n" ]
[ "0\n0\n0\n3 0 1 2\n2 1 2\n2 0 2\n2 0 1\n", "0\n1 0\n" ]
The XOR sum of numbers is the result of bitwise sum of numbers modulo 2.
[ { "input": "7\n7\n6\n5\n4\n3\n2\n1", "output": "0\n0\n0\n3 0 1 2\n2 1 2\n2 0 2\n2 0 1" }, { "input": "2\n5\n5", "output": "0\n1 0" }, { "input": "10\n81\n97\n12\n2\n16\n96\n80\n99\n6\n83", "output": "0\n0\n0\n0\n0\n0\n3 0 1 5\n2 1 3\n0\n2 0 3" }, { "input": "10\n15106\n13599\...
31
0
0
23,759
0
none
[ "none" ]
null
null
You must have heard of the two brothers dreaming of ruling the world. With all their previous plans failed, this time they decided to cooperate with each other in order to rule the world. As you know there are *n* countries in the world. These countries are connected by *n*<=-<=1 directed roads. If you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once. Each of the brothers wants to establish his reign in some country, then it's possible for him to control the countries that can be reached from his country using directed roads. The brothers can rule the world if there exists at most two countries for brothers to choose (and establish their reign in these countries) so that any other country is under control of at least one of them. In order to make this possible they want to change the direction of minimum number of roads. Your task is to calculate this minimum number of roads.
The first line of input contains an integer *n* (1<=≤<=*n*<=≤<=3000). Each of the next *n*<=-<=1 lines contains two space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*) saying there is a road from country *a**i* to country *b**i*. Consider that countries are numbered from 1 to *n*. It's guaranteed that if you don't consider direction of the roads there is a unique path between every pair of countries in the world, passing through each road at most once.
In the only line of output print the minimum number of roads that their direction should be changed so that the brothers will be able to rule the world.
[ "4\n2 1\n3 1\n4 1\n", "5\n2 1\n2 3\n4 3\n4 5\n" ]
[ "1\n", "0\n" ]
none
[]
92
0
0
23,785
138
Literature Lesson
[ "implementation" ]
null
null
Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes. Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels. Two lines rhyme if their suffixes that start from the *k*-th vowels (counting from the end) match. If a line has less than *k* vowels, then such line can't rhyme with any other line. For example, if *k*<==<=1, lines *commit* and *hermit* rhyme (the corresponding suffixes equal *it*), and if *k*<==<=2, they do not rhyme (*ommit*<=≠<=*ermit*). Today on a literature lesson Vera learned that quatrains can contain four different schemes of rhymes, namely the following ones (the same letters stand for rhyming lines): - Clerihew (*aabb*); - Alternating (*abab*); - Enclosed (*abba*). If all lines of a quatrain pairwise rhyme, then the quatrain can belong to any rhyme scheme (this situation is represented by *aaaa*). If all quatrains of a poem belong to the same rhyme scheme, then we can assume that the whole poem belongs to this rhyme scheme. If in each quatrain all lines pairwise rhyme, then the rhyme scheme of the poem is *aaaa*. Let us note that it doesn't matter whether lines from different quatrains rhyme with each other or not. In other words, it is possible that different quatrains aren't connected by a rhyme. Vera got a long poem as a home task. The girl has to analyse it and find the poem rhyme scheme. Help Vera cope with the task.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=2500, 1<=≤<=*k*<=≤<=5) — the number of quatrains in the poem and the vowel's number, correspondingly. Next 4*n* lines contain the poem. Each line is not empty and only consists of small Latin letters. The total length of the lines does not exceed 104. If we assume that the lines are numbered starting from 1, then the first quatrain contains lines number 1, 2, 3, 4; the second one contains lines number 5, 6, 7, 8; and so on.
Print the rhyme scheme of the poem as "aabb", "abab", "abba", "aaaa"; or "NO" if the poem does not belong to any of the above mentioned schemes.
[ "1 1\nday\nmay\nsun\nfun\n", "1 1\nday\nmay\ngray\nway\n", "2 1\na\na\na\na\na\na\ne\ne\n", "2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill\n" ]
[ "aabb\n", "aaaa\n", "aabb\n", "NO\n" ]
In the last sample both quatrains have rhymes but finding the common scheme is impossible, so the answer is "NO".
[ { "input": "1 1\nday\nmay\nsun\nfun", "output": "aabb" }, { "input": "1 1\nday\nmay\ngray\nway", "output": "aaaa" }, { "input": "2 1\na\na\na\na\na\na\ne\ne", "output": "aabb" }, { "input": "2 1\nday\nmay\nsun\nfun\ntest\nhill\nfest\nthrill", "output": "NO" }, { "...
62
0
0
23,818
0
none
[ "none" ]
null
null
Let's assume that - *v*(*n*) is the largest prime number, that does not exceed *n*;- *u*(*n*) is the smallest prime number strictly greater than *n*. Find .
The first line contains integer *t* (1<=≤<=*t*<=≤<=500) — the number of testscases. Each of the following *t* lines of the input contains integer *n* (2<=≤<=*n*<=≤<=109).
Print *t* lines: the *i*-th of them must contain the answer to the *i*-th test as an irreducible fraction "*p*/*q*", where *p*,<=*q* are integers, *q*<=&gt;<=0.
[ "2\n2\n3\n" ]
[ "1/6\n7/30\n" ]
none
[ { "input": "2\n2\n3", "output": "1/6\n7/30" }, { "input": "1\n1000000000", "output": "999999941999999673/1999999887999999118" }, { "input": "5\n3\n6\n9\n10\n5", "output": "7/30\n5/14\n61/154\n9/22\n23/70" }, { "input": "5\n5\n8\n18\n17\n17", "output": "23/70\n59/154\n17/3...
46
0
0
23,824
201
Guess That Car!
[ "math", "ternary search" ]
null
null
A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!". The game show takes place on a giant parking lot, which is 4*n* meters long from north to south and 4*m* meters wide from west to east. The lot has *n*<=+<=1 dividing lines drawn from west to east and *m*<=+<=1 dividing lines drawn from north to south, which divide the parking lot into *n*·*m* 4 by 4 meter squares. There is a car parked strictly inside each square. The dividing lines are numbered from 0 to *n* from north to south and from 0 to *m* from west to east. Each square has coordinates (*i*,<=*j*) so that the square in the north-west corner has coordinates (1,<=1) and the square in the south-east corner has coordinates (*n*,<=*m*). See the picture in the notes for clarifications. Before the game show the organizers offer Yura to occupy any of the (*n*<=+<=1)·(*m*<=+<=1) intersection points of the dividing lines. After that he can start guessing the cars. After Yura chooses a point, he will be prohibited to move along the parking lot before the end of the game show. As Yura is a car expert, he will always guess all cars he is offered, it's just a matter of time. Yura knows that to guess each car he needs to spend time equal to the square of the euclidean distance between his point and the center of the square with this car, multiplied by some coefficient characterizing the machine's "rarity" (the rarer the car is, the harder it is to guess it). More formally, guessing a car with "rarity" *c* placed in a square whose center is at distance *d* from Yura takes *c*·*d*2 seconds. The time Yura spends on turning his head can be neglected. It just so happened that Yura knows the "rarity" of each car on the parking lot in advance. Help him choose his point so that the total time of guessing all cars is the smallest possible.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=1000) — the sizes of the parking lot. Each of the next *n* lines contains *m* integers: the *j*-th number in the *i*-th line describes the "rarity" *c**ij* (0<=≤<=*c**ij*<=≤<=100000) of the car that is located in the square with coordinates (*i*,<=*j*).
In the first line print the minimum total time Yura needs to guess all offered cars. In the second line print two numbers *l**i* and *l**j* (0<=≤<=*l**i*<=≤<=*n*,<=0<=≤<=*l**j*<=≤<=*m*) — the numbers of dividing lines that form a junction that Yura should choose to stand on at the beginning of the game show. If there are multiple optimal starting points, print the point with smaller *l**i*. If there are still multiple such points, print the point with smaller *l**j*. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
[ "2 3\n3 4 5\n3 9 1\n", "3 4\n1 0 0 0\n0 0 3 0\n0 0 5 5\n" ]
[ "392\n1 1\n", "240\n2 3\n" ]
In the first test case the total time of guessing all cars is equal to 3·8 + 3·8 + 4·8 + 9·8 + 5·40 + 1·40 = 392. The coordinate system of the field:
[ { "input": "2 3\n3 4 5\n3 9 1", "output": "392\n1 1" }, { "input": "3 4\n1 0 0 0\n0 0 3 0\n0 0 5 5", "output": "240\n2 3" }, { "input": "4 7\n91811 50656 97940 70982 88108 31856 80371\n94488 4672 15935 10209 22935 55803 57593\n79510 213 92494 7670 49727 97141 54221\n89004 67886 99994 222...
124
0
0
23,839
201
Clear Symmetry
[ "constructive algorithms", "dp", "math" ]
null
null
Consider some square matrix *A* with side *n* consisting of zeros and ones. There are *n* rows numbered from 1 to *n* from top to bottom and *n* columns numbered from 1 to *n* from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the *i*-row and the *j*-th column as *A**i*,<=*j*. Let's call matrix *A* clear if no two cells containing ones have a common side. Let's call matrix *A* symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (*i*,<=*j*) (1<=≤<=*i*,<=*j*<=≤<=*n*) both of the following conditions must be met: *A**i*,<=*j*<==<=*A**n*<=-<=*i*<=+<=1,<=*j* and *A**i*,<=*j*<==<=*A**i*,<=*n*<=-<=*j*<=+<=1. Let's define the sharpness of matrix *A* as the number of ones in it. Given integer *x*, your task is to find the smallest positive integer *n* such that there exists a clear symmetrical matrix *A* with side *n* and sharpness *x*.
The only line contains a single integer *x* (1<=≤<=*x*<=≤<=100) — the required sharpness of the matrix.
Print a single number — the sought value of *n*.
[ "4\n", "9\n" ]
[ "3\n", "5\n" ]
The figure below shows the matrices that correspond to the samples:
[ { "input": "4", "output": "3" }, { "input": "9", "output": "5" }, { "input": "10", "output": "5" }, { "input": "12", "output": "5" }, { "input": "1", "output": "1" }, { "input": "19", "output": "7" }, { "input": "3", "output": "5" }, ...
248
0
0
23,880
908
New Year and Buggy Bot
[ "brute force", "implementation" ]
null
null
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single exit in the maze. Its position is denoted with the character 'E'. This position has no obstacle in it. The robot can only move up, left, right, or down. When Bob programmed the robot, he wrote down a string of digits consisting of the digits 0 to 3, inclusive. He intended for each digit to correspond to a distinct direction, and the robot would follow the directions in order to reach the exit. Unfortunately, he forgot to actually assign the directions to digits. The robot will choose some random mapping of digits to distinct directions. The robot will map distinct digits to distinct directions. The robot will then follow the instructions according to the given string in order and chosen mapping. If an instruction would lead the robot to go off the edge of the maze or hit an obstacle, the robot will crash and break down. If the robot reaches the exit at any point, then the robot will stop following any further instructions. Bob is having trouble debugging his robot, so he would like to determine the number of mappings of digits to directions that would lead the robot to the exit.
The first line of input will contain two integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=50), denoting the dimensions of the maze. The next *n* lines will contain exactly *m* characters each, denoting the maze. Each character of the maze will be '.', '#', 'S', or 'E'. There will be exactly one 'S' and exactly one 'E' in the maze. The last line will contain a single string *s* (1<=≤<=|*s*|<=≤<=100) — the instructions given to the robot. Each character of *s* is a digit from 0 to 3.
Print a single integer, the number of mappings of digits to directions that will lead the robot to the exit.
[ "5 6\n.....#\nS....#\n.#....\n.#....\n...E..\n333300012\n", "6 6\n......\n......\n..SE..\n......\n......\n......\n01232123212302123021\n", "5 3\n...\n.S.\n###\n.E.\n...\n3\n" ]
[ "1\n", "14\n", "0\n" ]
For the first sample, the only valid mapping is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/87a55361bde12e4223a96f0e1d83b94428f26f02.png" style="max-width: 100.0%;max-height: 100.0%;"/>, where *D* is down, *L* is left, *U* is up, *R* is right.
[ { "input": "5 6\n.....#\nS....#\n.#....\n.#....\n...E..\n333300012", "output": "1" }, { "input": "6 6\n......\n......\n..SE..\n......\n......\n......\n01232123212302123021", "output": "14" }, { "input": "5 3\n...\n.S.\n###\n.E.\n...\n3", "output": "0" }, { "input": "10 10\n.#...
46
0
3
23,922
958
Maximum Control (medium)
[ "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
null
null
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets. The Galaxy contains *N* planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets. A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits. Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every *K*<==<=1,<=2,<=3,<=...,<=*N*, the maximum number of planets that can be controlled with a fleet consisting of *K* ships.
The first line of the input contains an integer *N* (1<=≤<=*N*<=≤<=105) – the number of planets in the galaxy. The next *N*<=-<=1 lines describe the hyperspace tunnels between the planets. Each of the *N*<=-<=1 lines contains two space-separated integers *u* and *v* (1<=≤<=*u*,<=*v*<=≤<=*N*) indicating that there is a bidirectional hyperspace tunnel between the planets *u* and *v*. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
On a single line, print *N* space-separated integers. The *K*-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of *K* ships.
[ "3\n1 2\n2 3\n", "4\n1 2\n3 2\n4 2\n" ]
[ "1 3 3 ", "1 3 4 4 " ]
Consider the first example. If *K* = 1, then Heidi can only send one ship to some planet and control it. However, for *K* ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
[ { "input": "3\n1 2\n2 3", "output": "1 3 3 " }, { "input": "4\n1 2\n3 2\n4 2", "output": "1 3 4 4 " }, { "input": "19\n2 19\n7 15\n8 10\n16 1\n12 5\n11 5\n6 18\n12 14\n14 15\n2 6\n9 14\n4 17\n16 10\n4 2\n7 18\n3 2\n9 13\n11 10", "output": "1 14 16 17 18 19 19 19 19 19 19 19 19 19 19 ...
140
512,000
0
23,964
825
Minimal Labels
[ "data structures", "dfs and similar", "graphs", "greedy" ]
null
null
You are given a directed acyclic graph with *n* vertices and *m* edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected. You should assign labels to all vertices in such a way that: - Labels form a valid permutation of length *n* — an integer sequence such that each integer from 1 to *n* appears exactly once in it. - If there exists an edge from vertex *v* to vertex *u* then *label**v* should be smaller than *label**u*. - Permutation should be lexicographically smallest among all suitable. Find such sequence of labels to satisfy all the conditions.
The first line contains two integer numbers *n*, *m* (2<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=105). Next *m* lines contain two integer numbers *v* and *u* (1<=≤<=*v*,<=*u*<=≤<=*n*,<=*v*<=≠<=*u*) — edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.
Print *n* numbers — lexicographically smallest correct permutation of labels of vertices.
[ "3 3\n1 2\n1 3\n3 2\n", "4 5\n3 1\n4 1\n2 3\n3 4\n2 4\n", "5 4\n3 1\n2 1\n2 3\n4 5\n" ]
[ "1 3 2 \n", "4 1 2 3 \n", "3 1 2 4 5 \n" ]
none
[ { "input": "3 3\n1 2\n1 3\n3 2", "output": "1 3 2 " }, { "input": "4 5\n3 1\n4 1\n2 3\n3 4\n2 4", "output": "4 1 2 3 " }, { "input": "5 4\n3 1\n2 1\n2 3\n4 5", "output": "3 1 2 4 5 " }, { "input": "2 1\n2 1", "output": "2 1 " }, { "input": "5 10\n5 2\n4 1\n2 1\n3 ...
390
30,924,800
3
24,040
172
BHTML+BCSS
[ "*special", "dfs and similar", "expression parsing" ]
null
null
This problem is about imaginary languages BHTML and BCSS, which slightly resemble HTML and CSS. Read the problem statement carefully as the resemblance is rather slight and the problem uses very simplified analogs. You are given a BHTML document that resembles HTML but is much simpler. It is recorded as a sequence of opening and closing tags. A tag that looks like "&lt;tagname&gt;" is called an opening tag and a tag that looks like "&lt;/tagname&gt;" is called a closing tag. Besides, there are self-closing tags that are written as "&lt;tagname/&gt;" and in this problem they are fully equivalent to "&lt;tagname&gt;&lt;/tagname&gt;". All tagnames in this problem are strings consisting of lowercase Latin letters with length from 1 to 10 characters. Tagnames of different tags may coincide. The document tags form a correct bracket sequence, that is, we can obtain an empty sequence from the given one using the following operations: - remove any self-closing tag "&lt;tagname/&gt;", - remove a pair of an opening and a closing tag that go consecutively (in this order) and have the same names. In other words, remove substring "&lt;tagname&gt;&lt;/tagname&gt;". For example, you may be given such document: "&lt;header&gt;&lt;p&gt;&lt;a/&gt;&lt;b&gt;&lt;/b&gt;&lt;/p&gt;&lt;/header&gt;&lt;footer&gt;&lt;/footer&gt;" but you may not be given documents "&lt;a&gt;", "&lt;a&gt;&lt;/b&gt;", "&lt;/a&gt;&lt;a&gt;" or "&lt;a&gt;&lt;b&gt;&lt;/a&gt;&lt;/b&gt;". Obviously, for any opening tag there is the only matching closing one — each such pair is called an element. A self-closing tag also is an element. Let's consider that one element is nested inside another one, if tags of the first element are between tags of the second one. An element is not nested to itself. For instance, in the example above element "b" is nested in "header" and in "p", but it isn't nested in "a" and "footer", also it isn't nested to itself ("b"). Element "header" has three elements nested in it, and "footer" has zero. We need the BCSS rules to apply styles when displaying elements of the BHTML documents. Each rule is recorded as a subsequence of words "*x*1 *x*2 ... *x**n*". This rule has effect over all such elements *t*, which satisfy both conditions from the list: - there is a sequence of nested elements with tagnames "*x*1", "*x*2", ..., "*x**n*" (that is, the second element is nested in the first one, the third element is nested in the second one and so on), - this sequence ends with element *t* (i.e. tagname of element *t* equals "*x**n*"). For example, element "b" meets the conditions of the rule "a b" if for element "b" exists element "a" in which it is nested. Element "c" meets the conditions of the rule "a b b c", if three elements exist: "a", "b", "b", and in the chain "a"-"b"-"b"-"c" each following element is nested in the previous one. Given a BHTML document and a set of BCSS rules, write a program that determines the number of elements that meet the conditions of each rule.
The first line of the input contains a BHTML-document. The document has length from 4 to 106 characters. The document has a correct structure, doesn't contain spaces or any other unnecessary characters. Tagnames consist of lowercase Latin letters, their lengths are from 1 to 10 characters. The second line contains an integer *m* (1<=≤<=*m*<=≤<=200) — the number of queries. Then *m* lines contain the queries, one per line. Each query is a sequence *x*1,<=*x*2,<=...,<=*x**n*, where *x**i* is the *i*-th element of the query, and *n* (1<=≤<=*n*<=≤<=200) is the number of elements in the query. The elements are separated by single spaces. Each query doesn't begin with and doesn't end with a space. Each query element is a sequence of lowercase Latin letters with length from 1 to 10.
Print *m* lines, the *j*-th line should contain the number of elements of the document that correspond to the *j*-th BCSS-rule. If there are no such elements at all, print on the line 0.
[ "&lt;a&gt;&lt;b&gt;&lt;b&gt;&lt;/b&gt;&lt;/b&gt;&lt;/a&gt;&lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;b&gt;&lt;v/&gt;&lt;/b&gt;&lt;/a&gt;&lt;b&gt;&lt;/b&gt;\n4\na\na b b\na b\nb a\n", "&lt;b&gt;&lt;aa/&gt;&lt;/b&gt;&lt;aa&gt;&lt;b/&gt;&lt;b/&gt;&lt;/aa&gt;\n5\naa b\nb\naa\nb aa\na\n" ]
[ "2\n1\n4\n0\n", "2\n3\n2\n1\n0\n" ]
none
[]
46
0
0
24,057