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
437
The Child and Polygon
[ "dp", "geometry" ]
null
null
This time our child has a simple polygon. He has to find the number of ways to split the polygon into non-degenerate triangles, each way must satisfy the following requirements: - each vertex of each triangle is one of the polygon vertex; - each side of the polygon must be the side of exactly one triangle; - the area of intersection of every two triangles equals to zero, and the sum of all areas of triangles equals to the area of the polygon; - each triangle must be completely inside the polygon; - each side of each triangle must contain exactly two vertices of the polygon. The picture below depicts an example of a correct splitting. Please, help the child. Calculate the described number of ways modulo 1000000007 (109<=<=+<=<=7) for him.
The first line contains one integer *n* (3<=≤<=*n*<=≤<=200) — the number of vertices of the polygon. Then follow *n* lines, each line containing two integers. The *i*-th line contains *x**i*,<=*y**i* (|*x**i*|,<=|*y**i*|<=≤<=107) — the *i*-th vertex of the polygon in clockwise or counterclockwise order. It's guaranteed that the polygon is simple.
Output the number of ways modulo 1000000007 (109<=<=+<=<=7).
[ "4\n0 0\n0 1\n1 1\n1 0\n", "4\n0 0\n1 0\n0 1\n-1 0\n", "5\n0 0\n1 0\n1 1\n0 1\n-2 -1\n" ]
[ "2\n", "1\n", "3\n" ]
In the first sample, there are two possible splittings: In the second sample, there are only one possible splitting:
[]
31
0
0
24,065
55
Beautiful numbers
[ "dp", "number theory" ]
D. Beautiful numbers
4
256
Volodya is an odd boy and his taste is strange as well. It seems to him that a positive integer number is beautiful if and only if it is divisible by each of its nonzero digits. We will not argue with this and just count the quantity of beautiful numbers in given ranges.
The first line of the input contains the number of cases *t* (1<=≤<=*t*<=≤<=10). Each of the next *t* lines contains two natural numbers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=9<=·1018). Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cin (also you may use %I64d).
Output should contain *t* numbers — answers to the queries, one number per line — quantities of beautiful numbers in given intervals (from *l**i* to *r**i*, inclusively).
[ "1\n1 9\n", "1\n12 15\n" ]
[ "9\n", "2\n" ]
none
[ { "input": "1\n1 9", "output": "9" }, { "input": "1\n12 15", "output": "2" }, { "input": "1\n25 53", "output": "7" }, { "input": "1\n1 1000", "output": "138" }, { "input": "1\n1 100000", "output": "4578" }, { "input": "2\n234 59843\n46 3243", "outp...
1,902
45,568,000
3.677373
24,092
159
Zebra Tower
[ "*special", "data structures", "greedy", "sortings" ]
null
null
Little Janet likes playing with cubes. Actually, she likes to play with anything whatsoever, cubes or tesseracts, as long as they are multicolored. Each cube is described by two parameters — color *c**i* and size *s**i*. A Zebra Tower is a tower that consists of cubes of exactly two colors. Besides, the colors of the cubes in the tower must alternate (colors of adjacent cubes must differ). The Zebra Tower should have at least two cubes. There are no other limitations. The figure below shows an example of a Zebra Tower. A Zebra Tower's height is the sum of sizes of all cubes that form the tower. Help little Janet build the Zebra Tower of the maximum possible height, using the available cubes.
The first line contains an integer *n* (2<=≤<=*n*<=≤<=105) — the number of cubes. Next *n* lines contain the descriptions of the cubes, one description per line. A cube description consists of two space-separated integers *c**i* and *s**i* (1<=≤<=*c**i*,<=*s**i*<=≤<=109) — the *i*-th cube's color and size, correspondingly. It is guaranteed that there are at least two cubes of different colors.
Print the description of the Zebra Tower of the maximum height in the following form. In the first line print the tower's height, in the second line print the number of cubes that form the tower, and in the third line print the space-separated indices of cubes in the order in which they follow in the tower from the bottom to the top. Assume that the cubes are numbered from 1 to *n* in the order in which they were given in the input. If there are several existing Zebra Towers with maximum heights, it is allowed to print any of them. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "4\n1 2\n1 3\n2 4\n3 3\n", "2\n1 1\n2 1\n" ]
[ "9\n3\n2 3 1 \n", "2\n2\n2 1 \n" ]
none
[ { "input": "4\n1 2\n1 3\n2 4\n3 3", "output": "9\n3\n2 3 1 " }, { "input": "2\n1 1\n2 1", "output": "2\n2\n2 1 " }, { "input": "3\n1 2\n2 2\n2 1", "output": "5\n3\n2 1 3 " }, { "input": "4\n2 1\n2 1\n1 1\n1 2", "output": "5\n4\n4 2 3 1 " }, { "input": "6\n1 1\n1 1...
46
307,200
0
24,103
0
none
[ "none" ]
null
null
Arpa has found a list containing *n* numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1. Arpa can perform two types of operations: - Choose a number and delete it with cost *x*. - Choose a number and increase it by 1 with cost *y*. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number. Help Arpa to find the minimum possible cost to make the list good.
First line contains three integers *n*, *x* and *y* (1<=≤<=*n*<=≤<=5·105, 1<=≤<=*x*,<=*y*<=≤<=109) — the number of elements in the list and the integers *x* and *y*. Second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=106) — the elements of the list.
Print a single integer: the minimum possible cost to make the list good.
[ "4 23 17\n1 17 17 16\n", "10 6 2\n100 49 71 73 66 96 8 60 41 63\n" ]
[ "40\n", "10\n" ]
In example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17). A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd [here](https://en.wikipedia.org/wiki/Greatest_common_divisor).
[]
0
0
-1
24,127
0
none
[ "none" ]
null
null
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2*n* members and coincidentally Natalia Fan Club also has 2*n* members. Each member of MDC is assigned a unique id *i* from 0 to 2*n*<=-<=1. The same holds for each member of NFC. One of the parts of this tradition is one by one dance, where each member of MDC dances with a member of NFC. A dance pair is a pair of numbers (*a*,<=*b*) such that member *a* from MDC dances with member *b* from NFC. The complexity of a pairs' assignment is the number of pairs of dancing pairs (*a*,<=*b*) and (*c*,<=*d*) such that *a*<=&lt;<=*c* and *b*<=&gt;<=*d*. You are given a binary number of length *n* named *x*. We know that member *i* from MDC dances with member from NFC. Your task is to calculate the complexity of this assignment modulo 1000000007 (109<=+<=7). Expression denotes applying «XOR» to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in C++ and Java it denotes as «^», in Pascal — «xor».
The first line of input contains a binary number *x* of lenght *n*, (1<=≤<=*n*<=≤<=100). This number may contain leading zeros.
Print the complexity of the given dance assignent modulo 1000000007 (109<=+<=7).
[ "11\n", "01\n", "1\n" ]
[ "6\n", "2\n", "1\n" ]
none
[ { "input": "11", "output": "6" }, { "input": "01", "output": "2" }, { "input": "1", "output": "1" }, { "input": "1111111111111111111111111111111111", "output": "68817500" }, { "input": "0000000000000000000000000000000000000", "output": "0" }, { "input"...
92
0
0
24,132
497
Subsequences Return
[ "dp", "matrices" ]
null
null
Assume that *s**k*(*n*) equals the sum of digits of number *n* in the *k*-based notation. For example, *s*2(5)<==<=*s*2(1012)<==<=1<=+<=0<=+<=1<==<=2, *s*3(14)<==<=*s*3(1123)<==<=1<=+<=1<=+<=2<==<=4. The sequence of integers *a*0,<=...,<=*a**n*<=-<=1 is defined as . Your task is to calculate the number of distinct subsequences of sequence *a*0,<=...,<=*a**n*<=-<=1. Calculate the answer modulo 109<=+<=7. Sequence *a*1,<=...,<=*a**k* is called to be a subsequence of sequence *b*1,<=...,<=*b**l*, if there is a sequence of indices 1<=≤<=*i*1<=&lt;<=...<=&lt;<=*i**k*<=≤<=*l*, such that *a*1<==<=*b**i*1, ..., *a**k*<==<=*b**i**k*. In particular, an empty sequence (i.e. the sequence consisting of zero elements) is a subsequence of any sequence.
The first line contains two space-separated numbers *n* and *k* (1<=≤<=*n*<=≤<=1018, 2<=≤<=*k*<=≤<=30).
In a single line print the answer to the problem modulo 109<=+<=7.
[ "4 2\n", "7 7\n" ]
[ "11\n", "128\n" ]
In the first sample the sequence *a*<sub class="lower-index">*i*</sub> looks as follows: (0, 1, 1, 0). All the possible subsequences are: In the second sample the sequence *a*<sub class="lower-index">*i*</sub> looks as follows: (0, 1, 2, 3, 4, 5, 6). The subsequences of this sequence are exactly all increasing sequences formed from numbers from 0 to 6. It is easy to see that there are 2<sup class="upper-index">7</sup> = 128 such sequences.
[]
30
0
0
24,137
83
Doctor
[ "binary search", "math", "sortings" ]
B. Doctor
2
256
There are *n* animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number *i* in the queue will have to visit his office exactly *a**i* times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving *k* animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out.
The first line of input data contains two space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=105, 0<=≤<=*k*<=≤<=1014). In the second line are given space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109). Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
If the doctor will overall carry out less than *k* examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers — number of animals in the order in which they stand in the queue. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.
[ "3 3\n1 2 1\n", "4 10\n3 3 2 1\n", "7 10\n1 3 3 1 2 3 1\n" ]
[ "2 ", "-1\n", "6 2 3 " ]
In the first sample test: - Before examination: {1, 2, 3} - After the first examination: {2, 3} - After the second examination: {3, 2} - After the third examination: {2} In the second sample test: - Before examination: {1, 2, 3, 4, 5, 6, 7} - After the first examination: {2, 3, 4, 5, 6, 7} - After the second examination: {3, 4, 5, 6, 7, 2} - After the third examination: {4, 5, 6, 7, 2, 3} - After the fourth examination: {5, 6, 7, 2, 3} - After the fifth examination: {6, 7, 2, 3, 5} - After the sixth examination: {7, 2, 3, 5, 6} - After the seventh examination: {2, 3, 5, 6} - After the eighth examination: {3, 5, 6, 2} - After the ninth examination: {5, 6, 2, 3} - After the tenth examination: {6, 2, 3}
[ { "input": "3 3\n1 2 1", "output": "2 " }, { "input": "4 10\n3 3 2 1", "output": "-1" }, { "input": "7 10\n1 3 3 1 2 3 1", "output": "6 2 3 " }, { "input": "1 0\n1", "output": "1 " }, { "input": "6 101\n9 78 54 62 2 91", "output": "4 6 2 3 " }, { "inpu...
122
307,200
0
24,200
5
Bindian Signalizing
[ "data structures" ]
E. Bindian Signalizing
4
256
Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by *n* hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night. In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other. An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.
The first line of the input data contains an integer number *n* (3<=≤<=*n*<=≤<=106), *n* — the amount of hills around the capital. The second line contains *n* numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.
Print the required amount of pairs.
[ "5\n1 2 4 5 3\n" ]
[ "7\n" ]
none
[ { "input": "5\n1 2 4 5 3", "output": "7" }, { "input": "3\n2118 2118 2118", "output": "3" }, { "input": "3\n2221 1976 2221", "output": "3" }, { "input": "3\n140 989 2895", "output": "3" }, { "input": "4\n2440 2440 2440 2440", "output": "6" }, { "input"...
2,308
103,731,200
3.518286
24,272
690
Collective Mindsets (medium)
[]
null
null
Way to go! Heidi now knows how many brains there must be for her to get one. But throwing herself in the midst of a clutch of hungry zombies is quite a risky endeavor. Hence Heidi wonders: what is the smallest number of brains that must be in the chest for her to get out at all (possibly empty-handed, but alive)? The brain dinner night will evolve just as in the previous subtask: the same crowd is present, the *N*<=-<=1 zombies have the exact same mindset as before and Heidi is to make the first proposal, which must be accepted by at least half of the attendees for her to survive.
The only line of input contains one integer: *N*, the number of attendees (1<=≤<=*N*<=≤<=109).
Output one integer: the smallest number of brains in the chest which allows Heidi to merely survive.
[ "1\n", "3\n", "99\n" ]
[ "0\n", "1\n", "49\n" ]
none
[ { "input": "1", "output": "0" }, { "input": "3", "output": "1" }, { "input": "2", "output": "0" }, { "input": "4", "output": "0" }, { "input": "5", "output": "2" }, { "input": "6", "output": "1" }, { "input": "7", "output": "3" }, {...
61
0
0
24,274
480
Parking Lot
[ "data structures", "divide and conquer" ]
null
null
Petya's been bored at work and he is killing the time by watching the parking lot at the office. The parking lot looks from above like an *n*<=×<=*m* table (a cell of the table corresponds to a single parking spot). Some spots in the parking lot are taken, others are empty. Petya watches cars riding into the parking lot one by one. After a car settles down at the parking spot, Petya amuzes himself by counting what maximum square of empty spots (i.e. a square subtable) can be seen on the parking lot if we look at it from above. Also, he takes notes of the square's size (side length) in his notebook. You task is: given the state of the parking lot at the initial moment of time and the information about where the arriving cars park, restore what Petya wrote in his notebook. It is midday, so nobody leaves the lot.
The first line contains three integers *n*, *m* and *k* — the sizes of the parking lot and the number of arriving cars after Petya started his watch (1<=≤<=*n*,<=*m*,<=*k*<=≤<=2000). Each of the following *n* lines contains *m* characters 'X' and '.', where 'X' means a taken spot and '.' means an empty spot. Each of the next *k* lines contains a pair of integers *x**i*, *y**i* — the number of row and column of the spot the corresponding car takes (1<=≤<=*x**i*<=≤<=*n*, 1<=≤<=*y**i*<=≤<=*m*). It is guaranteed that this place was empty. You can assume that a car enters a parking lot only after the previous car successfully finds a spot.
Print *k* integers — the length of the side of the maximum square of empty spots after the corresponding car has entered the parking lot.
[ "7 8 4\n........\nX.....X.\n........\n........\n.X......\n........\n........\n1 5\n6 4\n3 5\n4 6\n" ]
[ "5\n4\n4\n3\n" ]
none
[]
30
0
0
24,329
809
Hitchhiking in the Baltic States
[ "data structures", "dp" ]
null
null
Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit *n* towns. However it turned out that sights in *i*-th town are open for visitors only on days from *l**i* to *r**i*. What to do? Leha proposed to choose for each town *i* a day, when they will visit this town, i.e any integer *x**i* in interval [*l**i*,<=*r**i*]. After that Noora choses some subsequence of towns *id*1,<=*id*2,<=...,<=*id**k*, which friends are going to visit, that at first they are strictly increasing, i.e *id**i*<=&lt;<=*id**i*<=+<=1 is for all integers *i* from 1 to *k*<=-<=1, but also the dates of the friends visits are strictly increasing, i.e *x**id**i*<=&lt;<=*x**id**i*<=+<=1 is true for all integers *i* from 1 to *k*<=-<=1. Please help Leha and Noora in choosing such *x**i* for each town *i*, and such subsequence of towns *id*1,<=*id*2,<=...,<=*id**k*, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=3·105) denoting the number of towns Leha and Noora intended to visit. Each line *i* of the *n* subsequent lines contains two integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=109), denoting that sights in *i*-th town are open for visitors on any day .
Print a single integer denoting the maximal number of towns, that Leha and Noora can visit.
[ "5\n6 6\n1 2\n3 4\n2 2\n1 4\n" ]
[ "3\n" ]
Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer.
[]
46
0
0
24,334
706
Hard problem
[ "dp", "strings" ]
null
null
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help. Vasiliy is given *n* strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on). To reverse the *i*-th string Vasiliy has to spent *c**i* units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order. String *A* is lexicographically smaller than string *B* if it is shorter than *B* (|*A*|<=&lt;<=|*B*|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in *A* is smaller than the character in *B*. For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=100<=000) — the number of strings. The second line contains *n* integers *c**i* (0<=≤<=*c**i*<=≤<=109), the *i*-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the *i*-th string. Then follow *n* lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100<=000.
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print <=-<=1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
[ "2\n1 2\nba\nac\n", "3\n1 3 1\naa\nba\nac\n", "2\n5 5\nbbb\naaa\n", "2\n3 3\naaa\naa\n" ]
[ "1\n", "1\n", "-1\n", "-1\n" ]
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller. In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1. In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 1.
[ { "input": "2\n1 2\nba\nac", "output": "1" }, { "input": "3\n1 3 1\naa\nba\nac", "output": "1" }, { "input": "2\n5 5\nbbb\naaa", "output": "-1" }, { "input": "2\n3 3\naaa\naa", "output": "-1" }, { "input": "4\n0 0 8 6\nbi\nqp\nbt\nya", "output": "8" }, { ...
62
0
0
24,348
774
Stepan's Series
[ "*special", "dp" ]
null
null
Well, the series which Stepan watched for a very long time, ended. In total, the series had *n* episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch. Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to *k*.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 0<=≤<=*k*<=≤<=*n*) — the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of *n* symbols "Y", "N" and "?". If the *i*-th symbol equals "Y", Stepan remembers that he has watched the episode number *i*. If the *i*-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number *i*. If the *i*-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number *i* or not.
If Stepan's dissatisfaction can be exactly equal to *k*, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes).
[ "5 2\nNYNNY\n", "6 1\n????NN\n" ]
[ "YES\n", "NO\n" ]
In the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row — the episode number 3 and the episode number 4. The answer is "YES", because *k* = 2. In the second test *k* = 1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row — number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive.
[ { "input": "5 2\nNYNNY", "output": "YES" }, { "input": "6 1\n????NN", "output": "NO" }, { "input": "100 8\nNYNNY?YNNNNNN?NNNNNYNY?YYNYNN?NNNY??NNYNYNNNYNNNYNNNNNNNNY?NNNYNYN?NNNY?YY?NNYNN?NNNYNNYNNYN?NNYNYNN", "output": "YES" }, { "input": "10 1\nNY???NY?Y?", "output": "Y...
93
307,200
0
24,358
556
Case of Fake Numbers
[ "brute force", "implementation" ]
null
null
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of *n* similar gears. Each gear has *n* teeth containing all numbers from 0 to *n*<=-<=1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if *n*<==<=5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0,<=1,<=2,<=...,<=*n*<=-<=1. Write a program that determines whether the given puzzle is real or fake.
The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — the number of gears. The second line contains *n* digits *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=*n*<=-<=1) — the sequence of active teeth: the active tooth of the *i*-th gear contains number *a**i*.
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
[ "3\n1 0 0\n", "5\n4 2 1 4 3\n", "4\n0 2 3 1\n" ]
[ "Yes\n", "Yes\n", "No\n" ]
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
[ { "input": "3\n1 0 0", "output": "Yes" }, { "input": "5\n4 2 1 4 3", "output": "Yes" }, { "input": "4\n0 2 3 1", "output": "No" }, { "input": "1\n0", "output": "Yes" }, { "input": "2\n1 0", "output": "Yes" }, { "input": "5\n2 4 4 1 1", "output": "Y...
46
0
3
24,469
69
Game
[ "implementation" ]
C. Game
2
256
In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts. After the composing composite artifact, all the components disappear. Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts.
The first line has 4 natural numbers: *k* (1<=≤<=*k*<=≤<=100) — the number of Kostya's allies, *n* (1<=≤<=*n*<=≤<=50) — the number of basic artifacts, *m* (0<=≤<=*m*<=≤<=50) — the number of composite artifacts, *q* (1<=≤<=*q*<=≤<=500) — the number of his friends' purchases. The following *n* lines contain the names of basic artifacts. After them *m* lines contain the descriptions of composite artifacts in the following format: &lt;Art. Name&gt;: &lt;Art. №1&gt; &lt;Art. №1 Number&gt;, &lt;Art. №2&gt; &lt;Art. №2 Number&gt;, ... &lt;Art. №X&gt; &lt;Art. №Х Number&gt; All the numbers are natural numbers not exceeding 100 (1<=≤<=*X*<=≤<=*n*). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following *q* lines is characterized by the number *a**i*, the number of a friend who has bought the artifact (1<=≤<=*a**i*<=≤<=*k*), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the *i*-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it.
The output file should consist of *k* blocks. The first line should contain number *b**i* — the number of different artifacts the *i*-th ally has. Then the block should contain *b**i* lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the *b**i* should be positive.
[ "2 3 2 5\ndesolator\nrefresher\nperseverance\nvanguard: desolator 1, refresher 1\nmaelstorm: perseverance 2\n1 desolator\n2 perseverance\n1 refresher\n2 desolator\n2 perseverance\n" ]
[ "1\nvanguard 1\n2\ndesolator 1\nmaelstorm 1\n" ]
none
[ { "input": "2 3 2 5\ndesolator\nrefresher\nperseverance\nvanguard: desolator 1, refresher 1\nmaelstorm: perseverance 2\n1 desolator\n2 perseverance\n1 refresher\n2 desolator\n2 perseverance", "output": "1\nvanguard 1\n2\ndesolator 1\nmaelstorm 1" }, { "input": "2 3 2 5\na\nb\nc\nd: a 1, b 1\ne: c 2\...
186
307,200
0
24,626
662
International Olympiad
[ "constructive algorithms", "greedy", "implementation", "math" ]
null
null
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where *y* stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string *y* that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition. For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995. You are given a list of abbreviations. For each of them determine the year it stands for.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=1000) — the number of abbreviations to process. Then *n* lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.
For each abbreviation given in the input, find the year of the corresponding Olympiad.
[ "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0\n", "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999\n" ]
[ "2015\n12015\n1991\n1989\n1990\n", "1989\n1999\n2999\n9999\n" ]
none
[ { "input": "5\nIAO'15\nIAO'2015\nIAO'1\nIAO'9\nIAO'0", "output": "2015\n12015\n1991\n1989\n1990" }, { "input": "4\nIAO'9\nIAO'99\nIAO'999\nIAO'9999", "output": "1989\n1999\n2999\n9999" }, { "input": "1\nIAO'111110", "output": "1111110" }, { "input": "2\nIAO'0\nIAO'00", "o...
124
2,252,800
0
24,628
492
Vanya and Field
[ "math" ]
null
null
Vanya decided to walk in the field of size *n*<=×<=*n* cells. The field contains *m* apple trees, the *i*-th apple tree is at the cell with coordinates (*x**i*,<=*y**i*). Vanya moves towards vector (*dx*,<=*dy*). That means that if Vanya is now at the cell (*x*,<=*y*), then in a second he will be at cell . The following condition is satisfied for the vector: , where is the largest integer that divides both *a* and *b*. Vanya ends his path when he reaches the square he has already visited. Vanya wonders, from what square of the field he should start his path to see as many apple trees as possible.
The first line contains integers *n*,<=*m*,<=*dx*,<=*dy*(1<=≤<=*n*<=≤<=106, 1<=≤<=*m*<=≤<=105, 1<=≤<=*dx*,<=*dy*<=≤<=*n*) — the size of the field, the number of apple trees and the vector of Vanya's movement. Next *m* lines contain integers *x**i*,<=*y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=*n*<=-<=1) — the coordinates of apples. One cell may contain multiple apple trees.
Print two space-separated numbers — the coordinates of the cell from which you should start your path. If there are several answers you are allowed to print any of them.
[ "5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1\n", "2 3 1 1\n0 0\n0 1\n1 1\n" ]
[ "1 3\n", "0 0\n" ]
In the first sample Vanya's path will look like: (1, 3) - (3, 1) - (0, 4) - (2, 2) - (4, 0) - (1, 3) In the second sample: (0, 0) - (1, 1) - (0, 0)
[ { "input": "5 5 2 3\n0 0\n1 2\n1 3\n2 4\n3 1", "output": "1 3" }, { "input": "2 3 1 1\n0 0\n0 1\n1 1", "output": "0 0" }, { "input": "5 5 2 4\n0 0\n1 2\n1 3\n2 4\n3 1", "output": "1 2" }, { "input": "6 6 5 5\n0 0\n0 1\n0 2\n0 3\n0 4\n0 5", "output": "0 0" }, { "in...
46
0
0
24,720
858
Polycarp's phone book
[ "data structures", "implementation", "sortings" ]
null
null
There are *n* phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for which there is a substring equal to the entered sequence of digits. For example, is there are three phone numbers in Polycarp's contacts: 123456789, 100000000 and 100123456, then: - if he enters 00 two numbers will show up: 100000000 and 100123456, - if he enters 123 two numbers will show up 123456789 and 100123456, - if he enters 01 there will be only one number 100123456. For each of the phone numbers in Polycarp's contacts, find the minimum in length sequence of digits such that if Polycarp enters this sequence, Berdroid shows this only phone number.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=70000) — the total number of phone contacts in Polycarp's contacts. The phone numbers follow, one in each line. Each number is a positive 9-digit integer starting with a digit from 1 to 9. All the numbers are distinct.
Print exactly *n* lines: the *i*-th of them should contain the shortest non-empty sequence of digits, such that if Polycarp enters it, the Berdroid OS shows up only the *i*-th number from the contacts. If there are several such sequences, print any of them.
[ "3\n123456789\n100000000\n100123456\n", "4\n123456789\n193456789\n134567819\n934567891\n" ]
[ "9\n000\n01\n", "2\n193\n81\n91\n" ]
none
[ { "input": "3\n123456789\n100000000\n100123456", "output": "9\n000\n01" }, { "input": "4\n123456789\n193456789\n134567819\n934567891", "output": "2\n193\n81\n91" }, { "input": "1\n167038488", "output": "4" }, { "input": "5\n115830748\n403459907\n556271610\n430358099\n41396141...
3,182
184,217,600
3
24,780
105
Transmigration
[ "implementation" ]
A. Transmigration
2
256
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes are characterized by different skills. Unfortunately, the skills that are uncommon for the given character's class are quite difficult to obtain. To avoid this limitation, there is the so-called transmigration. Transmigration is reincarnation of the character in a new creature. His soul shifts to a new body and retains part of his experience from the previous life. As a result of transmigration the new character gets all the skills of the old character and the skill levels are reduced according to the *k* coefficient (if the skill level was equal to *x*, then after transmigration it becomes equal to [*kx*], where [*y*] is the integral part of *y*). If some skill's levels are strictly less than 100, these skills are forgotten (the character does not have them any more). After that the new character also gains the skills that are specific for his class, but are new to him. The levels of those additional skills are set to 0. Thus, one can create a character with skills specific for completely different character classes via transmigrations. For example, creating a mage archer or a thief warrior is possible. You are suggested to solve the following problem: what skills will the character have after transmigration and what will the levels of those skills be?
The first line contains three numbers *n*, *m* and *k* — the number of skills the current character has, the number of skills specific for the class into which the character is going to transmigrate and the reducing coefficient respectively; *n* and *m* are integers, and *k* is a real number with exactly two digits after decimal point (1<=≤<=*n*,<=*m*<=≤<=20, 0.01<=≤<=*k*<=≤<=0.99). Then follow *n* lines, each of which describes a character's skill in the form "*name* *exp*" — the skill's name and the character's skill level: *name* is a string and *exp* is an integer in range from 0 to 9999, inclusive. Then follow *m* lines each of which contains names of skills specific for the class, into which the character transmigrates. All names consist of lowercase Latin letters and their lengths can range from 1 to 20 characters, inclusive. All character's skills have distinct names. Besides the skills specific for the class into which the player transmigrates also have distinct names.
Print on the first line number *z* — the number of skills the character will have after the transmigration. Then print *z* lines, on each of which print a skill's name and level, separated by a single space. The skills should be given in the lexicographical order.
[ "5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost\n" ]
[ "6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0\n" ]
none
[ { "input": "5 4 0.75\naxe 350\nimpaler 300\nionize 80\nmegafire 120\nmagicboost 220\nheal\nmegafire\nshield\nmagicboost", "output": "6\naxe 262\nheal 0\nimpaler 225\nmagicboost 165\nmegafire 0\nshield 0" }, { "input": "1 1 0.50\nstaff 1005\nionize", "output": "2\nionize 0\nstaff 502" }, { ...
622
14,336,000
0
24,814
23
Oranges and Apples
[ "constructive algorithms", "sortings" ]
C. Oranges and Apples
1
256
In 2*N*<=-<=1 boxes there are apples and oranges. Your task is to choose *N* boxes so, that they will contain not less than half of all the apples and not less than half of all the oranges.
The first input line contains one number *T* — amount of tests. The description of each test starts with a natural number *N* — amount of boxes. Each of the following 2*N*<=-<=1 lines contains numbers *a**i* and *o**i* — amount of apples and oranges in the *i*-th box (0<=≤<=*a**i*,<=*o**i*<=≤<=109). The sum of *N* in all the tests in the input doesn't exceed 105. All the input numbers are integer.
For each test output two lines. In the first line output YES, if it's possible to choose *N* boxes, or NO otherwise. If the answer is positive output in the second line *N* numbers — indexes of the chosen boxes. Boxes are numbered from 1 in the input order. Otherwise leave the second line empty. Separate the numbers with one space.
[ "2\n2\n10 15\n5 7\n20 18\n1\n0 0\n" ]
[ "YES\n1 3\nYES\n1\n" ]
none
[ { "input": "2\n2\n10 15\n5 7\n20 18\n1\n0 0", "output": "YES\n3 1\nYES\n1" } ]
1,294
24,371,200
3.307605
24,842
254
Anagram
[ "greedy", "strings" ]
null
null
String *x* is an anagram of string *y*, if we can rearrange the letters in string *x* and get exact string *y*. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not. You are given two strings *s* and *t* of the same length, consisting of uppercase English letters. You need to get the anagram of string *t* from string *s*. You are permitted to perform the replacing operation: every operation is replacing some character from the string *s* by any other character. Get the anagram of string *t* in the least number of replacing operations. If you can get multiple anagrams of string *t* in the least number of operations, get the lexicographically minimal one. The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string *p* of length *n* is lexicographically smaller than string *q* of the same length, if *p*1<==<=*q*1, *p*2<==<=*q*2, ..., *p**k*<=-<=1<==<=*q**k*<=-<=1, *p**k*<=&lt;<=*q**k* for some *k* (1<=≤<=*k*<=≤<=*n*). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.
The input consists of two lines. The first line contains string *s*, the second line contains string *t*. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.
In the first line print *z* — the minimum number of replacement operations, needed to get an anagram of string *t* from string *s*. In the second line print the lexicographically minimum anagram that could be obtained in *z* operations.
[ "ABA\nCBA\n", "CDBABC\nADCABD\n" ]
[ "1\nABC\n", "2\nADBADC\n" ]
The second sample has eight anagrams of string *t*, that can be obtained from string *s* by replacing exactly two letters: "ADBADC", "ADDABC", "CDAABD", "CDBAAD", "CDBADA", "CDDABA", "DDAABC", "DDBAAC". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is "ADBADC".
[ { "input": "ABA\nCBA", "output": "1\nABC" }, { "input": "CDBABC\nADCABD", "output": "2\nADBADC" }, { "input": "AABAA\nBBAAA", "output": "1\nAABAB" }, { "input": "OVGHK\nRPGUC", "output": "4\nCPGRU" }, { "input": "CCAACBA\nBBBAACC", "output": "2\nBCAACBB" }, ...
60
0
-1
24,864
899
Letters Removing
[ "data structures", "strings" ]
null
null
Petya has a string of length *n* consisting of small and large English letters and digits. He performs *m* operations. Each operation is described with two integers *l* and *r* and a character *c*: Petya removes from the string all characters *c* on positions between *l* and *r*, inclusive. It's obvious that the length of the string remains the same or decreases after each operation. Find how the string will look like after Petya performs all *m* operations.
The first string contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the length of the string and the number of operations. The second line contains the string of length *n*, consisting of small and large English letters and digits. Positions in the string are enumerated from 1. Each of the next *m* lines contains two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*), followed by a character *c*, which is a small or large English letter or a digit. This line describes one operation. It is guaranteed that *r* doesn't exceed the length of the string *s* before current operation.
Print the string Petya will obtain after performing all *m* operations. If the strings becomes empty after all operations, print an empty line.
[ "4 2\nabac\n1 3 a\n2 2 c\n", "3 2\nA0z\n1 3 0\n1 1 z\n", "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a\n", "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A\n" ]
[ "b\n", "Az\n", "tFrg4\n", "AB\n" ]
In the first example during the first operation both letters 'a' are removed, so the string becomes "bc". During the second operation the letter 'c' (on the second position) is removed, and the string becomes "b". In the second example during the first operation Petya removes '0' from the second position. After that the string becomes "Az". During the second operations the string doesn't change.
[ { "input": "4 2\nabac\n1 3 a\n2 2 c", "output": "b" }, { "input": "3 2\nA0z\n1 3 0\n1 1 z", "output": "Az" }, { "input": "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a", "output": "tFrg4" }, { "input": "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A", "output": "AB" }...
31
5,529,600
0
24,915
340
Bubble Sort Graph
[ "binary search", "data structures", "dp" ]
null
null
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with *n* elements *a*1, *a*2, ..., *a**n* in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it *G*) initially has *n* vertices and 0 edges. During Bubble Sort execution, edges appear as described in the following algorithm (pseudocode). For a graph, an independent set is a set of vertices in a graph, no two of which are adjacent (so there are no edges between vertices of an independent set). A maximum independent set is an independent set which has maximum cardinality. Given the permutation, find the size of the maximum independent set of graph *G*, if we use such permutation as the premutation *a* in procedure bubbleSortGraph.
The first line of the input contains an integer *n* (2<=≤<=*n*<=≤<=105). The next line contains *n* distinct integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=*n*).
Output a single integer — the answer to the problem.
[ "3\n3 1 2\n" ]
[ "2\n" ]
Consider the first example. Bubble sort swaps elements 3 and 1. We add edge (1, 3). Permutation is now [1, 3, 2]. Then bubble sort swaps elements 3 and 2. We add edge (2, 3). Permutation is now sorted. We have a graph with 3 vertices and 2 edges (1, 3) and (2, 3). Its maximal independent set is [1, 2].
[ { "input": "3\n3 1 2", "output": "2" }, { "input": "5\n4 2 1 3 5", "output": "3" }, { "input": "10\n1 9 8 10 2 3 4 6 5 7", "output": "6" }, { "input": "50\n12 24 42 43 36 3 40 29 7 34 10 13 28 9 35 23 25 21 19 4 20 18 11 38 41 48 6 46 33 17 31 37 2 30 32 44 45 5 47 49 16 15 5...
1,000
7,065,600
0
24,916
38
Let's Go Rolling!
[ "dp", "sortings" ]
E. Let's Go Rolling!
2
256
On a number axis directed from the left rightwards, *n* marbles with coordinates *x*1,<=*x*2,<=...,<=*x**n* are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number *i* is equal to *c**i*, number *c**i* may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: - the sum of the costs of stuck pins; - the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.
The first input line contains an integer *n* (1<=≤<=*n*<=≤<=3000) which is the number of marbles. The next *n* lines contain the descriptions of the marbles in pairs of integers *x**i*, *c**i* (<=-<=109<=≤<=*x**i*,<=*c**i*<=≤<=109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.
Output the single number — the least fine you will have to pay.
[ "3\n2 3\n3 4\n1 2\n", "4\n1 7\n3 1\n5 10\n6 1\n" ]
[ "5\n", "11\n" ]
none
[ { "input": "3\n2 3\n3 4\n1 2", "output": "5" }, { "input": "4\n1 7\n3 1\n5 10\n6 1", "output": "11" }, { "input": "1\n-948943148 10", "output": "10" }, { "input": "5\n864449017 54\n864449026 504\n864449027 308\n864449028 284\n864449030 249", "output": "97" }, { "i...
186
307,200
0
24,962
380
Sereja and Prefixes
[ "binary search", "brute force" ]
null
null
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in *m* stages. Each time he either adds a new number to the end of the sequence or takes *l* first elements of the current sequence and adds them *c* times to the end. More formally, if we represent the current sequence as *a*1,<=*a*2,<=...,<=*a**n*, then after we apply the described operation, the sequence transforms into *a*1,<=*a*2,<=...,<=*a**n*[,<=*a*1,<=*a*2,<=...,<=*a**l*] (the block in the square brackets must be repeated *c* times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.
The first line contains integer *m* (1<=≤<=*m*<=≤<=105) — the number of stages to build a sequence. Next *m* lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer *x**i* (1<=≤<=*x**i*<=≤<=105) — the number to add. Type 2 means copying a prefix of length *l**i* to the end *c**i* times, in this case the line further contains two integers *l**i*,<=*c**i* (1<=≤<=*l**i*<=≤<=105,<=1<=≤<=*c**i*<=≤<=104), *l**i* is the length of the prefix, *c**i* is the number of copyings. It is guaranteed that the length of prefix *l**i* is never larger than the current length of the sequence. The next line contains integer *n* (1<=≤<=*n*<=≤<=105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. 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 the elements that Sereja is interested in, in the order in which their numbers occur in the input.
[ "6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16\n" ]
[ "1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4\n" ]
none
[ { "input": "6\n1 1\n1 2\n2 2 1\n1 3\n2 5 2\n1 4\n16\n1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16", "output": "1 2 1 2 3 1 2 1 2 3 1 2 1 2 3 4" }, { "input": "2\n1 33085\n1 44638\n2\n1 2", "output": "33085 44638" }, { "input": "10\n1 57757\n1 45234\n1 80807\n1 38496\n1 27469\n1 42645\n1 72643\...
982
50,380,800
3
24,966
908
New Year and Original Order
[ "dp", "math" ]
null
null
Let *S*(*n*) denote the number that represents the digits of *n* in sorted order. For example, *S*(1)<==<=1,<=*S*(5)<==<=5,<=*S*(50394)<==<=3459,<=*S*(353535)<==<=333555. Given a number *X*, compute modulo 109<=+<=7.
The first line of input will contain the integer *X* (1<=≤<=*X*<=≤<=10700).
Print a single integer, the answer to the question.
[ "21\n", "345342\n" ]
[ "195\n", "390548434\n" ]
The first few values of *S* are 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 12. The sum of these values is 195.
[ { "input": "21", "output": "195" }, { "input": "345342", "output": "390548434" }, { "input": "9438174368", "output": "419438859" }, { "input": "33340691714056185860211260984431382156326935244157", "output": "683387308" }, { "input": "606593899524279654880666327437...
997
0
0
24,983
30
King's Problem?
[ "geometry", "greedy" ]
D. King's Problem?
3
256
Every true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom. King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are *n* cities in the kingdom at points with coordinates (*x*1,<=0),<=(*x*2,<=0),<=...,<=(*x**n*,<=0), and there is one city at point (*x**n*<=+<=1,<=*y**n*<=+<=1). King starts his journey in the city number *k*. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point.
The first line contains two integers *n* and *k* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*k*<=≤<=*n*<=+<=1) — amount of cities and index of the starting city. The second line contains *n*<=+<=1 numbers *x**i*. The third line contains *y**n*<=+<=1. All coordinates are integers and do not exceed 106 by absolute value. No two cities coincide.
Output the minimum possible length of the journey. Your answer must have relative or absolute error less than 10<=-<=6.
[ "3 1\n0 1 2 1\n1\n", "3 1\n1 0 2 1\n1\n", "4 5\n0 5 -1 -5 2\n3\n" ]
[ "3.41421356237309490000", "3.82842712474619030000", "14.24264068711928400000" ]
none
[ { "input": "3 1\n0 1 2 1\n1", "output": "3.41421356237309490000" }, { "input": "3 1\n1 0 2 1\n1", "output": "3.82842712474619030000" }, { "input": "4 5\n0 5 -1 -5 2\n3", "output": "14.24264068711928400000" }, { "input": "4 1\n0 5 -1 -5 2\n3", "output": "16.858413792983193...
278
9,932,800
0
25,048
570
Pig and Palindromes
[ "combinatorics", "dp" ]
null
null
Peppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of *n* rows and *m* columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to *n*, and the columns — from left to right with numbers from 1 to *m*. Let's denote the cell at the intersection of the *r*-th row and the *c*-th column as (*r*,<=*c*). Initially the pig stands in cell (1,<=1), and in the end she wants to be in cell (*n*,<=*m*). Since the pig is in a hurry to get home, she can go from cell (*r*,<=*c*), only to either cell (*r*<=+<=1,<=*c*) or (*r*,<=*c*<=+<=1). She cannot leave the forest. The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem). Count the number of beautiful paths from cell (1,<=1) to cell (*n*,<=*m*). Since this number can be very large, determine the remainder after dividing it by 109<=+<=7.
The first line contains two integers *n*,<=*m* (1<=≤<=*n*,<=*m*<=≤<=500) — the height and width of the field. Each of the following *n* lines contains *m* lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.
Print a single integer — the number of beautiful paths modulo 109<=+<=7.
[ "3 4\naaab\nbaaa\nabba\n" ]
[ "3" ]
Picture illustrating possibilities for the sample test. <img class="tex-graphics" src="https://espresso.codeforces.com/bf73568d1cf80d89f66d4e472a91ae0339af83a2.png" style="max-width: 100.0%;max-height: 100.0%;"/> <img class="tex-graphics" src="https://espresso.codeforces.com/1e870880d976e642be85498efab6bbd10bae8a84.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "3 4\naaab\nbaaa\nabba", "output": "3" }, { "input": "2 2\nab\naa", "output": "2" }, { "input": "3 5\nqqqrw\nwqqtw\newqqq", "output": "3" }, { "input": "1 5\nabbba", "output": "1" }, { "input": "1 5\nabbbb", "output": "0" }, { "input": "1 4\...
2,573
9,625,600
3
25,247
685
Travelling Through the Snow Queen's Kingdom
[ "bitmasks", "brute force", "divide and conquer", "graphs" ]
null
null
Gerda is travelling to the palace of the Snow Queen. The road network consists of *n* intersections and *m* bidirectional roads. Roads are numbered from 1 to *m*. Snow Queen put a powerful spell on the roads to change the weather conditions there. Now, if Gerda steps on the road *i* at the moment of time less or equal to *i*, she will leave the road exactly at the moment *i*. In case she steps on the road *i* at the moment of time greater than *i*, she stays there forever. Gerda starts at the moment of time *l* at the intersection number *s* and goes to the palace of the Snow Queen, located at the intersection number *t*. Moreover, she has to be there at the moment *r* (or earlier), before the arrival of the Queen. Given the description of the road network, determine for *q* queries *l**i*, *r**i*, *s**i* and *t**i* if it's possible for Gerda to get to the palace on time.
The first line of the input contains integers *n*, *m* and *q* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*m*,<=*q*<=≤<=200<=000) — the number of intersections in the road network of Snow Queen's Kingdom, the number of roads and the number of queries you have to answer. The *i*-th of the following *m* lines contains the description of the road number *i*. The description consists of two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*n*, *v**i*<=≠<=*u**i*) — the indices of the intersections connected by the *i*-th road. It's possible to get both from *v**i* to *u**i* and from *u**i* to *v**i* using only this road. Each pair of intersection may appear several times, meaning there are several roads connecting this pair. Last *q* lines contain the queries descriptions. Each of them consists of four integers *l**i*, *r**i*, *s**i* and *t**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*m*, 1<=≤<=*s**i*,<=*t**i*<=≤<=*n*, *s**i*<=≠<=*t**i*) — the moment of time Gerda starts her journey, the last moment of time she is allowed to arrive to the palace, the index of the starting intersection and the index of the intersection where palace is located.
For each query print "Yes" (without quotes) if Gerda can be at the Snow Queen palace on time (not later than *r**i*) or "No" (without quotes) otherwise.
[ "5 4 6\n1 2\n2 3\n3 4\n3 5\n1 3 1 4\n1 3 2 4\n1 4 4 5\n1 4 4 1\n2 3 1 4\n2 2 2 3\n" ]
[ "Yes\nYes\nYes\nNo\nNo\nYes\n" ]
none
[]
30
0
0
25,402
39
Tram
[]
I. Tram
2
64
In a Berland city S*** there is a tram engine house and only one tram. Three people work in the house — the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly *c* minutes to complete the route. The head of the engine house controlled the tram’s movement, going outside every *c* minutes when the tram drove by the engine house, and the head left the driver without a bonus if he was even one second late. It used to be so. Afterwards the Berland Federal Budget gave money to make more tramlines in S***, and, as it sometimes happens, the means were used as it was planned. The tramlines were rebuilt and as a result they turned into a huge network. The previous loop route may have been destroyed. S*** has *n* crossroads and now *m* tramlines that links the pairs of crossroads. The traffic in Berland is one way so the tram can move along each tramline only in one direction. There may be several tramlines between two crossroads, which go same way or opposite ways. Every tramline links two different crossroads and for each crossroad there is at least one outgoing tramline. So, the tramlines were built but for some reason nobody gave a thought to increasing the number of trams in S***! The tram continued to ride alone but now the driver had an excellent opportunity to get rid of the unending control of the engine house head. For now due to the tramline network he could choose the route freely! Now at every crossroad the driver can arbitrarily choose the way he can go. The tram may even go to the parts of S*** from where it cannot return due to one way traffic. The driver is not afraid of the challenge: at night, when the city is asleep, he can return to the engine house safely, driving along the tramlines in the opposite direction. The city people were rejoicing for some of the had been waiting for the tram to appear on their streets for several years. However, the driver’s behavior enraged the engine house head. Now he tries to carry out an insidious plan of installing cameras to look after the rebellious tram. The plan goes as follows. The head of the engine house wants to install cameras at some crossroads, to choose a period of time *t* and every *t* minutes turn away from the favourite TV show to check where the tram is. Also the head of the engine house wants at all moments of time, divisible by *t*, and only at such moments the tram to appear on a crossroad under a camera. There must be a camera on the crossroad by the engine house to prevent possible terrorist attacks on the engine house head. Among all the possible plans the engine house head chooses the plan with the largest possible value of *t* (as he hates being distracted from his favourite TV show but he has to). If such a plan is not unique, pick the plan that requires the minimal possible number of cameras. Find such a plan.
The first line contains integers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=105) — the number of crossroads and tramlines in S*** respectively. The next *m* lines contain the descriptions of the tramlines in "*u* *v*" format, where *u* is the initial tramline crossroad and *v* is its final crossroad. The crossroads are numbered with integers from 1 to *n*, and the engine house is at the crossroad number 1.
In the first line output the value of *t*. In the next line output the value of *k* — the required number of the cameras. In the next line output space-separated numbers of the crossroads, where the cameras should be installed. Output the numbers in increasing order.
[ "4 5\n1 2\n2 3\n3 4\n4 1\n1 4\n" ]
[ "2\n2\n1 3\n" ]
none
[]
0
0
-1
25,442
405
Graph Cutting
[ "dfs and similar", "graphs" ]
null
null
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with *n* vertices (numbered from 1 to *n*) and *m* edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible!
The first line of input contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105), the number of vertices and the number of edges in the graph. The next *m* lines contain the description of the graph's edges. The *i*-th line contains two space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*), the numbers of the vertices connected by the *i*-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
If it is possible to cut the given graph into edge-distinct paths of length 2, output lines. In the *i*-th line print three space-separated integers *x**i*, *y**i* and *z**i*, the description of the *i*-th path. The graph should contain this path, i.e., the graph should contain edges (*x**i*,<=*y**i*) and (*y**i*,<=*z**i*). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them. If it is impossible to cut the given graph, print "No solution" (without quotes).
[ "8 12\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n3 5\n3 6\n5 6\n6 7\n6 8\n7 8\n", "3 3\n1 2\n2 3\n3 1\n", "3 2\n1 2\n2 3\n" ]
[ "1 2 4\n1 3 2\n1 4 3\n5 3 6\n5 6 8\n6 7 8", "No solution\n", "1 2 3\n" ]
none
[]
46
0
0
25,444
804
Expected diameter of a tree
[ "binary search", "brute force", "dfs and similar", "dp", "sortings", "trees" ]
null
null
Pasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem. We have a forest (acyclic undirected graph) with *n* vertices and *m* edges. There are *q* queries we should answer. In each query two vertices *v* and *u* are given. Let *V* be the set of vertices in the connected component of the graph that contains *v*, and *U* be the set of vertices in the connected component of the graph that contains *u*. Let's add an edge between some vertex and some vertex in and compute the value *d* of the resulting component. If the resulting component is a tree, the value *d* is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of *d*, if we choose vertices *a* and *b* from the sets uniformly at random? Can you help Pasha to solve this problem? The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices. Note that queries don't add edges to the initial forest.
The first line contains three integers *n*, *m* and *q*(1<=≤<=*n*,<=*m*,<=*q*<=≤<=105) — the number of vertices, the number of edges in the graph and the number of queries. Each of the next *m* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*), that means there is an edge between vertices *u**i* and *v**i*. It is guaranteed that the given graph is a forest. Each of the next *q* lines contains two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*) — the vertices given in the *i*-th query.
For each query print the expected value of *d* as described in the problem statement. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. Let's assume that your answer is *a*, and the jury's answer is *b*. The checker program will consider your answer correct, if .
[ "3 1 2\n1 3\n3 1\n2 3\n", "5 2 3\n2 4\n4 3\n4 2\n4 1\n2 5\n" ]
[ "-1\n2.0000000000\n", "-1\n2.6666666667\n2.6666666667\n" ]
In the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1 - 2, the other one is 2 - 3. In both ways the resulting diameter is 2, so the answer is 2. In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1 - 2 or 1 - 3 the diameter is 3, and for added edge 1 - 4 the diameter is 2. Thus, the answer is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f12c59a7dfd20580ff1e8e5eeab9ecd19cb3c3f1.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "3 1 2\n1 3\n3 1\n2 3", "output": "-1\n2.0000000000" }, { "input": "5 2 3\n2 4\n4 3\n4 2\n4 1\n2 5", "output": "-1\n2.6666666667\n2.6666666667" }, { "input": "17 15 13\n3 15\n3 1\n15 9\n16 6\n1 5\n1 8\n16 12\n15 7\n9 4\n6 11\n15 14\n9 10\n15 13\n1 17\n11 2\n7 3\n9 6\n9 7\n1 8\...
0
0
-1
25,456
351
Jeff and Rounding
[ "dp", "greedy", "implementation", "math" ]
null
null
Jeff got 2*n* real numbers *a*1,<=*a*2,<=...,<=*a*2*n* as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes *n* operations, each of them goes as follows: - choose indexes *i* and *j* (*i*<=≠<=*j*) that haven't been chosen yet; - round element *a**i* to the nearest integer that isn't more than *a**i* (assign to *a**i*: ⌊ *a**i* ⌋); - round element *a**j* to the nearest integer that isn't less than *a**j* (assign to *a**j*: ⌈ *a**j* ⌉). Nevertheless, Jeff doesn't want to hurt the feelings of the person who gave him the sequence. That's why the boy wants to perform the operations so as to make the absolute value of the difference between the sum of elements before performing the operations and the sum of elements after performing the operations as small as possible. Help Jeff find the minimum absolute value of the difference.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000). The next line contains 2*n* real numbers *a*1, *a*2, ..., *a*2*n* (0<=≤<=*a**i*<=≤<=10000), given with exactly three digits after the decimal point. The numbers are separated by spaces.
In a single line print a single real number — the required difference with exactly three digits after the decimal point.
[ "3\n0.000 0.500 0.750 1.000 2.000 3.000\n", "3\n4469.000 6526.000 4864.000 9356.383 7490.000 995.896\n" ]
[ "0.250\n", "0.279\n" ]
In the first test case you need to perform the operations as follows: (*i* = 1, *j* = 4), (*i* = 2, *j* = 3), (*i* = 5, *j* = 6). In this case, the difference will equal |(0 + 0.5 + 0.75 + 1 + 2 + 3) - (0 + 0 + 1 + 1 + 2 + 3)| = 0.25.
[ { "input": "3\n0.000 0.500 0.750 1.000 2.000 3.000", "output": "0.250" }, { "input": "3\n4469.000 6526.000 4864.000 9356.383 7490.000 995.896", "output": "0.279" }, { "input": "3\n673.674 9263.142 6780.000 9801.000 4640.000 8244.000", "output": "0.184" }, { "input": "3\n6470....
124
5,632,000
0
25,482
747
Comments
[ "dfs and similar", "expression parsing", "implementation", "strings" ]
null
null
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment. When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: - at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: - at first, print a integer *d* — the maximum depth of nesting comments; - after that print *d* lines, the *i*-th of them corresponds to nesting level *i*; - for the *i*-th row print comments of nesting level *i* in the order of their appearance in the Policarp's comments feed, separated by space.
The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros. The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid.
Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input.
[ "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\n", "a,5,A,0,a,0,A,0,a,0,A,0\n", "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0\n" ]
[ "3\nhello test one \nok bye two \na b \n", "2\na \nA a A a A \n", "4\nA K M \nB F H L N O \nC D G I P \nE J \n" ]
The first example is explained in the statements.
[ { "input": "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0", "output": "3\nhello test one \nok bye two \na b " }, { "input": "a,5,A,0,a,0,A,0,a,0,A,0", "output": "2\na \nA a A a A " }, { "input": "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0", "output": "4\nA K M \n...
0
0
-1
25,528
977
Divide by three, multiply by two
[ "dfs and similar", "math", "sortings" ]
null
null
Polycarp likes to play with numbers. He takes some integer number $x$, writes it down on the board, and then performs with it $n - 1$ operations of the two kinds: - divide the number $x$ by $3$ ($x$ must be divisible by $3$); - multiply the number $x$ by $2$. After each operation, Polycarp writes down the result on the board and replaces $x$ by the result. So there will be $n$ numbers on the board after all. You are given a sequence of length $n$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board. Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number. It is guaranteed that the answer exists.
The first line of the input contatins an integer number $n$ ($2 \le n \le 100$) — the number of the elements in the sequence. The second line of the input contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3 \cdot 10^{18}$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.
Print $n$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.
[ "6\n4 8 6 3 12 9\n", "4\n42 28 84 126\n", "2\n1000000000000000000 3000000000000000000\n" ]
[ "9 3 6 12 4 8 \n", "126 42 84 28 \n", "3000000000000000000 1000000000000000000 \n" ]
In the first example the given sequence can be rearranged in the following way: $[9, 3, 6, 12, 4, 8]$. It can match possible Polycarp's game which started with $x = 9$.
[ { "input": "6\n4 8 6 3 12 9", "output": "9 3 6 12 4 8 " }, { "input": "4\n42 28 84 126", "output": "126 42 84 28 " }, { "input": "2\n1000000000000000000 3000000000000000000", "output": "3000000000000000000 1000000000000000000 " }, { "input": "19\n46875000000000000 73242187500...
124
4,198,400
-1
25,550
173
Chamber of Secrets
[ "dfs and similar", "shortest paths" ]
null
null
"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny. The Chamber of Secrets is an *n*<=×<=*m* rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below. The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position. Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.
The first line of the input contains two integer numbers *n* and *m* (2<=≤<=*n*,<=*m*<=≤<=1000). Each of the next *n* lines contains *m* characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.
Print the minimum number of columns to make magic or -1 if it's impossible to do.
[ "3 3\n.#.\n...\n.#.\n", "4 3\n##.\n...\n.#.\n.#.\n" ]
[ "2\n", "2\n" ]
The figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.
[ { "input": "3 3\n.#.\n...\n.#.", "output": "2" }, { "input": "4 3\n##.\n...\n.#.\n.#.", "output": "2" }, { "input": "3 3\n###\n###\n###", "output": "2" }, { "input": "3 4\n..##\n....\n..#.", "output": "2" }, { "input": "4 3\n#.#\n...\n...\n.##", "output": "2" ...
280
409,600
0
25,638
325
Stadium and Games
[ "binary search", "math" ]
null
null
Daniel is organizing a football tournament. He has come up with the following tournament format: 1. In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even. 1. Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are *x* teams, there will be games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games. Daniel has already booked the stadium for *n* games. Help him to determine how many teams he should invite so that the tournament needs exactly *n* games. You should print all possible numbers of teams that will yield exactly *n* games in ascending order, or -1 if there are no such numbers.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=1018), the number of games that should be played. 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 all possible numbers of invited teams in ascending order, one per line. If exactly *n* games cannot be played, output one number: -1.
[ "3\n", "25\n", "2\n" ]
[ "3\n4\n", "20\n", "-1\n" ]
none
[ { "input": "3", "output": "3\n4" }, { "input": "25", "output": "20" }, { "input": "2", "output": "-1" }, { "input": "1", "output": "2" }, { "input": "15", "output": "10\n16" }, { "input": "314", "output": "-1" }, { "input": "524800", "o...
216
0
0
25,639
96
Lucky Numbers (easy)
[ "binary search", "bitmasks", "brute force" ]
B. Lucky Numbers (easy)
2
256
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not. One day Petya came across a positive integer *n*. Help him to find the least super lucky number which is not less than *n*.
The only line contains a positive integer *n* (1<=≤<=*n*<=≤<=109). This number doesn't have leading zeroes.
Output the least super lucky number that is more than or equal to *n*. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.
[ "4500\n", "47\n" ]
[ "4747\n", "47\n" ]
none
[ { "input": "4500", "output": "4747" }, { "input": "47", "output": "47" }, { "input": "1", "output": "47" }, { "input": "12", "output": "47" }, { "input": "4587", "output": "4747" }, { "input": "100", "output": "4477" }, { "input": "1007", ...
154
5,120,000
0
25,643
547
Mike and Fish
[ "constructive algorithms", "dfs and similar", "graphs" ]
null
null
As everyone knows, bears love fish. But Mike is a strange bear; He hates fish! The even more strange thing about him is he has an infinite number of blue and red fish. He has marked *n* distinct points in the plane. *i*-th point is point (*x**i*,<=*y**i*). He wants to put exactly one fish in each of these points such that the difference between the number of red fish and the blue fish on each horizontal or vertical line is at most 1. He can't find a way to perform that! Please help him.
The first line of input contains integer *n* (1<=≤<=*n*<=≤<=2<=×<=105). The next *n* lines contain the information about the points, *i*-th line contains two integers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=2<=×<=105), the *i*-th point coordinates. It is guaranteed that there is at least one valid answer.
Print the answer as a sequence of *n* characters 'r' (for red) or 'b' (for blue) where *i*-th character denotes the color of the fish in the *i*-th point.
[ "4\n1 1\n1 2\n2 1\n2 2\n", "3\n1 1\n1 2\n2 1\n" ]
[ "brrb\n", "brr\n" ]
none
[ { "input": "4\n1 1\n1 2\n2 1\n2 2", "output": "brrb" }, { "input": "3\n1 1\n1 2\n2 1", "output": "brr" }, { "input": "3\n157210 22861\n175396 39466\n40933 17093", "output": "rrr" }, { "input": "5\n55599 84144\n169207 98421\n1909 186625\n31525 147710\n7781 82078", "output"...
1,263
268,390,400
0
25,659
916
Jamie and Tree
[ "data structures", "trees" ]
null
null
To your surprise, Jamie is the final boss! Ehehehe. Jamie has given you a tree with *n* vertices, numbered from 1 to *n*. Initially, the root of the tree is the vertex with number 1. Also, each vertex has a value on it. Jamie also gives you three types of queries on the tree: 1 *v* — Change the tree's root to vertex with number *v*. 2 *u* *v* *x* — For each vertex in the subtree of smallest size that contains *u* and *v*, add *x* to its value. 3 *v* — Find sum of values of vertices in the subtree of vertex with number *v*. A subtree of vertex *v* is a set of vertices such that *v* lies on shortest path from this vertex to root of the tree. Pay attention that subtree of a vertex can change after changing the tree's root. Show your strength in programming to Jamie by performing the queries accurately!
The first line of input contains two space-separated integers *n* and *q* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*q*<=≤<=105) — the number of vertices in the tree and the number of queries to process respectively. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=108<=≤<=*a**i*<=≤<=108) — initial values of the vertices. Next *n*<=-<=1 lines contains two space-separated integers *u**i*,<=*v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*) describing edge between vertices *u**i* and *v**i* in the tree. The following *q* lines describe the queries. Each query has one of following formats depending on its type: 1 *v* (1<=≤<=*v*<=≤<=*n*) for queries of the first type. 2 *u* *v* *x* (1<=≤<=*u*,<=*v*<=≤<=*n*,<=<=-<=108<=≤<=*x*<=≤<=108) for queries of the second type. 3 *v* (1<=≤<=*v*<=≤<=*n*) for queries of the third type. All numbers in queries' descriptions are integers. The queries must be carried out in the given order. It is guaranteed that the tree is valid.
For each query of the third type, output the required answer. It is guaranteed that at least one query of the third type is given by Jamie.
[ "6 7\n1 4 2 8 5 7\n1 2\n3 1\n4 3\n4 5\n3 6\n3 1\n2 4 6 3\n3 4\n1 6\n2 2 4 -5\n1 4\n3 3\n", "4 6\n4 3 5 6\n1 2\n2 3\n3 4\n3 1\n1 3\n2 2 4 3\n1 1\n2 2 4 -3\n3 1\n" ]
[ "27\n19\n5\n", "18\n21\n" ]
The following picture shows how the tree varies after the queries in the first sample.
[]
30
0
0
25,677
513
Inversions problem
[ "dp" ]
null
null
You are given a permutation of *n* numbers *p*1,<=*p*2,<=...,<=*p**n*. We perform *k* operations of the following type: choose uniformly at random two indices *l* and *r* (*l*<=≤<=*r*) and reverse the order of the elements *p**l*,<=*p**l*<=+<=1,<=...,<=*p**r*. Your task is to find the expected value of the number of inversions in the resulting permutation.
The first line of input contains two integers *n* and *k* (1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=109). The next line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* — the given permutation. All *p**i* are different and in range from 1 to *n*. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. - In subproblem G1 (3 points), the constraints 1<=≤<=*n*<=≤<=6, 1<=≤<=*k*<=≤<=4 will hold. - In subproblem G2 (5 points), the constraints 1<=≤<=*n*<=≤<=30, 1<=≤<=*k*<=≤<=200 will hold. - In subproblem G3 (16 points), the constraints 1<=≤<=*n*<=≤<=100, 1<=≤<=*k*<=≤<=109 will hold.
Output the answer with absolute or relative error no more than 1*e*<=-<=9.
[ "3 1\n1 2 3\n", "3 4\n1 3 2\n" ]
[ "0.833333333333333\n", "1.458333333333334\n" ]
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/eb946338365d9781f7d2e9ec692c26702d0ae3a7.png" style="max-width: 100.0%;max-height: 100.0%;"/>, the interval will consist of a single element and the permutation will not be altered. With probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a063853bdfd761520e06382373fe270b6078994b.png" style="max-width: 100.0%;max-height: 100.0%;"/> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a063853bdfd761520e06382373fe270b6078994b.png" style="max-width: 100.0%;max-height: 100.0%;"/> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cc9273ddc69be58e22251bdf070c83670617a9a2.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "3 1\n1 2 3", "output": "0.833333333333333" }, { "input": "3 4\n1 3 2", "output": "1.458333333333334" }, { "input": "6 1\n4 2 5 1 3 6", "output": "6.380952380952381" }, { "input": "6 2\n1 4 6 5 2 3", "output": "6.954648526077097" }, { "input": "4 4\n2 3...
46
0
0
25,698
630
Indivisibility
[ "math", "number theory" ]
null
null
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus. A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that *n* people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.
The only line of the input contains one integer *n* (1<=≤<=*n*<=≤<=1018) — the prediction on the number of people who will buy the game.
Output one integer showing how many numbers from 1 to *n* are not divisible by any number from 2 to 10.
[ "12\n" ]
[ "2" ]
none
[ { "input": "12", "output": "2" }, { "input": "2519", "output": "576" }, { "input": "2521", "output": "577" }, { "input": "1", "output": "1" }, { "input": "314159265", "output": "71807832" }, { "input": "718281828459045235", "output": "1641787036477...
46
0
3
25,704
689
Friends and Subsequences
[ "binary search", "data structures" ]
null
null
Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows? Every one of them has an integer sequences *a* and *b* of length *n*. Being given a query of the form of pair of integers (*l*,<=*r*), Mike can instantly tell the value of while !Mike can instantly tell the value of . Now suppose a robot (you!) asks them all possible different queries of pairs of integers (*l*,<=*r*) (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) (so he will make exactly *n*(*n*<=+<=1)<=/<=2 queries) and counts how many times their answers coincide, thus for how many pairs is satisfied. How many occasions will the robot count?
The first line contains only integer *n* (1<=≤<=*n*<=≤<=200<=000). The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the sequence *a*. The third line contains *n* integer numbers *b*1,<=*b*2,<=...,<=*b**n* (<=-<=109<=≤<=*b**i*<=≤<=109) — the sequence *b*.
Print the only integer number — the number of occasions the robot will count, thus for how many pairs is satisfied.
[ "6\n1 2 3 2 1 4\n6 7 1 2 3 2\n", "3\n3 3 3\n1 1 1\n" ]
[ "2\n", "0\n" ]
The occasions in the first sample case are: 1.*l* = 4,*r* = 4 since *max*{2} = *min*{2}. 2.*l* = 4,*r* = 5 since *max*{2, 1} = *min*{2, 3}. There are no occasions in the second sample case since Mike will answer 3 to any query pair, but !Mike will always answer 1.
[ { "input": "6\n1 2 3 2 1 4\n6 7 1 2 3 2", "output": "2" }, { "input": "3\n3 3 3\n1 1 1", "output": "0" }, { "input": "17\n714413739 -959271262 714413739 -745891378 926207665 -404845105 -404845105 -959271262 -189641729 -670860364 714413739 -189641729 192457837 -745891378 -670860364 536388...
982
456,908,800
3
25,713
333
Chips
[ "greedy" ]
null
null
Gerald plays the following game. He has a checkered field of size *n*<=×<=*n* cells, where *m* various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for *n*<=-<=1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases: - At least one of the chips at least once fell to the banned cell. - At least once two chips were on the same cell. - At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.
The first line contains two space-separated integers *n* and *m* (2<=≤<=*n*<=≤<=1000, 0<=≤<=*m*<=≤<=105) — the size of the field and the number of banned cells. Next *m* lines each contain two space-separated integers. Specifically, the *i*-th of these lines contains numbers *x**i* and *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*) — the coordinates of the *i*-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to *n*, and the columns — from left to right from 1 to *n*.
Print a single integer — the maximum points Gerald can earn in this game.
[ "3 1\n2 2\n", "3 0\n", "4 3\n3 1\n3 2\n3 3\n" ]
[ "0\n", "1\n", "1\n" ]
In the first test the answer equals zero as we can't put chips into the corner cells. In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips. In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).
[ { "input": "3 1\n2 2", "output": "0" }, { "input": "3 0", "output": "1" }, { "input": "4 3\n3 1\n3 2\n3 3", "output": "1" }, { "input": "2 1\n1 1", "output": "0" }, { "input": "2 3\n1 2\n2 1\n2 2", "output": "0" }, { "input": "5 1\n3 2", "output": ...
1,000
28,672,000
0
25,725
171
ucyhf
[ "*special", "brute force", "implementation", "number theory" ]
null
null
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
jxu ydfkj sediyiji ev q iydwbu ydjuwuh *d* (1<=≤<=*d*<=≤<=11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
ekjfkj q iydwbu dkcruh.
[ "1\n" ]
[ "13\n" ]
none
[ { "input": "1", "output": "13" }, { "input": "2", "output": "17" }, { "input": "3", "output": "31" }, { "input": "4", "output": "37" }, { "input": "5", "output": "71" }, { "input": "6", "output": "73" }, { "input": "7", "output": "79" ...
746
1,228,800
-1
25,741
549
Happy Line
[ "constructive algorithms", "greedy", "sortings" ]
null
null
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of *n* Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, so each person agrees to swap places with the person right behind him for just 1 dollar. More formally, if person *a* stands just behind person *b*, then person *a* can pay person *b* 1 dollar, then *a* and *b* get swapped. Of course, if person *a* has zero dollars, he can not swap places with person *b*. Residents of Berland are strange people. In particular, they get upset when there is someone with a strictly smaller sum of money in the line in front of them. Can you help the residents of Berland form such order in the line so that they were all happy? A happy resident is the one who stands first in the line or the one in front of who another resident stands with not less number of dollars. Note that the people of Berland are people of honor and they agree to swap places only in the manner described above.
The first line contains integer *n* (1<=≤<=*n*<=≤<=200<=000) — the number of residents who stand in the line. The second line contains *n* space-separated integers *a**i* (0<=≤<=*a**i*<=≤<=109), where *a**i* is the number of Berland dollars of a man standing on the *i*-th position in the line. The positions are numbered starting from the end of the line.
If it is impossible to make all the residents happy, print ":(" without the quotes. Otherwise, print in the single line *n* space-separated integers, the *i*-th of them must be equal to the number of money of the person on position *i* in the new line. If there are multiple answers, print any of them.
[ "2\n11 8\n", "5\n10 9 7 10 6\n", "3\n12 3 3\n" ]
[ "9 10 ", ":(\n", "4 4 10 " ]
In the first sample two residents should swap places, after that the first resident has 10 dollars and he is at the head of the line and the second resident will have 9 coins and he will be at the end of the line. In the second sample it is impossible to achieve the desired result. In the third sample the first person can swap with the second one, then they will have the following numbers of dollars: 4 11 3, then the second person (in the new line) swaps with the third one, and the resulting numbers of dollars will equal to: 4 4 10. In this line everybody will be happy.
[ { "input": "2\n11 8", "output": "9 10 " }, { "input": "5\n10 9 7 10 6", "output": ":(" }, { "input": "3\n12 3 3", "output": "4 4 10 " }, { "input": "4\n7 3 9 10", "output": "4 6 9 10 " }, { "input": "1\n1", "output": "1 " }, { "input": "5\n15 5 8 6 3",...
1,000
14,233,600
0
25,755
888
Xor-MST
[ "bitmasks", "constructive algorithms", "data structures" ]
null
null
You are given a complete undirected graph with *n* vertices. A number *a**i* is assigned to each vertex, and the weight of an edge between vertices *i* and *j* is equal to *a**i*<=*xor*<=*a**j*. Calculate the weight of the minimum spanning tree in this graph.
The first line contains *n* (1<=≤<=*n*<=≤<=200000) — the number of vertices in the graph. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (0<=≤<=*a**i*<=&lt;<=230) — the numbers assigned to the vertices.
Print one number — the weight of the minimum spanning tree in the graph.
[ "5\n1 2 3 4 5\n", "4\n1 2 3 4\n" ]
[ "8\n", "8\n" ]
none
[ { "input": "5\n1 2 3 4 5", "output": "8" }, { "input": "4\n1 2 3 4", "output": "8" }, { "input": "1\n1", "output": "0" } ]
46
0
0
25,815
730
Toda 2
[ "greedy", "implementation" ]
null
null
A group of *n* friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the *i*-th friend is *r**i*. The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all *n* friends. So the friends are faced with the problem: how to make all their ratings equal. One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than *n*) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so *r**i*<==<=0 doesn't change after losing. The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members). The friends want to make their ratings equal but as high as possible. Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.
The first line contains a single integer *n* (2<=≤<=*n*<=≤<=100) — the number of friends. The second line contains *n* non-negative integers *r*1,<=*r*2,<=...,<=*r**n* (0<=≤<=*r**i*<=≤<=100), where *r**i* is the initial rating of the *i*-th friend.
In the first line, print a single integer *R* — the final rating of each of the friends. In the second line, print integer *t* — the number of matches the friends have to play. Each of the following *t* lines should contain *n* characters '0' or '1', where the *j*-th character of the *i*-th line is equal to: - '0', if friend *j* should not play in match *i*, - '1', if friend *j* should play in match *i*. Each line should contain between two and five characters '1', inclusive. The value *t* should not exceed 104, it is guaranteed that such solution exists. Remember that you shouldn't minimize the value *t*, but you should maximize *R*. If there are multiple solutions, print any of them.
[ "5\n4 5 1 7 4\n", "2\n1 2\n", "3\n1 1 1\n" ]
[ "1\n8\n01010\n00011\n01010\n10010\n00011\n11000\n00011\n11000\n", "0\n2\n11\n11\n", "1\n0\n" ]
none
[ { "input": "5\n4 5 1 7 4", "output": "1\n8\n01010\n00011\n01010\n10010\n00011\n11000\n00011\n11000" }, { "input": "2\n1 2", "output": "0\n2\n11\n11" }, { "input": "3\n1 1 1", "output": "1\n0" }, { "input": "10\n6 8 7 6 8 7 6 7 8 7", "output": "6\n4\n0100100010\n0000000111...
140
307,200
0
25,869
222
Reducing Fractions
[ "implementation", "math", "number theory", "sortings" ]
null
null
To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you.
The first input line contains two space-separated integers *n*, *m* (1<=≤<=*n*,<=*m*<=≤<=105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=107) — the numbers that are multiplied to produce the numerator. The third line contains *m* space-separated integers: *b*1,<=*b*2,<=...,<=*b**m* (1<=≤<=*b**i*<=≤<=107) — the numbers that are multiplied to produce the denominator.
Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print *n**out*,<=*m**out* must satisfy the inequality 1<=≤<=*n**out*,<=*m**out*<=≤<=105, and the actual values in the sets *a**out*,<=*i* and *b**out*,<=*i* must satisfy the inequality 1<=≤<=*a**out*,<=*i*,<=*b**out*,<=*i*<=≤<=107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer *x* (*x*<=&gt;<=1), that the numerator and the denominator of the printed fraction are divisible by *x*. If there are several matching answers, print any of them.
[ "3 2\n100 5 2\n50 10\n", "4 3\n2 5 10 20\n100 1 3\n" ]
[ "2 3\n2 1\n1 1 1\n", "1 1\n20\n3\n" ]
In the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1. In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3.
[ { "input": "3 2\n100 5 2\n50 10", "output": "2 3\n2 1\n1 1 1" }, { "input": "4 3\n2 5 10 20\n100 1 3", "output": "1 1\n20\n3" }, { "input": "2 3\n50 10\n100 5 2", "output": "2 3\n1 1 \n2 1 1 " }, { "input": "1 1\n1\n1", "output": "1 1\n1 \n1 " }, { "input": "3 2\n...
1,840
201,216,000
3
25,873
177
Party
[ "dfs and similar", "dsu", "graphs" ]
null
null
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friendship relations, and not to invite those who dislike each other. Both friendship and dislike are mutual feelings. More formally, for each invited person the following conditions should be fulfilled: - all his friends should also be invited to the party; - the party shouldn't have any people he dislikes; - all people who are invited to the party should be connected with him by friendship either directly or through a chain of common friends of arbitrary length. We'll say that people *a*1 and *a**p* are connected through a chain of common friends if there exists a sequence of people *a*2,<=*a*3,<=...,<=*a**p*<=-<=1 such that all pairs of people *a**i* and *a**i*<=+<=1 (1<=≤<=*i*<=&lt;<=*p*) are friends. Help the Beaver find the maximum number of acquaintances he can invite.
The first line of input contains an integer *n* — the number of the Beaver's acquaintances. The second line contains an integer *k* — the number of pairs of friends. Next *k* lines contain space-separated pairs of integers *u**i*,<=*v**i* — indices of people who form the *i*-th pair of friends. The next line contains an integer *m* — the number of pairs of people who dislike each other. Next *m* lines describe pairs of people who dislike each other in the same format as the pairs of friends were described. Each pair of people is mentioned in the input at most once . In particular, two persons cannot be friends and dislike each other at the same time. The input limitations for getting 30 points are: - 2<=≤<=*n*<=≤<=14 The input limitations for getting 100 points are: - 2<=≤<=*n*<=≤<=2000
Output a single number — the maximum number of people that can be invited to the party. If a group of people that meets all the requirements is impossible to select, output 0.
[ "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9\n" ]
[ "3" ]
Let's have a look at the example. Two groups of people can be invited: {1, 2, 3} and {4, 5}, thus the answer will be the size of the largest of these groups. Group {6, 7, 8, 9} doesn't fit, since it includes people 7 and 9 who dislike each other. Group {1, 2, 3, 4, 5} also doesn't fit, because not all of its members are connected by a chain of common friends (for example, people 2 and 5 aren't connected).
[ { "input": "9\n8\n1 2\n1 3\n2 3\n4 5\n6 7\n7 8\n8 9\n9 6\n2\n1 6\n7 9", "output": "3" }, { "input": "2\n1\n1 2\n0", "output": "2" }, { "input": "2\n0\n1\n1 2", "output": "1" }, { "input": "3\n2\n1 2\n1 3\n1\n2 3", "output": "0" }, { "input": "3\n3\n1 3\n2 1\n2 3\n...
154
0
0
25,952
653
Bear and Up-Down
[ "brute force", "implementation" ]
null
null
The life goes up and down, just like nice sequences. Sequence *t*1,<=*t*2,<=...,<=*t**n* is called nice if the following two conditions are satisfied: - *t**i*<=&lt;<=*t**i*<=+<=1 for each odd *i*<=&lt;<=*n*; - *t**i*<=&gt;<=*t**i*<=+<=1 for each even *i*<=&lt;<=*n*. For example, sequences (2,<=8), (1,<=5,<=1) and (2,<=5,<=1,<=100,<=99,<=120) are nice, while (1,<=1), (1,<=2,<=3) and (2,<=5,<=3,<=2) are not. Bear Limak has a sequence of positive integers *t*1,<=*t*2,<=...,<=*t**n*. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices *i*<=&lt;<=*j* and swap elements *t**i* and *t**j* in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
The first line of the input contains one integer *n* (2<=≤<=*n*<=≤<=150<=000) — the length of the sequence. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=150<=000) — the initial sequence. It's guaranteed that the given sequence is not nice.
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
[ "5\n2 8 4 7 7\n", "4\n200 150 100 50\n", "10\n3 2 1 4 1 4 1 4 1 4\n", "9\n1 2 3 4 5 6 7 8 9\n" ]
[ "2\n", "1\n", "8\n", "0\n" ]
In the first sample, there are two ways to get a nice sequence with one swap: 1. Swap *t*<sub class="lower-index">2</sub> = 8 with *t*<sub class="lower-index">4</sub> = 7. 1. Swap *t*<sub class="lower-index">1</sub> = 2 with *t*<sub class="lower-index">5</sub> = 7. In the second sample, there is only one way — Limak should swap *t*<sub class="lower-index">1</sub> = 200 with *t*<sub class="lower-index">4</sub> = 50.
[ { "input": "5\n2 8 4 7 7", "output": "2" }, { "input": "4\n200 150 100 50", "output": "1" }, { "input": "10\n3 2 1 4 1 4 1 4 1 4", "output": "8" }, { "input": "9\n1 2 3 4 5 6 7 8 9", "output": "0" }, { "input": "5\n1 1 1 4 3", "output": "1" }, { "input...
1,076
15,667,200
3
25,993
645
Robot Rapping Results Report
[ "binary search", "dp", "graphs" ]
null
null
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots operate under deterministic algorithms. In particular, robot *i* will beat robot *j* if and only if robot *i* has a higher skill level than robot *j*. And if robot *i* beats robot *j* and robot *j* beats robot *k*, then robot *i* will beat robot *k*. Since rapping is such a subtle art, two robots can never have the same skill level. Given the results of the rap battles in the order in which they were played, determine the minimum number of first rap battles that needed to take place before Bessie could order all of the robots by skill level.
The first line of the input consists of two integers, the number of robots *n* (2<=≤<=*n*<=≤<=100<=000) and the number of rap battles *m* (). The next *m* lines describe the results of the rap battles in the order they took place. Each consists of two integers *u**i* and *v**i* (1<=≤<=*u**i*,<=*v**i*<=≤<=*n*, *u**i*<=≠<=*v**i*), indicating that robot *u**i* beat robot *v**i* in the *i*-th rap battle. No two rap battles involve the same pair of robots. It is guaranteed that at least one ordering of the robots satisfies all *m* relations.
Print the minimum *k* such that the ordering of the robots by skill level is uniquely defined by the first *k* rap battles. If there exists more than one ordering that satisfies all *m* relations, output -1.
[ "4 5\n2 1\n1 3\n2 3\n4 2\n4 3\n", "3 2\n1 2\n3 2\n" ]
[ "4\n", "-1\n" ]
In the first sample, the robots from strongest to weakest must be (4, 2, 1, 3), which Bessie can deduce after knowing the results of the first four rap battles. In the second sample, both (1, 3, 2) and (3, 1, 2) are possible orderings of the robots from strongest to weakest after both rap battles.
[ { "input": "4 5\n2 1\n1 3\n2 3\n4 2\n4 3", "output": "4" }, { "input": "3 2\n1 2\n3 2", "output": "-1" }, { "input": "2 1\n1 2", "output": "1" }, { "input": "2 1\n2 1", "output": "1" }, { "input": "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5", "outp...
1,403
42,905,600
3
26,028
407
k-d-sequence
[ "data structures" ]
null
null
We'll call a sequence of integers a good *k*-*d* sequence if we can add to it at most *k* numbers in such a way that after the sorting the sequence will be an arithmetic progression with difference *d*. You got hold of some sequence *a*, consisting of *n* integers. Your task is to find its longest contiguous subsegment, such that it is a good *k*-*d* sequence.
The first line contains three space-separated integers *n*,<=*k*,<=*d* (1<=≤<=*n*<=≤<=2·105; 0<=≤<=*k*<=≤<=2·105; 0<=≤<=*d*<=≤<=109). The second line contains *n* space-separated integers: *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=≤<=*a**i*<=≤<=109) — the actual sequence.
Print two space-separated integers *l*,<=*r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) show that sequence *a**l*,<=*a**l*<=+<=1,<=...,<=*a**r* is the longest subsegment that is a good *k*-*d* sequence. If there are multiple optimal answers, print the one with the minimum value of *l*.
[ "6 1 2\n4 3 2 8 6 2\n" ]
[ "3 5\n" ]
In the first test sample the answer is the subsegment consisting of numbers 2, 8, 6 — after adding number 4 and sorting it becomes sequence 2, 4, 6, 8 — the arithmetic progression with difference 2.
[]
15
0
-1
26,124
784
Touchy-Feely Palindromes
[ "*special", "implementation" ]
null
null
The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive. Output "Yes" or "No".
The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.
Output "Yes" or "No".
[ "373\n", "121\n", "436\n" ]
[ "Yes\n", "No\n", "Yes\n" ]
none
[ { "input": "373", "output": "Yes" }, { "input": "121", "output": "No" }, { "input": "436", "output": "Yes" }, { "input": "7", "output": "Yes" }, { "input": "8", "output": "No" }, { "input": "4357087936", "output": "Yes" }, { "input": "80697...
46
0
3
26,199
744
Hongcow's Game
[ "bitmasks", "divide and conquer", "interactive" ]
null
null
This is an interactive problem. In the interaction section below you will see the information about flushing the output. In this problem, you will be playing a game with Hongcow. How lucky of you! Hongcow has a hidden *n* by *n* matrix *M*. Let *M**i*,<=*j* denote the entry *i*-th row and *j*-th column of the matrix. The rows and columns are labeled from 1 to *n*. The matrix entries are between 0 and 109. In addition, *M**i*,<=*i*<==<=0 for all valid *i*. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each *i*, you must find . To do this, you can ask Hongcow some questions. A question consists of giving Hongcow a subset of distinct indices {*w*1,<=*w*2,<=...,<=*w**k*}, with 1<=≤<=*k*<=≤<=*n*. Hongcow will respond with *n* integers. The *i*-th integer will contain the minimum value of *min*1<=≤<=*j*<=≤<=*k**M**i*,<=*w**j*. You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered. When you are ready to answer, print out a single integer <=-<=1 on its own line, then *n* integers on the next line. The *i*-th integer should be the minimum value in the *i*-th row of the matrix, excluding the *i*-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question. You will get Wrong Answer verdict if - Your question or answers are not in the format described in this statement. - You ask strictly more than 20 questions. - Your question contains duplicate indices. - The value of *k* in your question does not lie in the range from 1 to *n*, inclusive. - Your final answer is not correct.
The first line of input will contain a single integer *n* (2<=≤<=*n*<=≤<=1,<=000).
To print the final answer, print out the string -1 on its own line. Then, the next line should contain *n* integers. The *i*-th integer should be the minimum value of the *i*-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!
[ "3\n0 0 0\n2 7 0\n0 0 4\n3 0 8\n0 5 4", "2\n0 0\n0 0" ]
[ "3\n1 2 3\n1\n3\n2\n1 2\n1\n2\n1\n1\n-1\n2 5 4\n", "1\n2\n1\n1\n-1\n0 0" ]
In the first sample, Hongcow has the hidden matrix Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant. For the second sample, it is possible for off-diagonal elements of the matrix to be zero.
[]
62
614,400
3
26,339
185
Mushroom Scientists
[ "math", "ternary search" ]
null
null
As you very well know, the whole Universe traditionally uses three-dimensional Cartesian system of coordinates. In this system each point corresponds to three real coordinates (*x*,<=*y*,<=*z*). In this coordinate system, the distance between the center of the Universe and the point is calculated by the following formula: . Mushroom scientists that work for the Great Mushroom King think that the Universe isn't exactly right and the distance from the center of the Universe to a point equals *x**a*·*y**b*·*z**c*. To test the metric of mushroom scientists, the usual scientists offered them a task: find such *x*,<=*y*,<=*z* (0<=≤<=*x*,<=*y*,<=*z*; *x*<=+<=*y*<=+<=*z*<=≤<=*S*), that the distance between the center of the Universe and the point (*x*,<=*y*,<=*z*) is maximum possible in the metric of mushroom scientists. The mushroom scientists aren't good at maths, so they commissioned you to do the task. Note that in this problem, it is considered that 00<==<=1.
The first line contains a single integer *S* (1<=≤<=*S*<=≤<=103) — the maximum sum of coordinates of the sought point. The second line contains three space-separated integers *a*, *b*, *c* (0<=≤<=*a*,<=*b*,<=*c*<=≤<=103) — the numbers that describe the metric of mushroom scientists.
Print three real numbers — the coordinates of the point that reaches maximum value in the metrics of mushroom scientists. If there are multiple answers, print any of them that meets the limitations. A natural logarithm of distance from the center of the Universe to the given point in the metric of mushroom scientists shouldn't differ from the natural logarithm of the maximum distance by more than 10<=-<=6. We think that *ln*(0)<==<=<=-<=∞.
[ "3\n1 1 1\n", "3\n2 0 0\n" ]
[ "1.0 1.0 1.0\n", "3.0 0.0 0.0\n" ]
none
[ { "input": "3\n1 1 1", "output": "1.0 1.0 1.0" }, { "input": "3\n2 0 0", "output": "3.0 0.0 0.0" }, { "input": "10\n1 6 3", "output": "1.0 6.0 3.0" }, { "input": "9\n8 2 0", "output": "7.2 1.8 0.0" }, { "input": "1\n0 9 2", "output": "0.0 0.8181818181818182 0....
92
0
0
26,350
847
Load Testing
[ "greedy" ]
null
null
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last *n* minutes and in the *i*-th minute friends will send *a**i* requests. Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load. Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable. For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp. Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to *n*.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the duration of the load testing. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is the number of requests from friends in the *i*-th minute of the load testing.
Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.
[ "5\n1 4 3 2 5\n", "5\n1 2 2 2 1\n", "7\n10 20 40 50 70 90 30\n" ]
[ "6\n", "1\n", "0\n" ]
In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests. In the second example it is enough to make one additional request in the third minute, so the answer is 1. In the third example the load already satisfies all conditions described in the statement, so the answer is 0.
[ { "input": "5\n1 4 3 2 5", "output": "6" }, { "input": "5\n1 2 2 2 1", "output": "1" }, { "input": "7\n10 20 40 50 70 90 30", "output": "0" }, { "input": "1\n1", "output": "0" }, { "input": "2\n1 15", "output": "0" }, { "input": "4\n36 54 55 9", "o...
296
14,131,200
3
26,456
28
pSort
[ "dfs and similar", "dsu", "graphs" ]
B. pSort
2
256
One day *n* cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move *i*-th cell can exchange it's value with the value of some other *j*-th cell, if |*i*<=-<=*j*|<==<=*d**i*, where *d**i* is a favourite number of *i*-th cell. Cells make moves in any order, the number of moves is unlimited. The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to *n*. You are to determine whether the game could move to this state.
The first line contains positive integer *n* (1<=≤<=*n*<=≤<=100) — the number of cells in the array. The second line contains *n* distinct integers from 1 to *n* — permutation. The last line contains *n* integers from 1 to *n* — favourite numbers of the cells.
If the given state is reachable in the described game, output YES, otherwise NO.
[ "5\n5 4 3 2 1\n1 1 1 1 1\n", "7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1\n", "7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1\n" ]
[ "YES\n", "NO\n", "YES\n" ]
none
[ { "input": "5\n5 4 3 2 1\n1 1 1 1 1", "output": "YES" }, { "input": "7\n4 3 5 1 2 7 6\n4 6 6 1 6 6 1", "output": "NO" }, { "input": "7\n4 2 5 1 3 7 6\n4 6 6 1 6 6 1", "output": "YES" }, { "input": "6\n3 2 1 4 6 5\n3 6 1 6 6 1", "output": "YES" }, { "input": "6\n3 ...
280
20,172,800
3.892425
26,463
474
Ant colony
[ "data structures", "math", "number theory" ]
null
null
Mole is hungry again. He found one ant colony, consisting of *n* ants, ordered in a row. Each ant *i* (1<=≤<=*i*<=≤<=*n*) has a strength *s**i*. In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) and each pair of ants with indices between *l* and *r* (inclusively) will fight. When two ants *i* and *j* fight, ant *i* gets one battle point only if *s**i* divides *s**j* (also, ant *j* gets one battle point only if *s**j* divides *s**i*). After all fights have been finished, Mole makes the ranking. An ant *i*, with *v**i* battle points obtained, is going to be freed only if *v**i*<==<=*r*<=-<=*l*, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none. In order to choose the best sequence, Mole gives you *t* segments [*l**i*,<=*r**i*] and asks for each of them how many ants is he going to eat if those ants fight.
The first line contains one integer *n* (1<=≤<=*n*<=≤<=105), the size of the ant colony. The second line contains *n* integers *s*1,<=*s*2,<=...,<=*s**n* (1<=≤<=*s**i*<=≤<=109), the strengths of the ants. The third line contains one integer *t* (1<=≤<=*t*<=≤<=105), the number of test cases. Each of the next *t* lines contains two integers *l**i* and *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*), describing one query.
Print to the standard output *t* lines. The *i*-th line contains number of ants that Mole eats from the segment [*l**i*,<=*r**i*].
[ "5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5\n" ]
[ "4\n4\n1\n1\n" ]
In the first test battle points for each ant are *v* = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5. In the second test case battle points are *v* = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole. In the third test case battle points are *v* = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4. In the fourth test case battle points are *v* = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
[ { "input": "5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5", "output": "4\n4\n1\n1" } ]
31
0
0
26,482
161
Discounts
[ "constructive algorithms", "greedy", "sortings" ]
null
null
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them! Polycarpus has *k* carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible. Polycarpus must use all *k* carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
The first input line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=103) — the number of items in the supermarket and the number of carts, correspondingly. Next *n* lines describe the items as "*c**i* *t**i*" (without the quotes), where *c**i* (1<=≤<=*c**i*<=≤<=109) is an integer denoting the price of the *i*-th item, *t**i* (1<=≤<=*t**i*<=≤<=2) is an integer representing the type of item *i* (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
In the first line print a single real number with exactly one decimal place — the minimum total price of the items, including the discounts. In the following *k* lines print the descriptions of the items in the carts. In the *i*-th line print the description of the *i*-th cart as "*t* *b*1 *b*2 ... *b**t*" (without the quotes), where *t* is the number of items in the *i*-th cart, and the sequence *b*1,<=*b*2,<=...,<=*b**t* (1<=≤<=*b**j*<=≤<=*n*) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to *n* in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
[ "3 2\n2 1\n3 2\n3 1\n", "4 3\n4 1\n1 2\n2 2\n3 2\n" ]
[ "5.5\n2 1 2\n1 3\n", "8.0\n1 1\n2 4 2\n1 3\n" ]
In the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2·0.5 + (3 + 3·0.5) = 1 + 4.5 = 5.5.
[ { "input": "3 2\n2 1\n3 2\n3 1", "output": "5.5\n2 1 2\n1 3" }, { "input": "4 3\n4 1\n1 2\n2 2\n3 2", "output": "8.0\n1 1\n1 2\n2 3 4" }, { "input": "1 1\n1 1", "output": "0.5\n1 1" }, { "input": "1 1\n1 2", "output": "1.0\n1 1" }, { "input": "10 1\n1 1\n2 2\n1 1\...
280
20,172,800
0
26,528
705
Spider Man
[ "games", "math" ]
null
null
Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex. Initially there are *k* cycles, *i*-th of them consisting of exactly *v**i* vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, *x* vertices) among all available cycles and replace it by two cycles with *p* and *x*<=-<=*p* vertices where 1<=≤<=*p*<=&lt;<=*x* is chosen by the player. The player who cannot make a move loses the game (and his life!). Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the *i*-th test he adds a cycle with *a**i* vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of tests Peter is about to make. The second line contains *n* space separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), *i*-th of them stands for the number of vertices in the cycle added before the *i*-th test.
Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.
[ "3\n1 2 3\n", "5\n1 1 5 1 1\n" ]
[ "2\n1\n1\n", "2\n2\n2\n2\n2\n" ]
In the first sample test: In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses. In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses. In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins. In the second sample test: Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3. - If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses. - If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.
[ { "input": "3\n1 2 3", "output": "2\n1\n1" }, { "input": "5\n1 1 5 1 1", "output": "2\n2\n2\n2\n2" }, { "input": "1\n167959139", "output": "2" }, { "input": "10\n802030518 598196518 640274071 983359971 71550121 96204862 799843967 446173607 796619138 402690754", "output": ...
139
14,643,200
3
26,582
720
Cactusophobia
[ "dfs and similar", "flows" ]
null
null
Tree is a connected undirected graph that has no cycles. Edge cactus is a connected undirected graph without loops and parallel edges, such that each edge belongs to at most one cycle. Vasya has an edge cactus, each edge of this graph has some color. Vasya would like to remove the minimal number of edges in such way that his cactus turned to a tree. Vasya wants to make it in such a way that there were edges of as many different colors in the resulting tree, as possible. Help him to find how many different colors can the resulting tree have.
The first line contains two integers: *n*, *m* (2<=≤<=*n*<=≤<=10<=000) — the number of vertices and the number of edges in Vasya's graph, respectively. The following *m* lines contain three integers each: *u*, *v*, *c* (1<=≤<=*u*,<=*v*<=≤<=*n*, *u*<=≠<=*v*, 1<=≤<=*c*<=≤<=*m*) — the numbers of vertices connected by the corresponding edge, and its color. It is guaranteed that the described graph is indeed an edge cactus.
Output one integer: the maximal number of different colors that the resulting tree can have.
[ "4 4\n1 2 4\n2 3 1\n3 4 2\n4 2 3\n", "7 9\n1 2 1\n2 3 4\n3 1 5\n1 4 5\n4 5 2\n5 1 6\n1 6 4\n6 7 6\n7 1 3\n" ]
[ "3\n", "6\n" ]
none
[ { "input": "4 4\n1 2 4\n2 3 1\n3 4 2\n4 2 3", "output": "3" }, { "input": "7 9\n1 2 1\n2 3 4\n3 1 5\n1 4 5\n4 5 2\n5 1 6\n1 6 4\n6 7 6\n7 1 3", "output": "6" }, { "input": "5 6\n4 1 2\n4 2 3\n5 1 5\n1 3 1\n1 2 1\n5 3 4", "output": "4" }, { "input": "9 10\n8 7 2\n8 2 10\n8 4 2...
46
0
0
26,605
750
New Year and Fireworks
[ "brute force", "data structures", "dfs and similar", "dp", "implementation" ]
null
null
One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more parts, and so on. Limak, who lives in an infinite grid, has a single firework. The behaviour of the firework is described with a recursion depth *n* and a duration for each level of recursion *t*1,<=*t*2,<=...,<=*t**n*. Once Limak launches the firework in some cell, the firework starts moving upward. After covering *t*1 cells (including the starting cell), it explodes and splits into two parts, each moving in the direction changed by 45 degrees (see the pictures below for clarification). So, one part moves in the top-left direction, while the other one moves in the top-right direction. Each part explodes again after covering *t*2 cells, splitting into two parts moving in directions again changed by 45 degrees. The process continues till the *n*-th level of recursion, when all 2*n*<=-<=1 existing parts explode and disappear without creating new parts. After a few levels of recursion, it's possible that some parts will be at the same place and at the same time — it is allowed and such parts do not crash. Before launching the firework, Limak must make sure that nobody stands in cells which will be visited at least once by the firework. Can you count the number of those cells?
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=30) — the total depth of the recursion. The second line contains *n* integers *t*1,<=*t*2,<=...,<=*t**n* (1<=≤<=*t**i*<=≤<=5). On the *i*-th level each of 2*i*<=-<=1 parts will cover *t**i* cells before exploding.
Print one integer, denoting the number of cells which will be visited at least once by any part of the firework.
[ "4\n4 2 2 3\n", "6\n1 1 1 1 1 3\n", "1\n3\n" ]
[ "39\n", "85\n", "3\n" ]
For the first sample, the drawings below show the situation after each level of recursion. Limak launched the firework from the bottom-most red cell. It covered *t*<sub class="lower-index">1</sub> = 4 cells (marked red), exploded and divided into two parts (their further movement is marked green). All explosions are marked with an 'X' character. On the last drawing, there are 4 red, 4 green, 8 orange and 23 pink cells. So, the total number of visited cells is 4 + 4 + 8 + 23 = 39. For the second sample, the drawings below show the situation after levels 4, 5 and 6. The middle drawing shows directions of all parts that will move in the next level.
[]
1,746
268,390,400
0
26,668
282
XOR and OR
[ "constructive algorithms", "implementation", "math" ]
null
null
The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string. A Bitlandish string is a string made only of characters "0" and "1". BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string *a*, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as *x* and the other one as *y*. Then he calculates two values *p* and *q*: *p*<==<=*x* *xor* *y*, *q*<==<=*x* *or* *y*. Then he replaces one of the two taken characters by *p* and the other one by *q*. The *xor* operation means the bitwise excluding OR operation. The *or* operation is the bitwise OR operation. So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string. You've got two Bitlandish strings *a* and *b*. Your task is to check if it is possible for BitHaval to transform string *a* to string *b* in several (possibly zero) described operations.
The first line contains Bitlandish string *a*, the second line contains Bitlandish string *b*. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.
Print "YES" if *a* can be transformed into *b*, otherwise print "NO". Please do not print the quotes.
[ "11\n10\n", "1\n01\n", "000\n101\n" ]
[ "YES\n", "NO\n", "NO\n" ]
none
[ { "input": "11\n10", "output": "YES" }, { "input": "1\n01", "output": "NO" }, { "input": "000\n101", "output": "NO" }, { "input": "1101\n1111", "output": "YES" }, { "input": "11000001\n00000001", "output": "YES" }, { "input": "01\n10", "output": "Y...
62
0
0
26,716
42
Guilty --- to the kitchen!
[ "greedy", "implementation" ]
A. Guilty — to the kitchen!
2
256
It's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills. According to the borscht recipe it consists of *n* ingredients that have to be mixed in proportion litres (thus, there should be *a*1<=·*x*,<=...,<=*a**n*<=·*x* litres of corresponding ingredients mixed for some non-negative *x*). In the kitchen Volodya found out that he has *b*1,<=...,<=*b**n* litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a *V* litres volume pan (which means the amount of soup cooked can be between 0 and *V* litres). What is the volume of borscht Volodya will cook ultimately?
The first line of the input contains two space-separated integers *n* and *V* (1<=≤<=*n*<=≤<=20,<=1<=≤<=*V*<=≤<=10000). The next line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=100). Finally, the last line contains *n* space-separated integers *b**i* (0<=≤<=*b**i*<=≤<=100).
Your program should output just one real number — the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10<=-<=4.
[ "1 100\n1\n40\n", "2 100\n1 1\n25 30\n", "2 100\n1 1\n60 60\n" ]
[ "40.0\n", "50.0\n", "100.0\n" ]
none
[ { "input": "1 100\n1\n40", "output": "40.0" }, { "input": "2 100\n1 1\n25 30", "output": "50.0" }, { "input": "2 100\n1 1\n60 60", "output": "100.0" }, { "input": "2 100\n1 1\n50 50", "output": "100.0" }, { "input": "2 100\n1 2\n33 66", "output": "99.0" }, ...
92
0
3.977
26,770
856
Eleventh Birthday
[ "combinatorics", "dp", "math" ]
null
null
It is Borya's eleventh birthday, and he has got a great present: *n* cards with numbers. The *i*-th card has the number *a**i* written on it. Borya wants to put his cards in a row to get one greater number. For example, if Borya has cards with numbers 1, 31, and 12, and he puts them in a row in this order, he would get a number 13112. He is only 11, but he already knows that there are *n*! ways to put his cards in a row. But today is a special day, so he is only interested in such ways that the resulting big number is divisible by eleven. So, the way from the previous paragraph is good, because 13112<==<=1192<=×<=11, but if he puts the cards in the following order: 31, 1, 12, he would get a number 31112, it is not divisible by 11, so this way is not good for Borya. Help Borya to find out how many good ways to put the cards are there. Borya considers all cards different, even if some of them contain the same number. For example, if Borya has two cards with 1 on it, there are two good ways. Help Borya, find the number of good ways to put the cards. This number can be large, so output it modulo 998244353.
Input data contains multiple test cases. The first line of the input data contains an integer *t* — the number of test cases (1<=≤<=*t*<=≤<=100). The descriptions of test cases follow. Each test is described by two lines. The first line contains an integer *n* (1<=≤<=*n*<=≤<=2000) — the number of cards in Borya's present. The second line contains *n* integers *a**i* (1<=≤<=*a**i*<=≤<=109) — numbers written on the cards. It is guaranteed that the total number of cards in all tests of one input data doesn't exceed 2000.
For each test case output one line: the number of ways to put the cards to the table so that the resulting big number was divisible by 11, print the number modulo 998244353.
[ "4\n2\n1 1\n3\n1 31 12\n3\n12345 67 84\n9\n1 2 3 4 5 6 7 8 9\n" ]
[ "2\n2\n2\n31680\n" ]
none
[]
46
0
0
26,788
457
Distributed Join
[ "greedy" ]
null
null
Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic. Suppose she wants to join two tables, *A* and *B*. Each of them has certain number of rows which are distributed on different number of partitions. Table *A* is distributed on the first cluster consisting of *m* partitions. Partition with index *i* has *a**i* rows from *A*. Similarly, second cluster containing table *B* has *n* partitions, *i*-th one having *b**i* rows from *B*. In one network operation she can copy one row from any partition to any other partition. At the end, for each row from *A* and each row from *B* there should be a partition that has both rows. Determine the minimal number of network operations to achieve this.
First line contains two integer numbers, *m* and *n* (1<=≤<=*m*,<=*n*<=≤<=105). Second line contains description of the first cluster with *m* space separated integers, *a**i* (1<=≤<=*a**i*<=≤<=109). Similarly, third line describes second cluster with *n* space separated integers, *b**i* (1<=≤<=*b**i*<=≤<=109).
Print one integer — minimal number of copy operations.
[ "2 2\n2 6\n3 100\n", "2 3\n10 10\n1 1 1\n" ]
[ "11\n", "6\n" ]
In the first example it makes sense to move all the rows to the second partition of the second cluster which is achieved in 2 + 6 + 3 = 11 operations In the second example Piegirl can copy each row from *B* to the both partitions of the first cluster which needs 2·3 = 6 copy operations.
[ { "input": "2 2\n2 6\n3 100", "output": "11" }, { "input": "2 3\n10 10\n1 1 1", "output": "6" }, { "input": "2 2\n888381664 866366630\n170399907 404233949", "output": "1149267712" }, { "input": "3 4\n337369924 278848730 654933675\n866361693 732544605 890800310 350303294", ...
0
0
-1
26,835
103
Buying Sets
[ "flows", "graph matchings" ]
E. Buying Sets
2
256
The Hexadecimal virus loves playing with number sets — intersecting them, uniting them. One beautiful day she was surprised to find out that Scuzzy, her spherical pet cat, united all sets in one and ate the result! Something had to be done quickly and Hexadecimal rushed to the market. The market has *n* sets of numbers on sale. The virus wants to buy the following collection of sets: the number of sets in the collection should be exactly the same as the number of numbers in the union of all bought sets. Moreover, Hexadecimal wants to buy the cheapest suitable collection of set. Yet nothing's so easy! As Mainframe is a kingdom of pure rivalry markets, we know that the union of any *k* sets contains no less than *k* distinct numbers (for every positive integer *k*). Help the virus choose the suitable collection of sets. The collection can be empty.
The first line contains the only number *n* (1<=≤<=*n*<=≤<=300) — the number of sets available in the market. Next *n* lines describe the goods: first we are given *m**i* (1<=≤<=*m**i*<=≤<=*n*) — the number of distinct numbers in the *i*-th set, then follow *m**i* numbers — the set's elements. We know that the set's elements are distinct positive integers and they do not exceed *n*. The last line contains *n* integers whose absolute values do not exceed 106 — the price of each set.
Print a single number — the minimum price the virus will have to pay for such a collection of *k* sets that union of the collection's sets would have exactly *k* distinct numbers ().
[ "3\n1 1\n2 2 3\n1 3\n10 20 -3\n", "5\n2 1 2\n2 2 3\n2 3 4\n2 4 5\n2 5 1\n1 -1 1 -1 1\n", "5\n2 1 2\n2 2 3\n2 3 4\n2 4 5\n2 5 1\n-1 1 -1 1 -1\n" ]
[ "-3\n", "0\n", "-1\n" ]
none
[]
92
0
0
26,963
161
Abracadabra
[ "divide and conquer" ]
null
null
Polycarpus analyzes a string called abracadabra. This string is constructed using the following algorithm: - On the first step the string consists of a single character "a". - On the *k*-th step Polycarpus concatenates two copies of the string obtained on the (*k*<=-<=1)-th step, while inserting the *k*-th character of the alphabet between them. Polycarpus uses the alphabet that consists of lowercase Latin letters and digits (a total of 36 characters). The alphabet characters are numbered like this: the 1-st character is "a", the 2-nd — "b", ..., the 26-th — "z", the 27-th — "0", the 28-th — "1", ..., the 36-th — "9". Let's have a closer look at the algorithm. On the second step Polycarpus will concatenate two strings "a" and insert the character "b" between them, resulting in "aba" string. The third step will transform it into "abacaba", and the fourth one - into "abacabadabacaba". Thus, the string constructed on the *k*-th step will consist of 2*k*<=-<=1 characters. Polycarpus wrote down the string he got after 30 steps of the given algorithm and chose two non-empty substrings of it. Your task is to find the length of the longest common substring of the two substrings selected by Polycarpus. A substring *s*[*i*... *j*] (1<=≤<=*i*<=≤<=*j*<=≤<=|*s*|) of string *s* = *s*1*s*2... *s*|*s*| is a string *s**i**s**i*<=+<=1... *s**j*. For example, substring *s*[2...4] of string *s* = "abacaba" equals "bac". The string is its own substring. The longest common substring of two strings *s* and *t* is the longest string that is a substring of both *s* and *t*. For example, the longest common substring of "contest" and "systemtesting" is string "test". There can be several common substrings of maximum length.
The input consists of a single line containing four integers *l*1, *r*1, *l*2, *r*2 (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=109, *i*<==<=1,<=2). The numbers are separated by single spaces. *l**i* and *r**i* give the indices of the first and the last characters of the *i*-th chosen substring, correspondingly (*i*<==<=1,<=2). The characters of string abracadabra are numbered starting from 1.
Print a single number — the length of the longest common substring of the given strings. If there are no common substrings, print 0.
[ "3 6 1 4\n", "1 1 4 4\n" ]
[ "2\n", "0\n" ]
In the first sample the first substring is "acab", the second one is "abac". These two substrings have two longest common substrings "ac" and "ab", but we are only interested in their length — 2. In the second sample the first substring is "a", the second one is "c". These two substrings don't have any common characters, so the length of their longest common substring is 0.
[ { "input": "3 6 1 4", "output": "2" }, { "input": "1 1 4 4", "output": "0" }, { "input": "2 2 6 6", "output": "1" }, { "input": "73426655 594361930 343984155 989446962", "output": "379149396" }, { "input": "169720415 312105195 670978284 671296539", "output": "...
15
0
-1
26,989
436
Pudding Monsters
[ "dp" ]
null
null
Have you ever played Pudding Monsters? In this task, a simplified one-dimensional model of this game is used. Imagine an infinite checkered stripe, the cells of which are numbered sequentially with integers. Some cells of the strip have monsters, other cells of the strip are empty. All monsters are made of pudding, so if there are two monsters in the neighboring cells, they stick to each other (literally). Similarly, if several monsters are on consecutive cells, they all stick together in one block of monsters. We will call the stuck together monsters a block of monsters. A detached monster, not stuck to anyone else, is also considered a block. In one move, the player can take any block of monsters and with a movement of his hand throw it to the left or to the right. The selected monsters will slide on until they hit some other monster (or a block of monsters). For example, if a strip has three monsters in cells 1, 4 and 5, then there are only four possible moves: to send a monster in cell 1 to minus infinity, send the block of monsters in cells 4 and 5 to plus infinity, throw monster 1 to the right (it will stop in cell 3), throw a block of monsters in cells 4 and 5 to the left (they will stop in cells 2 and 3). Some cells on the strip are marked with stars. These are the special cells. The goal of the game is to make the largest possible number of special cells have monsters on them. You are given the numbers of the special cells on a strip as well as the initial position of all monsters. What is the maximum number of special cells that will contain monsters in the optimal game?
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=2000) — the number of monsters on the strip and the number of special cells. The second line contains *n* distinct integers — the numbers of the cells with monsters, then the third line contains *m* distinct integers — the numbers of the special cells. It is guaranteed that all the numbers of the cells are positive integers not exceeding 2·105.
Print a single integer — the maximum number of special cells that will contain monsters in the optimal game.
[ "3 2\n1 3 5\n2 4\n", "4 2\n1 3 4 6\n2 5\n", "4 2\n1 8 4 5\n7 2\n" ]
[ "2\n", "2\n", "1\n" ]
none
[]
46
0
0
27,047
370
Mittens
[ "constructive algorithms", "greedy", "sortings" ]
null
null
A Christmas party in city S. had *n* children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to *m*, and the children are numbered from 1 to *n*. Then the *i*-th child has both mittens of color *c**i*. The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children. The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.
The first line contains two integers *n* and *m* — the number of the children and the number of possible mitten colors (1<=≤<=*n*<=≤<=5000, 1<=≤<=*m*<=≤<=100). The second line contains *n* integers *c*1,<=*c*2,<=... *c**n*, where *c**i* is the color of the mittens of the *i*-th child (1<=≤<=*c**i*<=≤<=*m*).
In the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next *n* lines print the way the mittens can be distributed in this case. On the *i*-th of these lines print two space-separated integers: the color of the left and the color of the right mitten the *i*-th child will get. If there are multiple solutions, you can print any of them.
[ "6 3\n1 3 2 2 1 1\n", "4 2\n1 2 1 1\n" ]
[ "6\n2 1\n1 2\n2 1\n1 3\n1 2\n3 1\n", "2\n1 2\n1 1\n2 1\n1 1\n" ]
none
[ { "input": "6 3\n1 3 2 2 1 1", "output": "6\n2 1\n1 2\n2 1\n1 3\n1 2\n3 1" }, { "input": "4 2\n1 2 1 1", "output": "2\n1 2\n1 1\n2 1\n1 1" }, { "input": "1 1\n1", "output": "0\n1 1" }, { "input": "4 1\n1 1 1 1", "output": "0\n1 1\n1 1\n1 1\n1 1" }, { "input": "2 2...
46
0
0
27,065
620
Professor GukiZ and Two Arrays
[ "binary search", "two pointers" ]
null
null
Professor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a *s**a* as close as possible to the sum of the elements in the array b *s**b*. So he wants to minimize the value *v*<==<=|*s**a*<=-<=*s**b*|. In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5,<=1,<=3,<=2,<=4] and the array b is [3,<=3,<=2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2,<=1,<=3,<=2,<=4] and the new array b [3,<=3,<=5]. Professor doesn't want to make more than two swaps. Find the minimal value *v* and some sequence of no more than two swaps that will lead to the such value *v*. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.
The first line contains integer *n* (1<=≤<=*n*<=≤<=2000) — the number of elements in the array a. The second line contains *n* integers *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) — the elements of the array a. The third line contains integer *m* (1<=≤<=*m*<=≤<=2000) — the number of elements in the array b. The fourth line contains *m* integers *b**j* (<=-<=109<=≤<=*b**j*<=≤<=109) — the elements of the array b.
In the first line print the minimal value *v*<==<=|*s**a*<=-<=*s**b*| that can be got with no more than two swaps. The second line should contain the number of swaps *k* (0<=≤<=*k*<=≤<=2). Each of the next *k* lines should contain two integers *x**p*,<=*y**p* (1<=≤<=*x**p*<=≤<=*n*,<=1<=≤<=*y**p*<=≤<=*m*) — the index of the element in the array a and the index of the element in the array b in the *p*-th swap. If there are several optimal solutions print any of them. Print the swaps in order the professor did them.
[ "5\n5 4 3 2 1\n4\n1 1 1 1\n", "5\n1 2 3 4 5\n1\n15\n", "5\n1 2 3 4 5\n4\n1 2 3 4\n" ]
[ "1\n2\n1 1\n4 2\n", "0\n0\n", "1\n1\n3 1\n" ]
none
[ { "input": "5\n5 4 3 2 1\n4\n1 1 1 1", "output": "1\n2\n1 1\n4 2" }, { "input": "5\n1 2 3 4 5\n1\n15", "output": "0\n0" }, { "input": "5\n1 2 3 4 5\n4\n1 2 3 4", "output": "1\n1\n3 1" }, { "input": "1\n-42\n1\n-86", "output": "44\n0" }, { "input": "1\n-21\n10\n-43...
1,840
72,601,600
0
27,123
111
Petya and Spiders
[ "bitmasks", "dp", "dsu" ]
C. Petya and Spiders
2
256
Little Petya loves training spiders. Petya has a board *n*<=×<=*m* in size. Each cell of the board initially has a spider sitting on it. After one second Petya chooses a certain action for each spider, and all of them humbly perform its commands. There are 5 possible commands: to stay idle or to move from current cell to some of the four side-neighboring cells (that is, one command for each of the four possible directions). Petya gives the commands so that no spider leaves the field. It is allowed for spiders to pass through each other when they crawl towards each other in opposite directions. All spiders crawl simultaneously and several spiders may end up in one cell. Petya wants to know the maximum possible number of spider-free cells after one second.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=40,<=*n*·*m*<=≤<=40) — the board sizes.
In the first line print the maximum number of cells without spiders.
[ "1 1\n", "2 3\n" ]
[ "0\n", "4\n" ]
In the first sample the only possible answer is: s In the second sample one of the possible solutions is: s denotes command "stay idle", l, r, d, u denote commands "crawl left", "crawl right", "crawl down", "crawl up", correspondingly.
[ { "input": "1 1", "output": "0" }, { "input": "2 3", "output": "4" }, { "input": "4 1", "output": "2" }, { "input": "4 2", "output": "5" }, { "input": "4 3", "output": "8" }, { "input": "4 4", "output": "12" }, { "input": "1 40", "outpu...
31
0
0
27,172
729
Subordinates
[ "constructive algorithms", "data structures", "graphs", "greedy", "sortings" ]
null
null
There are *n* workers in a company, each of them has a unique id from 1 to *n*. Exaclty one of them is a chief, his id is *s*. Each worker except the chief has exactly one immediate superior. There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself. Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.
The first line contains two positive integers *n* and *s* (1<=≤<=*n*<=≤<=2·105, 1<=≤<=*s*<=≤<=*n*) — the number of workers and the id of the chief. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=*n*<=-<=1), where *a**i* is the number of superiors (not only immediate) the worker with id *i* reported about.
Print the minimum number of workers that could make a mistake.
[ "3 2\n2 0 2\n", "5 3\n1 0 0 4 1\n" ]
[ "1\n", "2\n" ]
In the first example it is possible that only the first worker made a mistake. Then: - the immediate superior of the first worker is the second worker, - the immediate superior of the third worker is the first worker, - the second worker is the chief.
[ { "input": "3 2\n2 0 2", "output": "1" }, { "input": "5 3\n1 0 0 4 1", "output": "2" }, { "input": "1 1\n0", "output": "0" }, { "input": "2 1\n0 0", "output": "1" }, { "input": "2 1\n0 1", "output": "0" }, { "input": "2 1\n1 0", "output": "2" }, ...
61
2,764,800
-1
27,203
176
Archaeology
[ "data structures", "dfs and similar", "trees" ]
null
null
This time you should help a team of researchers on an island in the Pacific Ocean. They research the culture of the ancient tribes that used to inhabit the island many years ago. Overall they've dug out *n* villages. Some pairs of villages were connected by roads. People could go on the roads in both directions. Overall there were exactly *n*<=-<=1 roads, and from any village one could get to any other one. The tribes were not peaceful and they had many wars. As a result of the wars, some villages were destroyed completely. During more peaceful years some of the villages were restored. At each moment of time people used only those roads that belonged to some shortest way between two villages that existed at the given moment. In other words, people used the minimum subset of roads in such a way, that it was possible to get from any existing village to any other existing one. Note that throughout the island's whole history, there existed exactly *n*<=-<=1 roads that have been found by the researchers. There never were any other roads. The researchers think that observing the total sum of used roads’ lengths at different moments of time can help to better understand the tribes' culture and answer several historical questions. You will be given the full history of the tribes' existence. Your task is to determine the total length of used roads at some moments of time.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of villages. The next *n*<=-<=1 lines describe the roads. The *i*-th of these lines contains three integers *a**i*, *b**i* and *c**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*, 1<=≤<=*c**i*<=≤<=109, 1<=≤<=*i*<=&lt;<=*n*) — the numbers of villages that are connected by the *i*-th road and the road's length. The numbers in the lines are separated by a space. The next line contains an integer *q* (1<=≤<=*q*<=≤<=105) — the number of queries. Then follow *q* queries, one per line, ordered by time. Each query belongs to one of three types: - "+ *x*" — village number *x* is restored (1<=≤<=*x*<=≤<=*n*). - "- *x*" — village number *x* is destroyed (1<=≤<=*x*<=≤<=*n*). - "?" — the archaeologists want to know the total length of the roads which were used for that time period. It is guaranteed that the queries do not contradict each other, that is, there won't be queries to destroy non-existing villages or restore the already existing ones. It is guaranteed that we have at least one query of type "?". It is also guaranteed that one can get from any village to any other one by the given roads. At the initial moment of time no village is considered to exist.
For each query of type "?" print the total length of used roads on a single line. You should print the answers to the queries in the order, in which they are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
[ "6\n1 2 1\n1 3 5\n4 1 7\n4 5 3\n6 4 2\n10\n+ 3\n+ 1\n?\n+ 6\n?\n+ 5\n?\n- 6\n- 3\n?\n" ]
[ "5\n14\n17\n10\n" ]
none
[]
92
0
0
27,219
37
Old Berland Language
[ "data structures", "greedy", "trees" ]
C. Old Berland Language
2
256
Berland scientists know that the Old Berland language had exactly *n* words. Those words had lengths of *l*1,<=*l*2,<=...,<=*l**n* letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol. Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.
The first line contains one integer *N* (1<=≤<=*N*<=≤<=1000) — the number of words in Old Berland language. The second line contains *N* space-separated integers — the lengths of these words. All the lengths are natural numbers not exceeding 1000.
If there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next *N* lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.
[ "3\n1 2 3\n", "3\n1 1 1\n" ]
[ "YES\n0\n10\n110\n", "NO\n" ]
none
[ { "input": "3\n1 2 3", "output": "YES\n0\n10\n110" }, { "input": "3\n1 1 1", "output": "NO" }, { "input": "10\n4 4 4 4 4 4 4 4 4 4", "output": "YES\n0000\n0001\n0010\n0011\n0100\n0101\n0110\n0111\n1000\n1001" }, { "input": "20\n6 7 7 7 7 6 7 7 7 7 7 7 7 7 7 7 7 7 6 7", "o...
310
3,174,400
3.916587
27,273
543
Listening to Music
[ "constructive algorithms", "data structures" ]
null
null
Please note that the memory limit differs from the standard. You really love to listen to music. During the each of next *s* days you will listen to exactly *m* songs from the playlist that consists of exactly *n* songs. Let's number the songs from the playlist with numbers from 1 to *n*, inclusive. The quality of song number *i* is *a**i*. On the *i*-th day you choose some integer *v* (*l**i*<=≤<=*v*<=≤<=*r**i*) and listen to songs number *v*,<=*v*<=+<=1,<=...,<=*v*<=+<=*m*<=-<=1. On the *i*-th day listening to one song with quality less than *q**i* increases your displeasure by exactly one. Determine what minimum displeasure you can get on each of the *s* next days.
The first line contains two positive integers *n*, *m* (1<=≤<=*m*<=≤<=*n*<=≤<=2·105). The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=&lt;<=230) — the description of songs from the playlist. The next line contains a single number *s* (1<=≤<=*s*<=≤<=2·105) — the number of days that you consider. The next *s* lines contain three integers each *l**i*,<=*r**i*,<=*x**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*<=-<=*m*<=+<=1; 0<=≤<=*x**i*<=&lt;<=230) — the description of the parameters for the *i*-th day. In order to calculate value *q**i*, you need to use formula: , where *ans**i* is the answer to the problem for day *i*. Assume that *ans*0<==<=0.
Print exactly *s* integers *ans*1,<=*ans*2,<=...,<=*ans**s*, where *ans**i* is the minimum displeasure that you can get on day *i*.
[ "5 3\n1 2 1 2 3\n5\n1 1 2\n1 3 2\n1 3 3\n1 3 5\n1 3 1\n" ]
[ "2\n0\n2\n3\n1\n" ]
none
[]
46
0
0
27,405
141
Take-off Ramps
[ "graphs", "shortest paths" ]
null
null
Vasya participates in a ski race along the *X* axis. The start is at point 0, and the finish is at *L*, that is, at a distance *L* meters from the start in the positive direction of the axis. Vasya has been training so hard that he can run one meter in exactly one second. Besides, there are *n* take-off ramps on the track, each ramp is characterized by four numbers: - *x**i* represents the ramp's coordinate - *d**i* represents from how many meters Vasya will land if he goes down this ramp - *t**i* represents the flight time in seconds - *p**i* is the number, indicating for how many meters Vasya should gather speed to get ready and fly off the ramp. As Vasya gathers speed, he should ski on the snow (that is, he should not be flying), but his speed still equals one meter per second. Vasya is allowed to move in any direction on the *X* axis, but he is prohibited to cross the start line, that is go to the negative semiaxis. Vasya himself chooses which take-off ramps he will use and in what order, that is, he is not obliged to take off from all the ramps he encounters. Specifically, Vasya can skip the ramp. It is guaranteed that *x**i*<=+<=*d**i*<=≤<=*L*, that is, Vasya cannot cross the finish line in flight. Vasya can jump from the ramp only in the positive direction of *X* axis. More formally, when using the *i*-th ramp, Vasya starts gathering speed at point *x**i*<=-<=*p**i*, jumps at point *x**i*, and lands at point *x**i*<=+<=*d**i*. He cannot use the ramp in opposite direction. Your task is to find the minimum time that Vasya will spend to cover the distance.
The first line contains two integers *n* and *L* (0<=≤<=*n*<=≤<=105, 1<=≤<=*L*<=≤<=109). Then *n* lines contain the descriptions of the ramps, each description is on a single line. Each description is a group of four non-negative integers *x**i*, *d**i*, *t**i*, *p**i* (0<=≤<=*x**i*<=≤<=*L*, 1<=≤<=*d**i*,<=*t**i*,<=*p**i*<=≤<=109, *x**i*<=+<=*d**i*<=≤<=*L*).
Print in the first line the minimum time in seconds Vasya needs to complete the track. Print in the second line *k* — the number of take-off ramps that Vasya needs to use, and print on the third line of output *k* numbers the number the take-off ramps Vasya used in the order in which he used them. Print each number exactly once, separate the numbers with a space. The ramps are numbered starting from 1 in the order in which they are given in the input.
[ "2 20\n5 10 5 5\n4 16 1 7\n", "2 20\n9 8 12 6\n15 5 1 1\n" ]
[ "15\n1\n1 ", "16\n1\n2 " ]
In the first sample, Vasya cannot use ramp 2, because then he will need to gather speed starting from point -3, which is not permitted by the statement. The optimal option is using ramp 1, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 0 + 5 + 5 + 5 = 15. In the second sample using ramp 1 is not optimal for Vasya as *t*<sub class="lower-index">1</sub> &gt; *d*<sub class="lower-index">1</sub>. The optimal option is using ramp 2, the resulting time is: moving to the point of gathering speed + gathering speed until reaching the takeoff ramp + flight time + moving to the finish line = 14 + 1 + 1 + 0 = 16.
[ { "input": "2 20\n5 10 5 5\n4 16 1 7", "output": "15\n1\n1 " }, { "input": "2 20\n9 8 12 6\n15 5 1 1", "output": "16\n1\n2 " }, { "input": "0 10", "output": "10\n0" }, { "input": "1 20\n2 1 10 1", "output": "20\n0" }, { "input": "3 50\n44 3 4 47\n2 40 33 2\n28 16 ...
124
614,400
0
27,448
8
Two Friends
[ "binary search", "geometry" ]
D. Two Friends
1
64
Two neighbours, Alan and Bob, live in the city, where there are three buildings only: a cinema, a shop and the house, where they live. The rest is a big asphalt square. Once they went to the cinema, and the film impressed them so deeply, that when they left the cinema, they did not want to stop discussing it. Bob wants to get home, but Alan has to go to the shop first, and only then go home. So, they agreed to cover some distance together discussing the film (their common path might pass through the shop, or they might walk circles around the cinema together), and then to part each other's company and go each his own way. After they part, they will start thinking about their daily pursuits; and even if they meet again, they won't be able to go on with the discussion. Thus, Bob's path will be a continuous curve, having the cinema and the house as its ends. Alan's path — a continuous curve, going through the shop, and having the cinema and the house as its ends. The film ended late, that's why the whole distance covered by Alan should not differ from the shortest one by more than *t*1, and the distance covered by Bob should not differ from the shortest one by more than *t*2. Find the maximum distance that Alan and Bob will cover together, discussing the film.
The first line contains two integers: *t*1,<=*t*2 (0<=≤<=*t*1,<=*t*2<=≤<=100). The second line contains the cinema's coordinates, the third one — the house's, and the last line — the shop's. All the coordinates are given in meters, are integer, and do not exceed 100 in absolute magnitude. No two given places are in the same building.
In the only line output one number — the maximum distance that Alan and Bob will cover together, discussing the film. Output the answer accurate to not less than 4 decimal places.
[ "0 2\n0 0\n4 0\n-3 0\n", "0 0\n0 0\n2 0\n1 0\n" ]
[ "1.0000000000\n", "2.0000000000\n" ]
none
[ { "input": "0 2\n0 0\n4 0\n-3 0", "output": "1.0000000000" }, { "input": "0 0\n0 0\n2 0\n1 0", "output": "2.0000000000" }, { "input": "0 2\n0 0\n40 0\n-31 1", "output": "1.0002538218" }, { "input": "100 2\n0 0\n4 0\n-3 0", "output": "6.0000000000" }, { "input": "2...
62
0
0
27,550
755
PolandBall and White-Red graph
[ "constructive algorithms", "graphs", "shortest paths" ]
null
null
PolandBall has an undirected simple graph consisting of *n* vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white and red. Colorfulness of the graph is a value *min*(*d**r*,<=*d**w*), where *d**r* is the diameter of the red subgraph and *d**w* is the diameter of white subgraph. The diameter of a graph is a largest value *d* such that shortest path between some pair of vertices in it is equal to *d*. If the graph is not connected, we consider its diameter to be -1. PolandBall wants the final graph to be as neat as possible. He wants the final colorfulness to be equal to *k*. Can you help him and find any graph which satisfies PolandBall's requests?
The only one input line contains two integers *n* and *k* (2<=≤<=*n*<=≤<=1000, 1<=≤<=*k*<=≤<=1000), representing graph's size and sought colorfulness.
If it's impossible to find a suitable graph, print -1. Otherwise, you can output any graph which fulfills PolandBall's requirements. First, output *m* — the number of red edges in your graph. Then, you should output *m* lines, each containing two integers *a**i* and *b**i*, (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*, *a**i*<=≠<=*b**i*) which means that there is an undirected red edge between vertices *a**i* and *b**i*. Every red edge should be printed exactly once, you can print the edges and the vertices of every edge in arbitrary order. Remember that PolandBall's graph should remain simple, so no loops or multiple edges are allowed.
[ "4 1\n", "5 2\n" ]
[ "-1\n", "4\n1 2\n2 3\n3 4\n4 5\n" ]
In the first sample case, no graph can fulfill PolandBall's requirements. In the second sample case, red graph is a path from 1 to 5. Its diameter is 4. However, white graph has diameter 2, because it consists of edges 1-3, 1-4, 1-5, 2-4, 2-5, 3-5.
[ { "input": "4 1", "output": "-1" }, { "input": "5 2", "output": "4\n1 2\n2 3\n3 4\n4 5" }, { "input": "500 3", "output": "123755\n1 2\n499 500\n2 3\n2 4\n2 5\n2 6\n2 7\n2 8\n2 9\n2 10\n2 11\n2 12\n2 13\n2 14\n2 15\n2 16\n2 17\n2 18\n2 19\n2 20\n2 21\n2 22\n2 23\n2 24\n2 25\n2 26\n2 2...
46
0
0
27,561
0
none
[ "none" ]
null
null
Two best friends Serozha and Gena play a game. Initially there is one pile consisting of *n* stones on the table. During one move one pile should be taken and divided into an arbitrary number of piles consisting of *a*1<=&gt;<=*a*2<=&gt;<=...<=&gt;<=*a**k*<=&gt;<=0 stones. The piles should meet the condition *a*1<=-<=*a*2<==<=*a*2<=-<=*a*3<==<=...<==<=*a**k*<=-<=1<=-<=*a**k*<==<=1. Naturally, the number of piles *k* should be no less than two. The friends play in turns. The player who cannot make a move loses. Serozha makes the first move. Who will win if both players play in the optimal way?
The single line contains a single integer *n* (1<=≤<=*n*<=≤<=105).
If Serozha wins, print *k*, which represents the minimal number of piles into which he can split the initial one during the first move in order to win the game. If Gena wins, print "-1" (without the quotes).
[ "3\n", "6\n", "100\n" ]
[ "2\n", "-1\n", "8\n" ]
none
[]
60
0
0
27,573
125
Hobbits' Party
[ "constructive algorithms", "greedy" ]
null
null
Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are *n* hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number *n*, to indicate the GP's maximum duration and the guest lists for each day.
The first line contains an integer *n* (3<=≤<=*n*<=≤<=10000), representing the number of hobbits.
In the first output line print a number *k* — the maximum duration of GP in days. Then on *k* lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to *n*.
[ "4\n", "5\n" ]
[ "3\n1 2 \n1 3 \n2 3 \n", "3\n1 2 \n1 3 \n2 3 \n" ]
none
[ { "input": "4", "output": "3\n1 2 \n1 3 \n2 3 " }, { "input": "5", "output": "3\n1 2 \n1 3 \n2 3 " }, { "input": "6", "output": "4\n1 2 3 \n1 4 5 \n2 4 6 \n3 5 6 " }, { "input": "7", "output": "4\n1 2 3 \n1 4 5 \n2 4 6 \n3 5 6 " }, { "input": "8", "output": "4...
92
0
0
27,590
442
Borya and Hanabi
[ "bitmasks", "brute force", "implementation" ]
null
null
Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game. Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding *n* cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has). The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints. A color hint goes like that: a player names some color and points at all the cards of this color. Similarly goes the value hint. A player names some value and points at all the cards that contain the value. Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.
The first line contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of Borya's cards. The next line contains the descriptions of *n* cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.
Print a single integer — the minimum number of hints that the other players should make.
[ "2\nG3 G3\n", "4\nG4 R4 R3 B3\n", "5\nB1 Y1 W1 G1 R1\n" ]
[ "0\n", "2\n", "4\n" ]
In the first sample Borya already knows for each card that it is a green three. In the second sample we can show all fours and all red cards. In the third sample you need to make hints about any four colors.
[ { "input": "2\nG3 G3", "output": "0" }, { "input": "4\nG4 R4 R3 B3", "output": "2" }, { "input": "5\nB1 Y1 W1 G1 R1", "output": "4" }, { "input": "10\nY4 B1 R3 G5 R5 W3 W5 W2 R1 Y1", "output": "6" }, { "input": "3\nG4 G3 B4", "output": "2" }, { "input"...
62
0
0
27,601
362
Fools and Foolproof Roads
[ "data structures", "dfs and similar", "dsu", "graphs", "greedy" ]
null
null
You must have heard all about the Foolland on your Geography lessons. Specifically, you must know that federal structure of this country has been the same for many centuries. The country consists of *n* cities, some pairs of cities are connected by bidirectional roads, each road is described by its length *l**i*. The fools lived in their land joyfully, but a recent revolution changed the king. Now the king is Vasily the Bear. Vasily divided the country cities into regions, so that any two cities of the same region have a path along the roads between them and any two cities of different regions don't have such path. Then Vasily decided to upgrade the road network and construct exactly *p* new roads in the country. Constructing a road goes like this: 1. We choose a pair of distinct cities *u*, *v* that will be connected by a new road (at that, it is possible that there already is a road between these cities). 1. We define the length of the new road: if cities *u*, *v* belong to distinct regions, then the length is calculated as *min*(109,<=*S*<=+<=1) (*S* — the total length of all roads that exist in the linked regions), otherwise we assume that the length equals 1000. 1. We build a road of the specified length between the chosen cities. If the new road connects two distinct regions, after construction of the road these regions are combined into one new region. Vasily wants the road constructing process to result in the country that consists exactly of *q* regions. Your task is to come up with such road constructing plan for Vasily that it meets the requirement and minimizes the total length of the built roads.
The first line contains four integers *n* (1<=≤<=*n*<=≤<=105), *m* (0<=≤<=*m*<=≤<=105), *p* (0<=≤<=*p*<=≤<=105), *q* (1<=≤<=*q*<=≤<=*n*) — the number of cities in the Foolland, the number of existing roads, the number of roads that are planned to construct and the required number of regions. Next *m* lines describe the roads that exist by the moment upgrading of the roads begun. Each of these lines contains three integers *x**i*, *y**i*, *l**i*: *x**i*, *y**i* — the numbers of the cities connected by this road (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*,<=*x**i*<=≠<=*y**i*), *l**i* — length of the road (1<=≤<=*l**i*<=≤<=109). Note that one pair of cities can be connected with multiple roads.
If constructing the roads in the required way is impossible, print a single string "NO" (without the quotes). Otherwise, in the first line print word "YES" (without the quotes), and in the next *p* lines print the road construction plan. Each line of the plan must consist of two distinct integers, giving the numbers of the cities connected by a road. The road must occur in the plan in the order they need to be constructed. If there are multiple optimal solutions, you can print any of them.
[ "9 6 2 2\n1 2 2\n3 2 1\n4 6 20\n1 3 8\n7 8 3\n5 7 2\n", "2 0 1 2\n", "2 0 0 2\n" ]
[ "YES\n9 5\n1 9\n", "NO\n", "YES\n" ]
Consider the first sample. Before the reform the Foolland consists of four regions. The first region includes cities 1, 2, 3, the second region has cities 4 and 6, the third region has cities 5, 7, 8, the fourth region has city 9. The total length of the roads in these cities is 11, 20, 5 and 0, correspondingly. According to the plan, we first build the road of length 6 between cities 5 and 9, then the road of length 23 between cities 1 and 9. Thus, the total length of the built roads equals 29.
[]
61
819,200
0
27,615
518
Arthur and Questions
[ "greedy", "implementation", "math", "ternary search" ]
null
null
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length *n* (*a*1,<=*a*2,<=...,<=*a**n*), consisting of integers and integer *k*, not exceeding *n*. This sequence had the following property: if you write out the sums of all its segments consisting of *k* consecutive elements (*a*1 <=+<= *a*2 ... <=+<= *a**k*,<= *a*2 <=+<= *a*3 <=+<= ... <=+<= *a**k*<=+<=1,<= ...,<= *a**n*<=-<=*k*<=+<=1 <=+<= *a**n*<=-<=*k*<=+<=2 <=+<= ... <=+<= *a**n*), then those numbers will form strictly increasing sequence. For example, for the following sample: *n*<==<=5,<= *k*<==<=3,<= *a*<==<=(1,<= 2,<= 4,<= 5,<= 6) the sequence of numbers will look as follows: (1 <=+<= 2 <=+<= 4,<= 2 <=+<= 4 <=+<= 5,<= 4 <=+<= 5 <=+<= 6) = (7,<= 11,<= 15), that means that sequence *a* meets the described property. Obviously the sequence of sums will have *n*<=-<=*k*<=+<=1 elements. Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |*a**i*|, where |*a**i*| is the absolute value of *a**i*.
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains *n* space-separated elements *a**i* (1<=≤<=*i*<=≤<=*n*). If *a**i* <==<= ?, then the *i*-th element of Arthur's sequence was replaced by a question mark. Otherwise, *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) is the *i*-th element of Arthur's sequence.
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print *n* integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |*a**i*|, where |*a**i*| is the absolute value of *a**i*. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
[ "3 2\n? 1 2\n", "5 1\n-10 -9 ? -7 -6\n", "5 3\n4 6 7 2 9\n" ]
[ "0 1 2 \n", "-10 -9 -8 -7 -6 \n", "Incorrect sequence\n" ]
none
[ { "input": "3 2\n? 1 2", "output": "0 1 2 " }, { "input": "5 1\n-10 -9 ? -7 -6", "output": "-10 -9 -8 -7 -6 " }, { "input": "5 3\n4 6 7 2 9", "output": "Incorrect sequence" }, { "input": "9 3\n? ? ? ? ? ? ? ? ?", "output": "-1 -1 -1 0 0 0 1 1 1 " }, { "input": "5 ...
405
21,401,600
3
27,616
0
none
[ "none" ]
null
null
Drazil created a following problem about putting 1<=×<=2 tiles into an *n*<=×<=*m* grid: "There is a grid with some cells that are empty and some cells that are occupied. You should use 1<=×<=2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it." But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ". Drazil found that the constraints for this task may be much larger than for the original task! Can you solve this new problem? Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2000). The following *n* lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.
If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1<=×<=2 tiles. Use characters "&lt;&gt;" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.
[ "3 3\n...\n.*.\n...\n", "4 4\n..**\n*...\n*.**\n....\n", "2 4\n*..*\n....\n", "1 1\n.\n", "1 1\n*\n" ]
[ "Not unique\n", "&lt;&gt;**\n*^&lt;&gt;\n*v**\n&lt;&gt;&lt;&gt;\n", "*&lt;&gt;*\n&lt;&gt;&lt;&gt;\n", "Not unique\n", "*\n" ]
In the first case, there are indeed two solutions: and so the answer is "Not unique".
[]
0
0
-1
27,632
914
Palindromes in a Tree
[ "bitmasks", "data structures", "divide and conquer", "trees" ]
null
null
You are given a tree (a connected acyclic undirected graph) of *n* vertices. Vertices are numbered from 1 to *n* and each vertex is assigned a character from a to t. A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome. For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex *u* to vertex *v* is considered to be the same as the path from vertex *v* to vertex *u*, and this path will be counted only once for each of the vertices it passes through.
The first line contains an integer *n* (2<=≤<=*n*<=≤<=2·105)  — the number of vertices in the tree. The next *n*<=-<=1 lines each contain two integers *u* and *v* (1<=<=≤<=<=*u*,<=*v*<=<=≤<=<=*n*,<=*u*<=≠<=*v*) denoting an edge connecting vertex *u* and vertex *v*. It is guaranteed that the given graph is a tree. The next line contains a string consisting of *n* lowercase characters from a to t where the *i*-th (1<=≤<=*i*<=≤<=*n*) character is the label of vertex *i* in the tree.
Print *n* integers in a single line, the *i*-th of which is the number of palindromic paths passing through vertex *i* in the tree.
[ "5\n1 2\n2 3\n3 4\n3 5\nabcbb\n", "7\n6 2\n4 3\n3 7\n5 2\n7 2\n1 4\nafefdfs\n" ]
[ "1 3 4 3 3 \n", "1 4 1 1 2 4 2 \n" ]
In the first sample case, the following paths are palindromic: 2 - 3 - 4 2 - 3 - 5 4 - 3 - 5 Additionally, all paths containing only one vertex are palindromic. Listed below are a few paths in the first sample that are not palindromic: 1 - 2 - 3 1 - 2 - 3 - 4 1 - 2 - 3 - 5
[ { "input": "5\n1 2\n2 3\n3 4\n3 5\nabcbb", "output": "1 3 4 3 3 " }, { "input": "7\n6 2\n4 3\n3 7\n5 2\n7 2\n1 4\nafefdfs", "output": "1 4 1 1 2 4 2 " }, { "input": "5\n3 1\n3 5\n5 4\n5 2\nticdm", "output": "1 1 1 1 1 " }, { "input": "10\n10 8\n3 2\n9 7\n1 5\n5 3\n7 6\n8 4\n1...
46
0
0
27,679
762
Maximum path
[ "dp", "greedy", "implementation" ]
null
null
You are given a rectangular table 3<=×<=*n*. Each cell contains an integer. You can move from one cell to another if they share a side. Find such path from the upper left cell to the bottom right cell of the table that doesn't visit any of the cells twice, and the sum of numbers written in the cells of this path is maximum possible.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105)  — the number of columns in the table. Next three lines contain *n* integers each  — the description of the table. The *j*-th number in the *i*-th line corresponds to the cell *a**ij* (<=-<=109<=≤<=*a**ij*<=≤<=109) of the table.
Output the maximum sum of numbers on a path from the upper left cell to the bottom right cell of the table, that doesn't visit any of the cells twice.
[ "3\n1 1 1\n1 -1 1\n1 1 1\n", "5\n10 10 10 -1 -1\n-1 10 10 10 10\n-1 10 10 10 10\n" ]
[ "7\n", "110\n" ]
The path for the first example: The path for the second example:
[ { "input": "3\n1 1 1\n1 -1 1\n1 1 1", "output": "7" }, { "input": "5\n10 10 10 -1 -1\n-1 10 10 10 10\n-1 10 10 10 10", "output": "110" }, { "input": "15\n-87 -91 31 63 91 35 -14 51 20 20 -20 -94 -59 77 76\n11 81 22 -29 91 -26 -10 -12 46 10 100 88 14 64 41\n26 -31 99 -39 -30 30 28 74 -7 2...
1,000
24,371,200
0
27,691
76
Mice
[ "greedy", "two pointers" ]
B. Mice
0
256
Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal. If there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located *N* mice and *M* pieces of cheese on a cartesian plane where all mice are located on the line *y*<==<=*Y*0 and all pieces of cheese — on another line *y*<==<=*Y*1. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice. Write a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.
The first line of the input contains four integer numbers *N* (1<=≤<=*N*<=≤<=105), *M* (0<=≤<=*M*<=≤<=105), *Y*0 (0<=≤<=*Y*0<=≤<=107), *Y*1 (0<=≤<=*Y*1<=≤<=107, *Y*0<=≠<=*Y*1). The second line contains a strictly increasing sequence of *N* numbers — *x* coordinates of mice. Third line contains a strictly increasing sequence of *M* numbers — *x* coordinates of cheese. All coordinates are integers and do not exceed 107 by absolute value.
The only line of output should contain one number — the minimal number of mice which will remain without cheese.
[ "3 2 0 2\n0 1 3\n2 5\n" ]
[ "1\n" ]
All the three mice will choose the first piece of cheese. Second and third mice will eat this piece. The first one will remain hungry, because it was running towards the same piece, but it was late. The second piece of cheese will remain uneaten.
[ { "input": "3 2 0 2\n0 1 3\n2 5", "output": "1" }, { "input": "7 11 10 20\n6 18 32 63 66 68 87\n6 8 15 23 25 41 53 59 60 75 90", "output": "1" }, { "input": "13 17 14 1\n6 9 10 12 17 25 91 100 118 136 145 163 172\n0 1 2 3 4 10 12 13 16 17 19 22 26 27 28 109 154", "output": "4" }, ...
311
14,745,600
3
27,728
401
Roman and Numbers
[ "bitmasks", "brute force", "combinatorics", "dp", "number theory" ]
null
null
Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number *n*, modulo *m*. Number *x* is considered close to number *n* modulo *m*, if: - it can be obtained by rearranging the digits of number *n*, - it doesn't have any leading zeroes, - the remainder after dividing number *x* by *m* equals 0. Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
The first line contains two integers: *n* (1<=≤<=*n*<=&lt;<=1018) and *m* (1<=≤<=*m*<=≤<=100).
In a single line print a single integer — the number of numbers close to number *n* modulo *m*.
[ "104 2\n", "223 4\n", "7067678 8\n" ]
[ "3\n", "1\n", "47\n" ]
In the first sample the required numbers are: 104, 140, 410. In the second sample the required number is 232.
[ { "input": "104 2", "output": "3" }, { "input": "223 4", "output": "1" }, { "input": "7067678 8", "output": "47" }, { "input": "202 10", "output": "1" }, { "input": "1306432 9", "output": "0" }, { "input": "9653092 9", "output": "0" }, { "i...
61
11,673,600
-1
27,821
557
Ann and Half-Palindrome
[ "data structures", "dp", "graphs", "string suffix structures", "strings", "trees" ]
null
null
Tomorrow Ann takes the hardest exam of programming where she should get an excellent mark. On the last theoretical class the teacher introduced the notion of a half-palindrome. String *t* is a half-palindrome, if for all the odd positions *i* () the following condition is held: *t**i*<==<=*t*|*t*|<=-<=*i*<=+<=1, where |*t*| is the length of string *t* if positions are indexed from 1. For example, strings "abaa", "a", "bb", "abbbaa" are half-palindromes and strings "ab", "bba" and "aaabaa" are not. Ann knows that on the exam she will get string *s*, consisting only of letters a and b, and number *k*. To get an excellent mark she has to find the *k*-th in the lexicographical order string among all substrings of *s* that are half-palyndromes. Note that each substring in this order is considered as many times as many times it occurs in *s*. The teachers guarantees that the given number *k* doesn't exceed the number of substrings of the given string that are half-palindromes. Can you cope with this problem?
The first line of the input contains string *s* (1<=≤<=|*s*|<=≤<=5000), consisting only of characters 'a' and 'b', where |*s*| is the length of string *s*. The second line contains a positive integer *k* —  the lexicographical number of the requested string among all the half-palindrome substrings of the given string *s*. The strings are numbered starting from one. It is guaranteed that number *k* doesn't exceed the number of substrings of the given string that are half-palindromes.
Print a substring of the given string that is the *k*-th in the lexicographical order of all substrings of the given string that are half-palindromes.
[ "abbabaab\n7\n", "aaaaa\n10\n", "bbaabb\n13\n" ]
[ "abaa\n", "aaa\n", "bbaabb\n" ]
By definition, string *a* = *a*<sub class="lower-index">1</sub>*a*<sub class="lower-index">2</sub>... *a*<sub class="lower-index">*n*</sub> is lexicographically less than string *b* = *b*<sub class="lower-index">1</sub>*b*<sub class="lower-index">2</sub>... *b*<sub class="lower-index">*m*</sub>, if either *a* is a prefix of *b* and doesn't coincide with *b*, or there exists such *i*, that *a*<sub class="lower-index">1</sub> = *b*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub> = *b*<sub class="lower-index">2</sub>, ... *a*<sub class="lower-index">*i* - 1</sub> = *b*<sub class="lower-index">*i* - 1</sub>, *a*<sub class="lower-index">*i*</sub> &lt; *b*<sub class="lower-index">*i*</sub>. In the first sample half-palindrome substrings are the following strings — a, a, a, a, aa, aba, abaa, abba, abbabaa, b, b, b, b, baab, bab, bb, bbab, bbabaab (the list is given in the lexicographical order).
[ { "input": "abbabaab\n7", "output": "abaa" }, { "input": "aaaaa\n10", "output": "aaa" }, { "input": "bbaabb\n13", "output": "bbaabb" }, { "input": "a\n1", "output": "a" }, { "input": "b\n1", "output": "b" }, { "input": "ababbbbbbbaaaaaaaabbbbbb\n23", ...
1,044
158,720,000
3
27,835
774
Pens And Days Of Week
[ "*special", "binary search", "number theory" ]
null
null
Stepan has *n* pens. Every day he uses them, and on the *i*-th day he uses the pen number *i*. On the (*n*<=+<=1)-th day again he uses the pen number 1, on the (*n*<=+<=2)-th — he uses the pen number 2 and so on. On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day. Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.
The first line contains the integer *n* (1<=≤<=*n*<=≤<=50<=000) — the number of pens Stepan has. The second line contains the sequence of integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where *a**i* is equal to the number of milliliters of ink which the pen number *i* currently has.
Print the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above. Pens are numbered in the order they are given in input data. The numeration begins from one. Note that the answer is always unambiguous, since several pens can not end at the same time.
[ "3\n3 3 3\n", "5\n5 4 5 4 4\n" ]
[ "2\n", "5\n" ]
In the first test Stepan uses ink of pens as follows: 1. on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it; 1. on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it; 1. on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it; 1. on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1 milliliters of ink in it; 1. on the day number 5 (Friday) Stepan will use the pen number 2, after that there will be 1 milliliters of ink in it; 1. on the day number 6 (Saturday) Stepan will use the pen number 3, after that there will be 1 milliliters of ink in it; 1. on the day number 7 (Sunday) Stepan will use the pen number 1, but it is a day of rest so he will not waste ink of this pen in it; 1. on the day number 8 (Monday) Stepan will use the pen number 2, after that this pen will run out of ink. So, the first pen which will not have ink is the pen number 2.
[ { "input": "3\n3 3 3", "output": "2" }, { "input": "5\n5 4 5 4 4", "output": "5" }, { "input": "28\n2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033 2033", "output": "1" }, { "input": "7\n10...
0
0
-1
27,843
196
Lexicographically Maximum Subsequence
[ "greedy", "strings" ]
null
null
You've got string *s*, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string *s*[*p*1*p*2... *p**k*]<==<=*s**p*1*s**p*2... *s**p**k*(1<=≤<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**k*<=≤<=|*s*|) a subsequence of string *s*<==<=*s*1*s*2... *s*|*s*|. String *x*<==<=*x*1*x*2... *x*|*x*| is lexicographically larger than string *y*<==<=*y*1*y*2... *y*|*y*|, if either |*x*|<=&gt;<=|*y*| and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x*|*y*|<==<=*y*|*y*|, or exists such number *r* (*r*<=&lt;<=|*x*|,<=*r*<=&lt;<=|*y*|), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=&gt;<=*y**r*<=+<=1. Characters in lines are compared like their ASCII codes.
The single line contains a non-empty string *s*, consisting only of lowercase English letters. The string's length doesn't exceed 105.
Print the lexicographically maximum subsequence of string *s*.
[ "ababba\n", "abbcbccacbbcbaaba\n" ]
[ "bbba\n", "cccccbba\n" ]
Let's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters). The first sample: aBaBBA The second sample: abbCbCCaCbbCBaaBA
[ { "input": "ababba", "output": "bbba" }, { "input": "abbcbccacbbcbaaba", "output": "cccccbba" }, { "input": "thankstosamarasauteddybearsforthiscontest", "output": "yttt" }, { "input": "cantouristsolveitlessthaninoneminute", "output": "vute" }, { "input": "areprete...
2,000
6,041,600
0
27,892
196
The Next Good String
[ "data structures", "greedy", "hashing", "strings" ]
null
null
In problems on strings one often has to find a string with some particular properties. The problem authors were reluctant to waste time on thinking of a name for some string so they called it good. A string is good if it doesn't have palindrome substrings longer than or equal to *d*. You are given string *s*, consisting only of lowercase English letters. Find a good string *t* with length |*s*|, consisting of lowercase English letters, which is lexicographically larger than *s*. Of all such strings string *t* must be lexicographically minimum. We will call a non-empty string *s*[*a* ... *b*]<==<=*s**a**s**a*<=+<=1... *s**b* (1<=≤<=*a*<=≤<=*b*<=≤<=|*s*|) a substring of string *s*<==<=*s*1*s*2... *s*|*s*|. A non-empty string *s*<==<=*s*1*s*2... *s**n* is called a palindrome if for all *i* from 1 to *n* the following fulfills: *s**i*<==<=*s**n*<=-<=*i*<=+<=1. In other words, palindrome read the same in both directions. String *x*<==<=*x*1*x*2... *x*|*x*| is lexicographically larger than string *y*<==<=*y*1*y*2... *y*|*y*|, if either |*x*|<=&gt;<=|*y*| and *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x*|*y*|<==<=*y*|*y*|, or there exists such number *r* (*r*<=&lt;<=|*x*|,<=*r*<=&lt;<=|*y*|), that *x*1<==<=*y*1,<=*x*2<==<=*y*2,<=... ,<=*x**r*<==<=*y**r* and *x**r*<=+<=1<=&gt;<=*y**r*<=+<=1. Characters in such strings are compared like their ASCII codes.
The first line contains integer *d* (1<=≤<=*d*<=≤<=|*s*|). The second line contains a non-empty string *s*, its length is no more than 4·105 characters. The string consists of lowercase English letters.
Print the good string that lexicographically follows *s*, has the same length and consists of only lowercase English letters. If such string does not exist, print "Impossible" (without the quotes).
[ "3\naaaaaaa\n", "3\nzzyzzzz\n", "4\nabbabbbabbb\n" ]
[ "aabbcaa\n", "Impossible\n", "abbbcaaabab\n" ]
none
[]
92
0
0
27,929
916
Jamie and To-do List
[ "data structures", "interactive", "trees" ]
null
null
Why I have to finish so many assignments??? Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment (lower value means more important) so he can decide which he needs to spend more time on. After a few days, Jamie finds out the list is too large that he can't even manage the list by himself! As you are a good friend of Jamie, help him write a program to support the following operations on the to-do list: - *set* *a**i* *x**i* — Add assignment *a**i* to the to-do list if it is not present, and set its priority to *x**i*. If assignment *a**i* is already in the to-do list, its priority is changed to *x**i*. - *remove* *a**i* — Remove assignment *a**i* from the to-do list if it is present in it. - *query* *a**i* — Output the number of assignments that are more important (have a smaller priority value) than assignment *a**i*, so Jamie can decide a better schedule. Output <=-<=1 if *a**i* is not in the to-do list. - *undo* *d**i* — Undo all changes that have been made in the previous *d**i* days (not including the day of this operation) At day 0, the to-do list is empty. In each of the following *q* days, Jamie will do exactly one out of the four operations. If the operation is a *query*, you should output the result of the query before proceeding to the next day, or poor Jamie cannot make appropriate decisions.
The first line consists of a single integer *q* (1<=≤<=*q*<=≤<=105) — the number of operations. The following *q* lines consists of the description of the operations. The *i*-th line consists of the operation that Jamie has done in the *i*-th day. The query has the following format: The first word in the line indicates the type of operation. It must be one of the following four: set, remove, query, undo. - If it is a set operation, a string *a**i* and an integer *x**i* follows (1<=≤<=*x**i*<=≤<=109). *a**i* is the assignment that need to be set to priority *x**i*. - If it is a remove operation, a string *a**i* follows. *a**i* is the assignment that need to be removed. - If it is a query operation, a string *a**i* follows. *a**i* is the assignment that needs to be queried. - If it is a undo operation, an integer *d**i* follows (0<=≤<=*d**i*<=&lt;<=*i*). *d**i* is the number of days that changes needed to be undone. All assignment names *a**i* only consists of lowercase English letters and have a length 1<=≤<=|*a**i*|<=≤<=15. It is guaranteed that the last operation is a query operation.
For each query operation, output a single integer — the number of assignments that have a priority lower than assignment *a**i*, or <=-<=1 if *a**i* is not in the to-do list.
[ "8\nset chemlabreport 1\nset physicsexercise 2\nset chinesemockexam 3\nquery physicsexercise\nquery chinesemockexam\nremove physicsexercise\nquery physicsexercise\nquery chinesemockexam\n", "8\nset physicsexercise 2\nset chinesemockexam 3\nset physicsexercise 1\nquery physicsexercise\nquery chinesemockexam\nundo ...
[ "1\n2\n-1\n1\n", "0\n1\n0\n-1\n", "-1\n-1\n-1\n", "-1\n" ]
none
[]
2,000
207,257,600
0
27,953
712
Memory and Scores
[ "combinatorics", "dp", "math" ]
null
null
Memory and his friend Lexa are competing to get higher score in one popular computer game. Memory starts with score *a* and Lexa starts with score *b*. In a single turn, both Memory and Lexa get some integer in the range [<=-<=*k*;*k*] (i.e. one integer among <=-<=*k*,<=<=-<=*k*<=+<=1,<=<=-<=*k*<=+<=2,<=...,<=<=-<=2,<=<=-<=1,<=0,<=1,<=2,<=...,<=*k*<=-<=1,<=*k*) and add them to their current scores. The game has exactly *t* turns. Memory and Lexa, however, are not good at this game, so they both always get a random integer at their turn. Memory wonders how many possible games exist such that he ends with a strictly higher score than Lexa. Two games are considered to be different if in at least one turn at least one player gets different score. There are (2*k*<=+<=1)2*t* games in total. Since the answer can be very large, you should print it modulo 109<=+<=7. Please solve this problem for Memory.
The first and only line of input contains the four integers *a*, *b*, *k*, and *t* (1<=≤<=*a*,<=*b*<=≤<=100, 1<=≤<=*k*<=≤<=1000, 1<=≤<=*t*<=≤<=100) — the amount Memory and Lexa start with, the number *k*, and the number of turns respectively.
Print the number of possible games satisfying the conditions modulo 1<=000<=000<=007 (109<=+<=7) in one line.
[ "1 2 2 1\n", "1 1 1 2\n", "2 12 3 1\n" ]
[ "6\n", "31\n", "0\n" ]
In the first sample test, Memory starts with 1 and Lexa starts with 2. If Lexa picks  - 2, Memory can pick 0, 1, or 2 to win. If Lexa picks  - 1, Memory can pick 1 or 2 to win. If Lexa picks 0, Memory can pick 2 to win. If Lexa picks 1 or 2, Memory cannot win. Thus, there are 3 + 2 + 1 = 6 possible games in which Memory wins.
[ { "input": "1 2 2 1", "output": "6" }, { "input": "1 1 1 2", "output": "31" }, { "input": "2 12 3 1", "output": "0" }, { "input": "4 6 2 1", "output": "3" }, { "input": "4 6 2 2", "output": "122" }, { "input": "6 4 2 2", "output": "435" }, { ...
2,000
9,420,800
0
28,005
205
Little Elephant and Sorting
[ "brute force", "greedy" ]
null
null
The Little Elephant loves sortings. He has an array *a* consisting of *n* integers. Let's number the array elements from 1 to *n*, then the *i*-th element will be denoted as *a**i*. The Little Elephant can make one move to choose an arbitrary pair of integers *l* and *r* (1<=≤<=*l*<=≤<=*r*<=≤<=*n*) and increase *a**i* by 1 for all *i* such that *l*<=≤<=*i*<=≤<=*r*. Help the Little Elephant find the minimum number of moves he needs to convert array *a* to an arbitrary array sorted in the non-decreasing order. Array *a*, consisting of *n* elements, is sorted in the non-decreasing order if for any *i* (1<=≤<=*i*<=&lt;<=*n*) *a**i*<=≤<=*a**i*<=+<=1 holds.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105) — the size of array *a*. The next line contains *n* integers, separated by single spaces — array *a* (1<=≤<=*a**i*<=≤<=109). The array elements are listed in the line in the order of their index's increasing.
In a single line print a single integer — the answer to the problem. 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.
[ "3\n1 2 3\n", "3\n3 2 1\n", "4\n7 4 1 47\n" ]
[ "0\n", "2\n", "6\n" ]
In the first sample the array is already sorted in the non-decreasing order, so the answer is 0. In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]). In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].
[ { "input": "3\n1 2 3", "output": "0" }, { "input": "3\n3 2 1", "output": "2" }, { "input": "4\n7 4 1 47", "output": "6" }, { "input": "10\n1 2 3 4 5 6 7 8 9 1000000000", "output": "0" }, { "input": "10\n1000000000 1 1000000000 1 1000000000 1 1000000000 1 100000000...
170
9,113,600
3
28,045
401
Sereja and Contests
[ "greedy", "implementation", "math" ]
null
null
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: *Div*1 (for advanced coders) and *Div*2 (for beginner coders). Two rounds, *Div*1 and *Div*2, can go simultaneously, (*Div*1 round cannot be held without *Div*2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the *Div*1 round is always greater. Sereja is a beginner coder, so he can take part only in rounds of *Div*2 type. At the moment he is taking part in a *Div*2 round, its identifier equals to *x*. Sereja remembers very well that he has taken part in exactly *k* rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed. Sereja is wondering: what minimum and what maximum number of *Div*2 rounds could he have missed? Help him find these two numbers.
The first line contains two integers: *x* (1<=≤<=*x*<=≤<=4000) — the round Sereja is taking part in today, and *k* (0<=≤<=*k*<=&lt;<=4000) — the number of rounds he took part in. Next *k* lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 *num*2 *num*1" (where *num*2 is the identifier of this *Div*2 round, *num*1 is the identifier of the *Div*1 round). It is guaranteed that *num*1<=-<=*num*2<==<=1. If Sereja took part in a usual *Div*2 round, then the corresponding line looks like: "2 *num*" (where *num* is the identifier of this *Div*2 round). It is guaranteed that the identifiers of all given rounds are less than *x*.
Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.
[ "3 2\n2 1\n2 2\n", "9 3\n1 2 3\n2 8\n1 4 5\n", "10 0\n" ]
[ "0 0", "2 3", "5 9" ]
In the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual *Div*2 round and the round with identifier 6 will be synchronous with the *Div*1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual *Div*2 rounds.
[ { "input": "3 2\n2 1\n2 2", "output": "0 0" }, { "input": "9 3\n1 2 3\n2 8\n1 4 5", "output": "2 3" }, { "input": "10 0", "output": "5 9" }, { "input": "10 2\n1 1 2\n1 8 9", "output": "3 5" }, { "input": "9 3\n1 4 5\n1 1 2\n1 6 7", "output": "2 2" }, { ...
499
5,427,200
3
28,068
988
Equal Sums
[ "implementation", "sortings" ]
null
null
You are given $k$ sequences of integers. The length of the $i$-th sequence equals to $n_i$. You have to choose exactly two sequences $i$ and $j$ ($i \ne j$) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence $i$ (its length will be equal to $n_i - 1$) equals to the sum of the changed sequence $j$ (its length will be equal to $n_j - 1$). Note that it's required to remove exactly one element in each of the two chosen sequences. Assume that the sum of the empty (of the length equals $0$) sequence is $0$.
The first line contains an integer $k$ ($2 \le k \le 2 \cdot 10^5$) — the number of sequences. Then $k$ pairs of lines follow, each pair containing a sequence. The first line in the $i$-th pair contains one integer $n_i$ ($1 \le n_i &lt; 2 \cdot 10^5$) — the length of the $i$-th sequence. The second line of the $i$-th pair contains a sequence of $n_i$ integers $a_{i, 1}, a_{i, 2}, \dots, a_{i, n_i}$. The elements of sequences are integer numbers from $-10^4$ to $10^4$. The sum of lengths of all given sequences don't exceed $2 \cdot 10^5$, i.e. $n_1 + n_2 + \dots + n_k \le 2 \cdot 10^5$.
If it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers $i$, $x$ ($1 \le i \le k, 1 \le x \le n_i$), in the third line — two integers $j$, $y$ ($1 \le j \le k, 1 \le y \le n_j$). It means that the sum of the elements of the $i$-th sequence without the element with index $x$ equals to the sum of the elements of the $j$-th sequence without the element with index $y$. Two chosen sequences must be distinct, i.e. $i \ne j$. You can print them in any order. If there are multiple possible answers, print any of them.
[ "2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1\n", "3\n1\n5\n5\n1 1 1 1 1\n2\n2 3\n", "4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2\n" ]
[ "YES\n2 6\n1 2\n", "NO\n", "YES\n2 2\n4 1\n" ]
In the first example there are two sequences $[2, 3, 1, 3, 2]$ and $[1, 1, 2, 2, 2, 1]$. You can remove the second element from the first sequence to get $[2, 1, 3, 2]$ and you can remove the sixth element from the second sequence to get $[1, 1, 2, 2, 2]$. The sums of the both resulting sequences equal to $8$, i.e. the sums are equal.
[ { "input": "2\n5\n2 3 1 3 2\n6\n1 1 2 2 2 1", "output": "YES\n2 1\n1 4" }, { "input": "3\n1\n5\n5\n1 1 1 1 1\n2\n2 3", "output": "NO" }, { "input": "4\n6\n2 2 2 2 2 2\n5\n2 2 2 2 2\n3\n2 2 2\n5\n2 2 2 2 2", "output": "YES\n4 1\n2 5" }, { "input": "2\n2\n0 -10000\n2\n10000 0",...
31
0
0
28,094
670
Correct Bracket Sequence Editor
[ "data structures", "dsu", "strings" ]
null
null
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))": - 1st bracket is paired with 8th, - 2d bracket is paired with 3d, - 3d bracket is paired with 2d, - 4th bracket is paired with 7th, - 5th bracket is paired with 6th, - 6th bracket is paired with 5th, - 7th bracket is paired with 4th, - 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: - «L» — move the cursor one position to the left, - «R» — move the cursor one position to the right, - «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below. All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor. Polycarp is very proud of his development, can you implement the functionality of his editor?
The first line contains three positive integers *n*, *m* and *p* (2<=≤<=*n*<=≤<=500<=000, 1<=≤<=*m*<=≤<=500<=000, 1<=≤<=*p*<=≤<=*n*) — the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that *n* is even. It is followed by the string of *n* characters "(" and ")" forming the correct bracket sequence. Then follow a string of *m* characters "L", "R" and "D" — a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.
Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.
[ "8 4 5\n(())()()\nRDLD\n", "12 5 3\n((()())(()))\nRRDLD\n", "8 8 8\n(())()()\nLLLLLLDD\n" ]
[ "()\n", "(()(()))\n", "()()\n" ]
In the first sample the cursor is initially at position 5. Consider actions of the editor: 1. command "R" — the cursor moves to the position 6 on the right; 1. command "D" — the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5; 1. command "L" — the cursor moves to the position 4 on the left; 1. command "D" — the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ().
[ { "input": "8 4 5\n(())()()\nRDLD", "output": "()" }, { "input": "12 5 3\n((()())(()))\nRRDLD", "output": "(()(()))" }, { "input": "8 8 8\n(())()()\nLLLLLLDD", "output": "()()" }, { "input": "4 2 2\n()()\nLD", "output": "()" }, { "input": "6 4 1\n()()()\nDRRD", ...
779
36,044,800
-1
28,098