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
607
Cross Sum
[ "binary search", "geometry" ]
null
null
Genos has been given *n* distinct lines on the Cartesian plane. Let be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter. Given a query point (*p*,<=*q*), let be the corresponding list of distances of all points in to the query point. Distance here refers to euclidean distance. As a refresher, the euclidean distance between two points (*x*1,<=*y*1) and (*x*2,<=*y*2) is . Genos is given a point (*p*,<=*q*) and a positive integer *m*. He is asked to find the sum of the *m* smallest elements in . Duplicate elements in are treated as separate elements. Genos is intimidated by Div1 E problems so he asked for your help.
The first line of the input contains a single integer *n* (2<=≀<=*n*<=≀<=50<=000)Β β€” the number of lines. The second line contains three integers *x*, *y* and *m* (|*x*|,<=|*y*|<=≀<=1<=000<=000, )Β β€” the encoded coordinates of the query point and the integer *m* from the statement above. The query point (*p*,<=*q*) is obtained as . In other words, divide *x* and *y* by 1000 to get the actual query point. denotes the length of the list and it is guaranteed that . Each of the next *n* lines contains two integers *a**i* and *b**i* (|*a**i*|,<=|*b**i*|<=≀<=1<=000<=000)Β β€” the parameters for a line of the form: . It is guaranteed that no two lines are the same, that is (*a**i*,<=*b**i*)<=β‰ <=(*a**j*,<=*b**j*) if *i*<=β‰ <=*j*.
Print a single real number, the sum of *m* smallest elements of . Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. To clarify, let's assume that your answer is *a* and the answer of the jury is *b*. The checker program will consider your answer correct if .
[ "4\n1000 1000 3\n1000 0\n-1000 0\n0 5000\n0 -5000\n", "2\n-1000000 -1000000 1\n1000000 -1000000\n999999 1000000\n", "3\n-1000 1000 3\n1000 0\n-1000 2000\n2000 -1000\n", "5\n-303667 189976 10\n-638 116487\n-581 44337\n1231 -756844\n1427 -44097\n8271 -838417\n" ]
[ "14.282170363\n", "2000001000.999999500\n", "6.000000000\n", "12953.274911829\n" ]
In the first sample, the three closest points have distances <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5d034d9a89435d5056a183760eb7b3b7a12cfd15.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6a579e51bf1610b7c34464ea52a3cadfb31a4f84.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the second sample, the two lines *y* = 1000*x* - 1000 and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e4e30c00edb4440677bee169d45b6f9ac80cdac3.png" style="max-width: 100.0%;max-height: 100.0%;"/> intersect at (2000000, 1999999000). This point has a distance of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5fd08d2caf504b763ce325cdb5478fdecfe37842.png" style="max-width: 100.0%;max-height: 100.0%;"/> from ( - 1000,  - 1000). In the third sample, the three lines all intersect at the point (1, 1). This intersection point is present three times in <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8d78ee8afbfce85cba4f37a7aaca3025736e21af.png" style="max-width: 100.0%;max-height: 100.0%;"/> since it is the intersection of three pairs of lines. Since the distance between the intersection point and the query point is 2, the answer is three times that or 6.
[]
7,000
426,905,600
0
142,852
960
Bandit Blues
[ "combinatorics", "dp", "fft", "math" ]
null
null
Japate, while traveling through the forest of Mala, saw *N* bags of gold lying in a row. Each bag has some distinct weight of gold between 1 to *N*. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag. Initially, he starts with an empty bag (zero weight). He considers the bags in some order. If the current bag has a higher weight than the bag in his hand, he picks the current bag. Japate put the bags in some order. Japate realizes that he will pick *A* bags, if he starts picking bags from the front, and will pick *B* bags, if he starts picking bags from the back. By picking we mean replacing the bag in his hand with the current one. Now he wonders how many permutations of bags are possible, in which he picks *A* bags from the front and *B* bags from back using the above strategy. Since the answer can be very large, output it modulo 998244353.
The only line of input contains three space separated integers *N* (1<=≀<=*N*<=≀<=105), *A* and *B* (0<=≀<=*A*,<=*B*<=≀<=*N*).
Output a single integer β€” the number of valid permutations modulo 998244353.
[ "1 1 1\n", "2 1 1\n", "2 2 1\n", "5 2 2\n" ]
[ "1", "0", "1", "22" ]
In sample case 1, the only possible permutation is [1] In sample cases 2 and 3, only two permutations of size 2 are possible:{[1, 2], [2, 1]}. The values of *a* and *b* for first permutation is 2 and 1, and for the second permutation these values are 1 and 2. In sample case 4, out of 120 permutations of [1, 2, 3, 4, 5] possible, only 22 satisfy the given constraints of *a* and *b*.
[]
46
0
0
144,031
391
Word Folding
[ "brute force" ]
null
null
You will receive 5 points for solving this problem. Manao has invented a new operation on strings that is called folding. Each fold happens between a pair of consecutive letters and places the second part of the string above first part, running in the opposite direction and aligned to the position of the fold. Using this operation, Manao converts the string into a structure that has one more level than there were fold operations performed. See the following examples for clarity. We will denote the positions of folds with '|' characters. For example, the word "ABRACADABRA" written as "AB|RACA|DAB|RA" indicates that it has been folded three times: first, between the leftmost pair of 'B' and 'R' letters; second, between 'A' and 'D'; and third, between the rightmost pair of 'B' and 'R' letters. Here are several examples of folded strings: One last example for "ABCD|EFGH|IJ|K": Manao noticed that each folded string can be viewed as several piles of letters. For instance, in the previous example, there are four piles, which can be read as "AHI", "BGJK", "CF", and "DE" from bottom to top. Manao wonders what is the highest pile of identical letters he can build using fold operations on a given word. Note that the pile should not contain gaps and should start at the bottom level. For example, in the rightmost of the four examples above, none of the piles would be considered valid since each of them has gaps, starts above the bottom level, or both.
The input will consist of one line containing a single string of *n* characters with 1<=≀<=*n*<=≀<=1000 and no spaces. All characters of the string will be uppercase letters. This problem doesn't have subproblems. You will get 5 points for the correct submission.
Print a single integer β€” the size of the largest pile composed of identical characters that can be seen in a valid result of folding operations on the given string.
[ "ABRACADABRA\n", "ABBBCBDB\n", "AB\n" ]
[ "3\n", "3\n", "1\n" ]
Consider the first example. Manao can create a pile of three 'A's using the folding "AB|RACAD|ABRA", which results in the following structure: In the second example, Manao can create a pile of three 'B's using the following folding: "AB|BB|CBDB". Another way for Manao to create a pile of three 'B's with "ABBBCBDB" is the following folding: "AB|B|BCBDB". In the third example, there are no folds performed and the string is just written in one line.
[ { "input": "ABRACADABRA", "output": "3" }, { "input": "ABBBCBDB", "output": "3" }, { "input": "AB", "output": "1" }, { "input": "ABBCDEFB", "output": "3" }, { "input": "THISISATEST", "output": "3" }, { "input": "Z", "output": "1" }, { "inpu...
124
0
0
144,580
369
Valera and Fools
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
null
null
One fine morning, *n* fools lined up in a row. After that, they numbered each other with numbers from 1 to *n*, inclusive. Each fool got a unique number. The fools decided not to change their numbers before the end of the fun. Every fool has exactly *k* bullets and a pistol. In addition, the fool number *i* has probability of *p**i* (in percent) that he kills the fool he shoots at. The fools decided to have several rounds of the fun. Each round of the fun looks like this: each currently living fool shoots at another living fool with the smallest number (a fool is not stupid enough to shoot at himself). All shots of the round are perfomed at one time (simultaneously). If there is exactly one living fool, he does not shoot. Let's define a situation as the set of numbers of all the living fools at the some time. We say that a situation is possible if for some integer number *j* (0<=≀<=*j*<=≀<=*k*) there is a nonzero probability that after *j* rounds of the fun this situation will occur. Valera knows numbers *p*1,<=*p*2,<=...,<=*p**n* and *k*. Help Valera determine the number of distinct possible situations.
The first line contains two integers *n*,<=*k* (1<=≀<=*n*,<=*k*<=≀<=3000) β€” the initial number of fools and the number of bullets for each fool. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (0<=≀<=*p**i*<=≀<=100) β€” the given probabilities (in percent).
Print a single number β€” the answer to the problem.
[ "3 3\n50 50 50\n", "1 1\n100\n", "2 1\n100 100\n", "3 3\n0 0 0\n" ]
[ "7\n", "1\n", "2\n", "1\n" ]
In the first sample, any situation is possible, except for situation {1, 2}. In the second sample there is exactly one fool, so he does not make shots. In the third sample the possible situations are {1, 2} (after zero rounds) and the "empty" situation {} (after one round). In the fourth sample, the only possible situation is {1, 2, 3}.
[ { "input": "3 3\n50 50 50", "output": "7" }, { "input": "1 1\n100", "output": "1" }, { "input": "2 1\n100 100", "output": "2" }, { "input": "3 3\n0 0 0", "output": "1" }, { "input": "5 2\n0 63 92 89 28", "output": "5" }, { "input": "103 42\n78 30 16 12...
436
77,516,800
0
144,797
374
Inna and Sequence
[ "binary search", "data structures", "dp", "trees" ]
null
null
Dima's spent much time thinking what present to give to Inna and gave her an empty sequence *w*. Now they want to fill sequence *w* with numbers zero and one. For that, they decided to play an amusing game. Before the game begins, Dima chooses *m* integers *a*1,<=*a*2,<=...,<=*a**m* (1<=≀<=*a*1<=&lt;<=*a*2<=&lt;<=...<=&lt;<=*a**m*). Then Inna and Dima start playing, that is, adding numbers to sequence *w*. Each new number they choose is added to the end of the sequence. At some moments of time Dima feels that the game is going to end too soon (and he wants to play with Inna as long as possible), so he hits a table hard with his fist. At that the *a*1-th, *a*2-th, *a*3-th, ..., *a**k*-th numbers from the beginning simultaneously fall out of the sequence (the sequence gets *k* numbers less). Here *k* is such maximum number that value *a**k* doesn't exceed the current length of the sequence. If number *a*1 is larger than the current length of *w*, then nothing falls out of the sequence. You are given the chronological sequence of events in the game. Each event is either adding a number to the end of sequence *w* or Dima's hit on the table. Calculate the sequence *w* after all these events happen.
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=106) showing how many events took place and how many numbers Dima chose. The next line contains *m* distinct integers *a**i* (1<=≀<=*a**i*<=≀<=106) sorted in the increasing order. Next *n* lines describe the events in the chronological order. Each line contains a single integer: -1, 0 or 1. Number -1 means that Dima hits the table. Number 0 means that Inna and Dima add number 0 to the end of the sequence. Number 1 means that Inna and Dima add number 1 to the end of the sequence.
In a single line print a sequence of numbers 0 and 1 β€” the elements of the sequence after all events happen. Print the elements of the sequence in the order from the beginning to the end of the sequence. If after all events the sequence ends up empty, print "Poor stack!".
[ "10 3\n1 3 6\n-1\n1\n1\n0\n0\n-1\n0\n1\n-1\n1\n", "2 1\n1\n1\n-1\n" ]
[ "011\n", "Poor stack!\n" ]
none
[ { "input": "10 3\n1 3 6\n-1\n1\n1\n0\n0\n-1\n0\n1\n-1\n1", "output": "011" }, { "input": "2 1\n1\n1\n-1", "output": "Poor stack!" }, { "input": "2 1\n1\n-1\n0", "output": "0" }, { "input": "11 2\n2 4\n1\n-1\n1\n-1\n0\n0\n-1\n1\n1\n1\n-1", "output": "111" }, { "inp...
0
0
-1
145,232
47
Cannon
[ "data structures", "geometry", "sortings" ]
E. Cannon
3
256
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the *Ox* axis is directed rightwards in the city's direction, the *Oy* axis is directed upwards (to the sky). The cannon will make *n* more shots. The cannon balls' initial speeds are the same in all the shots and are equal to *V*, so that every shot is characterized by only one number *alpha**i* which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (Ο€<=/<=4). We disregard the cannon sizes and consider the firing made from the point (0,<=0). The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: Think of the acceleration of gravity *g* as equal to 9.8. Bertown defends *m* walls. The *i*-th wall is represented as a vertical segment (*x**i*,<=0)<=-<=(*x**i*,<=*y**i*). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (*y*<==<=0) and stops. If the ball exactly hits the point (*x**i*,<=*y**i*), it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end.
The first line contains integers *n* and *V* (1<=≀<=*n*<=≀<=104,<=1<=≀<=*V*<=≀<=1000) which represent the number of shots and the initial speed of every ball. The second line contains *n* space-separated real numbers *alpha**i* (0<=&lt;<=*alpha**i*<=&lt;<=Ο€<=/<=4) which represent the angles in radians at which the cannon will fire. The third line contains integer *m* (1<=≀<=*m*<=≀<=105) which represents the number of walls. Then follow *m* lines, each containing two real numbers *x**i* and *y**i* (1<=≀<=*x**i*<=≀<=1000,<=0<=≀<=*y**i*<=≀<=1000) which represent the wall’s coordinates. All the real numbers have no more than 4 decimal digits. The walls may partially overlap or even coincide.
Print *n* lines containing two real numbers each β€” calculate for every ball the coordinates of its landing point. Your answer should have the relative or absolute error less than 10<=-<=4.
[ "2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9\n", "2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9\n" ]
[ "5.000000000 2.549499369\n4.000000000 0.378324889\n", "10.204081436 0.000000000\n4.000000000 0.378324889\n" ]
none
[ { "input": "2 10\n0.7853\n0.3\n3\n5.0 5.0\n4.0 2.4\n6.0 1.9", "output": "5.000000000 2.549499369\n4.000000000 0.378324889" }, { "input": "2 10\n0.7853\n0.3\n2\n4.0 2.4\n6.0 1.9", "output": "10.204081436 0.000000000\n4.000000000 0.378324889" }, { "input": "3 186\n0.4084\n0.4559\n0.1203\n3...
92
0
0
145,515
707
Garlands
[ "data structures" ]
null
null
Like all children, Alesha loves New Year celebration. During the celebration he and his whole family dress up the fir-tree. Like all children, Alesha likes to play with garlandsΒ β€” chains consisting of a lightbulbs. Alesha uses a grid field sized *n*<=Γ—<=*m* for playing. The rows of the field are numbered from 1 to *n* from the top to the bottom and columns are numbered from 1 to *m* from the left to the right. Alesha has *k* garlands which he places at the field. He does so in the way such that each lightbulb of each garland lies in the center of some cell in the field, and each cell contains at most one lightbulb. Of course lightbulbs, which are neighbours in some garland, appears in cells neighbouring by a side. The example of garland placing. Each garland is turned off or turned on at any moment. If some garland is turned on then each of its lightbulbs is turned on, the same applies for garland turned off. Each lightbulb in the whole garland set is unique, and thus, being turned on, brings Alesha some pleasure, described by an integer value. Turned off lightbulbs don't bring Alesha any pleasure. Alesha can turn garlands on and off and wants to know the sum of pleasure value which the lightbulbs, placed in the centers of the cells in some rectangular part of the field, bring him. Initially all the garlands are turned on. Alesha is still very little and can't add big numbers. He extremely asks you to help him.
The first line of the input contains three integers *n*, *m* and *k* (1<=≀<=*n*,<=*m*,<=*k*<=≀<=2000)Β β€” the number of field rows, the number of field columns and the number of garlands placed at the field respectively. Next lines contains garlands set description in the following format: The first line of a single garland description contains a single integer *len* (1<=≀<=*len*<=≀<=2000)Β β€” the number of lightbulbs in the garland. Each of the next *len* lines contains three integers *i*, *j* and *w* (1<=≀<=*i*<=≀<=*n*, 1<=≀<=*j*<=≀<=*m*, 1<=≀<=*w*<=≀<=109)Β β€” the coordinates of the cell containing a lightbullb and pleasure value Alesha gets from it if it is turned on. The lightbulbs are given in the order they are forming a chain in the garland. It is guaranteed that neighbouring lightbulbs are placed in the cells neighbouring by a side. The next line contains single integer *q* (1<=≀<=*q*<=≀<=106)Β β€” the number of events in Alesha's game. The next *q* lines describes events in chronological order. The *i*-th of them describes the *i*-th event in the one of the following formats: - SWITCH *i*Β β€” Alesha turns off *i*-th garland if it is turned on, or turns it on if it is turned off. It is guaranteed that 1<=≀<=*i*<=≀<=*k*. - ASK *x*1 *y*1 *x*2 *y*2Β β€” Alesha wants to know the sum of pleasure values the lightbulbs, placed in a rectangular part of the field. Top-left cell of a part has coordinates (*x*1,<=*y*1) and right-bottom cell has coordinates (*x*2,<=*y*2). It is guaranteed that 1<=≀<=*x*1<=≀<=*x*2<=≀<=*n* and 1<=≀<=*y*1<=≀<=*y*2<=≀<=*m*. There is no more than 2000 events of this type in the input. All the numbers in the input are integers. Please note that the input is quite large, so be careful while using some input ways. In particular, it's not recommended to use cin in codes on C++ and class Scanner in codes on Java.
For each ASK operation print the sum Alesha wants to know in a separate line. Print the answers in chronological order.
[ "4 4 3\n5\n1 1 2\n1 2 3\n2 2 1\n2 1 4\n3 1 7\n4\n1 3 1\n2 3 3\n2 4 3\n1 4 1\n7\n4 1 1\n4 2 9\n3 2 8\n3 3 3\n4 3 4\n4 4 1\n3 4 1\n2\nASK 2 2 3 3\nASK 1 1 4 4\n", "4 4 1\n8\n4 1 1\n3 1 2\n2 1 1\n1 1 7\n1 2 5\n2 2 4\n2 3 1\n1 3 1\n3\nASK 1 1 3 2\nSWITCH 1\nASK 1 1 3 2\n" ]
[ "15\n52\n", "19\n0\n" ]
<img class="tex-graphics" src="https://espresso.codeforces.com/9cc050397c0cf5696bf3273599ecbe1a65d3907b.png" style="max-width: 100.0%;max-height: 100.0%;"/> This image illustrates the first sample case.
[]
46
0
0
145,584
452
Permutation
[ "data structures", "divide and conquer", "hashing" ]
null
null
You are given a permutation of numbers from 1 to *n*. Determine whether there's a pair of integers *a*,<=*b* (1<=≀<=*a*,<=*b*<=≀<=*n*;Β *a*<=β‰ <=*b*) such that the element (note, that it is usual division, not integer one) is between *a* and *b* in this permutation.
First line consists of a single integer *n* (1<=≀<=*n*<=≀<=300000) β€” the size of permutation. Second line contains *n* integers β€” the permutation itself.
Print "YES", if such a pair exists, "NO" otherwise (in both cases without quotes, the answer is case insensitive).
[ "4\n1 3 4 2\n", "5\n1 5 2 4 3\n" ]
[ "NO\n", "YES\n" ]
In the second example 2 is between 1 and 3. Additionally 4 is between 3 and 5.
[ { "input": "4\n1 3 4 2", "output": "NO" }, { "input": "5\n1 5 2 4 3", "output": "YES" }, { "input": "100\n17 41 19 23 46 16 10 31 82 12 77 32 11 71 83 25 98 18 34 59 13 73 80 65 37 22 6 2 24 5 94 42 51 63 52 92 97 26 93 38 36 87 64 70 14 43 68 85 33 44 74 89 56 1 69 88 20 49 48 21 84 90 ...
296
46,899,200
0
145,703
506
Mr. Kitayuta's Gift
[ "combinatorics", "dp", "matrices", "strings" ]
null
null
Mr. Kitayuta has kindly given you a string *s* consisting of lowercase English letters. You are asked to insert exactly *n* lowercase English letters into *s* to make it a palindrome. (A palindrome is a string that reads the same forward and backward. For example, "noon", "testset" and "a" are all palindromes, while "test" and "kitayuta" are not.) You can choose any *n* lowercase English letters, and insert each of them to any position of *s*, possibly to the beginning or the end of *s*. You have to insert exactly *n* letters even if it is possible to turn *s* into a palindrome by inserting less than *n* letters. Find the number of the palindromes that can be obtained in this way, modulo 10007.
The first line contains a string *s* (1<=≀<=|*s*|<=≀<=200). Each character in *s* is a lowercase English letter. The second line contains an integer *n* (1<=≀<=*n*<=≀<=109).
Print the number of the palindromes that can be obtained, modulo 10007.
[ "revive\n1\n", "add\n2\n" ]
[ "1\n", "28\n" ]
For the first sample, you can obtain the palindrome "reviver" by inserting 'r' to the end of "revive". For the second sample, the following 28 palindromes can be obtained: "adada", "adbda", ..., "adzda", "dadad" and "ddadd".
[]
46
0
0
145,785
118
Fancy Number
[ "brute force", "greedy", "sortings", "strings" ]
null
null
A car number in Berland consists of exactly *n* digits. A number is called beautiful if it has at least *k* equal digits. Vasya wants to change the digits in his car's number so that the number became beautiful. To replace one of *n* digits Vasya has to pay the sum of money, equal to the absolute difference between the old digit and the new one. Help Vasya: find the minimum sum of money he should pay to make the number of his car beautiful. You should also find the resulting beautiful number. If there are several such numbers, then print the lexicographically minimum one.
The first line contains two space-separated integers *n* and *k* (2<=≀<=*n*<=≀<=104,<=2<=≀<=*k*<=≀<=*n*) which represent how many digits the number has and how many equal digits a beautiful number should have. The second line consists of *n* digits. It describes the old number of Vasya's car. It is guaranteed that the number contains no spaces and only contains digits.
On the first line print the minimum sum of money Vasya needs to change the number. On the second line print the car's new number. If there are several solutions, print the lexicographically minimum one.
[ "6 5\n898196\n", "3 2\n533\n", "10 6\n0001112223\n" ]
[ "4\n888188\n", "0\n533\n", "3\n0000002223\n" ]
In the first sample replacing the second digit with an "8" costs |9 - 8| = 1. Replacing the fifth digit with an "8" costs the same. Replacing the sixth digit costs |6 - 8| = 2. As a result, Vasya will pay 1 + 1 + 2 = 4 for a beautiful number "888188". The lexicographical comparison of strings is performed by the &lt; operator in modern programming languages. The string *x* is lexicographically smaller than the string *y*, if there exists such *i* (1 ≀ *i* ≀ *n*), that *x*<sub class="lower-index">*i*</sub> &lt; *y*<sub class="lower-index">*i*</sub>, and for any *j* (1 ≀ *j* &lt; *i*) *x*<sub class="lower-index">*j*</sub> = *y*<sub class="lower-index">*j*</sub>. The strings compared in this problem will always have the length *n*.
[ { "input": "6 5\n898196", "output": "4\n888188" }, { "input": "3 2\n533", "output": "0\n533" }, { "input": "10 6\n0001112223", "output": "3\n0000002223" }, { "input": "16 14\n6124258626539246", "output": "22\n4444448444449444" }, { "input": "45 32\n293440596342887...
92
0
0
145,806
36
Two Paths
[ "constructive algorithms", "dsu", "graphs", "implementation" ]
E. Two Paths
2
64
Once archaeologists found *m* mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as Β«*a* *b*Β» or Β«*b* *a*Β», where *a*,<=*b* are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey). During one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like Β«*a* *b*Β» could refer to the road from *a* to *b* as well as to the road from *b* to *a*. The archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them!
The first input line contains integer *m* (1<=≀<=*m*<=≀<=10000). Each of the following *m* lines describes one paper. Each description consists of two integers *a*,<=*b* (1<=≀<=*a*,<=*b*<=≀<=10000, *a*<=β‰ <=*b*).
In the first line output the number *L*1. That is the length of the first path, i.e. the amount of papers in its description. In the following line output *L*1 space-separated numbers β€” the indexes of the papers that describe the first path. In the third and fourth lines output similarly the length of the second path *L*2 and the path itself. Both paths must contain at least one road, i.e. condition *L*1<=&gt;<=0 and *L*2<=&gt;<=0 must be met. The papers are numbered from 1 to *m* according to the order of their appearance in the input file. The numbers should be output in the order in which the traveler passed the corresponding roads. If the answer is not unique, output any. If it’s impossible to find such two paths, output Β«-1Β». Don’t forget that each paper should be used exactly once, i.e *L*1<=+<=*L*2<==<=*m*.
[ "2\n4 5\n4 3\n", "1\n1 2\n" ]
[ "1\n2 \n1\n1\n", "-1\n" ]
none
[ { "input": "2\n4 5\n4 3", "output": "1\n2 \n1\n1" }, { "input": "1\n1 2", "output": "-1" }, { "input": "2\n4 5\n4 5", "output": "1\n1 \n1\n2" }, { "input": "2\n1 2\n3 4", "output": "1\n2 \n1\n1 " }, { "input": "2\n1 2\n2 3", "output": "1\n1 \n1\n2" }, { ...
62
0
-1
145,824
682
Alyona and Triangles
[ "geometry", "two pointers" ]
null
null
You are given *n* points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these *n* points, which area exceeds *S*. Alyona tried to construct a triangle with integer coordinates, which contains all *n* points and which area doesn't exceed 4*S*, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from *n* given points.
In the first line of the input two integers *n* and *S* (3<=≀<=*n*<=≀<=5000, 1<=≀<=*S*<=≀<=1018) are givenΒ β€” the number of points given and the upper bound value of any triangle's area, formed by any three of given *n* points. The next *n* lines describes given points: *i**th* of them consists of two integers *x**i* and *y**i* (<=-<=108<=≀<=*x**i*,<=*y**i*<=≀<=108)Β β€” coordinates of *i**th* point. It is guaranteed that there is at least one triple of points not lying on the same line.
Print the coordinates of three pointsΒ β€” vertices of a triangle which contains all *n* points and which area doesn't exceed 4*S*. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.
[ "4 1\n0 0\n1 0\n0 1\n1 1\n" ]
[ "-1 0\n2 0\n0 2" ]
[]
0
0
-1
146,101
0
none
[ "none" ]
null
null
You are given a table consisting of *n* rows and *m* columns. Each cell of the table contains either 0 or 1. In one move, you are allowed to pick any row or any column and invert all values, that is, replace 0 by 1 and vice versa. What is the minimum number of cells with value 1 you can get after applying some number of operations?
The first line of the input contains two integers *n* and *m* (1<=≀<=*n*<=≀<=20, 1<=≀<=*m*<=≀<=100<=000)Β β€” the number of rows and the number of columns, respectively. Then *n* lines follows with the descriptions of the rows. Each line has length *m* and contains only digits '0' and '1'.
Output a single integerΒ β€” the minimum possible number of ones you can get after applying some sequence of operations.
[ "3 4\n0110\n1010\n0111\n" ]
[ "2\n" ]
none
[]
31
0
0
146,162
507
The Maths Lecture
[ "dp", "implementation" ]
null
null
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't. First he gave Amr two positive integers *n* and *k*. Then he asked Amr, how many integer numbers *x*<=&gt;<=0 exist such that: - Decimal representation of *x* (without leading zeroes) consists of exactly *n* digits; - There exists some integer *y*<=&gt;<=0 such that: ; - decimal representation of *y* is a suffix of decimal representation of *x*. As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number *m*. Can you help Amr escape this embarrassing situation?
Input consists of three integers *n*,<=*k*,<=*m* (1<=≀<=*n*<=≀<=1000, 1<=≀<=*k*<=≀<=100, 1<=≀<=*m*<=≀<=109).
Print the required number modulo *m*.
[ "1 2 1000\n", "2 2 1000\n", "5 3 1103\n" ]
[ "4", "45", "590" ]
A suffix of a string *S* is a non-empty string that can be obtained by removing some number (possibly, zero) of first characters from *S*.
[ { "input": "1 2 1000", "output": "4" }, { "input": "2 2 1000", "output": "45" }, { "input": "5 3 1103", "output": "590" }, { "input": "2 17 10000", "output": "5" }, { "input": "3 9 10000", "output": "252" }, { "input": "6 64 941761822", "output": "...
327
6,656,000
3
146,299
403
Two Rooted Trees
[ "data structures", "implementation", "trees" ]
null
null
You have two rooted undirected trees, each contains *n* vertices. Let's number the vertices of each tree with integers from 1 to *n*. The root of each tree is at vertex 1. The edges of the first tree are painted blue, the edges of the second one are painted red. For simplicity, let's say that the first tree is blue and the second tree is red. Edge {*x*,<=*y*} is called bad for edge {*p*,<=*q*} if two conditions are fulfilled: 1. The color of edge {*x*,<=*y*} is different from the color of edge {*p*,<=*q*}. 1. Let's consider the tree of the same color that edge {*p*,<=*q*} is. Exactly one of vertices *x*, *y* lies both in the subtree of vertex *p* and in the subtree of vertex *q*. In this problem, your task is to simulate the process described below. The process consists of several stages: 1. On each stage edges of exactly one color are deleted. 1. On the first stage, exactly one blue edge is deleted. 1. Let's assume that at the stage *i* we've deleted edges {*u*1,<=*v*1}, {*u*2,<=*v*2}, ..., {*u**k*,<=*v**k*}. At the stage *i*<=+<=1 we will delete all undeleted bad edges for edge {*u*1,<=*v*1}, then we will delete all undeleted bad edges for edge {*u*2,<=*v*2} and so on until we reach edge {*u**k*,<=*v**k*}. For each stage of deleting edges determine what edges will be removed on the stage. Note that the definition of a bad edge always considers the initial tree before it had any edges removed.
The first line contains integer *n* (2<=≀<=*n*<=≀<=2Β·105) β€” the number of vertices in each tree. The next line contains *n*<=-<=1 positive integers *a*2,<=*a*3,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=*n*;Β *a**i*<=β‰ <=*i*) β€” the description of edges of the first tree. Number *a**i* means that the first tree has an edge connecting vertex *a**i* and vertex *i*. The next line contains *n*<=-<=1 positive integers *b*2,<=*b*3,<=...,<=*b**n* (1<=≀<=*b**i*<=≀<=*n*;Β *b**i*<=β‰ <=*i*) β€” the description of the edges of the second tree. Number *b**i* means that the second tree has an edge connecting vertex *b**i* and vertex *i*. The next line contains integer *idx* (1<=≀<=*idx*<=&lt;<=*n*) β€” the index of the blue edge that was removed on the first stage. Assume that the edges of each tree are numbered with numbers from 1 to *n*<=-<=1 in the order in which they are given in the input.
For each stage of removing edges print its description. Each description must consist of exactly two lines. If this is the stage when blue edges are deleted, then the first line of the description must contain word *Blue*, otherwise β€” word *Red*. In the second line print the indexes of the edges that will be deleted on this stage in the increasing order.
[ "5\n1 1 1 1\n4 2 1 1\n3\n" ]
[ "Blue\n3\nRed\n1 3\nBlue\n1 2\nRed\n2\n" ]
For simplicity let's assume that all edges of the root tree received some direction, so that all vertices are reachable from vertex 1. Then a subtree of vertex *v* is a set of vertices reachable from vertex *v* in the resulting directed graph (vertex *v* is also included in the set).
[]
30
0
0
146,602
237
Build String
[ "flows", "graphs" ]
null
null
You desperately need to build some string *t*. For that you've got *n* more strings *s*1,<=*s*2,<=...,<=*s**n*. To build string *t*, you are allowed to perform exactly |*t*| (|*t*| is the length of string *t*) operations on these strings. Each operation looks like that: 1. choose any non-empty string from strings *s*1,<=*s*2,<=...,<=*s**n*; 1. choose an arbitrary character from the chosen string and write it on a piece of paper; 1. remove the chosen character from the chosen string. Note that after you perform the described operation, the total number of characters in strings *s*1,<=*s*2,<=...,<=*s**n* decreases by 1. We are assumed to build string *t*, if the characters, written on the piece of paper, in the order of performed operations form string *t*. There are other limitations, though. For each string *s**i* you know number *a**i* β€” the maximum number of characters you are allowed to delete from string *s**i*. You also know that each operation that results in deleting a character from string *s**i*, costs *i* rubles. That is, an operation on string *s*1 is the cheapest (it costs 1 ruble), and the operation on string *s**n* is the most expensive one (it costs *n* rubles). Your task is to count the minimum amount of money (in rubles) you will need to build string *t* by the given rules. Consider the cost of building string *t* to be the sum of prices of the operations you use.
The first line of the input contains string *t* β€” the string that you need to build. The second line contains a single integer *n* (1<=≀<=*n*<=≀<=100) β€” the number of strings to which you are allowed to apply the described operation. Each of the next *n* lines contains a string and an integer. The *i*-th line contains space-separated string *s**i* and integer *a**i* (0<=≀<=*a**i*<=≀<=100). Number *a**i* represents the maximum number of characters that can be deleted from string *s**i*. All strings in the input only consist of lowercase English letters. All strings are non-empty. The lengths of all strings do not exceed 100 characters.
Print a single number β€” the minimum money (in rubles) you need in order to build string *t*. If there is no solution, print -1.
[ "bbaze\n3\nbzb 2\naeb 3\nba 10\n", "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5\n", "xyz\n4\naxx 8\nza 1\nefg 4\nt 1\n" ]
[ "8\n", "18\n", "-1\n" ]
Notes to the samples: In the first sample from the first string you should take characters "b" and "z" with price 1 ruble, from the second string characters "a", "e" ΠΈ "b" with price 2 rubles. The price of the string *t* in this case is 2Β·1 + 3Β·2 = 8. In the second sample from the first string you should take two characters "a" with price 1 ruble, from the second string character "c" with price 2 rubles, from the third string two characters "a" with price 3 rubles, from the fourth string two characters "b" with price 4 rubles. The price of the string *t* in this case is 2Β·1 + 1Β·2 + 2Β·3 + 2Β·4 = 18. In the third sample the solution doesn't exist because there is no character "y" in given strings.
[ { "input": "bbaze\n3\nbzb 2\naeb 3\nba 10", "output": "8" }, { "input": "abacaba\n4\naba 2\nbcc 1\ncaa 2\nbbb 5", "output": "18" }, { "input": "xyz\n4\naxx 8\nza 1\nefg 4\nt 1", "output": "-1" }, { "input": "aaabbtttefg\n6\nabbbca 3\nffatgg 2\nyioa 4\nppaeg 2\naetgffff 4\ntre...
466
26,931,200
3
146,708
0
none
[ "none" ]
null
null
This is an interactive problem. Bob lives in a square grid of size $n \times n$, with rows numbered $1$ through $n$ from top to bottom, and columns numbered $1$ through $n$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $n$. Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed. You can ask at most $4 \cdot n$ queries of form "? $r_1$ $c_1$ $r_2$ $c_2$" ($1 \le r_1 \le r_2 \le n$, $1 \le c_1 \le c_2 \le n$). The answer will be "YES" if Bob can get from a cell $(r_1, c_1)$ to a cell $(r_2, c_2)$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $n - 1$, i.e. the following condition must be satisfied: $(r_2 - r_1) + (c_2 - c_1) \ge n - 1$. It's guaranteed that Bob can get from the top-left corner $(1, 1)$ to the bottom-right corner $(n, n)$ and your task is to find a way to do it. You should print the answer in form "! S" where $S$ is a string of length $2 \cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $1$, the right move increases the second coordinate by $1$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.
The only line of the input contains an integer $n$ ($2 \le n \le 500$) β€” the size of the grid.
When you are ready to print the answer, print a single line containing "! S" where where $S$ is a string of length $2 \cdot n - 2$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $(1, 1)$ to the cell $(n, n)$ passing only through allowed cells.
[ "4\nΒ \nYES\nΒ \nNO\nΒ \nYES\nΒ \nYES\nΒ \n" ]
[ "? 1 1 4 4\nΒ \n? 1 2 4 3\nΒ \n? 4 1 4 4\nΒ \n? 1 4 4 4\nΒ \n! RDRRDD\n" ]
The first example is shown on the picture below. To hack, use the following input format: The first line should contain a single integer $n$ ($2 \le n \le 500$)Β β€” the size of the grid. Each of the next $n$ lines should contain a string of $n$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell. For example, the following text encodes the example shown above:
[ { "input": "5\n.....\n.###.\n.###.\n.###.\n...#.", "output": "used 8 queries\nRRRRDDDD" }, { "input": "7\n.......\n.......\n.......\n.......\n......#\n.......\n....#..", "output": "used 12 queries\nRRRRRDDDDDRD" }, { "input": "2\n..\n..", "output": "used 2 queries\nRD" }, { "...
171
307,200
3
147,695
0
none
[ "none" ]
null
null
You are given a sequence of positive integers *x*1,<=*x*2,<=...,<=*x**n* and two non-negative integers *a* and *b*. Your task is to transform *a* into *b*. To do that, you can perform the following moves: - subtract 1 from the current *a*; - subtract *a* mod *x**i* (1<=≀<=*i*<=≀<=*n*) from the current *a*. Operation *a* mod *x**i* means taking the remainder after division of number *a* by number *x**i*. Now you want to know the minimum number of moves needed to transform *a* into *b*.
The first line contains a single integer *n* (1<=≀<=<=*n*<=≀<=105). The second line contains *n* space-separated integers *x*1,<=*x*2,<=...,<=*x**n* (2<=≀<=<=*x**i*<=≀<=109). The third line contains two integers *a* and *b* (0<=<=≀<=*b*<=≀<=<=*a*<=≀<=109, *a*<=-<=*b*<=≀<=106).
Print a single integer β€” the required minimum number of moves needed to transform number *a* into number *b*.
[ "3\n3 4 5\n30 17\n", "3\n5 6 7\n1000 200\n" ]
[ "6\n", "206\n" ]
none
[]
1,000
65,945,600
0
147,919
245
Suggested Friends
[ "brute force", "graphs" ]
null
null
Polycarpus works as a programmer in a start-up social network. His boss gave his a task to develop a mechanism for determining suggested friends. Polycarpus thought much about the task and came to the folowing conclusion. Let's say that all friendship relationships in a social network are given as *m* username pairs *a**i*,<=*b**i* (*a**i*<=β‰ <=*b**i*). Each pair *a**i*,<=*b**i* means that users *a**i* and *b**i* are friends. Friendship is symmetric, that is, if *a**i* is friends with *b**i*, then *b**i* is also friends with *a**i*. User *y* is a suggested friend for user *x*, if the following conditions are met: 1. *x*<=β‰ <=*y*; 1. *x* and *y* aren't friends; 1. among all network users who meet the first two conditions, user *y* has most of all common friends with user *x*. User *z* is a common friend of user *x* and user *y* (*z*<=β‰ <=*x*,<=*z*<=β‰ <=*y*), if *x* and *z* are friends, and *y* and *z* are also friends. Your task is to help Polycarpus to implement a mechanism for determining suggested friends.
The first line contains a single integer *m* (1<=≀<=*m*<=≀<=5000) β€” the number of pairs of friends in the social network. Next *m* lines contain pairs of names of the users who are friends with each other. The *i*-th line contains two space-separated names *a**i* and *b**i* (*a**i*<=β‰ <=*b**i*). The users' names are non-empty and consist of at most 20 uppercase and lowercase English letters. It is guaranteed that each pair of friends occurs only once in the input. For example, the input can't contain *x*, *y* and *y*, *x* at the same time. It is guaranteed that distinct users have distinct names. It is guaranteed that each social network user has at least one friend. The last thing guarantees that each username occurs at least once in the input.
In the first line print a single integer *n* β€” the number of network users. In next *n* lines print the number of suggested friends for each user. In the *i*-th line print the name of the user *c**i* and the number of his suggested friends *d**i* after a space. You can print information about the users in any order.
[ "5\nMike Gerald\nKate Mike\nKate Tank\nGerald Tank\nGerald David\n", "4\nvalera vanya\nvalera edik\npasha valera\nigor valera\n" ]
[ "5\nMike 1\nGerald 1\nKate 1\nTank 1\nDavid 2\n", "5\nvalera 0\nvanya 3\nedik 3\npasha 3\nigor 3\n" ]
In the first test case consider user David. Users Mike and Tank have one common friend (Gerald) with David. User Kate has no common friends with David. That's why David's suggested friends are users Mike and Tank.
[]
436
11,059,200
0
148,046
587
Duff in Beach
[ "dp" ]
null
null
While Duff was resting in the beach, she accidentally found a strange array *b*0,<=*b*1,<=...,<=*b**l*<=-<=1 consisting of *l* positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, *a*0,<=...,<=*a**n*<=-<=1 that *b* can be build from *a* with formula: *b**i*<==<=*a**i* *mod* *n* where *a* *mod* *b* denoted the remainder of dividing *a* by *b*. Duff is so curious, she wants to know the number of subsequences of *b* like *b**i*1,<=*b**i*2,<=...,<=*b**i**x* (0<=≀<=*i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**x*<=&lt;<=*l*), such that: - 1<=≀<=*x*<=≀<=*k* - For each 1<=≀<=*j*<=≀<=*x*<=-<=1, - For each 1<=≀<=*j*<=≀<=*x*<=-<=1, *b**i**j*<=≀<=*b**i**j*<=+<=1. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109<=+<=7. Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.
The first line of input contains three integers, *n*,<=*l* and *k* (1<=≀<=*n*,<=*k*, *n*<=Γ—<=*k*<=≀<=106 and 1<=≀<=*l*<=≀<=1018). The second line contains *n* space separated integers, *a*0,<=*a*1,<=...,<=*a**n*<=-<=1 (1<=≀<=*a**i*<=≀<=109 for each 0<=≀<=*i*<=≀<=*n*<=-<=1).
Print the answer modulo 1<=000<=000<=007 in one line.
[ "3 5 3\n5 9 1\n", "5 10 3\n1 2 3 4 5\n" ]
[ "10\n", "25\n" ]
In the first sample case, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/d9d8fe92937aeef2bcddb9d213e5587f0f950087.png" style="max-width: 100.0%;max-height: 100.0%;"/>. So all such sequences are: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/54d7dd513b50dae3415992b37dcf6f8ff2f24a73.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fcd7414fd5b0b1459adc9dafca95e6d5a23b0d7d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f6d2e0d0317c10a3c5213068fb1d1e1f53ff26eb.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8f6627cad3dd113f47d84a1226f30fe423939757.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c6db71d99107f752b5caa1ba7e44af1d2302e5db.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a06ffb7bf9126fd634a790703c0bbfda00c60aa1.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/b086d545b6c80640ea8558920709e3c51ba3bf43.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/661b7811fccac48a9e96733bc99c3dfec93ad6d7.png" style="max-width: 100.0%;max-height: 100.0%;"/>, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/8756896f0d00888771e69f1a9ccddeee19d4a9ab.png" style="max-width: 100.0%;max-height: 100.0%;"/> and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e771f8119b1b8218c875759aa03e38312514c9a2.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[]
46
0
0
148,297
51
Pentagon
[ "combinatorics", "graphs", "matrices" ]
E. Pentagon
10
256
According to the last order issued by the president of Berland every city of the country must have its own Ministry Defense building (their own Pentagon). A megapolis Berbourg was not an exception. This city has *n* junctions, some pairs of which are connected by two-way roads. Overall there are *m* roads in the city, no more than one between each pair of junctions. At the moment choosing a location place for Pentagon in Berbourg is being discussed. It has been decided that Pentagon should cover the territory of five different junctions which are joined into a cycle by roads. In the order to build Pentagon a special wall will be built along the roads (with high-tension razor, high-voltage wire and other attributes). Thus, the number of possible ways of building Pentagon in the city is equal to the number of different cycles at lengths of 5, composed of junctions and roads. Your task is to prints the number of ways of building Pentagon in Berbourg. Only well-optimized solutions will be accepted. Please, test your code on the maximal testcase.
The first line contains two integers *n* and *m* (1<=≀<=*n*<=≀<=700;0<=≀<=*m*<=≀<=*n*Β·(*n*<=-<=1)<=/<=2), where *n* represents the number of junctions and *m* is the number of roads in the city. Then follow *m* lines containing the road descriptions, one in each line. Every road is set by a number of integers *a**i*,<=*b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*;*a**i*<=β‰ <=*b**i*), where *a**i* and *b**i* represent the numbers of junctions, connected by the road. The junctions are numbered from 1 to *n*. It is not guaranteed that from any junction one can get to any other one moving along the roads.
Print the single number which represents the required number of ways. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).
[ "5 5\n1 2\n2 3\n3 4\n4 5\n5 1\n", "5 10\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4\n3 5\n4 5\n" ]
[ "1\n", "12\n" ]
none
[]
92
0
0
149,038
238
Boring Partition
[ "constructive algorithms" ]
null
null
This problem is the most boring one you've ever seen. Given a sequence of integers *a*1,<=*a*2,<=...,<=*a**n* and a non-negative integer *h*, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the result subsequences. Note, that one of the result subsequences can be empty. Let's define function *f*(*a**i*,<=*a**j*) on pairs of distinct elements (that is *i*<=β‰ <=*j*) in the original sequence. If *a**i* and *a**j* are in the same subsequence in the current partition then *f*(*a**i*,<=*a**j*)<==<=*a**i*<=+<=*a**j* otherwise *f*(*a**i*,<=*a**j*)<==<=*a**i*<=+<=*a**j*<=+<=*h*. Consider all possible values of the function *f* for some partition. We'll call the goodness of this partiotion the difference between the maximum value of function *f* and the minimum value of function *f*. Your task is to find a partition of the given sequence *a* that have the minimal possible goodness among all possible partitions.
The first line of input contains integers *n* and *h* (2<=≀<=*n*<=≀<=105,<=0<=≀<=*h*<=≀<=108). In the second line there is a list of *n* space-separated integers representing *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=108).
The first line of output should contain the required minimum goodness. The second line describes the optimal partition. You should print *n* whitespace-separated integers in the second line. The *i*-th integer is 1 if *a**i* is in the first subsequence otherwise it should be 2. If there are several possible correct answers you are allowed to print any of them.
[ "3 2\n1 2 3\n", "5 10\n0 1 0 2 1\n" ]
[ "1\n1 2 2 \n", "3\n2 2 2 2 2 \n" ]
In the first sample the values of *f* are as follows: *f*(1, 2) = 1 + 2 + 2 = 5, *f*(1, 3) = 1 + 3 + 2 = 6 and *f*(2, 3) = 2 + 3 = 5. So the difference between maximum and minimum values of *f* is 1. In the second sample the value of *h* is large, so it's better for one of the sub-sequences to be empty.
[ { "input": "3 2\n1 2 3", "output": "1\n1 2 2 " }, { "input": "5 10\n0 1 0 2 1", "output": "3\n2 2 2 2 2 " }, { "input": "9 0\n11 22 33 44 55 66 77 88 99", "output": "154\n2 2 2 2 2 2 2 2 2 " }, { "input": "10 100\n2705446 2705444 2705446 2705445 2705448 2705447 2705444 270544...
124
102,400
-1
149,304
58
Calendar
[ "greedy", "strings" ]
D. Calendar
2
256
BerOilGasDiamondBank has branches in *n* cities, at that *n* is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly *n*<=/<=2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol *d* is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the *n*<=/<=2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line. Help BerOilGasDiamondBank and construct the required calendar.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=104, *n* is even) which is the number of branches. Then follow *n* lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol *d* (*d* has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.
Print *n*<=/<=2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "&lt;" operator in the modern programming languages.
[ "4\nb\naa\nhg\nc\n.\n", "2\naa\na\n!\n", "2\naa\na\n|\n" ]
[ "aa.b\nc.hg\n", "a!aa\n", "aa|a\n" ]
none
[ { "input": "4\nb\naa\nhg\nc\n.", "output": "aa.b\nc.hg" }, { "input": "2\naa\na\n!", "output": "a!aa" }, { "input": "2\naa\na\n|", "output": "aa|a" }, { "input": "4\nqhcivbxotj\nirgxzzxvw\npxdmcyszvk\nyyaevcdal\n~", "output": "irgxzzxvw~pxdmcyszvk\nqhcivbxotj~yyaevcdal" ...
2,000
307,200
0
149,796
93
Flags
[ "dp", "math", "matrices" ]
D. Flags
2
256
When Igor K. was a freshman, his professor strictly urged him, as well as all other freshmen, to solve programming Olympiads. One day a problem called "Flags" from a website called Timmy's Online Judge caught his attention. In the problem one had to find the number of three-colored flags that would satisfy the condition... actually, it doesn't matter. Igor K. quickly found the formula and got the so passionately desired Accepted. However, the professor wasn't very much impressed. He decided that the problem represented on Timmy's Online Judge was very dull and simple: it only had three possible colors of flag stripes and only two limitations. He suggested a complicated task to Igor K. and the fellow failed to solve it. Of course, we won't tell anybody that the professor couldn't solve it as well. And how about you? Can you solve the problem? The flags consist of one or several parallel stripes of similar width. The stripes can be one of the following colors: white, black, red or yellow. You should find the number of different flags with the number of stripes from *L* to *R*, if: - a flag cannot have adjacent stripes of one color; - a flag cannot have adjacent white and yellow stripes; - a flag cannot have adjacent red and black stripes; - a flag cannot have the combination of black, white and red stripes following one after another in this or reverse order; - symmetrical flags (as, for example, a WB and a BW flag, where W and B stand for the white and black colors) are considered the same.
The only line contains two integers *L* and *R* (1<=≀<=*L*<=≀<=*R*<=≀<=109). They are the lower and upper borders of the number of stripes on the flag.
Print a single number β€” the number of different flags that would satisfy the condition of the problem and would have from *L* to *R* stripes, modulo 1000000007.
[ "3 4\n", "5 6\n" ]
[ "23", "64" ]
In the first test the following flags exist (they are listed in the lexicographical order, the letters B, R, W, Y stand for Black, Red, White and Yellow correspondingly): 3 stripes: BWB, BYB, BYR, RWR, RYR, WBW, WBY, WRW, WRY, YBY, YRY (overall 11 flags). 4 stripes: BWBW, BWBY, BYBW, BYBY, BYRW, BYRY, RWRW, RWRY, RYBW, RYBY, RYRW, RYRY (12 flags). That's why the answer to test 1 is equal to 11 + 12 = 23.
[ { "input": "3 4", "output": "23" }, { "input": "5 6", "output": "64" }, { "input": "3 3", "output": "11" }, { "input": "3 5", "output": "51" }, { "input": "3 6", "output": "87" }, { "input": "3 7", "output": "162" }, { "input": "3 8", "...
62
0
0
152,739
477
Dreamoon and Notepad
[ "data structures" ]
null
null
Dreamoon has just created a document of hard problems using notepad.exe. The document consists of *n* lines of text, *a**i* denotes the length of the *i*-th line. He now wants to know what is the fastest way to move the cursor around because the document is really long. Let (*r*,<=*c*) be a current cursor position, where *r* is row number and *c* is position of cursor in the row. We have 1<=≀<=*r*<=≀<=*n* and 0<=≀<=*c*<=≀<=*a**r*. We can use following six operations in notepad.exe to move our cursor assuming the current cursor position is at (*r*,<=*c*): 1. up key: the new cursor position (*nr*,<=*nc*)<==<=(*max*(*r*<=-<=1,<=1),<=*min*(*a**nr*,<=*c*)) 1. down key: the new cursor position (*nr*,<=*nc*)<==<=(*min*(*r*<=+<=1,<=*n*),<=*min*(*a**nr*,<=*c*)) 1. left key: the new cursor position (*nr*,<=*nc*)<==<=(*r*,<=*max*(0,<=*c*<=-<=1)) 1. right key: the new cursor position (*nr*,<=*nc*)<==<=(*r*,<=*min*(*a**nr*,<=*c*<=+<=1)) 1. HOME key: the new cursor position (*nr*,<=*nc*)<==<=(*r*,<=0) 1. END key: the new cursor position (*nr*,<=*nc*)<==<=(*r*,<=*a**r*) You're given the document description (*n* and sequence *a**i*) and *q* queries from Dreamoon. Each query asks what minimal number of key presses is needed to move the cursor from (*r*1,<=*c*1) to (*r*2,<=*c*2).
The first line contains an integer *n*(1<=≀<=*n*<=≀<=400,<=000) β€” the number of lines of text. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n*(1<=≀<=*a**i*<=≀<=108). The third line contains an integer *q*(1<=≀<=*q*<=≀<=400,<=000). Each of the next *q* lines contains four integers *r*1,<=*c*1,<=*r*2,<=*c*2 representing a query (1<=≀<=*r*1,<=*r*2<=≀<=*n*,<=0<=≀<=*c*1<=≀<=*a**r*1,<=0<=≀<=*c*2<=≀<=*a**r*2).
For each query print the result of the query.
[ "9\n1 3 5 3 1 3 5 3 1\n4\n3 5 3 1\n3 3 7 3\n1 0 3 3\n6 0 7 3\n", "2\n10 5\n1\n1 0 1 5\n" ]
[ "2\n5\n3\n2\n", "3\n" ]
In the first sample, the first query can be solved with keys: HOME, right. The second query can be solved with keys: down, down, down, END, down. The third query can be solved with keys: down, END, down. The fourth query can be solved with keys: END, down.
[]
31
0
0
152,937
878
Magic Breeding
[ "bitmasks" ]
null
null
Nikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have *k* creatures numbered from 1 to *k*. Creatures have *n* different characteristics. Sasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to the maximum of the corresponding characteristics of used creatures. Nikita has a similar spell, but in his spell, each characteristic of the new creature is equal to the minimum of the corresponding characteristics of used creatures. A new creature gets the smallest unused number. They use their spells and are interested in some characteristics of their new creatures. Help them find out these characteristics.
The first line contains integers *n*, *k* and *q* (1<=≀<=*n*<=≀<=105, 1<=≀<=*k*<=≀<=12, 1<=≀<=*q*<=≀<=105) β€” number of characteristics, creatures and queries. Next *k* lines describe original creatures. The line *i* contains *n* numbers *a**i*1,<=*a**i*2,<=...,<=*a**in* (1<=≀<=*a**ij*<=≀<=109)Β β€” characteristics of the *i*-th creature. Each of the next *q* lines contains a query. The *i*-th of these lines contains numbers *t**i*, *x**i* and *y**i* (1<=≀<=*t**i*<=≀<=3). They denote a query: - *t**i*<==<=1 means that Sasha used his spell to the creatures *x**i* and *y**i*. - *t**i*<==<=2 means that Nikita used his spell to the creatures *x**i* and *y**i*. - *t**i*<==<=3 means that they want to know the *y**i*-th characteristic of the *x**i*-th creature. In this case 1<=≀<=*y**i*<=≀<=*n*. It's guaranteed that all creatures' numbers are valid, that means that they are created before any of the queries involving them.
For each query with *t**i*<==<=3 output the corresponding characteristic.
[ "2 2 4\n1 2\n2 1\n1 1 2\n2 1 2\n3 3 1\n3 4 2\n", "5 3 8\n1 2 3 4 5\n5 1 2 3 4\n4 5 1 2 3\n1 1 2\n1 2 3\n2 4 5\n3 6 1\n3 6 2\n3 6 3\n3 6 4\n3 6 5\n" ]
[ "2\n1\n", "5\n2\n2\n3\n4\n" ]
In the first sample, Sasha makes a creature with number 3 and characteristics (2, 2). Nikita makes a creature with number 4 and characteristics (1, 1). After that they find out the first characteristic for the creature 3 and the second characteristic for the creature 4.
[]
46
0
0
153,242
739
Recover a functional graph
[ "graph matchings" ]
null
null
Functional graph is a directed graph in which all vertices have outdegree equal to 1. Loops are allowed. Some vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem). Let's compute two values for each vertex. *precycle**i* is the amount of edges we should pass to get to a vertex which is a part of some cycle (zero, if *i* itself lies on a cycle), *cycle**i* is the length of the cycle we get to. You are given the information about these values for some functional graph. For each vertex you know the values *precycle**i* and *cycle**i*, however, instead of some values there can be the question mark. It means that these values are unknown. Build any functional graph that suits the description or determine that there is no such graph.
The first line contains single integer *n* (1<=≀<=*n*<=≀<=300)Β β€” the number of vertices in the graph. Each of the next *n* lines contain two integersΒ β€” *precycle**i* (0<=≀<=*precycle**i*<=≀<=*n*<=-<=1) and *cycle**i* (1<=≀<=*cycle**i*<=≀<=*n*). There could be question marks instead of some of these values.
In case there is no solution, print -1. Otherwise, print *n* integers. *i*-th of them is the number of vertex to which the edge form the *i*-th vertex go. The vertices should be in the same order as they go in input data. If there are multiple solutions, print any of them.
[ "3\n0 3\n0 3\n? ?\n", "5\n3 2\n? ?\n? ?\n? ?\n? ?\n", "8\n? 3\n? ?\n0 2\n0 2\n0 3\n0 3\n0 3\n3 3\n", "1\n? ?\n", "6\n0 3\n0 3\n0 3\n0 3\n0 3\n0 3\n", "2\n1 1\n1 1\n" ]
[ "2 3 1 \n", "5 3 2 2 4 \n", "5 1 4 3 6 7 5 2 \n", "1 \n", "2 3 1 5 6 4 \n", "-1\n" ]
none
[]
46
0
0
153,278
193
Two Segments
[ "data structures" ]
null
null
Nick has some permutation consisting of *p* integers from 1 to *n*. A segment [*l*,<=*r*] (*l*<=≀<=*r*) is a set of elements *p**i* satisfying *l*<=≀<=*i*<=≀<=*r*. Nick calls a pair of segments [*a*0,<=*a*1] and [*b*0,<=*b*1] (1<=≀<=*a*0<=≀<=*a*1<=&lt;<=*b*0<=≀<=*b*1<=≀<=*n*) good if all their (*a*1<=-<=*a*0<=+<=*b*1<=-<=*b*0<=+<=2) elements, when sorted in ascending order, form an arithmetic progression with a difference of 1. That is, when they sorted in ascending order, the elements are in the form {*x*,<=*x*<=+<=1,<=*x*<=+<=2,<=...,<=*x*<=+<=*m*<=-<=1}, for some *x* and *m*. Your task is to find the number of distinct pairs of good segments in the given permutation. Two pairs of segments are considered distinct if the sets of elements contained in these pairs of segments are distinct. For example, any segment [*l*,<=*r*] (*l*<=&lt;<=*r*) can be represented as a pair of segments, as [*l*,<=*i*] and [*i*<=+<=1,<=*r*] (*l*<=≀<=*i*<=≀<=*r*). As all these pairs consist of the same set of elements, they are considered identical. See the notes accompanying the sample tests for clarification.
The first line contains integer *n* (1<=≀<=*n*<=≀<=3Β·105) β€” the permutation size. The second line contains *n* space-separated distinct integers *p**i*, (1<=≀<=*p**i*<=≀<=*n*).
Print a single integer β€” the number of good pairs of segments of permutation *p*. 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", "5\n1 4 5 3 2\n", "5\n5 4 3 1 2\n" ]
[ "3\n", "10\n", "10\n" ]
In the first sample the following pairs of segments are good: ([1, 1], [2, 2]); ([2, 2], [3, 3]); ([1, 2], [3, 3]). Pair of segments ([1, 1], [2, 3]) is by definition equivalent to pair ([1, 2], [3, 3]), since both of them covers the same set of elements, namely {1, 2, 3}. In the third sample the following pairs of segments are good: ([4, 4], [5, 5]); ([3, 3],[4, 5]); ([2, 2],[3, 5]); ([1, 1],[2, 5]); ([3, 3],[5, 5]); ([2, 3],[5, 5]); ([1, 3],[5, 5]); ([2, 2],[3, 3]); ([1, 1],[2, 3]); ([1, 1],[2, 2]).
[]
124
0
0
153,562
568
Sign Posts
[ "brute force", "geometry", "math" ]
null
null
One Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities. The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he has only *k* signs. Help the minister to solve his problem, otherwise the poor guy can lose not only his position, but also his head. More formally, every road in the Khanate is a line on the *Oxy* plane, given by an equation of the form *Ax*<=+<=*By*<=+<=*C*<==<=0 (*A* and *B* are not equal to 0 at the same time). You are required to determine whether you can put signs in at most *k* points so that each road had at least one sign installed.
The input starts with two positive integers *n*, *k* (1<=≀<=*n*<=≀<=105,<=1<=≀<=*k*<=≀<=5) Next *n* lines contain three integers each, *A**i*,<=*B**i*,<=*C**i*, the coefficients of the equation that determines the road (|*A**i*|,<=|*B**i*|,<=|*C**i*|<=≀<=105, *A**i*2<=+<=*B**i*2<=β‰ <=0). It is guaranteed that no two roads coincide.
If there is no solution, print "NO" in the single line (without the quotes). Otherwise, print in the first line "YES" (without the quotes). In the second line print a single number *m* (*m*<=≀<=*k*) β€” the number of used signs. In the next *m* lines print the descriptions of their locations. Description of a location of one sign is two integers *v*,<=*u*. If *u* and *v* are two distinct integers between 1 and *n*, we assume that sign is at the point of intersection of roads number *v* and *u*. If *u*<==<=<=-<=1, and *v* is an integer between 1 and *n*, then the sign is on the road number *v* in the point not lying on any other road. In any other case the description of a sign will be assumed invalid and your answer will be considered incorrect. In case if *v*<==<=*u*, or if *v* and *u* are the numbers of two non-intersecting roads, your answer will also be considered incorrect. The roads are numbered starting from 1 in the order in which they follow in the input.
[ "3 1\n1 0 0\n0 -1 0\n7 -93 0\n", "3 1\n1 0 0\n0 1 0\n1 1 3\n", "2 3\n3 4 5\n5 6 7\n" ]
[ "YES\n1\n1 2\n", "NO\n", "YES\n2\n1 -1\n2 -1\n" ]
Note that you do not have to minimize *m*, but it shouldn't be more than *k*. In the first test all three roads intersect at point (0,0). In the second test all three roads form a triangle and there is no way to place one sign so that it would stand on all three roads at once.
[]
30
0
0
153,904
86
Long sequence
[ "brute force", "math", "matrices" ]
E. Long sequence
2
256
A sequence *a*0,<=*a*1,<=... is called a recurrent binary sequence, if each term *a**i* (*i*<==<=0,<=1,<=...) is equal to 0 or 1 and there exist coefficients such that Note that such a sequence can be uniquely recovered from any *k*-tuple {*a**s*,<=*a**s*<=+<=1,<=...,<=*a**s*<=+<=*k*<=-<=1} and so it is periodic. Moreover, if a *k*-tuple contains only zeros, then the sequence contains only zeros, so this case is not very interesting. Otherwise the minimal period of the sequence is not greater than 2*k*<=-<=1, as *k*-tuple determines next element, and there are 2*k*<=-<=1 non-zero *k*-tuples. Let us call a sequence long if its minimal period is exactly 2*k*<=-<=1. Your task is to find a long sequence for a given *k*, if there is any.
Input contains a single integer *k* (2<=≀<=*k*<=≀<=50).
If there is no long sequence for a given *k*, output "-1" (without quotes). Otherwise the first line of the output should contain *k* integer numbers: *c*1,<=*c*2,<=...,<=*c**k* (coefficients). The second line should contain first *k* elements of the sequence: *a*0,<=*a*1,<=...,<=*a**k*<=-<=1. All of them (elements and coefficients) should be equal to 0 or 1, and at least one *c**i* has to be equal to 1. If there are several solutions, output any.
[ "2\n", "3\n" ]
[ "1 1\n1 0\n", "0 1 1\n1 1 1\n" ]
1. In the first sample: *c*<sub class="lower-index">1</sub> = 1, *c*<sub class="lower-index">2</sub> = 1, so *a*<sub class="lower-index">*n*</sub> = *a*<sub class="lower-index">*n* - 1</sub> + *a*<sub class="lower-index">*n* - 2</sub> (*mod* 2). Thus the sequence will be: so its period equals 3 = 2<sup class="upper-index">2</sup> - 1. 2. In the second sample: *c*<sub class="lower-index">1</sub> = 0, *c*<sub class="lower-index">2</sub> = 1, *c*<sub class="lower-index">3</sub> = 1, so *a*<sub class="lower-index">*n*</sub> = *a*<sub class="lower-index">*n* - 2</sub> + *a*<sub class="lower-index">*n* - 3</sub> (*mod* 2). Thus our sequence is: and its period equals 7 = 2<sup class="upper-index">3</sup> - 1. Periods are colored.
[]
92
0
0
154,193
367
Sereja and Intervals
[ "combinatorics", "dp" ]
null
null
Sereja is interested in intervals of numbers, so he has prepared a problem about intervals for you. An interval of numbers is a pair of integers [*l*,<=*r*] (1<=≀<=*l*<=≀<=*r*<=≀<=*m*). Interval [*l*1,<=*r*1] belongs to interval [*l*2,<=*r*2] if the following condition is met: *l*2<=≀<=*l*1<=≀<=*r*1<=≀<=*r*2. Sereja wants to write out a sequence of *n* intervals [*l*1,<=*r*1], [*l*2,<=*r*2], ..., [*l**n*,<=*r**n*] on a piece of paper. At that, no interval in the sequence can belong to some other interval of the sequence. Also, Sereja loves number *x* very much and he wants some (at least one) interval in the sequence to have *l**i*<==<=*x*. Sereja wonders, how many distinct ways to write such intervals are there? Help Sereja and find the required number of ways modulo 1000000007 (109<=+<=7). Two ways are considered distinct if there is such *j* (1<=≀<=*j*<=≀<=*n*), that the *j*-th intervals in two corresponding sequences are not equal.
The first line contains integers *n*, *m*, *x* (1<=≀<=*n*Β·*m*<=≀<=100000,<=1<=≀<=*x*<=≀<=*m*) β€” the number of segments in the sequence, the constraints on the numbers in segments and Sereja's favourite number.
In a single line print the answer modulo 1000000007 (109<=+<=7).
[ "1 1 1\n", "3 5 1\n", "2 3 3\n" ]
[ "1\n", "240\n", "6\n" ]
In third example next sequences will be correct: {[1, 1], [3, 3]}, {[1, 2], [3, 3]}, {[2, 2], [3, 3]}, {[3, 3], [1, 1]}, {[3, 3], [2, 2]}, {[3, 3], [1, 2]}.
[ { "input": "1 1 1", "output": "1" }, { "input": "3 5 1", "output": "240" }, { "input": "2 3 3", "output": "6" }, { "input": "11 79 54", "output": "311673892" }, { "input": "18 46 26", "output": "592264671" }, { "input": "8 96 61", "output": "725548...
327
4,300,800
3
154,493
850
Tournament Construction
[ "constructive algorithms", "dp", "graphs", "greedy", "math" ]
null
null
Ivan is reading a book about tournaments. He knows that a tournament is an oriented graph with exactly one oriented edge between each pair of vertices. The score of a vertex is the number of edges going outside this vertex. Yesterday Ivan learned Landau's criterion: there is tournament with scores *d*1<=≀<=*d*2<=≀<=...<=≀<=*d**n* if and only if for all 1<=≀<=*k*<=&lt;<=*n* and . Now, Ivan wanna solve following problem: given a set of numbers *S*<==<={*a*1,<=*a*2,<=...,<=*a**m*}, is there a tournament with given set of scores? I.e. is there tournament with sequence of scores *d*1,<=*d*2,<=...,<=*d**n* such that if we remove duplicates in scores, we obtain the required set {*a*1,<=*a*2,<=...,<=*a**m*}? Find a tournament with minimum possible number of vertices.
The first line contains a single integer *m* (1<=≀<=*m*<=≀<=31). The next line contains *m* distinct integers *a*1,<=*a*2,<=...,<=*a**m* (0<=≀<=*a**i*<=≀<=30)Β β€” elements of the set *S*. It is guaranteed that all elements of the set are distinct.
If there are no such tournaments, print string "=(" (without quotes). Otherwise, print an integer *n*Β β€” the number of vertices in the tournament. Then print *n* lines with *n* charactersΒ β€” matrix of the tournament. The *j*-th element in the *i*-th row should be 1 if the edge between the *i*-th and the *j*-th vertices is oriented towards the *j*-th vertex, and 0 otherwise. The main diagonal should contain only zeros.
[ "2\n1 2\n", "2\n0 3\n" ]
[ "4\n0011\n1001\n0100\n0010\n", "6\n000111\n100011\n110001\n011001\n001101\n000000\n" ]
none
[]
46
0
0
154,776
610
Alphabet Permutations
[ "data structures", "strings" ]
null
null
You are given a string *s* of length *n*, consisting of first *k* lowercase English letters. We define a *c*-repeat of some string *q* as a string, consisting of *c* copies of the string *q*. For example, string "acbacbacbacb" is a 4-repeat of the string "acb". Let's say that string *a* contains string *b* as a subsequence, if string *b* can be obtained from *a* by erasing some symbols. Let *p* be a string that represents some permutation of the first *k* lowercase English letters. We define function *d*(*p*) as the smallest integer such that a *d*(*p*)-repeat of the string *p* contains string *s* as a subsequence. There are *m* operations of one of two types that can be applied to string *s*: 1. Replace all characters at positions from *l**i* to *r**i* by a character *c**i*. 1. For the given *p*, that is a permutation of first *k* lowercase English letters, find the value of function *d*(*p*). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function *d*(*p*) for all operations of the second type.
The first line contains three positive integers *n*, *m* and *k* (1<=≀<=*n*<=≀<=200<=000,<=1<=≀<=*m*<=≀<=20000,<=1<=≀<=*k*<=≀<=10)Β β€” the length of the string *s*, the number of operations and the size of the alphabet respectively. The second line contains the string *s* itself. Each of the following lines *m* contains a description of some operation: 1. Operation of the first type starts with 1 followed by a triple *l**i*, *r**i* and *c**i*, that denotes replacement of all characters at positions from *l**i* to *r**i* by character *c**i* (1<=≀<=*l**i*<=≀<=*r**i*<=≀<=*n*, *c**i* is one of the first *k* lowercase English letters). 1. Operation of the second type starts with 2 followed by a permutation of the first *k* lowercase English letters.
For each query of the second type the value of function *d*(*p*).
[ "7 4 3\nabacaba\n1 3 5 b\n2 abc\n1 4 4 c\n2 cba\n" ]
[ "6\n5\n" ]
After the first operation the string *s* will be abbbbba. In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc. After the third operation the string *s* will be abbcbba. In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA. Uppercase letters means the occurrences of symbols from the string *s*.
[ { "input": "7 4 3\nabacaba\n1 3 5 b\n2 abc\n1 4 4 c\n2 cba", "output": "6\n5" }, { "input": "5 5 3\ncbcab\n1 2 4 b\n2 cab\n2 bca\n1 2 3 a\n1 2 2 c", "output": "4\n5" }, { "input": "10 10 3\ncababcacaa\n1 3 3 b\n2 acb\n2 abc\n1 8 10 c\n1 7 9 c\n1 4 7 b\n2 cba\n1 5 6 a\n1 9 9 c\n2 acb", ...
46
0
0
155,112
26
Parquet
[ "combinatorics", "constructive algorithms", "greedy", "implementation" ]
C. Parquet
2
256
Once Bob decided to lay a parquet floor in his living room. The living room is of size *n*<=Γ—<=*m* metres. Bob had planks of three types: *a* planks 1<=Γ—<=2 meters, *b* planks 2<=Γ—<=1 meters, and *c* planks 2<=Γ—<=2 meters. Help Bob find out, if it is possible to parquet the living room with such a set of planks, and if it is possible, find one of the possible ways to do so. Bob doesn't have to use all the planks.
The first input line contains 5 space-separated integer numbers *n*, *m*, *a*, *b*, *c* (1<=≀<=*n*,<=*m*<=≀<=100,<=0<=≀<=*a*,<=*b*,<=*c*<=≀<=104), *n* and *m* β€” the living room dimensions, *a*, *b* and *c* β€” amount of planks 1<=Γ—<=2, 2<=Γ—<=1 ΠΈ 2<=Γ—<=2 respectively. It's not allowed to turn the planks.
If it is not possible to parquet the room with such a set of planks, output IMPOSSIBLE. Otherwise output one of the possible ways to parquet the room β€” output *n* lines with *m* lower-case Latin letters each. Two squares with common sides should contain the same letters, if they belong to one and the same plank, and different letters otherwise. Different planks can be marked with one and the same letter (see examples). If the answer is not unique, output any.
[ "2 6 2 2 1\n", "1 1 100 100 100\n", "4 4 10 10 10\n" ]
[ "aabcca\naabdda\n", "IMPOSSIBLE\n", "aabb\naabb\nbbaa\nbbaa\n" ]
none
[ { "input": "2 6 2 2 1", "output": "aaccab\naaddab" }, { "input": "1 1 100 100 100", "output": "IMPOSSIBLE" }, { "input": "4 4 10 10 10", "output": "aacc\naacc\nccaa\nccaa" }, { "input": "2 2 0 0 1", "output": "aa\naa" }, { "input": "2 3 2 1 0", "output": "aac\...
156
0
0
155,259
134
Swaps
[ "constructive algorithms", "graphs", "greedy" ]
null
null
There are *n* players sitting at a round table. All of them have *s* cards of *n* colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: - as the players swap, a player can give a card of his color only; - a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); - during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all *n* people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps.
The first line contains integers *n* (1<=≀<=*n*<=≀<=200000) and *s* (1<=≀<=*s*<=≀<=200000). The second line contains *n* numbers, the *i*-th number stands for how many cards the *i*-th player has by the moment the game starts. It is possible that a player has no cards initially.
On the first line print "No" if such sequence of swaps is impossible. Otherwise, print "Yes". If the answer is positive, next print number *k* β€” the number of the swaps. Then on *k* lines describe the swaps by pairs of indices of the swapping players. Print the swaps and the numbers of the swaps in any order.
[ "4 8\n2 2 2 2\n", "6 12\n1 1 2 2 3 3\n", "5 5\n0 0 0 0 5\n" ]
[ "Yes\n4\n4 3\n4 2\n1 3\n1 2\n", "Yes\n6\n6 5\n6 4\n6 3\n5 4\n5 3\n2 1\n", "No\n" ]
none
[]
404
2,150,400
-1
155,356
802
Marmots (hard)
[ "math", "probabilities" ]
null
null
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population *P* from their random number before responding to Heidi's request. Also, there are now villages with as few as a single inhabitant, meaning that . Can you help Heidi find out whether a village follows a Poisson or a uniform distribution?
Same as for the easy and medium versions. But remember that now 1<=≀<=*P*<=≀<=1000 and that the marmots may provide positive as well as negative integers.
Output one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answers came from a uniform distribution.
[]
[]
none
[]
46
409,600
3
155,491
427
Police Patrol
[ "greedy", "implementation", "math", "ternary search" ]
null
null
Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the *x*-axis. Currently, there are *n* criminals along the road. No police station has been built on this road yet, so the mayor wants to build one. As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most *m* criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away. Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.
The first line of the input will have two integers *n*Β (1<=≀<=*n*<=≀<=106) and *m*Β (1<=≀<=*m*<=≀<=106) separated by spaces. The next line will contain *n* integers separated by spaces. The *i**th* integer is the position of the *i**th* criminal on the *x*-axis. Absolute value of positions will not exceed 109. If a criminal has position *x*, he/she is located in the point (*x*,<=0) of the plane. The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane. Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.
Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.
[ "3 6\n1 2 3\n", "5 5\n-7 -6 -3 -1 1\n", "1 369\n0\n", "11 2\n-375 -108 1336 1453 1598 1892 2804 3732 4291 4588 4822\n" ]
[ "4\n", "16\n", "0\n", "18716\n" ]
none
[]
31
0
0
155,652
513
Constrained Tree
[ "dfs and similar" ]
null
null
You need to find a binary tree of size *n* that satisfies a given set of *c* constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the *i*-th constraint you are given two labels, *a**i* and *b**i* and a direction, left or right. In case of left direction, *b**i* is an element of the subtree rooted at *a**i*'s left child. Similarly in the case of right direction *b**i* is an element of the subtree rooted at *a**i*'s right child.
The first line of input contains two integers *n* and *c*. The next *c* lines contain 2 integers *a**i*, *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*) and either "LEFT" or "RIGHT" denoting whether *b* is in the subtree rooted at *a**i*'s left child or in the subtree rooted at *a**i*'s right child. The problem consists of multiple 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 D1 (9 points), the constraints 1<=≀<=*n*<=≀<=100, 1<=≀<=*c*<=≀<=50 will hold. - In subproblem D2 (8 points), the constraints 1<=≀<=*n*<=≀<=1000000, 1<=≀<=*c*<=≀<=100000 will hold.
Output will be on a single line. Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as *n* space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices. If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).
[ "3 2\n1 2 LEFT\n1 3 RIGHT\n", "3 2\n1 2 RIGHT\n1 3 LEFT\n" ]
[ "2 1 3\n", "IMPOSSIBLE\n" ]
Consider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3). Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order. For other information regarding in-order and pre-order, see [http://en.wikipedia.org/wiki/Tree_traversal](https://en.wikipedia.org/wiki/Tree_traversal).
[]
46
0
0
156,050
845
Guards In The Storehouse
[ "bitmasks", "dp" ]
null
null
Polycarp owns a shop in the capital of Berland. Recently the criminal activity in the capital increased, so Polycarp is thinking about establishing some better security in the storehouse of his shop. The storehouse can be represented as a matrix with *n* rows and *m* columns. Each element of the matrix is either . (an empty space) or x (a wall). Polycarp wants to hire some guards (possibly zero) to watch for the storehouse. Each guard will be in some cell of matrix and will protect every cell to the right of his own cell and every cell to the bottom of his own cell, until the nearest wall. More formally, if the guard is standing in the cell (*x*0,<=*y*0), then he protects cell (*x*1,<=*y*1) if all these conditions are met: - (*x*1,<=*y*1) is an empty cell; - either *x*0<==<=*x*1 and *y*0<=≀<=*y*1, or *x*0<=≀<=*x*1 and *y*0<==<=*y*1; - there are no walls between cells (*x*0,<=*y*0) and (*x*1,<=*y*1). There can be a guard between these cells, guards can look through each other. Guards can be placed only in empty cells (and can protect only empty cells). The plan of placing the guards is some set of cells where guards will be placed (of course, two plans are different if there exists at least one cell that is included in the first plan, but not included in the second plan, or vice versa). Polycarp calls a plan suitable if there is not more than one empty cell that is not protected. Polycarp wants to know the number of suitable plans. Since it can be very large, you have to output it modulo 109<=+<=7.
The first line contains two numbers *n* and *m* β€” the length and the width of the storehouse (1<=≀<=*n*,<=*m*<=≀<=250, 1<=≀<=*nm*<=≀<=250). Then *n* lines follow, *i*th line contains a string consisting of *m* characters β€” *i*th row of the matrix representing the storehouse. Each character is either . or x.
Output the number of suitable plans modulo 109<=+<=7.
[ "1 3\n.x.\n", "2 2\nxx\nxx\n", "2 2\n..\n..\n", "3 1\nx\n.\nx\n" ]
[ "3\n", "1\n", "10\n", "2\n" ]
In the first example you have to put at least one guard, so there are three possible arrangements: one guard in the cell (1, 1), one guard in the cell (1, 3), and two guards in both these cells.
[ { "input": "1 3\n.x.", "output": "3" }, { "input": "2 2\nxx\nxx", "output": "1" }, { "input": "2 2\n..\n..", "output": "10" }, { "input": "3 1\nx\n.\nx", "output": "2" }, { "input": "100 2\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n..\n.....
92
5,836,800
0
156,109
19
Deletion of Repeats
[ "greedy", "hashing", "string suffix structures" ]
C. Deletion of Repeats
2
256
Once Bob saw a string. It contained so many different letters, that the letters were marked by numbers, but at the same time each letter could be met in the string at most 10 times. Bob didn't like that string, because it contained repeats: a repeat of length *x* is such a substring of length 2*x*, that its first half coincides character by character with its second half. Bob started deleting all the repeats from the string. He does it as follows: while it's possible, Bob takes the shortest repeat, if it is not unique, he takes the leftmost one, and deletes its left half and everything that is to the left of this repeat. You're given the string seen by Bob. Find out, what it will look like after Bob deletes all the repeats in the way described above.
The first input line contains integer *n* (1<=≀<=*n*<=≀<=105) β€” length of the string. The following line contains *n* space-separated integer numbers from 0 to 109 inclusive β€” numbers that stand for the letters of the string. It's guaranteed that each letter can be met in the string at most 10 times.
In the first line output the length of the string's part, left after Bob's deletions. In the second line output all the letters (separated by a space) of the string, left after Bob deleted all the repeats in the described way.
[ "6\n1 2 3 1 2 3\n", "7\n4 5 6 5 6 7 7\n" ]
[ "3\n1 2 3 \n", "1\n7 \n" ]
none
[ { "input": "6\n1 2 3 1 2 3", "output": "3\n1 2 3 " }, { "input": "7\n4 5 6 5 6 7 7", "output": "1\n7 " }, { "input": "10\n5 7 2 1 8 8 5 10 2 5", "output": "5\n8 5 10 2 5 " }, { "input": "10\n0 1 1 1 0 3 0 1 4 0", "output": "7\n1 0 3 0 1 4 0 " }, { "input": "10\n0 ...
92
0
0
156,153
1,009
Allowed Letters
[ "bitmasks", "flows", "graph matchings", "graphs", "greedy" ]
null
null
Polycarp has just launched his new startup idea. The niche is pretty free and the key vector of development sounds really promising, so he easily found himself some investors ready to sponsor the company. However, he is yet to name the startup! Actually, Polycarp has already came up with the name but some improvement to it will never hurt. So now he wants to swap letters at some positions in it to obtain the better name. It isn't necessary for letters to be adjacent. In addition, each of the investors has chosen some index in the name and selected a set of letters that can go there. Indices chosen by different investors are pairwise distinct. If some indices aren't chosen by any investor then any letter can go there. Finally, Polycarp is sure that the smallest lexicographically name is the best. (Like why do you think Google decided to become Alphabet?) More formally, you are given a string consisting of lowercase Latin letters from "a" to "f". You can swap letters at any positions arbitrary number of times (zero swaps is also possible). What is the smallest lexicographically name you can obtain such that the letter at every position is among the allowed letters? If Polycarp can't produce any valid name then print "Impossible".
The first line is the string $s$ ($1 \le |s| \le 10^5$) β€” the name Polycarp has came up with. The string consists only of lowercase Latin letters from "a" to "f". The second line contains a single integer $m$ ($0 \le m \le |s|$) β€” the number of investors. The $i$-th of the next $m$ lines contain an integer number $pos_i$ and a non-empty string of allowed characters for $pos_i$ ($1 \le pos_i \le |s|$). Each string contains pairwise distinct letters from "a" to "f". $pos_1, pos_2, \dots, pos_m$ are pairwise distinct. If any position of the string doesn't appear in the investors demands then any letter can go in this position.
If Polycarp can't produce any valid name then print "Impossible". Otherwise print the smallest lexicographically name Polycarp can obtain by swapping letters in string $s$ such that the letter at every position is among the allowed ones.
[ "bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef\n", "abacaba\n0\n", "fc\n2\n1 cfab\n2 f\n" ]
[ "deadbeef\n", "aaaabbc\n", "cf\n" ]
none
[ { "input": "bedefead\n5\n2 e\n1 dc\n5 b\n7 ef\n6 ef", "output": "deadbeef" }, { "input": "abacaba\n0", "output": "aaaabbc" }, { "input": "fc\n2\n1 cfab\n2 f", "output": "cf" }, { "input": "bbcbbc\n6\n1 c\n2 c\n3 b\n4 ab\n5 ab\n6 ab", "output": "ccbbbb" }, { "input...
2,000
0
0
156,445
138
World of Darkraft
[ "dp", "games" ]
null
null
Recently Roma has become the happy owner of a new game World of Darkraft. This game combines elements of virtually all known genres, and on one of the later stages of the game Roma faced difficulties solving a puzzle. In this part Roma fights with a cunning enemy magician. The battle takes place on a rectangular field plaid *n*<=Γ—<=*m*. Each cell contains one magical character: L, R or X. Initially all the squares of the field are "active". The players, Roma and enemy magician, take turns. Roma makes the first move. During a move a player selects one of the active cells. Then depending on the image in the character in the cell one of the following actions takes place: - L β€” magical waves radiate from the cell to the left downwards and to the right upwards along diagonal paths. All cells on the path of the waves (including the selected cell too) become inactive. The waves continue until the next inactive cell or to the edge of the field if there are no inactive cells on the way. - R β€” the magical waves radiate to the left upwards and to the right downwards. - X β€” the magical waves radiate in all four diagonal directions. If the next player cannot make a move (i.e., all cells are inactive), he loses. Roma has been trying to defeat the computer opponent for three days but he just keeps losing. He asks you to help him and determine whether it is guaranteed that he can beat the opponent, or he will have to hack the game.
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=20). Next *n* lines contain *m* characters describing the playing field: the *j*-th character of the *i*-th line equals to the magical character of the corresponding field square.
On the first line print "WIN" if Roma can win or "LOSE" if it is impossible to win considering that the opponent pays optimally.
[ "2 2\nRL\nLR\n", "2 2\nRR\nRR\n" ]
[ "LOSE\n", "WIN\n" ]
In the first test each move makes one diagonal line of the square inactive, thus it is guaranteed that Roma loses after two moves. There are three variants of making a move in the second test: to "finish off" the main diagonal line or any of the squares that are left. That means that after three moves the game stops and Roma wins.
[]
278
2,867,200
-1
156,902
0
none
[ "none" ]
null
null
You are given *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Denote this list of integers as *T*. Let *f*(*L*) be a function that takes in a non-empty list of integers *L*. The function will output another integer as follows: - First, all integers in *L* are padded with leading zeros so they are all the same length as the maximum length number in *L*. - We will construct a string where the *i*-th character is the minimum of the *i*-th character in padded input numbers. - The output is the number representing the string interpreted in base 10. For example *f*(10,<=9)<==<=0, *f*(123,<=321)<==<=121, *f*(530,<=932,<=81)<==<=30. Define the function In other words, *G*(*x*) is the sum of squares of sum of elements of nonempty subsequences of *T* that evaluate to *x* when plugged into *f* modulo 1<=000<=000<=007, then multiplied by *x*. The last multiplication is not modded. You would like to compute *G*(0),<=*G*(1),<=...,<=*G*(999<=999). To reduce the output size, print the value , where denotes the bitwise XOR operator.
The first line contains the integer *n* (1<=≀<=*n*<=≀<=1<=000<=000)Β β€” the size of list *T*. The next line contains *n* space-separated integers, *a*1,<=*a*2,<=...,<=*a**n* (0<=≀<=*a**i*<=≀<=999<=999)Β β€” the elements of the list.
Output a single integer, the answer to the problem.
[ "3\n123 321 555\n", "1\n999999\n", "10\n1 1 1 1 1 1 1 1 1 1\n" ]
[ "292711924\n", "997992010006992\n", "28160\n" ]
For the first sample, the nonzero values of *G* are *G*(121) = 144 611 577, *G*(123) = 58 401 999, *G*(321) = 279 403 857, *G*(555) = 170 953 875. The bitwise XOR of these numbers is equal to 292 711 924. For example, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/53a1c46c7cd2d3d56e89fe99af6328601758b327.png" style="max-width: 100.0%;max-height: 100.0%;"/>, since the subsequences [123] and [123, 555] evaluate to 123 when plugged into *f*. For the second sample, we have <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/330ab8a9387bb33a82877190f4439f4e9ccd8e92.png" style="max-width: 100.0%;max-height: 100.0%;"/> For the last sample, we have <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/0e0eeb7662af22bf04ea1a2ea669b162d53ad7ba.png" style="max-width: 100.0%;max-height: 100.0%;"/>, where <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4f42013cbab8c31325f2cf28b60aa2ccc1cf89d3.png" style="max-width: 100.0%;max-height: 100.0%;"/> is the binomial coefficient.
[ { "input": "3\n123 321 555", "output": "292711924" }, { "input": "1\n999999", "output": "997992010006992" }, { "input": "10\n1 1 1 1 1 1 1 1 1 1", "output": "28160" }, { "input": "3\n534185 663311 372491", "output": "1081839767962341" }, { "input": "10\n595436 647...
30
0
0
157,068
749
Inversions After Shuffle
[ "data structures", "probabilities" ]
null
null
You are given a permutation of integers from 1 to *n*. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally: 1. Pick a random segment (continuous subsequence) from *l* to *r*. All segments are equiprobable. 1. Let *k*<==<=*r*<=-<=*l*<=+<=1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to *k*, *p*1,<=*p*2,<=...,<=*p**k*. All *k*! permutation are equiprobable. 1. This permutation is applied to elements of the chosen segment, i.e. permutation *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*,<=*a**l*<=+<=1,<=...,<=*a**r*<=-<=1,<=*a**r*,<=*a**r*<=+<=1,<=...,<=*a**n* is transformed to *a*1,<=*a*2,<=...,<=*a**l*<=-<=1,<=*a**l*<=-<=1<=+<=*p*1,<=*a**l*<=-<=1<=+<=*p*2,<=...,<=*a**l*<=-<=1<=+<=*p**k*<=-<=1,<=*a**l*<=-<=1<=+<=*p**k*,<=*a**r*<=+<=1,<=...,<=*a**n*. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (*i*,<=*j*) such that *i*<=&lt;<=*j* and *a**i*<=&gt;<=*a**j*. Find the expected number of inversions after we apply exactly one operation mentioned above.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=100<=000)Β β€” the length of the permutation. The second line contains *n* distinct integers from 1 to *n*Β β€” elements of the permutation.
Print one real valueΒ β€” the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=9. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
[ "3\n2 3 1\n" ]
[ "1.916666666666666666666666666667\n" ]
none
[ { "input": "3\n2 3 1", "output": "1.916666666666666666666666666667" }, { "input": "1\n1", "output": "0.000000000000000000000000000000" }, { "input": "2\n1 2", "output": "0.166666666666666666666666666667" }, { "input": "2\n2 1", "output": "0.833333333333333333333333333333"...
31
0
0
157,198
44
Shooting Gallery
[ "data structures", "implementation" ]
G. Shooting Gallery
5
256
Berland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shooting gallery. During the elaboration process it turned out that the program that imitates the process of shooting effectively, is needed. To formulate the requirements to the program, the shooting gallery was formally described. A 3D Cartesian system of coordinates was introduced, where the *X* axis ran across the gallery floor along the line, along which the shooters are located, the *Y* axis ran vertically along the gallery wall and the positive direction of the *Z* axis matched the shooting direction. Let's call the *XOY* plane a shooting plane and let's assume that all the bullets are out of the muzzles at the points of this area and fly parallel to the *Z* axis. Every clay pigeon can be represented as a rectangle whose sides are parallel to *X* and *Y* axes, and it has a positive *z*-coordinate. The distance between a clay pigeon and the shooting plane is always different for every target. The bullet hits the target if it goes through the inner area or border of the rectangle corresponding to it. When the bullet hits the target, the target falls down vertically into the crawl-space of the shooting gallery and cannot be shot at any more. The targets are tough enough, that's why a bullet can not pierce a target all the way through and if a bullet hits a target it can't fly on. In input the simulator program is given the arrangement of all the targets and also of all the shots in the order of their appearance. The program should determine which target was hit by which shot. If you haven't guessed it yet, you are the one who is to write such a program.
The first line contains an integer *n* (1<=≀<=*n*<=≀<=105) β€” the number of targets. Each of the subsequent *n* lines contains the description of a target. The target is described by five integers *x**l*,<=*x**r*,<=*y**l*,<=*y**r*,<=*z*, that determine it's location in space (0<=≀<=*x**l*<=&lt;<=*x**r*<=≀<=107,<=0<=≀<=*y**l*<=&lt;<=*y**r*<=≀<=107,<=0<=&lt;<=*z*<=≀<=107). The next line contains an integer *m* (1<=≀<=*m*<=≀<=105), determining the number of shots. Then in *m* lines shots are described. Every shot is determined by the coordinates of a bullet on the shooting plane (*x*,<=*y*) (0<=≀<=*x*,<=*y*<=≀<=107, the coordinates of bullets are integers). The shots are given in the order of their firing. The intervals between shots are large enough, and a target falls very quickly, that's why assume that a falling target can not be an obstruction for all the shots following the one that hit it.
For every shot in the single line print the number of the target which the shot has hit, or 0, if the bullet did not hit any target. The targets are numbered starting from 1 in the order in which they were given in the input data.
[ "2\n1 4 1 4 1\n2 5 2 6 2\n4\n0 0\n3 3\n4 5\n3 5\n" ]
[ "0\n1\n2\n0\n" ]
none
[]
30
0
0
157,477
0
none
[ "none" ]
null
null
Long ago, when Petya was a schoolboy, he was very much interested in the Petr# language grammar. During one lesson Petya got interested in the following question: how many different continuous substrings starting with the *s**begin* and ending with the *s**end* (it is possible *s**begin*<==<=*s**end*), the given string *t* has. Substrings are different if and only if their contents aren't equal, their positions of occurence don't matter. Petya wasn't quite good at math, that's why he couldn't count this number. Help him!
The input file consists of three lines. The first line contains string *t*. The second and the third lines contain the *s**begin* and *s**end* identificators, correspondingly. All three lines are non-empty strings consisting of lowercase Latin letters. The length of each string doesn't exceed 2000 characters.
Output the only number β€” the amount of different substrings of *t* that start with *s**begin* and end with *s**end*.
[ "round\nro\nou\n", "codeforces\ncode\nforca\n", "abababab\na\nb\n", "aba\nab\nba\n" ]
[ "1\n", "0\n", "4\n", "1\n" ]
In the third sample there are four appropriate different substrings. They are: ab, abab, ababab, abababab. In the fourth sample identificators intersect.
[ { "input": "round\nro\nou", "output": "1" }, { "input": "codeforces\ncode\nforca", "output": "0" }, { "input": "abababab\na\nb", "output": "4" }, { "input": "aba\nab\nba", "output": "1" }, { "input": "abcdefghijklmnopqrstuvwxyz\nabc\nxyz", "output": "1" }, ...
2,000
25,497,600
0
157,776
794
Replace All
[ "combinatorics", "dp", "math" ]
null
null
Igor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem: Given two strings *x* and *y* which consist of the English letters 'A' and 'B' only, a pair of strings (*s*,<=*t*) is called good if: - *s* and *t* consist of the characters '0' and '1' only.- 1<=≀<=|*s*|,<=|*t*|<=≀<=*n*, where |*z*| denotes the length of string *z*, and *n* is a fixed positive integer.- If we replace all occurrences of 'A' in *x* and *y* with the string *s*, and replace all occurrences of 'B' in *x* and *y* with the string *t*, then the two obtained from *x* and *y* strings are equal. For example, if *x*<==<=AAB, *y*<==<=BB and *n*<==<=4, then (01, 0101) is one of good pairs of strings, because both obtained after replacing strings are "01010101". The flexibility of a pair of strings *x* and *y* is the number of pairs of good strings (*s*,<=*t*). The pairs are ordered, for example the pairs (0, 1) and (1, 0) are different. You're given two strings *c* and *d*. They consist of characters 'A', 'B' and '?' only. Find the sum of flexibilities of all possible pairs of strings (*c*',<=*d*') such that *c*' and *d*' can be obtained from *c* and *d* respectively by replacing the question marks with either 'A' or 'B', modulo 109<=+<=7.
The first line contains the string *c* (1<=≀<=|*c*|<=≀<=3Β·105). The second line contains the string *d* (1<=≀<=|*d*|<=≀<=3Β·105). The last line contains a single integer *n* (1<=≀<=*n*<=≀<=3Β·105).
Output a single integer: the answer to the problem, modulo 109<=+<=7.
[ "A?\n?\n3\n", "A\nB\n10\n" ]
[ "2\n", "2046\n" ]
For the first sample, there are four possible pairs of (*c*', *d*'). If (*c*', *d*') = (AA, A), then the flexibility is 0. If (*c*', *d*') = (AB, A), then the flexibility is 0. If (*c*', *d*') = (AA, B), then the flexibility is 2, as the pairs of binary strings (1, 11), (0, 00) are the only good pairs. If (*c*', *d*') = (AB, B), then the flexibility is 0. Thus, the total flexibility is 2. For the second sample, there are 2<sup class="upper-index">1</sup> + 2<sup class="upper-index">2</sup> + ... + 2<sup class="upper-index">10</sup> = 2046 possible binary strings of length not greater 10, and the set of pairs of good strings is precisely the set of pairs (*s*, *s*), where *s* is a binary string of length not greater than 10.
[]
30
0
0
157,795
341
Candies Game
[ "constructive algorithms", "greedy" ]
null
null
Iahub is playing an uncommon game. Initially, he has *n* boxes, numbered 1, 2, 3, ..., *n*. Each box has some number of candies in it, described by a sequence *a*1, *a*2, ..., *a**n*. The number *a**k* represents the number of candies in box *k*. The goal of the game is to move all candies into exactly two boxes. The rest of *n*<=-<=2 boxes must contain zero candies. Iahub is allowed to do several (possible zero) moves. At each move he chooses two different boxes *i* and *j*, such that *a**i*<=≀<=*a**j*. Then, Iahub moves from box *j* to box *i* exactly *a**i* candies. Obviously, when two boxes have equal number of candies, box number *j* becomes empty. Your task is to give him a set of moves such as Iahub to archive the goal of the game. If Iahub can't win the game for the given configuration of boxes, output -1. Please note that in case there exist a solution, you don't need to print the solution using minimal number of moves.
The first line of the input contains integer *n* (3<=≀<=*n*<=≀<=1000). The next line contains *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n* β€” sequence elements. It is guaranteed that sum of all numbers in sequence *a* is up to 106.
In case there exists no solution, output -1. Otherwise, in the first line output integer *c* (0<=≀<=*c*<=≀<=106), representing number of moves in your solution. Each of the next *c* lines should contain two integers *i* and *j* (1<=≀<=*i*,<=*j*<=≀<=*n*,<=*i*<=β‰ <=*j*): integers *i*, *j* in the *k*th line mean that at the *k*-th move you will move candies from the *j*-th box to the *i*-th one.
[ "3\n3 6 9\n", "3\n0 1 0\n", "4\n0 1 1 0\n" ]
[ "2\n2 3\n1 3\n", "-1", "0\n" ]
For the first sample, after the first move the boxes will contain 3, 12 and 3 candies. After the second move, the boxes will contain 6, 12 and 0 candies. Now all candies are in exactly 2 boxes. For the second sample, you can observe that the given configuration is not valid, as all candies are in a single box and they should be in two boxes. Also, any move won't change the configuration, so there exists no solution. For the third sample, all candies are already in 2 boxes. Hence, no move is needed.
[]
154
1,024,000
0
157,880
119
String Transformation
[ "hashing", "strings" ]
null
null
Let *s* be a string whose length equals *n*. Its characters are numbered from 0 to *n*<=-<=1, *i* and *j* are integers, 0<=≀<=*i*<=&lt;<=*j*<=&lt;<=*n*. Let's define function *f* as follows: *f*(*s*,<=*i*,<=*j*)<==<=*s*[*i*<=+<=1... *j*<=-<=1]<=+<=*r*(*s*[*j*... *n*<=-<=1])<=+<=*r*(*s*[0... *i*]). Here *s*[*p*... *q*] is a substring of string *s*, that starts in position *p* and ends in position *q* (inclusive); "+" is the string concatenation operator; *r*(*x*) is a string resulting from writing the characters of the *x* string in the reverse order. If *j*<==<=*i*<=+<=1, then the substring *s*[*i*<=+<=1... *j*<=-<=1] is considered empty. You are given two strings *a* and *b*. Find such values of *i* and *j*, that *f*(*a*,<=*i*,<=*j*)<==<=*b*. Number *i* should be maximally possible. If for this *i* there exists several valid values of *j*, choose the minimal *j*.
The first two input lines are non-empty strings *a* and *b* correspondingly. Each string's length does not exceed 106 characters. The strings can contain any characters with ASCII codes from 32 to 126 inclusive.
Print two integers *i*, *j* β€” the answer to the problem. If no solution exists, print "-1 -1" (without the quotes).
[ "Die Polizei untersucht eine Straftat im IT-Bereich.\nuntersucht eine Straftat.hciereB-TI mi ieziloP eiD\n", "cbaaaa\naaaabc\n", "123342\n3324212\n" ]
[ "11 36\n", "4 5\n", "-1 -1" ]
none
[]
124
1,740,800
0
157,913
256
Lucky Arrays
[ "data structures" ]
null
null
Little Maxim loves interesting problems. He decided to share one such problem with you. Initially there is an array *a*, consisting of *n* zeroes. The elements of the array are indexed, starting from 1. Then follow queries to change array *a*. Each query is characterized by two integers *v**i*,<=*t**i*. In the answer to the query we should make the *v**i*-th array element equal *t**i* (*a**v**i*<==<=*t**i*;Β 1<=≀<=*v**i*<=≀<=*n*). Maxim thinks that some pairs of integers (*x*,<=*y*) are good and some are not. Maxim thinks that array *a*, consisting of *n* integers, is lucky, if for all integer *i*, (1<=≀<=*i*<=≀<=*n*<=-<=1) the pair of integers (*a**i*,<=*a**i*<=+<=1) β€” is good. Note that the order of numbers in the pairs is important, that is, specifically, (1,<=2)<=β‰ <=(2,<=1). After each query to change array *a* Maxim wants to know, how many ways there are to replace all zeroes in array *a* with integers from one to three so as to make the resulting array (without zeroes) lucky. Of course, distinct zeroes can be replaced by distinct integers. Maxim told you the sequence of queries and all pairs of integers he considers lucky. Help Maxim, solve this problem for him.
The first line contains integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=77777) β€” the number of elements in the array and the number of commands. The next three lines contain matrix *w*, consisting only of zeroes and ones; the *j*-th number in the *i*-th of these lines β€” *w**i*,<=*j*. If *w**i*,<=*j*<==<=1 (1<=≀<=*i*,<=*j*<=≀<=3), then pair (*i*,<=*j*) is good, otherwise it is not good. Matrix does not have to be symmetric relative to the main diagonal. Next *m* lines contain pairs of integers *v**i*,<=*t**i* (1<=≀<=*v**i*<=≀<=*n*,<=0<=≀<=*t**i*<=≀<=3) β€” the queries to change the array.
Print *m* integers β€” the *i*-th number should equal to the number of ways to replace all zeroes in array *a* (changed after the *i*-th query) by integers from one to three so as to make the resulting array (without zeroes) lucky. Separate the numbers by whitespaces. As the answers can be rather large, print the remainder from dividing them by 777777777.
[ "3 10\n1 1 0\n1 0 0\n1 1 1\n1 1\n1 3\n2 2\n3 0\n2 1\n3 0\n3 1\n2 0\n3 1\n1 0\n" ]
[ "3\n6\n1\n1\n2\n2\n1\n3\n3\n6\n" ]
none
[]
122
4,403,200
0
158,043
946
Fibonacci String Subsequences
[ "combinatorics", "dp", "matrices" ]
null
null
You are given a binary string *s* (each character of this string is either 0 or 1). Let's denote the cost of string *t* as the number of occurences of *s* in *t*. For example, if *s* is 11 and *t* is 111011, then the cost of *t* is 3. Let's also denote the Fibonacci strings sequence as follows: - *F*(0) is 0;- *F*(1) is 1;- *F*(*i*)<==<=*F*(*i*<=-<=1)<=+<=*F*(*i*<=-<=2) if *i*<=&gt;<=1, where <=+<= means the concatenation of two strings. Your task is to calculate the sum of costs of all subsequences of the string *F*(*x*). Since answer may be large, calculate it modulo 109<=+<=7.
The first line contains two integers *n* and *x* (1<=≀<=*n*<=≀<=100, 0<=≀<=*x*<=≀<=100) β€” the length of *s* and the index of a Fibonacci string you are interested in, respectively. The second line contains *s* β€” a string consisting of *n* characters. Each of these characters is either 0 or 1.
Print the only integer β€” the sum of costs of all subsequences of the string *F*(*x*), taken modulo 109<=+<=7.
[ "2 4\n11\n", "10 100\n1010101010\n" ]
[ "14\n", "553403224\n" ]
none
[ { "input": "2 4\n11", "output": "14" }, { "input": "10 100\n1010101010", "output": "553403224" }, { "input": "10 5\n0110111100", "output": "0" }, { "input": "100 100\n0001010101110010010100111011010101101111110001101101010111011101010000111000110001111010001001000001", "o...
3,500
31,232,000
0
158,415
148
Porcelain
[ "dp" ]
null
null
During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed. The collection of porcelain is arranged neatly on *n* shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items β€” the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves. You are given the values of all items. Your task is to find the maximal damage the princess' tantrum of *m* shrieks can inflict on the collection of porcelain.
The first line of input data contains two integers *n* (1<=≀<=*n*<=≀<=100) and *m* (1<=≀<=*m*<=≀<=10000). The next *n* lines contain the values of the items on the shelves: the first number gives the number of items on this shelf (an integer between 1 and 100, inclusive), followed by the values of the items (integers between 1 and 100, inclusive), in the order in which they appear on the shelf (the first number corresponds to the leftmost item, the last one β€” to the rightmost one). The total number of items is guaranteed to be at least *m*.
Output the maximal total value of a tantrum of *m* shrieks.
[ "2 3\n3 3 7 2\n3 4 1 5\n", "1 3\n4 4 3 1 2\n" ]
[ "15\n", "9\n" ]
In the first case there are two shelves, each with three items. To maximize the total value of the items chosen, one can take two items from the left side of the first shelf and one item from the right side of the second shelf. In the second case there is only one shelf, so all three items are taken from it β€” two from the left side and one from the right side.
[ { "input": "2 3\n3 3 7 2\n3 4 1 5", "output": "15" }, { "input": "1 3\n4 4 3 1 2", "output": "9" }, { "input": "1 4\n6 5 1 10 1 1 5", "output": "21" }, { "input": "3 2\n1 10\n1 2\n1 5", "output": "15" }, { "input": "1 68\n100 26 58 15 8 69 66 49 97 18 74 27 39 19 ...
46
0
0
158,593
283
Cows and Cool Sequences
[ "dp", "math", "number theory" ]
null
null
Bessie and the cows have recently been playing with "cool" sequences and are trying to construct some. Unfortunately they are bad at arithmetic, so they need your help! A pair (*x*,<=*y*) of positive integers is "cool" if *x* can be expressed as the sum of *y* consecutive integers (not necessarily positive). A sequence (*a*1,<=*a*2,<=...,<=*a**n*) is "cool" if the pairs (*a*1,<=*a*2),<=(*a*2,<=*a*3),<=...,<=(*a**n*<=-<=1,<=*a**n*) are all cool. The cows have a sequence of *n* positive integers, *a*1,<=*a*2,<=...,<=*a**n*. In one move, they may replace some *a**i* with any other positive integer (there are no other limits on the new value of *a**i*). Determine the smallest number of moves needed to make the resulting sequence cool.
The first line contains a single integer, *n* (2<=≀<=*n*<=≀<=5000). The next line contains *n* space-separated integers, *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=1015). 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.
A single integer, the minimum number of *a**i* that must be changed to make the sequence cool.
[ "3\n6 4 1\n", "4\n20 6 3 4\n" ]
[ "0\n", "2\n" ]
In the first sample, the sequence is already cool, so we don't need to change any elements. In the second sample, we can change *a*<sub class="lower-index">2</sub> to 5 and *a*<sub class="lower-index">3</sub> to 10 to make (20, 5, 10, 4) which is cool. This changes 2 elements.
[]
2,000
2,252,800
0
158,824
154
Flatland Fencing
[ "games", "math" ]
null
null
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on one, the winner (or rather, the survivor) transfers to the next round. Before the battle both participants stand at the specified points on the *Ox* axis with integer coordinates. Then they make moves in turn. The first participant moves first, naturally. During a move, the first participant can transfer from the point *x* to any integer point of the interval [*x*<=+<=*a*; *x*<=+<=*b*]. The second participant can transfer during a move to any integer point of the interval [*x*<=-<=*b*; *x*<=-<=*a*]. That is, the options for the players' moves are symmetric (note that the numbers *a* and *b* are not required to be positive, and if *a*<=≀<=0<=≀<=*b*, then staying in one place is a correct move). At any time the participants can be located arbitrarily relative to each other, that is, it is allowed to "jump" over the enemy in any direction. A participant wins if he uses his move to transfer to the point where his opponent is. Of course, the princess has already chosen a husband and now she wants to make her sweetheart win the tournament. He has already reached the tournament finals and he is facing the last battle. The princess asks the tournament manager to arrange the tournament finalists in such a way that her sweetheart wins the tournament, considering that both players play optimally. However, the initial location of the participants has already been announced, and we can only pull some strings and determine which participant will be first and which one will be second. But how do we know which participant can secure the victory? Alas, the princess is not learned in the military affairs... Therefore, she asks you to determine how the battle will end considering that both opponents play optimally. Also, if the first player wins, your task is to determine his winning move.
The first line contains four space-separated integers β€” *x*1, *x*2, *a* and *b* (*x*1<=β‰ <=*x*2, *a*<=≀<=*b*, <=-<=109<=≀<=*x*1,<=*x*2,<=*a*,<=*b*<=≀<=109) β€” coordinates of the points where the first and the second participant start, and the numbers that determine the players' moves, correspondingly.
On the first line print the outcome of the battle as "FIRST" (without the quotes), if both players play optimally and the first player wins. Print "SECOND" (without the quotes) if the second player wins and print "DRAW" (without the quotes), if nobody is able to secure the victory. If the first player wins, print on the next line the single integer *x* β€” the coordinate of the point where the first player should transfer to win. The indicated move should be valid, that is, it should meet the following condition: *x*1<=+<=*a*<=≀<=*x*<=≀<=*x*1<=+<=*b*. If there are several winning moves, print any of them. If the first participant can't secure the victory, then you do not have to print anything.
[ "0 2 0 4\n", "0 2 1 1\n", "0 2 0 1\n" ]
[ "FIRST\n2\n", "SECOND\n", "DRAW\n" ]
In the first sample the first player can win in one move. In the second sample the first participant must go to point 1, where the second participant immediately goes and wins. In the third sample changing the position isn't profitable to either participant, so nobody wins.
[ { "input": "0 2 0 4", "output": "FIRST\n2" }, { "input": "0 2 1 1", "output": "SECOND" }, { "input": "0 2 0 1", "output": "DRAW" }, { "input": "3 1 -2 2", "output": "FIRST\n1" }, { "input": "3 10 1 6", "output": "SECOND" }, { "input": "1 2 2 2", "o...
124
0
0
159,007
913
Power Substring
[ "math", "number theory" ]
null
null
You are given *n* positive integers *a*1,<=*a*2,<=...,<=*a**n*. For every *a**i* you need to find a positive integer *k**i* such that the decimal notation of 2*k**i* contains the decimal notation of *a**i* as a substring among its last *min*(100,<=*length*(2*k**i*)) digits. Here *length*(*m*) is the length of the decimal notation of *m*. Note that you don't have to minimize *k**i*. The decimal notations in this problem do not contain leading zeros.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=2<=000)Β β€” the number of integers *a**i*. Each of the next *n* lines contains a positive integer *a**i* (1<=≀<=*a**i*<=&lt;<=1011).
Print *n* lines. The *i*-th of them should contain a positive integer *k**i* such that the last *min*(100,<=*length*(2*k**i*)) digits of 2*k**i* contain the decimal notation of *a**i* as a substring. Integers *k**i* must satisfy 1<=≀<=*k**i*<=≀<=1050. It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.
[ "2\n8\n2\n", "2\n3\n4857\n" ]
[ "3\n1\n", "5\n20\n" ]
none
[ { "input": "2\n8\n2", "output": "3\n1" }, { "input": "2\n3\n4857", "output": "5\n20" }, { "input": "7\n1\n7\n9\n5\n6\n10\n4", "output": "9\n17\n13\n21\n4\n42\n2" }, { "input": "10\n384\n179\n982\n466\n646\n226\n759\n798\n291\n852", "output": "14\n493\n230\n150\n66\n2050\n...
2,000
8,601,600
0
159,065
754
Dasha and cyclic table
[ "bitmasks", "brute force", "fft", "strings", "trees" ]
null
null
Dasha is fond of challenging puzzles: Rubik's Cube 3<=Γ—<=3<=Γ—<=3, 4<=Γ—<=4<=Γ—<=4, 5<=Γ—<=5<=Γ—<=5 and so on. This time she has a cyclic table of size *n*<=Γ—<=*m*, and each cell of the table contains a lowercase English letter. Each cell has coordinates (*i*,<=*j*) (0<=≀<=*i*<=&lt;<=*n*, 0<=≀<=*j*<=&lt;<=*m*). The table is cyclic means that to the right of cell (*i*,<=*j*) there is the cell , and to the down there is the cell . Dasha has a pattern as well. A pattern is a non-cyclic table of size *r*<=Γ—<=*c*. Each cell is either a lowercase English letter or a question mark. Each cell has coordinates (*i*,<=*j*) (0<=≀<=*i*<=&lt;<=*r*, 0<=≀<=*j*<=&lt;<=*c*). The goal of the puzzle is to find all the appearance positions of the pattern in the cyclic table. We say that the cell (*i*,<=*j*) of cyclic table is an appearance position, if for every pair (*x*,<=*y*) such that 0<=≀<=*x*<=&lt;<=*r* and 0<=≀<=*y*<=&lt;<=*c* one of the following conditions holds: - There is a question mark in the cell (*x*,<=*y*) of the pattern, or - The cell of the cyclic table equals to the cell (*x*,<=*y*) of the pattern. Dasha solved this puzzle in no time, as well as all the others she ever tried. Can you solve it?.
The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=400)Β β€” the cyclic table sizes. Each of the next *n* lines contains a string of *m* lowercase English charactersΒ β€” the description of the cyclic table. The next line contains two integers *r* and *c* (1<=≀<=*r*,<=*c*<=≀<=400)Β β€” the sizes of the pattern. Each of the next *r* lines contains a string of *c* lowercase English letter and/or characters '?'Β β€” the description of the pattern.
Print *n* lines. Each of the *n* lines should contain *m* characters. Each of the characters should equal '0' or '1'. The *j*-th character of the *i*-th (0-indexed) line should be equal to '1', in case the cell (*i*,<=*j*) is an appearance position, otherwise it should be equal to '0'.
[ "5 7\nqcezchs\nhhedywq\nwikywqy\nqckrqzt\nbqexcxz\n3 2\n??\nyw\n?q\n", "10 10\nfwtoayylhw\nyyaryyjawr\nywrdzwhscy\nhnsyyxiphn\nbnjwzyyjvo\nkkjgseenwn\ngvmiflpcsy\nlxvkwrobwu\nwyybbcocyy\nyysijsvqry\n2 2\n??\nyy\n", "8 6\nibrgxl\nxqdcsg\nokbcgi\ntvpetc\nxgxxig\nigghzo\nlmlaza\ngpswzv\n1 4\ngx??\n" ]
[ "0000100\n0001001\n0000000\n0000000\n0000000\n", "1000100000\n0000000001\n0001000000\n0000010000\n0000000000\n0000000000\n0000000000\n0100000010\n1000000001\n0000010000\n", "000100\n000001\n000000\n000000\n010001\n000000\n000000\n000000\n" ]
none
[]
6,000
358,400,000
0
159,641
198
Cube Snake
[ "constructive algorithms" ]
null
null
You've got an *n*<=Γ—<=*n*<=Γ—<=*n* cube, split into unit cubes. Your task is to number all unit cubes in this cube with positive integers from 1 to *n*3 so that: - each number was used as a cube's number exactly once; - for each 1<=≀<=*i*<=&lt;<=*n*3, unit cubes with numbers *i* and *i*<=+<=1 were neighbouring (that is, shared a side); - for each 1<=≀<=*i*<=&lt;<=*n* there were at least two different subcubes with sizes *i*<=Γ—<=*i*<=Γ—<=*i*, made from unit cubes, which are numbered with consecutive numbers. That is, there are such two numbers *x* and *y*, that the unit cubes of the first subcube are numbered by numbers *x*, *x*<=+<=1, ..., *x*<=+<=*i*3<=-<=1, and the unit cubes of the second subcube are numbered by numbers *y*, *y*<=+<=1, ..., *y*<=+<=*i*3<=-<=1. Find and print the required numeration of unit cubes of the cube.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=50) β€” the size of the cube, whose unit cubes need to be numbered.
Print all layers of the cube as *n* *n*<=Γ—<=*n* matrices. Separate them with new lines. Print the layers in the order in which they follow in the cube. See the samples for clarifications. It is guaranteed that there always is a solution that meets the conditions given in the problem statement.
[ "3\n" ]
[ "1 4 17 \n2 3 18 \n27 26 19 \n\n8 5 16 \n7 6 15 \n24 25 20 \n\n9 12 13 \n10 11 14 \n23 22 21 \n\n" ]
In the sample the cubes with sizes 2 × 2 × 2 are numbered with integers 1, ..., 8 and 5, ..., 12.
[]
60
0
0
159,697
815
Karen and Cards
[ "binary search", "combinatorics", "data structures", "geometry" ]
null
null
Karen just got home from the supermarket, and is getting ready to go to sleep. After taking a shower and changing into her pajamas, she looked at her shelf and saw an album. Curious, she opened it and saw a trading card collection. She recalled that she used to play with those cards as a child, and, although she is now grown-up, she still wonders a few things about it. Each card has three characteristics: strength, defense and speed. The values of all characteristics of all cards are positive integers. The maximum possible strength any card can have is *p*, the maximum possible defense is *q* and the maximum possible speed is *r*. There are *n* cards in her collection. The *i*-th card has a strength *a**i*, defense *b**i* and speed *c**i*, respectively. A card beats another card if at least two of its characteristics are strictly greater than the corresponding characteristics of the other card. She now wonders how many different cards can beat all the cards in her collection. Two cards are considered different if at least one of their characteristics have different values.
The first line of input contains four integers, *n*, *p*, *q* and *r* (1<=≀<=*n*,<=*p*,<=*q*,<=*r*<=≀<=500000), the number of cards in the collection, the maximum possible strength, the maximum possible defense, and the maximum possible speed, respectively. The next *n* lines each contain three integers. In particular, the *i*-th line contains *a**i*, *b**i* and *c**i* (1<=≀<=*a**i*<=≀<=*p*, 1<=≀<=*b**i*<=≀<=*q*, 1<=≀<=*c**i*<=≀<=*r*), the strength, defense and speed of the *i*-th collection card, respectively.
Output a single integer on a line by itself, the number of different cards that can beat all the cards in her collection.
[ "3 4 4 5\n2 2 5\n1 3 4\n4 1 1\n", "5 10 10 10\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n1 1 1\n" ]
[ "10\n", "972\n" ]
In the first test case, the maximum possible strength is 4, the maximum possible defense is 4 and the maximum possible speed is 5. Karen has three cards: - The first card has strength 2, defense 2 and speed 5. - The second card has strength 1, defense 3 and speed 4. - The third card has strength 4, defense 1 and speed 1. There are 10 cards that beat all the cards here: 1. The card with strength 3, defense 3 and speed 5. 1. The card with strength 3, defense 4 and speed 2. 1. The card with strength 3, defense 4 and speed 3. 1. The card with strength 3, defense 4 and speed 4. 1. The card with strength 3, defense 4 and speed 5. 1. The card with strength 4, defense 3 and speed 5. 1. The card with strength 4, defense 4 and speed 2. 1. The card with strength 4, defense 4 and speed 3. 1. The card with strength 4, defense 4 and speed 4. 1. The card with strength 4, defense 4 and speed 5. In the second test case, the maximum possible strength is 10, the maximum possible defense is 10 and the maximum possible speed is 10. Karen has five cards, all with strength 1, defense 1 and speed 1. Any of the 972 cards which have at least two characteristics greater than 1 can beat all of the cards in her collection.
[]
46
0
0
159,797
391
Stock Trading
[ "dp" ]
null
null
This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points. Manao has developed a model to predict the stock price of a company over the next *n* days and wants to design a profit-maximizing trading algorithm to make use of these predictions. Unfortunately, Manao's trading account has the following restrictions: - It only allows owning either zero or one shares of stock at a time; - It only allows buying or selling a share of this stock once per day; - It allows a maximum of *k* buy orders over the next *n* days; For the purposes of this problem, we define a trade to a be the act of buying one share of stock on day *i*, then holding the stock until some day *j*<=&gt;<=*i* at which point the share is sold. To restate the above constraints, Manao is permitted to make at most *k* non-overlapping trades during the course of an *n*-day trading period for which Manao's model has predictions about the stock price. Even though these restrictions limit the amount of profit Manao can make compared to what would be achievable with an unlimited number of trades or the ability to hold more than one share at a time, Manao still has the potential to make a lot of money because Manao's model perfectly predicts the daily price of the stock. For example, using this model, Manao could wait until the price is low, then buy one share and hold until the price reaches a high value, then sell for a profit, and repeat this process up to *k* times until *n* days have passed. Nevertheless, Manao is not satisfied by having a merely good trading algorithm, and wants to develop an optimal strategy for trading subject to these constraints. Help Manao achieve this goal by writing a program that will determine when to buy and sell stock to achieve the greatest possible profit during the *n*-day trading period subject to the above constraints.
The first line contains two integers *n* and *k*, separated by a single space, with . The *i*-th of the following *n* lines contains a single integer *p**i* (0<=≀<=*p**i*<=≀<=1012), where *p**i* represents the price at which someone can either buy or sell one share of stock on day *i*. 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 F1 (8 points), *n* will be between 1 and 3000, inclusive. - In subproblem F2 (15 points), *n* will be between 1 and 100000, inclusive. - In subproblem F3 (10 points), *n* will be between 1 and 4000000, inclusive.
For this problem, the program will only report the amount of the optimal profit, rather than a list of trades that can achieve this profit. Therefore, the program should print one line containing a single integer, the maximum profit Manao can achieve over the next *n* days with the constraints of starting with no shares on the first day of trading, always owning either zero or one shares of stock, and buying at most *k* shares over the course of the *n*-day trading period.
[ "10 2\n2\n7\n3\n9\n8\n7\n9\n7\n1\n9\n", "10 5\n2\n7\n3\n9\n8\n7\n9\n7\n1\n9\n" ]
[ "15\n", "21\n" ]
In the first example, the best trade overall is to buy at a price of 1 on day 9 and sell at a price of 9 on day 10 and the second best trade overall is to buy at a price of 2 on day 1 and sell at a price of 9 on day 4. Since these two trades do not overlap, both can be made and the profit is the sum of the profits of the two trades. Thus the trade strategy looks like this: The total profit is then (9 - 2) + (9 - 1) = 15. In the second example, even though Manao is allowed up to 5 trades there are only 4 profitable trades available. Making a fifth trade would cost Manao money so he only makes the following 4: The total profit is then (7 - 2) + (9 - 3) + (9 - 7) + (9 - 1) = 21.
[ { "input": "10 2\n2\n7\n3\n9\n8\n7\n9\n7\n1\n9", "output": "15" }, { "input": "10 5\n2\n7\n3\n9\n8\n7\n9\n7\n1\n9", "output": "21" }, { "input": "2 1\n2\n1", "output": "0" } ]
3,000
245,964,800
0
159,904
183
Cyclic Coloring
[ "dfs and similar" ]
null
null
You are given a directed graph *G* with *n* vertices and *m* arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the *k* (*k*<=≀<=*n*) colors in such way that for all arcs of the graph leading from a vertex *u* to vertex *v*, vertex *v* is painted with the next color of the color used to paint vertex *u*. The colors are numbered cyclically 1 through *k*. This means that for each color *i* (*i*<=&lt;<=*k*) its next color is color *i*<=+<=1. In addition, the next color of color *k* is color 1. Note, that if *k*<==<=1, then the next color for color 1 is again color 1. Your task is to find and print the largest possible value of *k* (*k*<=≀<=*n*) such that it's possible to color *G* as described above with *k* colors. Note that you don't necessarily use all the *k* colors (that is, for each color *i* there does not necessarily exist a vertex that is colored with color *i*).
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=105), denoting the number of vertices and the number of arcs of the given digraph, respectively. Then *m* lines follow, each line will contain two space-separated integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*), which means that the *i*-th arc goes from vertex *a**i* to vertex *b**i*. Multiple arcs and self-loops are allowed.
Print a single integer β€” the maximum possible number of the colors that can be used to paint the digraph (i.e. *k*, as described in the problem statement). Note that the desired value of *k* must satisfy the inequality 1<=≀<=*k*<=≀<=*n*.
[ "4 4\n1 2\n2 1\n3 4\n4 3\n", "5 2\n1 4\n2 5\n", "4 5\n1 2\n2 3\n3 1\n2 4\n4 1\n", "4 4\n1 1\n1 2\n2 1\n1 2\n" ]
[ "2\n", "5\n", "3\n", "1\n" ]
For the first example, with *k* = 2, this picture depicts the two colors (arrows denote the next color of that color). With *k* = 2 a possible way to paint the graph is as follows. It can be proven that no larger value for *k* exists for this test case. For the second example, here's the picture of the *k* = 5 colors. A possible coloring of the graph is: For the third example, here's the picture of the *k* = 3 colors. A possible coloring of the graph is:
[]
60
0
0
160,001
267
Dominoes
[ "dfs and similar", "graphs" ]
null
null
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the right side (domino "1-4" turns into "4-1").
The first line contains number *n* (1<=<=≀<=<=*n*<=<=≀<=<=100). Next *n* lines contains the dominoes. Each of these lines contains two numbers β€” the number of points (spots) on the left and the right half, correspondingly. The numbers of points (spots) are non-negative integers from 0 to 6.
Print "No solution", if it is impossible to arrange the dominoes in the required manner. If the solution exists, then describe any way to arrange the dominoes. You put the dominoes from left to right. In each of *n* lines print the index of the domino to put in the corresponding position and then, after a space, character "+" (if you don't need to turn the domino) or "–" (if you need to turn it).
[ "5\n1 2\n2 4\n2 4\n6 4\n2 1\n" ]
[ "2 -\n1 -\n5 -\n3 +\n4 -\n" ]
none
[ { "input": "5\n1 2\n2 4\n2 4\n6 4\n2 1", "output": "2 -\n1 -\n5 -\n3 +\n4 -" }, { "input": "1\n0 0", "output": "1 +" }, { "input": "1\n5 5", "output": "1 +" }, { "input": "5\n0 0\n0 0\n0 0\n0 0\n0 0", "output": "1 +\n2 +\n3 +\n4 +\n5 +" }, { "input": "4\n0 0\n0 0\...
0
0
-1
160,258
1,009
Dominant Indices
[ "data structures", "dsu", "trees" ]
null
null
You are given a rooted undirected tree consisting of $n$ vertices. Vertex $1$ is the root. Let's denote a depth array of vertex $x$ as an infinite sequence $[d_{x, 0}, d_{x, 1}, d_{x, 2}, \dots]$, where $d_{x, i}$ is the number of vertices $y$ such that both conditions hold: - $x$ is an ancestor of $y$; - the simple path from $x$ to $y$ traverses exactly $i$ edges. The dominant index of a depth array of vertex $x$ (or, shortly, the dominant index of vertex $x$) is an index $j$ such that: - for every $k &lt; j$, $d_{x, k} &lt; d_{x, j}$; - for every $k &gt; j$, $d_{x, k} \le d_{x, j}$. For every vertex in the tree calculate its dominant index.
The first line contains one integer $n$ ($1 \le n \le 10^6$) β€” the number of vertices in a tree. Then $n - 1$ lines follow, each containing two integers $x$ and $y$ ($1 \le x, y \le n$, $x \ne y$). This line denotes an edge of the tree. It is guaranteed that these edges form a tree.
Output $n$ numbers. $i$-th number should be equal to the dominant index of vertex $i$.
[ "4\n1 2\n2 3\n3 4\n", "4\n1 2\n1 3\n1 4\n", "4\n1 2\n2 3\n2 4\n" ]
[ "0\n0\n0\n0\n", "1\n0\n0\n0\n", "2\n1\n0\n0\n" ]
none
[ { "input": "4\n1 2\n2 3\n3 4", "output": "0\n0\n0\n0" }, { "input": "4\n1 2\n1 3\n1 4", "output": "1\n0\n0\n0" }, { "input": "4\n1 2\n2 3\n2 4", "output": "2\n1\n0\n0" }, { "input": "1", "output": "0" }, { "input": "2\n1 2", "output": "0\n0" } ]
77
0
0
160,514
812
Sagheer and Kindergarten
[ "dfs and similar", "graphs", "implementation", "trees" ]
null
null
Sagheer is working at a kindergarten. There are *n* children and *m* different toys. These children use well-defined protocols for playing with the toys: - Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set.- If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever.- Children request toys at distinct moments of time. No two children request a toy at the same time.- If a child is granted a toy, he never gives it back until he finishes playing with his lovely set.- If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting.- If two children are waiting for the same toy, then the child who requested it first will take the toy first. Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy. Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set. Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child *x* that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child *x* is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child *x* will make his last request, how many children will start crying? You will be given the scenario and *q* independent queries. Each query will be of the form *x* *y* meaning that the last request of the child *x* is for the toy *y*. Your task is to help Sagheer find the size of the maximal crying set when child *x* makes his last request.
The first line contains four integers *n*, *m*, *k*, *q* (1<=≀<=*n*,<=*m*,<=*k*,<=*q*<=≀<=105)Β β€” the number of children, toys, scenario requests and queries. Each of the next *k* lines contains two integers *a*, *b* (1<=≀<=*a*<=≀<=*n* and 1<=≀<=*b*<=≀<=*m*)Β β€” a scenario request meaning child *a* requests toy *b*. The requests are given in the order they are made by children. Each of the next *q* lines contains two integers *x*, *y* (1<=≀<=*x*<=≀<=*n* and 1<=≀<=*y*<=≀<=*m*)Β β€” the request to be added to the scenario meaning child *x* will request toy *y* just after getting the toy he is waiting for (if any). It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.
For each query, print on a single line the number of children who will start crying when child *x* makes his last request for toy *y*. Please answer all queries independent of each other.
[ "3 3 5 1\n1 1\n2 2\n3 3\n1 2\n2 3\n3 1\n", "5 4 7 2\n1 1\n2 2\n2 1\n5 1\n3 3\n4 4\n4 1\n5 3\n5 4\n" ]
[ "3\n", "0\n2\n" ]
In the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying. In the second example, at the beginning, child *i* is holding toy *i* for 1 ≀ *i* ≀ 4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now: - In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play.- In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying.
[ { "input": "3 3 5 1\n1 1\n2 2\n3 3\n1 2\n2 3\n3 1", "output": "3" }, { "input": "5 4 7 2\n1 1\n2 2\n2 1\n5 1\n3 3\n4 4\n4 1\n5 3\n5 4", "output": "0\n2" }, { "input": "15 16 30 5\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n8 8\n9 9\n10 10\n11 11\n12 12\n13 13\n14 14\n15 15\n1 16\n2 1\n3 2\n4 1\n...
0
0
0
161,385
0
none
[ "none" ]
null
null
Polycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations: - adding any bracket in any position (in the beginning, the end, or between any two existing brackets); - cyclic shift β€” moving the last bracket from the end of the sequence to the beginning. Polycarpus can apply any number of operations to his sequence and adding a cyclic shift in any order. As a result, he wants to get the correct bracket sequence of the minimum possible length. If there are several such sequences, Polycarpus is interested in the lexicographically smallest one. Help him find such a sequence. Acorrect bracket sequence is a sequence of opening and closing brackets, from which you can get a correct arithmetic expression by adding characters "1" and "+" . Each opening bracket must correspond to a closed one. For example, the sequences "(())()", "()", "(()(()))" are correct and ")(", "(()" and "(()))(" are not. The sequence *a*1 *a*2... *a**n* is lexicographically smaller than sequence *b*1 *b*2... *b**n*, if there is such number *i* from 1 to *n*, that*a**k*<==<=*b**k* for 1<=≀<=*k*<=&lt;<=*i* and *a**i*<=&lt;<=*b**i*. Consider that "(" <=&lt;<= ")".
The first line contains Polycarpus's sequence consisting of characters "(" and ")". The length of a line is from 1 to 1<=000<=000.
Print a correct bracket sequence of the minimum length that Polycarpus can obtain by his operations. If there are multiple such sequences, print the lexicographically minimum one.
[ "()(())\n", "()(\n" ]
[ "(())()", "(())" ]
The sequence in the first example is already correct, but to get the lexicographically minimum answer, you need to perform four cyclic shift operations. In the second example you need to add a closing parenthesis between the second and third brackets and make a cyclic shift. You can first make the shift, and then add the bracket at the end.
[]
46
0
0
161,503
132
Bits of merry old England
[ "flows", "graphs" ]
null
null
Another feature of Shakespeare language is that the variables are named after characters of plays by Shakespeare, and all operations on them (value assignment, output etc.) look like a dialog with other characters. New values of variables are defined in a rather lengthy way, so a programmer should try to minimize their usage. You have to print the given sequence of *n* integers. To do this, you have *m* variables and two types of operations on them: - variable=integer - print(variable) Any of the *m* variables can be used as variable. Variables are denoted by lowercase letters between "a" and "z", inclusive. Any integer number can be used as integer. Let's say that the penalty for using first type of operations equals to the number of set bits in the number integer. There is no penalty on using second type of operations. Find and output the program which minimizes the penalty for printing the given sequence of numbers.
The first line of input contains integers *n* and *m* (1<=≀<=*n*<=≀<=250, 1<=≀<=*m*<=≀<=26). The second line contains the sequence to be printed. Each element of the sequence is an integer between 1 and 109, inclusive. The sequence has to be printed in the given order (from left to right).
Output the number of lines in the optimal program and the optimal penalty. Next, output the program itself, one command per line. If there are several programs with minimal penalty, output any of them (you have only to minimize the penalty).
[ "7 2\n1 2 2 4 2 1 2\n", "6 3\n1 2 3 1 2 3\n" ]
[ "11 4\nb=1\nprint(b)\na=2\nprint(a)\nprint(a)\nb=4\nprint(b)\nprint(a)\nb=1\nprint(b)\nprint(a)\n", "9 4\nc=1\nprint(c)\nb=2\nprint(b)\na=3\nprint(a)\nprint(c)\nprint(b)\nprint(a)\n" ]
none
[]
92
0
0
162,078
922
Divisibility
[ "constructive algorithms", "dp", "greedy", "number theory" ]
null
null
Imp is really pleased that you helped him. But it you solve the last problem, his gladness would raise even more. - *a* is strictly less than *b*; - *a* divides *b* without a remainder. You are to find such a set , which is a subset of {1,<=2,<=...,<=*n*} (the set that contains all positive integers not greater than *n*), that .
The only line contains two integers *n* and *k* .
If there is no answer, print "No". Otherwise, in the first line print "Yes", in the secondΒ β€” an integer *m* that denotes the size of the set you have found, in the second line print *m* integersΒ β€” the elements of the set , in any order. If there are multiple answers, print any of them.
[ "3 3\n", "6 6\n", "8 3\n" ]
[ "No\n", "Yes\n5\n1 2 4 5 6 ", "Yes\n4\n2 4 5 8\n" ]
In the second sample, the valid pairs in the output set are (1, 2), (1, 4), (1, 5), (1, 6), (2, 4), (2, 6). Thus, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/4057b55892a1e3b05e542533e16a59ad31321f41.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the third example, the valid pairs in the output set are (2, 4), (4, 8), (2, 8). Thus, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/381bc7acb76735c55592c41fe2170804b47f0f62.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "3 3", "output": "No" }, { "input": "6 6", "output": "Yes\n5\n1 2 4 5 6 " }, { "input": "8 3", "output": "Yes\n3\n1 2 4 " }, { "input": "10 10", "output": "Yes\n7\n1 2 4 5 6 7 8 " }, { "input": "300000 1000000000", "output": "No" }, { "input...
46
0
0
162,877
498
Name That Tune
[ "dp", "probabilities", "two pointers" ]
null
null
It turns out that you are a great fan of rock band AC/PE. Peter learned that and started the following game: he plays the first song of the list of *n* songs of the group, and you have to find out the name of the song. After you tell the song name, Peter immediately plays the following song in order, and so on. The *i*-th song of AC/PE has its recognizability *p**i*. This means that if the song has not yet been recognized by you, you listen to it for exactly one more second and with probability of *p**i* percent you recognize it and tell it's name. Otherwise you continue listening it. Note that you can only try to guess it only when it is integer number of seconds after the moment the song starts playing. In all AC/PE songs the first words of chorus are the same as the title, so when you've heard the first *t**i* seconds of *i*-th song and its chorus starts, you immediately guess its name for sure. For example, in the song Highway To Red the chorus sounds pretty late, but the song has high recognizability. In the song Back In Blue, on the other hand, the words from the title sound close to the beginning of the song, but it's hard to name it before hearing those words. You can name both of these songs during a few more first seconds. Determine the expected number songs of you will recognize if the game lasts for exactly *T* seconds (i. e. you can make the last guess on the second *T*, after that the game stops). If all songs are recognized faster than in *T* seconds, the game stops after the last song is recognized.
The first line of the input contains numbers *n* and *T* (1<=≀<=*n*<=≀<=5000, 1<=≀<=*T*<=≀<=5000), separated by a space. Next *n* lines contain pairs of numbers *p**i* and *t**i* (0<=≀<=*p**i*<=≀<=100, 1<=≀<=*t**i*<=≀<=*T*). The songs are given in the same order as in Petya's list.
Output a single number β€” the expected number of the number of songs you will recognize in *T* seconds. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
[ "2 2\n50 2\n10 1\n", "2 2\n0 2\n100 2\n", "3 3\n50 3\n50 2\n25 2\n", "2 2\n0 2\n0 2\n" ]
[ "1.500000000\n", "1.000000000\n", "1.687500000\n", "1.000000000\n" ]
none
[]
46
0
0
163,216
467
Alex and Complicated Task
[ "data structures", "dp", "greedy" ]
null
null
After you have read all the problems, probably, you think Alex is genius person. That's true! One day he came up with the following task. Given a sequence of integer numbers *a*1,<=*a*2,<=...,<=*a**n*. You are to find a longest sequence *b*1,<=*b*2,<=...,<=*b*4*m*, that satisfies the following conditions: - *b*4*k*<=+<=1<==<=*b*4*k*<=+<=3 for all valid integer *k*; - *b*4*k*<=+<=2<==<=*b*4*k*<=+<=4 for all valid integer *k*; - sequence *b* is subsequence of *a* (not necessarily contiguous subsequence). And finally... Alex had given this complicated task to George, and George gave it to you. Help George to cope with the task.
The first line contains a single integer *n* (1<=≀<=*n*<=≀<=5Β·105). The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109).
In the first line print a single integer 4*m* β€” the maximal possible length of required sequence *b*. In the second line print 4*m* integers *b*1,<=*b*2,<=...,<=*b*4*m*, that is required sequence. If there are multiple optimal answers you may print any of them.
[ "4\n3 5 3 5\n", "10\n35 1 2 1 2 35 100 200 100 200\n" ]
[ "4\n3 5 3 5\n", "8\n1 2 1 2 100 200 100 200\n" ]
none
[ { "input": "4\n3 5 3 5", "output": "4\n3 5 3 5" }, { "input": "10\n35 1 2 1 2 35 100 200 100 200", "output": "8\n1 2 1 2 100 200 100 200" }, { "input": "9\n20 12 9 8 13 7 4 9 8", "output": "4\n9 8 9 8" }, { "input": "14\n15 11 1 16 12 10 8 2 13 14 10 8 2 18", "output": "4...
46
0
0
163,259
547
Mike and Friends
[ "data structures", "string suffix structures", "strings", "trees" ]
null
null
What-The-Fatherland is a strange country! All phone numbers there are strings consisting of lowercase English letters. What is double strange that a phone number can be associated with several bears! In that country there is a rock band called CF consisting of *n* bears (including Mike) numbered from 1 to *n*. Phone number of *i*-th member of CF is *s**i*. May 17th is a holiday named Phone Calls day. In the last Phone Calls day, everyone called all the numbers that are substrings of his/her number (one may call some number several times). In particular, everyone called himself (that was really strange country). Denote as *call*(*i*,<=*j*) the number of times that *i*-th member of CF called the *j*-th member of CF. The geek Mike has *q* questions that he wants to ask you. In each question he gives you numbers *l*,<=*r* and *k* and you should tell him the number
The first line of input contains integers *n* and *q* (1<=≀<=*n*<=≀<=2<=Γ—<=105 and 1<=≀<=*q*<=≀<=5<=Γ—<=105). The next *n* lines contain the phone numbers, *i*-th line contains a string *s**i* consisting of lowercase English letters (). The next *q* lines contain the information about the questions, each of them contains integers *l*,<=*r* and *k* (1<=≀<=*l*<=≀<=*r*<=≀<=*n* and 1<=≀<=*k*<=≀<=*n*).
Print the answer for each question in a separate line.
[ "5 5\na\nab\nabab\nababab\nb\n1 5 1\n3 5 1\n1 5 2\n1 5 3\n1 4 5\n" ]
[ "7\n5\n6\n3\n6\n" ]
none
[ { "input": "5 5\na\nab\nabab\nababab\nb\n1 5 1\n3 5 1\n1 5 2\n1 5 3\n1 4 5", "output": "7\n5\n6\n3\n6" }, { "input": "5 10\nudo\nwzb\nlt\ny\ns\n3 4 2\n1 2 1\n5 5 1\n3 5 5\n1 2 5\n4 4 1\n2 4 5\n5 5 5\n1 3 5\n4 5 1", "output": "0\n1\n0\n1\n0\n0\n0\n1\n0\n0" }, { "input": "1 1\na\n1 1 1", ...
3,000
4,608,000
0
163,627
812
Sagheer and Apple Tree
[ "games", "trees" ]
null
null
Sagheer is playing a game with his best friend Soliman. He brought a tree with *n* nodes numbered from 1 to *n* and rooted at node 1. The *i*-th node has *a**i* apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length). Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses. In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: 1. eat the apples, if the node is a leaf. 1. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes *u* and *v* and swap the apples of *u* with the apples of *v*. Can you help Sagheer count the number of ways to make the swap (i.e. to choose *u* and *v*) after which he will win the game if both players play optimally? (*u*,<=*v*) and (*v*,<=*u*) are considered to be the same pair.
The first line will contain one integer *n* (2<=≀<=*n*<=≀<=105) β€” the number of nodes in the apple tree. The second line will contain *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=107) β€” the number of apples on each node of the tree. The third line will contain *n*<=-<=1 integers *p*2,<=*p*3,<=...,<=*p**n* (1<=≀<=*p**i*<=≀<=*n*) β€” the parent of each node of the tree. Node *i* has parent *p**i* (for 2<=≀<=*i*<=≀<=*n*). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
On a single line, print the number of different pairs of nodes (*u*,<=*v*), *u*<=β‰ <=*v* such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (*u*,<=*v*) and (*v*,<=*u*) are considered to be the same pair.
[ "3\n2 2 3\n1 1\n", "3\n1 2 3\n1 1\n", "8\n7 2 2 5 4 3 1 1\n1 1 1 4 4 5 6\n" ]
[ "1\n", "0\n", "4\n" ]
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move. In the second sample, There is no swap that will make Sagheer win the game. Note that Sagheer must make the swap even if he can win with the initial tree.
[ { "input": "3\n2 2 3\n1 1", "output": "1" }, { "input": "3\n1 2 3\n1 1", "output": "0" }, { "input": "8\n7 2 2 5 4 3 1 1\n1 1 1 4 4 5 6", "output": "4" }, { "input": "6\n7 7 7 7 7 7\n1 1 1 1 1", "output": "0" }, { "input": "6\n3 1 1 1 2 2\n1 1 1 1 1", "output"...
93
307,200
0
163,895
778
Selling Numbers
[ "dp", "sortings" ]
null
null
Boris really likes numbers and even owns a small shop selling interesting numbers. He has *n* decimal numbers *B**i*. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values *c**d*, where *c**d* is the cost of the digit *d*. Of course, Boris is interested in that numbers he owns have the maximum cost possible. Recently Boris got hold of the magical artifact *A*, which can allow him to increase the cost of his collection. Artifact is a string, consisting of digits and '?' symbols. To use the artifact, Boris must replace all '?' with digits to get a decimal number without leading zeros (it is also not allowed to get number 0). After that, the resulting number is added to all numbers *B**i* in Boris' collection. He uses the artifact exactly once. What is the maximum cost of the collection Boris can achieve after using the artifact?
First line contains artifact *A*, consisting of digits '0'–'9' and '?' symbols (1<=≀<=|*A*|<=≀<=1000). Next line contains *n*Β β€” the amount of numbers in Boris' collection (1<=≀<=*n*<=≀<=1000). Next *n* lines contain integers *B**i* (1<=≀<=*B**i*<=&lt;<=101000). *A* doesn't start with '0'. Last line contains ten integersΒ β€” costs of digits *c*0,<=*c*1,<=...,<=*c*9 (0<=≀<=*c**i*<=≀<=1000).
Output one integerΒ β€” the maximum possible cost of the collection after using the artifact.
[ "42\n3\n89\n1\n958\n0 0 1 1 2 2 3 3 4 4\n", "?5?\n4\n2203\n5229\n276\n6243\n2 1 6 1 1 2 5 2 2 3\n" ]
[ "4\n", "62\n" ]
In the second sample input, the optimal way is to compose the number 453. After adding this number, Boris will have numbers 2656, 5682, 729 and 6696. The total cost of all digits in them is equal to 18 + 15 + 11 + 18 = 62.
[ { "input": "42\n3\n89\n1\n958\n0 0 1 1 2 2 3 3 4 4", "output": "4" }, { "input": "?5?\n4\n2203\n5229\n276\n6243\n2 1 6 1 1 2 5 2 2 3", "output": "62" }, { "input": "7\n1\n3\n8 1 5 4 7 8 4 7 5 5", "output": "9" }, { "input": "??\n15\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n...
15
0
-1
164,939
617
Watering Flowers
[ "implementation" ]
null
null
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values *r*1(*r*1<=β‰₯<=0) and *r*2(*r*2<=β‰₯<=0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such *r*1 and *r*2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed *r*1, or the distance to the second fountain doesn't exceed *r*2. It's OK if some flowers are watered by both fountains. You need to decrease the amount of water you need, that is set such *r*1 and *r*2 that all the flowers are watered and the *r*12<=+<=*r*22 is minimum possible. Find this minimum value.
The first line of the input contains integers *n*, *x*1, *y*1, *x*2, *y*2 (1<=≀<=*n*<=≀<=2000, <=-<=107<=≀<=*x*1,<=*y*1,<=*x*2,<=*y*2<=≀<=107)Β β€” the number of flowers, the coordinates of the first and the second fountain. Next follow *n* lines. The *i*-th of these lines contains integers *x**i* and *y**i* (<=-<=107<=≀<=*x**i*,<=*y**i*<=≀<=107)Β β€” the coordinates of the *i*-th flower. It is guaranteed that all *n*<=+<=2 points in the input are distinct.
Print the minimum possible value *r*12<=+<=*r*22. Note, that in this problem optimal answer is always integer.
[ "2 -1 0 5 3\n0 2\n5 2\n", "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4\n" ]
[ "6\n", "33\n" ]
The first sample is (*r*<sub class="lower-index">1</sub><sup class="upper-index">2</sup> = 5, *r*<sub class="lower-index">2</sub><sup class="upper-index">2</sup> = 1): <img class="tex-graphics" src="https://espresso.codeforces.com/15e780f508832a19b14698dd8eb54b4c0dd131bf.png" style="max-width: 100.0%;max-height: 100.0%;"/> The second sample is (*r*<sub class="lower-index">1</sub><sup class="upper-index">2</sup> = 1, *r*<sub class="lower-index">2</sub><sup class="upper-index">2</sup> = 32): <img class="tex-graphics" src="https://espresso.codeforces.com/da4dc31002cc9b37092d64035ab56ad8544c0d7b.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "2 -1 0 5 3\n0 2\n5 2", "output": "6" }, { "input": "4 0 0 5 0\n9 4\n8 3\n-1 0\n1 4", "output": "33" }, { "input": "5 -6 -4 0 10\n-7 6\n-9 7\n-5 -1\n-2 1\n-8 10", "output": "100" }, { "input": "10 -68 10 87 22\n30 89\n82 -97\n-52 25\n76 -22\n-20 95\n21 25\n2 -3\n45...
46
0
0
165,241
371
Subway Innovation
[ "greedy", "math", "two pointers" ]
null
null
Berland is going through tough times β€” the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter! The President of Berland was forced to leave only *k* of the currently existing *n* subway stations. The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the *Ox* axis, the *i*-th station is at point with coordinate *x**i*. In such case the distance between stations *i* and *j* is calculated by a simple formula |*x**i*<=-<=*x**j*|. Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such *k* stations that minimize the average commute time in the subway! Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train. Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such *k* stations that the average commute time in the subway is minimized.
The first line of the input contains integer *n* (3<=≀<=*n*<=≀<=3Β·105) β€” the number of the stations before the innovation. The second line contains the coordinates of the stations *x*1,<=*x*2,<=...,<=*x**n* (<=-<=108<=≀<=*x**i*<=≀<=108). The third line contains integer *k* (2<=≀<=*k*<=≀<=*n*<=-<=1) β€” the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.
Print a sequence of *k* distinct integers *t*1,<=*t*2,<=...,<=*t**k* (1<=≀<=*t**j*<=≀<=*n*) β€” the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through *n* in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose *k* stations. If there are multiple such ways, you are allowed to print any of them.
[ "3\n1 100 101\n2\n" ]
[ "2 3 " ]
In the sample testcase the optimal answer is to destroy the first station (with *x* = 1). The average commute time will be equal to 1 in this way.
[ { "input": "3\n1 100 101\n2", "output": "2 3 " }, { "input": "5\n11 21 30 40 50\n3", "output": "1 2 3 " }, { "input": "3\n0 -4 -3\n2", "output": "2 3 " }, { "input": "4\n5 -7 8 1\n2", "output": "1 3 " }, { "input": "5\n-4 -2 10 -9 -10\n2", "output": "5 4 " }...
15
0
0
165,560
53
Dead Ends
[ "bitmasks", "dp" ]
E. Dead Ends
5
256
Life in Bertown has become hard. The city has too many roads and the government spends too much to maintain them. There are *n* junctions and *m* two way roads, at which one can get from each junction to any other one. The mayor wants to close some roads so that the number of roads left totaled to *n*<=-<=1 roads and it were still possible to get from each junction to any other one. Besides, the mayor is concerned with the number of dead ends which are the junctions from which only one road goes. There shouldn't be too many or too few junctions. Having discussed the problem, the mayor and his assistants decided that after the roads are closed, the road map should contain exactly *k* dead ends. Your task is to count the number of different ways of closing the roads at which the following conditions are met: - There are exactly *n*<=-<=1 roads left. - It is possible to get from each junction to any other one. - There are exactly *k* dead ends on the resulting map. Two ways are considered different if there is a road that is closed in the first way, and is open in the second one.
The first line contains three integers *n*, *m* and *k* (3<=≀<=*n*<=≀<=10,<=*n*<=-<=1<=≀<=*m*<=≀<=*n*Β·(*n*<=-<=1)<=/<=2,<=2<=≀<=*k*<=≀<=*n*<=-<=1) which represent the number of junctions, roads and dead ends correspondingly. Then follow *m* lines each containing two different integers *v*1 and *v*2 (1<=≀<=*v*1,<=*v*2<=≀<=*n*,<=*v*1<=β‰ <=*v*2) which represent the number of junctions connected by another road. There can be no more than one road between every pair of junctions. The junctions are numbered with integers from 1 to *n*. It is guaranteed that it is possible to get from each junction to any other one along the original roads.
Print a single number β€” the required number of ways.
[ "3 3 2\n1 2\n2 3\n1 3\n", "4 6 2\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n", "4 6 3\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4\n" ]
[ "3\n", "12\n", "4\n" ]
none
[ { "input": "3 3 2\n1 2\n2 3\n1 3", "output": "3" }, { "input": "4 6 2\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4", "output": "12" }, { "input": "4 6 3\n1 2\n2 3\n3 4\n4 1\n1 3\n2 4", "output": "4" }, { "input": "5 4 3\n2 1\n5 3\n3 2\n1 4", "output": "0" }, { "input": "5 10 2\n...
374
7,270,400
3.949058
165,945
354
Transferring Pyramid
[ "dp" ]
null
null
Vasya and Petya are using an interesting data storing structure: a pyramid. The pyramid consists of *n* rows, the *i*-th row contains *i* cells. Each row is shifted half a cell to the left relative to the previous row. The cells are numbered by integers from 1 to as shown on the picture below. An example of a pyramid at *n*<==<=5 is: This data structure can perform operations of two types: 1. Change the value of a specific cell. It is described by three integers: "*t* *i* *v*", where *t*<==<=1 (the type of operation), *i* β€” the number of the cell to change and *v* the value to assign to the cell. 1. Change the value of some subpyramid. The picture shows a highlighted subpyramid with the top in cell 5. It is described by *s*<=+<=2 numbers: "*t* *i* *v*1 *v*2 ... *v**s*", where *t*<==<=2, *i* β€” the number of the top cell of the pyramid, *s* β€” the size of the subpyramid (the number of cells it has), *v**j* β€” the value you should assign to the *j*-th cell of the subpyramid. Formally: a subpyramid with top at the *i*-th cell of the *k*-th row (the 5-th cell is the second cell of the third row) will contain cells from rows from *k* to *n*, the (*k*<=+<=*p*)-th row contains cells from the *i*-th to the (*i*<=+<=*p*)-th (0<=≀<=*p*<=≀<=*n*<=-<=*k*). Vasya and Petya had two identical pyramids. Vasya changed some cells in his pyramid and he now wants to send his changes to Petya. For that, he wants to find a sequence of operations at which Petya can repeat all Vasya's changes. Among all possible sequences, Vasya has to pick the minimum one (the one that contains the fewest numbers). You have a pyramid of *n* rows with *k* changed cells. Find the sequence of operations which result in each of the *k* changed cells being changed by at least one operation. Among all the possible sequences pick the one that contains the fewest numbers.
The first line contains two integers *n* and *k* (1<=≀<=*n*,<=*k*<=≀<=105). The next *k* lines contain the coordinates of the modified cells *r**i* and *c**i* (1<=≀<=*c**i*<=≀<=*r**i*<=≀<=*n*) β€” the row and the cell's number in the row. All cells are distinct.
Print a single number showing how many numbers the final sequence has.
[ "4 5\n3 1\n3 3\n4 1\n4 3\n4 4\n", "7 11\n2 2\n3 1\n4 3\n5 1\n5 2\n5 5\n6 4\n7 2\n7 3\n7 4\n7 5\n" ]
[ "10\n", "26\n" ]
One of the possible solutions of the first sample consists of two operations: 2 4 *v*<sub class="lower-index">4</sub> *v*<sub class="lower-index">7</sub> *v*<sub class="lower-index">8</sub> 2 6 *v*<sub class="lower-index">6</sub> *v*<sub class="lower-index">9</sub> *v*<sub class="lower-index">10</sub> The picture shows the changed cells color-highlighted. The subpyramid used by the first operation is highlighted blue and the subpyramid used by the first operation is highlighted yellow:
[ { "input": "4 5\n3 1\n3 3\n4 1\n4 3\n4 4", "output": "10" }, { "input": "7 11\n2 2\n3 1\n4 3\n5 1\n5 2\n5 5\n6 4\n7 2\n7 3\n7 4\n7 5", "output": "26" }, { "input": "2 3\n1 1\n2 1\n2 2", "output": "5" }, { "input": "10 15\n2 1\n3 2\n4 1\n4 2\n4 3\n5 5\n7 6\n7 7\n8 2\n8 6\n9 7\...
1,263
268,390,400
0
166,036
830
Perpetual Motion Machine
[ "constructive algorithms", "dp", "graphs", "implementation", "math", "trees" ]
null
null
Developer Petr thinks that he invented a perpetual motion machine. Namely, he has a lot of elements, which work in the following way. Each element has one controller that can be set to any non-negative real value. If a controller is set on some value *x*, then the controller consumes *x*2 energy units per second. At the same time, any two elements connected by a wire produce *y*Β·*z* energy units per second, where *y* and *z* are the values set on their controllers. Petr has only a limited number of wires, so he has already built some scheme of elements and wires, and is now interested if it's possible to set the controllers in such a way that the system produces at least as much power as it consumes, and at least one controller is set on the value different from 0. Help him check this, and if it's possible, find the required integer values that should be set. It is guaranteed that if there exist controllers' settings satisfying the above conditions, then there exist required integer values not greater than 106.
There are several (at least one) test cases in the input. The first line contains single integerΒ β€” the number of test cases. There is an empty line before each test case. The first line of test case contains two integers *n* and *m* (1<=≀<=*n*<=≀<=105, 0<=≀<=*m*<=≀<=105)Β β€” the number of elements in the scheme and the number of wires. After that, *m* lines follow, each of them contains two integers *a* and *b* (1<=≀<=*a*,<=*b*<=≀<=*n*)Β β€” two elements connected by a wire. No element is connected with itself, no two elements are connected by more than one wire. It is guaranteed that the sum of *n* and the sum of *m* over all test cases do not exceed 105. For hacks you can only use tests with one test case.
Print answer for each test case. For each test case print "YES" if it's possible to set the controllers in such a way that the consumed power is not greater than the power produced, and the required values on the next line. The settings should be integers from 0 to 106, inclusive, and at least one value should be different from 0. If there are multiple answers, print any of them. If it's not possible to set the controllers in the required way, print one line "NO".
[ "4\nΒ \n4 4\n1 2\n2 3\n3 4\n4 2\nΒ \n3 2\n2 3\n3 1\nΒ \n4 6\n1 2\n3 4\n4 2\n1 4\n1 3\n3 2\nΒ \n10 9\n2 1\n3 2\n5 2\n6 2\n2 7\n2 8\n2 9\n2 10\n4 2\n" ]
[ "YES\n1 2 2 1\nNO\nYES\n1 1 1 1\nYES\n1 5 1 1 1 1 1 1 1 1\n" ]
In the first example it's possible to set the controllers in the required way, for example, in the following way: set 1 on the first element, set 2 on the second and on the third, set 1 on the fourth. The consumed power is then equal to 1<sup class="upper-index">2</sup> + 2<sup class="upper-index">2</sup> + 2<sup class="upper-index">2</sup> + 1<sup class="upper-index">2</sup> = 10 energy units per second, the produced power is equal to 1Β·2 + 2Β·2 + 2Β·1 + 2Β·1 = 10 energy units per second. Thus the answer is "YES". In the second test case it's not possible to set the controllers in the required way. For example, if we set all controllers to 0.5, then the consumed powers equals 0.75 energy units per second, while produced power equals 0.5 energy units per second.
[]
31
0
0
166,103
185
Visit of the Great
[ "math", "number theory" ]
null
null
The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King. We know that only *LCM*(*k*2*l*<=+<=1,<=*k*2*l*<=+<=1<=+<=1,<=...,<=*k*2*r*<=+<=1) dwarves can see the Great Mushroom King. Numbers *k*, *l*, *r* are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves. The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers *k**i*, *l**i*, *r**i*, chosen by the Great Mushroom King for this visit. They also know a prime number *p**i*. Help them to count the remainder of dividing the number of dwarves who can see the King, by number *p**i*, for each visit.
The first line contains the single integer *t* (1<=≀<=*t*<=≀<=105) β€” the number of the King's visits. Each of the following *t* input lines contains four space-separated integers *k**i*, *l**i*, *r**i* and *p**i* (1<=≀<=*k**i*<=≀<=106;Β 0<=≀<=*l**i*<=≀<=*r**i*<=≀<=1018;Β 2<=≀<=*p**i*<=≀<=109) β€” the numbers, chosen by the Great Mushroom King and the prime module, correspondingly. It is guaranteed that for all visits number *p**i* is prime. 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.
For each visit print the answer on a single line β€” the remainder of dividing the number of the dwarves who can see the King this time, by number *p**i*. Print the answers for the visits in the order, in which the visits are described in the input.
[ "2\n3 1 10 2\n5 0 4 3\n" ]
[ "0\n0\n" ]
We consider that *LCM*(*a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*n*</sub>) represents the least common multiple of numbers *a*<sub class="lower-index">1</sub>, *a*<sub class="lower-index">2</sub>, ..., *a*<sub class="lower-index">*n*</sub>. We consider that *x*<sup class="upper-index">0</sup> = 1, for any *x*.
[]
3,000
180,736,000
0
166,391
316
Tidying Up
[ "flows" ]
null
null
Smart Beaver is careful about his appearance and pays special attention to shoes so he has a huge number of pairs of shoes from the most famous brands of the forest. He's trying to handle his shoes carefully so that each pair stood side by side. But by the end of the week because of his very active lifestyle in his dressing room becomes a mess. Smart Beaver from ABBYY is not only the brightest beaver in the area, but he also is the most domestically oriented. For example, on Mondays the Smart Beaver cleans everything in his home. It's Monday morning. Smart Beaver does not want to spend the whole day cleaning, besides, there is much in to do and it’s the gym day, so he wants to clean up as soon as possible. Now the floors are washed, the dust is wiped off β€” it’s time to clean up in the dressing room. But as soon as the Smart Beaver entered the dressing room, all plans for the day were suddenly destroyed: chaos reigned there and it seemed impossible to handle, even in a week. Give our hero some hope: tell him what is the minimum number of shoes need to change the position to make the dressing room neat. The dressing room is rectangular and is divided into *n*<=Γ—<=*m* equal squares, each square contains exactly one shoe. Each pair of shoes has a unique number that is integer from 1 to , more formally, a square with coordinates (*i*,<=*j*) contains an integer number of the pair which is lying on it. The Smart Beaver believes that the dressing room is neat only when each pair of sneakers lies together. We assume that the pair of sneakers in squares (*i*1,<=*j*1) and (*i*2,<=*j*2) lies together if |*i*1<=-<=*i*2|<=+<=|*j*1<=-<=*j*2|<==<=1.
The first line contains two space-separated integers *n* and *m*. They correspond to the dressing room size. Next *n* lines contain *m* space-separated integers each. Those numbers describe the dressing room. Each number corresponds to a snicker. It is guaranteed that: - *n*Β·*m* is even. - All numbers, corresponding to the numbers of pairs of shoes in the dressing room, will lie between 1 and . - Each number from 1 to will occur exactly twice. The input limits for scoring 30 points are (subproblem C1): - 2<=≀<=*n*,<=*m*<=≀<=8. The input limits for scoring 100 points are (subproblems C1+C2): - 2<=≀<=*n*,<=*m*<=≀<=80.
Print exactly one integer β€” the minimum number of the sneakers that need to change their location.
[ "2 3\n1 1 2\n2 3 3\n", "3 4\n1 3 2 6\n2 1 5 6\n4 4 5 3\n" ]
[ "2\n", "4\n" ]
[ { "input": "2 3\n1 1 2\n2 3 3", "output": "2" }, { "input": "3 4\n1 3 2 6\n2 1 5 6\n4 4 5 3", "output": "4" }, { "input": "2 2\n1 2\n1 2", "output": "0" }, { "input": "2 2\n1 1\n2 2", "output": "0" }, { "input": "2 2\n2 1\n1 2", "output": "2" }, { "inp...
248
8,499,200
3
167,971
331
Shave Beaver!
[ "implementation" ]
null
null
The Smart Beaver has recently designed and built an innovative nanotechnologic all-purpose beaver mass shaving machine, "Beavershave 5000". Beavershave 5000 can shave beavers by families! How does it work? Very easily! There are *n* beavers, each of them has a unique id from 1 to *n*. Consider a permutation *a*1,<=*a*2,<=...,<=*a**n* of *n* these beavers. Beavershave 5000 needs one session to shave beavers with ids from *x* to *y* (inclusive) if and only if there are such indices *i*1<=&lt;<=*i*2<=&lt;<=...<=&lt;<=*i**k*, that *a**i*1<==<=*x*, *a**i*2<==<=*x*<=+<=1, ..., *a**i**k*<=-<=1<==<=*y*<=-<=1, *a**i**k*<==<=*y*. And that is really convenient. For example, it needs one session to shave a permutation of beavers 1,<=2,<=3,<=...,<=*n*. If we can't shave beavers from *x* to *y* in one session, then we can split these beavers into groups [*x*,<=*p*1], [*p*1<=+<=1,<=*p*2], ..., [*p**m*<=+<=1,<=*y*] (*x*<=≀<=*p*1<=&lt;<=*p*2<=&lt;<=...<=&lt;<=*p**m*<=&lt;<=*y*), in such a way that the machine can shave beavers in each group in one session. But then Beavershave 5000 needs *m*<=+<=1 working sessions to shave beavers from *x* to *y*. All beavers are restless and they keep trying to swap. So if we consider the problem more formally, we can consider queries of two types: - what is the minimum number of sessions that Beavershave 5000 needs to shave beavers with ids from *x* to *y*, inclusive? - two beavers on positions *x* and *y* (the beavers *a**x* and *a**y*) swapped. You can assume that any beaver can be shaved any number of times.
The first line contains integer *n* β€” the total number of beavers, 2<=≀<=*n*. The second line contains *n* space-separated integers β€” the initial beaver permutation. The third line contains integer *q* β€” the number of queries, 1<=≀<=*q*<=≀<=105. The next *q* lines contain the queries. Each query *i* looks as *p**i* *x**i* *y**i*, where *p**i* is the query type (1 is to shave beavers from *x**i* to *y**i*, inclusive, 2 is to swap beavers on positions *x**i* and *y**i*). All queries meet the condition: 1<=≀<=*x**i*<=&lt;<=*y**i*<=≀<=*n*. - to get 30 points, you need to solve the problem with constraints: *n*<=≀<=100 (subproblem B1); - to get 100 points, you need to solve the problem with constraints: *n*<=≀<=3Β·105 (subproblems B1+B2). Note that the number of queries *q* is limited 1<=≀<=*q*<=≀<=105 in both subproblem B1 and subproblem B2.
For each query with *p**i*<==<=1, print the minimum number of Beavershave 5000 sessions.
[ "5\n1 3 4 2 5\n6\n1 1 5\n1 3 4\n2 2 3\n1 1 5\n2 1 5\n1 1 5\n" ]
[ "2\n1\n3\n5\n" ]
none
[]
937
0
0
168,002
432
Square Tiling
[ "constructive algorithms", "greedy" ]
null
null
You have an *n*<=Γ—<=*m* rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: - each cell must be painted some color (the colors are marked by uppercase Latin letters); - we will assume that two cells of the table are connected if they are of the same color and share a side; each connected region of the table must form a square. Given *n* and *m*, find lexicographically minimum coloring of the table that meets the described properties.
The first line contains two integers, *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=100).
Print lexicographically minimum coloring of the table that meets the described conditions. One coloring (let's call it X) is considered lexicographically less than the other one (let's call it Y), if: - consider all the table cells from left to right and from top to bottom (first, the first cell in the first row, then the second cell in the first row and so on); - let's find in this order the first cell that has distinct colors in two colorings; - the letter that marks the color of the cell in X, goes alphabetically before the letter that marks the color of the cell in Y.
[ "1 3\n", "2 2\n", "3 4\n" ]
[ "ABA\n", "AA\nAA\n", "AAAB\nAAAC\nAAAB\n" ]
none
[]
61
0
0
168,013
229
Gifts
[ "combinatorics", "dp", "math", "probabilities" ]
null
null
Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with *n* gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for *n* names of items from the list. If the fish's list has *p* occurrences of the given name, then the old man can't ask for this name of item more than *p* times. The old man knows that if he asks for *s* gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose *s* gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the *n* names in such a way that he can get *n* gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly. The old man wondered, what is the probability that he can get *n* most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.
The first line contains two space-separated integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=1000) β€” the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then *m* lines follow: the *i*-th line first contains integer *k**i* (*k**i*<=&gt;<=0)Β β€” the number of distinct prices of gifts with the *i*-th name, then *k**i* distinct space-separated integers *c**ij* (1<=≀<=*c**ij*<=≀<=109), the gifts' prices. It is guaranteed that the sum of all *k**i* doesn't exceed 1000. It is guaranteed that *n* is not greater than the total number of the gifts.
On a single line print one real number β€” the probability of getting *n* most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10<=-<=9.
[ "3 1\n3 10 20 30\n", "3 2\n1 40\n4 10 20 30 40\n" ]
[ "1.000000000\n", "0.166666667\n" ]
none
[]
30
0
0
168,818
578
Walking!
[ "constructive algorithms", "greedy" ]
null
null
There is a sand trail in front of Alice's home. In daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walking by alternating left foot and right foot. For example, suppose that one person walked through the trail and left some footprints. The footprints are RRLRL in order along the trail ('R' means right foot and 'L' means left foot). You might think the outcome of the footprints is strange. But in fact, some steps are resulting from walking backwards! There are some possible order of steps that produce these footprints such as 1<=β†’<=3<=β†’<=2<=β†’<=5<=β†’<=4 or 2<=β†’<=3<=β†’<=4<=β†’<=5<=β†’<=1 (we suppose that the distance between two consecutive steps can be arbitrarily long). The number of backward steps from above two examples are 2 and 1 separately. Alice is interested in these footprints. Whenever there is a person walking trough the trail, she takes a picture of all these footprints along the trail and erase all of them so that next person will leave a new set of footprints. We know that people walk by alternating right foot and left foot, but we don't know if the first step is made by left foot or right foot. Alice wants to know the minimum possible number of backward steps made by a person. But it's a little hard. Please help Alice to calculate it. You also need to construct one possible history of these footprints.
Only one line containing the string *S* (1<=≀<=|*S*|<=≀<=100<=000) containing all footprints in order along the trail from entrance to exit. It is guaranteed that there is at least one possible footprint history.
You should output 2 lines. The first line should contain a number denoting the minimum number of backward steps. The second line should contain a permutation of integers from 1 to |*S*|. This permutation should denote the order of footprints that may possible be used by person walked there. If there are several possible answers, you may output any of them.
[ "RRLRL\n", "RLRLRLRLR\n", "RRRRRLLLL\n" ]
[ "1\n2 5 1 3 4\n", "0\n1 2 3 4 5 6 7 8 9\n", "4\n4 9 3 8 2 7 1 6 5\n" ]
For the first sample, one possible order is 2 → 5 → 1 → 3 → 4, among them only the step 5 → 1 is backward step so the answer is 1. For the second example one possible order is just to follow the order of input, thus there are no backward steps. For the third sample, there will be 4 backward steps because every step from L to R will be a backward step.
[ { "input": "RRLRL", "output": "1\n2 5 1 3 4" }, { "input": "RLRLRLRLR", "output": "0\n1 2 3 4 5 6 7 8 9" }, { "input": "RRRRRLLLL", "output": "4\n4 9 3 8 2 7 1 6 5" }, { "input": "RRLLRRRRLLRRLLRRLLLLRRLL", "output": "3\n8 14 16 20 7 13 15 19 2 4 6 10 12 18 22 24 1 3 5 9 ...
61
307,200
0
168,902
507
Breaking Good
[ "dfs and similar", "dp", "graphs", "shortest paths" ]
null
null
Breaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers. Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of *n* cities with *m* bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning. The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city *n*. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan. First of all the path which they are going to use on their way back from city 1 to their headquarters *n* must be as short as possible, since it is important to finish operation as fast as possible. Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation. Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired). Can you help Walter complete his task and gain the gang's trust?
The first line of input contains two integers *n*,<=*m* (2<=≀<=*n*<=≀<=105, ), the number of cities and number of roads respectively. In following *m* lines there are descriptions of roads. Each description consists of three integers *x*,<=*y*,<=*z* (1<=≀<=*x*,<=*y*<=≀<=*n*, ) meaning that there is a road connecting cities number *x* and *y*. If *z*<==<=1, this road is working, otherwise it is not.
In the first line output one integer *k*, the minimum possible number of roads affected by gang. In the following *k* lines output three integers describing roads that should be affected. Each line should contain three integers *x*,<=*y*,<=*z* (1<=≀<=*x*,<=*y*<=≀<=*n*, ), cities connected by a road and the new state of a road. *z*<==<=1 indicates that the road between cities *x* and *y* should be repaired and *z*<==<=0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from *z*. After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and *n*. If there are multiple optimal answers output any.
[ "2 1\n1 2 0\n", "4 4\n1 2 1\n1 3 0\n2 3 1\n3 4 1\n", "8 9\n1 2 0\n8 3 0\n2 3 1\n1 4 1\n8 7 0\n1 5 1\n4 6 1\n5 7 0\n6 8 0\n" ]
[ "1\n1 2 1\n", "3\n1 2 0\n1 3 1\n2 3 0\n", "3\n2 3 0\n1 5 0\n6 8 1\n" ]
In the first test the only path is 1 - 2 In the second test the only shortest path is 1 - 3 - 4 In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8
[ { "input": "2 1\n1 2 0", "output": "1\n1 2 1" }, { "input": "4 4\n1 2 1\n1 3 0\n2 3 1\n3 4 1", "output": "3\n1 2 0\n1 3 1\n2 3 0" }, { "input": "8 9\n1 2 0\n8 3 0\n2 3 1\n1 4 1\n8 7 0\n1 5 1\n4 6 1\n5 7 0\n6 8 0", "output": "3\n2 3 0\n1 5 0\n6 8 1" }, { "input": "9 10\n1 2 0\...
46
0
0
169,366
77
Domino Carpet
[ "dp", "implementation" ]
D. Domino Carpet
2
256
...Mike the TV greets you again! Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you! This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other things ... Having watched the commercial, virus Hexadecimal also wanted to get a Domino Carpet and wanted badly to be photographed in front of it. But of course, a virus will never consent to buying a licensed Carpet! So she ordered a truck of dominoes and decided to make such a Carpet herself. The original Domino Carpet is a field of squares *n*<=Γ—<=*m* in size. Each square is half of a domino, and can be rotated either vertically or horizontally, independently from its neighbors. Vertically rotated domino halves look like this: And horizontally rotated halves look like this: Notice, that some halves looks the same in both rotations, but other halves differ. Dominoes bought by Hexadecimal are represented by uncuttable chips 1<=Γ—<=2 in size, which can be laid either vertically or horizontally. If the chip is laid vertically, then both of it's halves should be laid vertically orientated; if the chip is laid horizontally, then both of it's halves should be laid horizontally. The samples of valid and invalid dominoes laid vertically and horizontally are: Virus Hexadecimal assembles her own Domino Carpet so that the following conditions are satisfied: - each carpet square is covered by a domino chip, i.e. there are no empty squares; - all domino chips lie entirely within the carpet and don't overlap with each other; - if there is a horizontal domino chip with its left half in column *j* then there are no horizontal domino chips with their left halves in columns *j*<=-<=1 or *j*<=+<=1. Before starting to assemble her own Domino Carpet, the virus wants to know the number of ways to achieve the intended purpose modulo 109<=+<=7. You can assume that the virus has an infinitely large number of dominoes of each type.
The first line contains two integers *n* and *m*, separated by a space β€” the size of the Domino Carpet (1<=≀<=*n*,<=*m*<=≀<=250). Next 4*n*<=+<=1 lines contain 4*m*<=+<=1 symbols. Each square of the Domino Carpet, which is a domino half, is described by a 3<=Γ—<=3 square. Symbol 'O' in this square indicates the presence of a point, symbol '.' β€” its absence. Each 3<=Γ—<=3 square is delineated from adjacent squares by symbols '#' as shown in the examples. It is guaranteed that every box describes the correct half of a domino. In all pretests the Domino Carpets have the size of 2<=Γ—<=2 and 4<=Γ—<=4.
Print a single number, the number of ways to assemble the Domino Carpet modulo 109<=+<=7, using only standard dominoes of size 1<=Γ—<=2.
[ "3 4\n#################\n#O..#...#O.O#...#\n#.O.#.O.#.O.#...#\n#..O#...#O.O#...#\n#################\n#O.O#OOO#O.O#...#\n#.O.#...#...#.O.#\n#O.O#OOO#O.O#...#\n#################\n#O.O#...#O.O#...#\n#...#...#...#.O.#\n#O.O#...#O.O#...#\n#################\n", "2 2\n#########\n#O.O#O.O#\n#.O.#...#\n#O.O#O.O#\n########...
[ "3", "2", "0" ]
A note to the first example: all correct ways to make Domino Carpet are represented below: And this way is incorrect:
[ { "input": "3 4\n#################\n#O..#...#O.O#...#\n#.O.#.O.#.O.#...#\n#..O#...#O.O#...#\n#################\n#O.O#OOO#O.O#...#\n#.O.#...#...#.O.#\n#O.O#OOO#O.O#...#\n#################\n#O.O#...#O.O#...#\n#...#...#...#.O.#\n#O.O#...#O.O#...#\n#################", "output": "3" }, { "input": "2 2\n#...
92
0
0
169,472
549
Yura and Developers
[ "data structures", "divide and conquer" ]
null
null
Yura has a team of *k* developers and a list of *n* tasks numbered from 1 to *n*. Yura is going to choose some tasks to be done this week. Due to strange Looksery habits the numbers of chosen tasks should be a segment of consecutive integers containing no less than 2 numbers, i. e. a sequence of form *l*,<=*l*<=+<=1,<=...,<=*r* for some 1<=≀<=*l*<=&lt;<=*r*<=≀<=*n*. Every task *i* has an integer number *a**i* associated with it denoting how many man-hours are required to complete the *i*-th task. Developers are not self-confident at all, and they are actually afraid of difficult tasks. Knowing that, Yura decided to pick up a hardest task (the one that takes the biggest number of man-hours to be completed, among several hardest tasks with same difficulty level he chooses arbitrary one) and complete it on his own. So, if tasks with numbers [*l*,<=*r*] are chosen then the developers are left with *r*<=-<=*l* tasks to be done by themselves. Every developer can spend any integer amount of hours over any task, but when they are done with the whole assignment there should be exactly *a**i* man-hours spent over the *i*-th task. The last, but not the least problem with developers is that one gets angry if he works more than another developer. A set of tasks [*l*,<=*r*] is considered good if it is possible to find such a distribution of work that allows to complete all the tasks and to have every developer working for the same amount of time (amount of work performed by Yura doesn't matter for other workers as well as for him). For example, let's suppose that Yura have chosen tasks with following difficulties: *a*<==<=[1,<=2,<=3,<=4], and he has three developers in his disposal. He takes the hardest fourth task to finish by himself, and the developers are left with tasks with difficulties [1,<=2,<=3]. If the first one spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours and every task has been worked over for the required amount of time. As another example, if the first task required two hours instead of one to be completed then it would be impossible to assign the tasks in a way described above. Besides work, Yura is fond of problem solving. He wonders how many pairs (*l*,<=*r*) (1<=≀<=*l*<=&lt;<=*r*<=≀<=*n*) exists such that a segment [*l*,<=*r*] is good? Yura has already solved this problem, but he has no time to write the code. Please, help Yura and implement the solution for this problem.
The first line of input contains two positive integers: *n* and *k* (1<=≀<=*n*<=≀<=300<=000,<=1<=≀<=*k*<=≀<=1<=000<=000), the number of tasks in the list and the number of developers in Yura's disposal. The second line contains *n* integers *a**i* (1<=≀<=*a**i*<=≀<=109).
Output a single integer β€” the number of pairs (*l*,<=*r*) satisfying the conditions from the statement.
[ "4 3\n1 2 3 4\n", "4 2\n4 4 7 4\n" ]
[ "3\n", "6\n" ]
In the first sample there are three good segments: 1. [1;3] β€” the hardest task requires 3 man-hours, so there are tasks left that require 1 and 2 man-hours. A solution is to make first developer work on the first task for an hour, while second and third developers work on the second task. Each developer works exactly one hour.1. [1;4] β€” the hardest task requires 4 man-hours, so there are tasks left that require 1, 2 and 3 man-hours. If the first developer spends an hour on the first task and an hour on the third one, the second developer spends two hours on the second task and the third developer spends two hours on the third task, then they are done, since every developer worked exactly for two hours.1. [3;4] β€” the hardest task requires 4 man-hours, so there is only one task left that requires 3 man-hours. A solution is to make each developer work for an hour.
[]
0
0
-1
169,552
0
none
[ "none" ]
null
null
As you know, the most intelligent beings on the Earth are, of course, cows. This conclusion was reached long ago by the Martian aliens, as well as a number of other intelligent civilizations from outer space. Sometimes cows gather into cowavans. This seems to be seasonal. But at this time the cows become passive and react poorly to external stimuli. A cowavan is a perfect target for the Martian scientific saucer, it's time for large-scale abductions, or, as the Martians say, raids. Simply put, a cowavan is a set of cows in a row. If we number all cows in the cowavan with positive integers from 1 to *n*, then we can formalize the popular model of abduction, known as the (*a*,<=*b*)-Cowavan Raid: first they steal a cow number *a*, then number *a*<=+<=*b*, then β€” number *a*<=+<=2Β·*b*, and so on, until the number of an abducted cow exceeds *n*. During one raid the cows are not renumbered. The aliens would be happy to place all the cows on board of their hospitable ship, but unfortunately, the amount of cargo space is very, very limited. The researchers, knowing the mass of each cow in the cowavan, made *p* scenarios of the (*a*,<=*b*)-raid. Now they want to identify the following thing for each scenario individually: what total mass of pure beef will get on board of the ship. All the scenarios are independent, in the process of performing the calculations the cows are not being stolen.
The first line contains the only positive integer *n* (1<=≀<=*n*<=≀<=3Β·105) β€” the number of cows in the cowavan. The second number contains *n* positive integer *w**i*, separated by spaces, where the *i*-th number describes the mass of the *i*-th cow in the cowavan (1<=≀<=*w**i*<=≀<=109). The third line contains the only positive integer *p* β€” the number of scenarios of (*a*,<=*b*)-raids (1<=≀<=*p*<=≀<=3Β·105). Each following line contains integer parameters *a* and *b* of the corresponding scenario (1<=≀<=*a*,<=*b*<=≀<=*n*).
Print for each scenario of the (*a*,<=*b*)-raid the total mass of cows, that can be stolen using only this scenario. Please, do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is recommended to use the cin, cout streams of the %I64d specificator.
[ "3\n1 2 3\n2\n1 1\n1 2\n", "4\n2 3 5 7\n3\n1 3\n2 3\n2 2\n" ]
[ "6\n4\n", "9\n3\n10\n" ]
none
[]
30
102,400
-1
170,011
353
Antichain
[ "dp", "graph matchings", "greedy" ]
null
null
You have a directed acyclic graph *G*, consisting of *n* vertexes, numbered from 0 to *n*<=-<=1. The graph contains *n* edges numbered from 0 to *n*<=-<=1. An edge with number *i* connects vertexes *i* and (*i*<=+<=1)Β *mod*Β *n*, and it can be directed in either direction (from *i* to (*i*<=+<=1)Β *mod*Β *n*, or vise versa). Operation *x*Β *mod*Β *y* means taking the remainder after dividing number *x* by number *y*. Let's call two vertexes *u* and *v* in graph *G* comparable if the graph contains a path either from *u* to *v* or from *v* to *u*. We'll assume that an antichain is a set of vertexes of graph *G*, where any two distinct vertexes are not comparable. The size of an antichain is the number of vertexes in the corresponding set. An antichain is maximum if the graph doesn't have antichains of a larger size. Your task is to find the size of the maximum antichain in graph *G*.
The first line contains the sequence of characters *s*0*s*1... *s**n*<=-<=1 (2<=≀<=*n*<=≀<=106), consisting of numbers zero and one. The length of the line (number *n*) corresponds to the number of vertexes and edges in graph *G*. If character *s**i* (*i*<=β‰₯<=0) equals 0, then the edge between vertexes *i* and (*i*<=+<=1)Β *mod*Β *n* is directed from the *i*-th vertex to the (*i*<=+<=1)Β *mod*Β *n*-th one, otherwise β€” to the opposite point. It is guaranteed that the given graph is acyclic.
Print a single integer β€” the size of the maximum antichain of graph *G*.
[ "001\n", "110010\n" ]
[ "1\n", "3\n" ]
Consider the first test sample. The graph's *G* edges are: 0 → 1, 1 → 2, 0 → 2. We can choose the set of vertexes [0] as the maximum antichain. We cannot choose an antichain of larger size.
[ { "input": "001", "output": "1" }, { "input": "110010", "output": "3" }, { "input": "0010011110", "output": "3" }, { "input": "0111001010101110001100000010011000100101110010001100111110101110001110101010111000010010011000000110", "output": "35" }, { "input": "0110...
154
5,427,200
3
170,102
923
Perpetual Subtraction
[ "fft", "math", "matrices" ]
null
null
There is a number *x* initially written on a blackboard. You repeat the following action a fixed amount of times: 1. take the number *x* currently written on a blackboard and erase it 1. select an integer uniformly at random from the range [0,<=*x*] inclusive, and write it on the blackboard Determine the distribution of final number given the distribution of initial number and the number of steps.
The first line contains two integers, *N* (1<=≀<=*N*<=≀<=105)Β β€” the maximum number written on the blackboardΒ β€” and *M* (0<=≀<=*M*<=≀<=1018)Β β€” the number of steps to perform. The second line contains *N*<=+<=1 integers *P*0,<=*P*1,<=...,<=*P**N* (0<=≀<=*P**i*<=&lt;<=998244353), where *P**i* describes the probability that the starting number is *i*. We can express this probability as irreducible fraction *P*<=/<=*Q*, then . It is guaranteed that the sum of all *P**i*s equals 1 (modulo 998244353).
Output a single line of *N*<=+<=1 integers, where *R**i* is the probability that the final number after *M* steps is *i*. It can be proven that the probability may always be expressed as an irreducible fraction *P*<=/<=*Q*. You are asked to output .
[ "2 1\n0 0 1\n", "2 2\n0 0 1\n", "9 350\n3 31 314 3141 31415 314159 3141592 31415926 314159265 649178508\n" ]
[ "332748118 332748118 332748118\n", "942786334 610038216 443664157\n", "822986014 12998613 84959018 728107923 939229297 935516344 27254497 413831286 583600448 442738326\n" ]
In the first case, we start with number 2. After one step, it will be 0, 1 or 2 with probability 1/3 each. In the second case, the number will remain 2 with probability 1/9. With probability 1/9 it stays 2 in the first round and changes to 1 in the next, and with probability 1/6 changes to 1 in the first round and stays in the second. In all other cases the final integer is 0.
[]
46
0
0
170,132
165
Beard Graph
[ "data structures", "dsu", "trees" ]
null
null
Let's define a non-oriented connected graph of *n* vertices and *n*<=-<=1 edges as a beard, if all of its vertices except, perhaps, one, have the degree of 2 or 1 (that is, there exists no more than one vertex, whose degree is more than two). Let us remind you that the degree of a vertex is the number of edges that connect to it. Let each edge be either black or white. Initially all edges are black. You are given the description of the beard graph. Your task is to analyze requests of the following types: - paint the edge number *i* black. The edge number *i* is the edge that has this number in the description. It is guaranteed that by the moment of this request the *i*-th edge is white - paint the edge number *i* white. It is guaranteed that by the moment of this request the *i*-th edge is black - find the length of the shortest path going only along the black edges between vertices *a* and *b* or indicate that no such path exists between them (a path's length is the number of edges in it) The vertices are numbered with integers from 1 to *n*, and the edges are numbered with integers from 1 to *n*<=-<=1.
The first line of the input contains an integer *n* (2<=≀<=*n*<=≀<=105) β€” the number of vertices in the graph. Next *n*<=-<=1 lines contain edges described as the numbers of vertices *v**i*, *u**i* (1<=≀<=*v**i*,<=*u**i*<=≀<=*n*, *v**i*<=β‰ <=*u**i*) connected by this edge. It is guaranteed that the given graph is connected and forms a beard graph, and has no self-loops or multiple edges. The next line contains an integer *m* (1<=≀<=*m*<=≀<=3Β·105) β€” the number of requests. Next *m* lines contain requests in the following form: first a line contains an integer *type*, which takes values ​​from 1 to 3, and represents the request type. If *type*<==<=1, then the current request is a request to paint the edge black. In this case, in addition to number *type* the line should contain integer *id* (1<=≀<=*id*<=≀<=*n*<=-<=1), which represents the number of the edge to paint. If *type*<==<=2, then the current request is a request to paint the edge white, its form is similar to the previous request. If *type*<==<=3, then the current request is a request to find the distance. In this case, in addition to *type*, the line should contain two integers *a*, *b* (1<=≀<=*a*,<=*b*<=≀<=*n*, *a* can be equal to *b*) β€” the numbers of vertices, the distance between which must be found. The numbers in all lines are separated by exactly one space. The edges are numbered in the order in which they are given in the input.
For each request to "find the distance between vertices *a* and *b*" print the result. If there is no path going only along the black edges between vertices *a* and *b*, then print "-1" (without the quotes). Print the results in the order of receiving the requests, separate the numbers with spaces or line breaks.
[ "3\n1 2\n2 3\n7\n3 1 2\n3 1 3\n3 2 3\n2 2\n3 1 2\n3 1 3\n3 2 3\n", "6\n1 5\n6 4\n2 3\n3 5\n5 6\n6\n3 3 4\n2 5\n3 2 6\n3 1 2\n2 3\n3 3 1\n" ]
[ "1\n2\n1\n1\n-1\n-1\n", "3\n-1\n3\n2\n" ]
In the first sample vertices 1 and 2 are connected with edge number 1, and vertices 2 and 3 are connected with edge number 2. Before the repainting edge number 2 each vertex is reachable from each one along the black edges. Specifically, the shortest path between 1 and 3 goes along both edges. If we paint edge number 2 white, vertex 3 will end up cut off from other vertices, that is, no path exists from it to any other vertex along the black edges.
[ { "input": "3\n1 2\n2 3\n7\n3 1 2\n3 1 3\n3 2 3\n2 2\n3 1 2\n3 1 3\n3 2 3", "output": "1\n2\n1\n1\n-1\n-1" }, { "input": "6\n1 5\n6 4\n2 3\n3 5\n5 6\n6\n3 3 4\n2 5\n3 2 6\n3 1 2\n2 3\n3 3 1", "output": "3\n-1\n3\n2" }, { "input": "3\n2 3\n1 3\n4\n3 3 1\n3 2 2\n3 1 3\n2 2", "output": ...
3,150
92,057,600
3
170,379
234
Champions' League
[ "implementation" ]
null
null
In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world β€” the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups. The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose *n* teams will take part in the group stage (*n* is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as *m* (). Each team has a rating β€” an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating). After that four "baskets" are formed, each of which will contain *m* teams: the first *m* teams with the highest rating go to the first basket, the following *m* teams go to the second one, and so on. Then the following procedure repeats *m*<=-<=1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets. The four teams remaining in the baskets after (*m*<=-<=1) such procedures are performed, form the last group. In the real draw the random selection of teams from the basket is performed by people β€” as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers *x*,<=*a*,<=*b*,<=*c*. Every time there is a call to the random number generator, it produces the following actions: - calculates ; - replaces parameter *x* by value *y* (assigns ); - returns *x* as another random number. Operation means taking the remainder after division: , . A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number *k*. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to *s*<=-<=1, in the order of decreasing rating, where *s* is the current size of the basket. Then a team number is taken from the basket. Given a list of teams and the parameters of the random number generator, determine the result of the draw.
The first input line contains integer *n* (4<=≀<=*n*<=≀<=64, *n* is divisible by four) β€” the number of teams that take part in the sorting. The second line contains four space-separated integers *x*,<=*a*,<=*b*,<=*c* (1<=≀<=*x*,<=*a*,<=*b*,<=*c*<=≀<=1000) β€” the parameters of the random number generator. Each of the following *n* lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct.
Print the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format.
[ "8\n1 3 1 7\nBarcelona 158\nMilan 90\nSpartak 46\nAnderlecht 48\nCeltic 32\nBenfica 87\nZenit 79\nMalaga 16\n" ]
[ "Group A:\nBarcelona\nBenfica\nSpartak\nCeltic\nGroup B:\nMilan\nZenit\nAnderlecht\nMalaga\n" ]
In the given sample the random number generator will be executed four times: - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/2d76d911e7446d6db4b0be2679ce6e5ab930ab92.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/cc339c0d810046d7adb9ef4339e48f5554842ae2.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/74fb01e5b91f6c73ead806139c45f3e73fa1232d.png" style="max-width: 100.0%;max-height: 100.0%;"/>, - <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/f8a9ac4805dfae22b7d7a65c5daa8f4cc5a21a5a.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "8\n1 3 1 7\nBarcelona 158\nMilan 90\nSpartak 46\nAnderlecht 48\nCeltic 32\nBenfica 87\nZenit 79\nMalaga 16", "output": "Group A:\nBarcelona\nBenfica\nSpartak\nCeltic\nGroup B:\nMilan\nZenit\nAnderlecht\nMalaga" }, { "input": "4\n777 556 763 235\nkRnl 221\nSnxtrev 981\nBAaxtAFAyfYKea 390\...
62
0
-1
170,402
83
Two Subsequences
[ "bitmasks", "dp" ]
E. Two Subsequences
2
256
On an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you. Let {*a*1,<=*a*2,<=...,<=*a**n*} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: - *f*(empty sequence)<==<=empty string - *f*(*s*)<==<=*s*. - *f*(*s*1,<=*s*2)<==<= the smallest in length string, which has one of the prefixes equal to *s*1 and one of the suffixes equal to *s*2. For example, *f*(001,<=011)<==<=0011, *f*(111,<=011)<==<=111011. - *f*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=*f*(*f*(*a*1,<=*a*2,<=*a**n*<=-<=1),<=*a**n*). For example, *f*(000,<=000,<=111)<==<=*f*(*f*(000,<=000),<=111)<==<=*f*(000,<=111)<==<=000111. Valera faces a real challenge: he should divide the given sequence {*a*1,<=*a*2,<=...,<=*a**n*} into two subsequences {*b*1,<=*b*2,<=...,<=*b**k*} and {*c*1,<=*c*2,<=...,<=*c**m*}, *m*<=+<=*k*<==<=*n*, so that the value of *S*<==<=|*f*(*b*1,<=*b*2,<=...,<=*b**k*)|<=+<=|*f*(*c*1,<=*c*2,<=...,<=*c**m*)| took the minimum possible value. Here |*p*| denotes the length of the string *p*. Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences *b* and *c* don't have to be consecutive in the original sequence *a*, i. e. elements of *b* and *c* can alternate in *a* (see samples 2 and 3). Help Valera to find the minimum possible value of *S*.
The first line of input data contains an integer *n* β€” the number of strings (1<=≀<=*n*<=≀<=2Β·105). Then on *n* lines follow elements of the sequence β€” strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The *i*<=+<=1-th input line contains the *i*-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.
Print a single number β€” the minimum possible value of *S*.
[ "3\n01\n10\n01\n", "4\n000\n111\n110\n001\n", "5\n10101\n01010\n11111\n01000\n10010\n" ]
[ "4\n", "8\n", "17\n" ]
Detailed answers to the tests: - The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |*f*(01, 10, 01)| = |*f*(*f*(01, 10), 01)| = |*f*(010, 01)| = |0101| = 4. - The best option is: *b* = {000, 001}, *c* = {111, 110}. *S* = |*f*(000, 001)| + |*f*(111, 110)| = |0001| + |1110| = 8. - The best option is: *b* = {10101, 01010, 01000}, *c* = {11111, 10010}. *S* = |10101000| + |111110010| = 17.
[ { "input": "3\n01\n10\n01", "output": "4" }, { "input": "4\n000\n111\n110\n001", "output": "8" }, { "input": "5\n10101\n01010\n11111\n01000\n10010", "output": "17" }, { "input": "1\n0", "output": "1" }, { "input": "2\n0\n1", "output": "2" }, { "input":...
2,000
184,832,000
0
170,716
908
New Year and Boolean Bridges
[]
null
null
Your friend has a hidden directed graph with *n* nodes. Let *f*(*u*,<=*v*) be true if there is a directed path from node *u* to node *v*, and false otherwise. For each pair of distinct nodes, *u*,<=*v*, you know at least one of the three statements is true: 1. 1. 1. Here AND, OR and XOR mean AND, OR and exclusive OR operations, respectively. You are given an *n* by *n* matrix saying which one of the three statements holds for each pair of vertices. The entry in the *u*-th row and *v*-th column has a single character. 1. If the first statement holds, this is represented by the character 'A'. 1. If the second holds, this is represented by the character 'O'. 1. If the third holds, this is represented by the character 'X'. 1. The diagonal of this matrix will only contain the character '-'. Note that it is possible that a pair of nodes may satisfy multiple statements, in which case, the character given will represent one of the true statements for that pair. This matrix is also guaranteed to be symmetric. You would like to know if there is a directed graph that is consistent with this matrix. If it is impossible, print the integer -1. Otherwise, print the minimum number of edges that could be consistent with this information.
The first line will contain an integer *n* (1<=≀<=*n*<=≀<=47), the number of nodes. The next *n* lines will contain *n* characters each: the matrix of what you know about the graph connectivity in the format described in the statement.
Print the minimum number of edges that is consistent with the given information, or -1 if it is impossible.
[ "4\n-AAA\nA-AA\nAA-A\nAAA-\n", "3\n-XX\nX-X\nXX-\n" ]
[ "4\n", "2\n" ]
Sample 1: The hidden graph is a strongly connected graph. We can put all four nodes in a cycle. Sample 2: One valid graph is 3 → 1 → 2. For each distinct pair, exactly one of *f*(*u*, *v*), *f*(*v*, *u*) holds.
[]
30
0
0
170,884
584
Anton and Ira
[ "constructive algorithms", "greedy", "math" ]
null
null
Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible. More formally, we have two permutations, *p* and *s* of numbers from 1 to *n*. We can swap *p**i* and *p**j*, by paying |*i*<=-<=*j*| coins for it. Find and print the smallest number of coins required to obtain permutation *s* from permutation *p*. Also print the sequence of swap operations at which we obtain a solution.
The first line contains a single number *n* (1<=≀<=*n*<=≀<=2000) β€” the length of the permutations. The second line contains a sequence of *n* numbers from 1 to *n* β€” permutation *p*. Each number from 1 to *n* occurs exactly once in this line. The third line contains a sequence of *n* numbers from 1 to *n* β€” permutation *s*. Each number from 1 to *n* occurs once in this line.
In the first line print the minimum number of coins that you need to spend to transform permutation *p* into permutation *s*. In the second line print number *k* (0<=≀<=*k*<=≀<=2Β·106) β€” the number of operations needed to get the solution. In the next *k* lines print the operations. Each line must contain two numbers *i* and *j* (1<=≀<=*i*,<=*j*<=≀<=*n*, *i*<=β‰ <=*j*), which means that you need to swap *p**i* and *p**j*. It is guaranteed that the solution exists.
[ "4\n4 2 1 3\n3 2 4 1\n" ]
[ "3\n2\n4 3\n3 1\n" ]
In the first sample test we swap numbers on positions 3 and 4 and permutation *p* becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to *s*. We pay |3 - 1| = 2 coins for that. In total we pay three coins.
[ { "input": "4\n4 2 1 3\n3 2 4 1", "output": "3\n2\n3 4\n1 3" }, { "input": "1\n1\n1", "output": "0\n0" }, { "input": "2\n1 2\n1 2", "output": "0\n0" }, { "input": "3\n3 2 1\n1 3 2", "output": "2\n2\n2 3\n1 2" }, { "input": "6\n4 5 2 6 3 1\n1 5 2 4 6 3", "outpu...
77
0
0
171,038
732
Tourist Reform
[ "dfs and similar", "graphs" ]
null
null
Berland is a tourist country! At least, it can become suchΒ β€” the government of Berland is confident about this. There are *n* cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possible to get from any city to any other city using given two-ways roads. According to the reform each road will become one-way. It will be oriented to one of two directions. To maximize the tourist attraction of Berland, after the reform for each city *i* the value *r**i* will be calculated. It will equal to the number of cities *x* for which there is an oriented path from the city *i* to the city *x*. In other words, *r**i* will equal the number of cities which can be reached from the city *i* by roads. The government is sure that tourist's attention will be focused on the minimum value of *r**i*. Help the government of Berland make the reform to maximize the minimum of *r**i*.
The first line contains two integers *n*,<=*m* (2<=≀<=*n*<=≀<=400<=000,<=1<=≀<=*m*<=≀<=400<=000)Β β€” the number of cities and the number of roads. The next *m* lines describe roads in Berland: the *j*-th of them contains two integers *u**j* and *v**j* (1<=≀<=*u**j*,<=*v**j*<=≀<=*n*, *u**j*<=β‰ <=*v**j*), where *u**j* and *v**j* are the numbers of cities which are connected by the *j*-th road. The cities are numbered from 1 to *n*. It is guaranteed that it is possible to get from any city to any other by following two-ways roads. In Berland there are no roads which connect the same pair of cities.
In the first line print single integerΒ β€” the maximum possible value *min*1<=≀<=*i*<=≀<=*n*{*r**i*} after the orientation of roads. The next *m* lines must contain the description of roads after the orientation: the *j*-th of them must contain two integers *u**j*,<=*v**j*, it means that the *j*-th road will be directed from the city *u**j* to the city *v**j*. Print roads in the same order as they are given in the input data.
[ "7 9\n4 3\n2 6\n7 1\n4 1\n7 3\n3 5\n7 4\n6 5\n2 5\n" ]
[ "4\n4 3\n6 2\n7 1\n1 4\n3 7\n5 3\n7 4\n5 6\n2 5\n" ]
none
[ { "input": "7 9\n4 3\n2 6\n7 1\n4 1\n7 3\n3 5\n7 4\n6 5\n2 5", "output": "4\n4 3\n6 2\n7 1\n1 4\n3 7\n5 3\n7 4\n5 6\n2 5" }, { "input": "2 1\n2 1", "output": "1\n2 1" }, { "input": "3 2\n1 3\n1 2", "output": "1\n3 1\n2 1" }, { "input": "3 3\n3 1\n3 2\n1 2", "output": "3\n...
31
0
0
171,426
97
Domino
[ "brute force", "implementation" ]
A. Domino
0
256
Little Gennady was presented with a set of domino for his birthday. The set consists of 28 different dominoes of size 2<=Γ—<=1. Both halves of each domino contain one digit from 0 to 6. The figure that consists of 28 dominoes is called magic, if it can be fully covered with 14 non-intersecting squares of size 2<=Γ—<=2 so that each square contained four equal numbers. Every time Gennady assembles a magic figure, some magic properties of the set appear β€” he wins the next contest. Gennady noticed that he can't assemble a figure that has already been assembled, otherwise someone else wins the contest. Gennady chose a checked field of size *n*<=Γ—<=*m* and put there rectangular chips of sizes 1<=Γ—<=2 and 2<=Γ—<=1. Each chip fully occupies exactly two neighboring squares of the field. Those chips do not overlap but they can touch each other. Overall the field has exactly 28 chips, equal to the number of dominoes in the set. Now Gennady wants to replace each chip with a domino so that a magic figure appeared as a result. Different chips should be replaced by different dominoes. Determine in what number of contests Gennady can win over at the given position of the chips. You are also required to find one of the possible ways of replacing chips with dominoes to win the next Codeforces round.
The first line contains two positive integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=30). Each of the following *n* lines contains *m* characters, which is the position of chips on the field. The dots stand for empty spaces, Latin letters from "a" to "z" and "A", "B" stand for the positions of the chips. There are exactly 28 chips on the field. The squares covered by the same chip are marked by the same letter, different chips are marked by different letters. It is guaranteed that the field's description is correct. It is also guaranteed that at least one solution exists.
Print on the first line the number of ways to replace chips with dominoes to get a magic figure. That is the total number of contests that can be won using this arrangement of the chips. Next *n* lines containing *m* characters each, should contain a field from dots and numbers from 0 to 6 β€” any of the possible solutions. All dominoes should be different.
[ "8 8\n.aabbcc.\n.defghi.\nkdefghij\nklmnopqj\n.lmnopq.\n.rstuvw.\nxrstuvwy\nxzzAABBy\n" ]
[ "10080\n.001122.\n.001122.\n33440055\n33440055\n.225566.\n.225566.\n66113344\n66113344\n" ]
none
[]
92
0
0
171,560
676
The Last Fight Between Human and AI
[ "math" ]
null
null
100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet. The following game was chosen for the fights: initially there is a polynomial Polynomial *P*(*x*) is said to be divisible by polynomial *Q*(*x*) if there exists a representation *P*(*x*)<==<=*B*(*x*)*Q*(*x*), where *B*(*x*) is also some polynomial. Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?
The first line of the input contains two integers *n* and *k* (1<=≀<=*n*<=≀<=100<=000,<=|*k*|<=≀<=10<=000)Β β€” the size of the polynomial and the integer *k*. The *i*-th of the following *n*<=+<=1 lines contain character '?' if the coefficient near *x**i*<=-<=1 is yet undefined or the integer value *a**i*, if the coefficient is already known (<=-<=10<=000<=≀<=*a**i*<=≀<=10<=000). Each of integers *a**i* (and even *a**n*) may be equal to 0. Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.
Print "Yes" (without quotes) if the human has winning strategy, or "No" (without quotes) otherwise.
[ "1 2\n-1\n?\n", "2 100\n-10000\n0\n1\n", "4 5\n?\n1\n?\n1\n?\n" ]
[ "Yes\n", "Yes", "No" ]
In the first sample, computer set *a*<sub class="lower-index">0</sub> to  - 1 on the first move, so if human can set coefficient *a*<sub class="lower-index">1</sub> to 0.5 and win. In the second sample, all coefficients are already set and the resulting polynomial is divisible by *x* - 100, so the human has won.
[ { "input": "1 2\n-1\n?", "output": "Yes" }, { "input": "2 100\n-10000\n0\n1", "output": "Yes" }, { "input": "4 5\n?\n1\n?\n1\n?", "output": "No" }, { "input": "68 -9959\n-3666\n-3501\n9169\n5724\n1478\n-643\n-3039\n-5537\n-4295\n-1856\n-6720\n6827\n-39\n-9509\n-7005\n1942\n-5...
46
0
0
171,717
521
Cycling City
[ "dfs and similar", "graphs" ]
null
null
You are organizing a cycling race on the streets of the city. The city contains *n* junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself. You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route β€” the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: - all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same);- to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes);- no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit). Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.
The first line contains two integers *n* and *m* (1<=≀<=*n*,<=*m*<=≀<=2Β·105) β€” the number of intersections and roads, respectively. The following *m* lines contain two integers β€” the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself. Please note that it is not guaranteed that you can get from any junction to any other one by using the roads.
If it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "*l* *p*1 ... *p**l*", where *l* is the number of intersections in the route, and *p*1,<=...,<=*p**l* are their numbers in the order they follow. The routes must meet all the requirements specified in the statement. If it is impossible to make the routes in accordance with the requirements, print NO.
[ "4 4\n1 2\n2 3\n3 4\n4 1\n", "5 6\n1 2\n1 3\n1 4\n2 5\n3 5\n4 5\n" ]
[ "NO\n", "YES\n3 5 4 1\n3 5 3 1\n3 5 2 1\n" ]
none
[ { "input": "4 4\n1 2\n2 3\n3 4\n4 1", "output": "NO" }, { "input": "5 6\n1 2\n1 3\n1 4\n2 5\n3 5\n4 5", "output": "YES\n3 5 4 1\n3 5 3 1\n3 5 2 1" }, { "input": "10 10\n7 6\n2 1\n9 3\n6 1\n6 10\n4 1\n7 5\n5 1\n4 10\n5 6", "output": "YES\n4 6 10 4 1\n3 6 5 1\n2 6 1" }, { "inpu...
0
0
-1
171,777
441
Valera and Number
[ "bitmasks", "dp", "math", "probabilities" ]
null
null
Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below: Now Valera wonders: given the values *x*, *k* and *p*, what is the expected value of the resulting number *s*?
The first line of the input contains three integers *x*,<=*k*,<=*p* (1<=≀<=*x*<=≀<=109;Β 1<=≀<=*k*<=≀<=200;Β 0<=≀<=*p*<=≀<=100).
Print the required expected value. Your answer will be considered correct if the absolute or relative error doesn't exceed 10<=-<=6.
[ "1 1 50\n", "5 3 0\n", "5 3 25\n" ]
[ "1.0000000000000\n", "3.0000000000000\n", "1.9218750000000\n" ]
If the concept of expected value is new to you, you can read about it by the link: http://en.wikipedia.org/wiki/Expected_value
[ { "input": "1 1 50", "output": "1.0000000000000" }, { "input": "5 3 0", "output": "3.0000000000000" }, { "input": "5 3 25", "output": "1.9218750000000" }, { "input": "1132123 200 0", "output": "0.0000000000000" }, { "input": "1213112 200 100", "output": "203.0...
62
0
3
171,899
794
Choosing Carrot
[ "games", "math" ]
null
null
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are *n* carrots arranged in a line. The *i*-th carrot from the left has juiciness *a**i*. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose. To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS. Oleg is a sneaky bank client. When Igor goes to a restroom, he performs *k* moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each *k* such that 0<=≀<=*k*<=≀<=*n*<=-<=1, what is the juiciness of the carrot they will give to ZS if he makes *k* extra moves beforehand and both players play optimally?
The first line of input contains a single integer *n* (1<=≀<=*n*<=≀<=3Β·105)Β β€” the total number of carrots. The next line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≀<=*a**i*<=≀<=109). Here *a**i* denotes the juiciness of the *i*-th carrot from the left of the line.
Output *n* space-separated integers *x*0,<=*x*1,<=...,<=*x**n*<=-<=1. Here, *x**i* denotes the juiciness of the carrot the friends will present to ZS if *k*<==<=*i*.
[ "4\n1 2 3 5\n", "5\n1000000000 1000000000 1000000000 1000000000 1\n" ]
[ "3 3 5 5\n", "1000000000 1000000000 1000000000 1000000000 1000000000\n" ]
For the first example, When *k* = 0, one possible optimal game is as follows: - Oleg eats the carrot with juiciness 1.- Igor eats the carrot with juiciness 5.- Oleg eats the carrot with juiciness 2.- The remaining carrot has juiciness 3. When *k* = 1, one possible optimal play is as follows: - Oleg eats the carrot with juiciness 1 beforehand.- Oleg eats the carrot with juiciness 2.- Igor eats the carrot with juiciness 5.- The remaining carrot has juiciness 3. When *k* = 2, one possible optimal play is as follows: - Oleg eats the carrot with juiciness 1 beforehand.- Oleg eats the carrot with juiciness 2 beforehand.- Oleg eats the carrot with juiciness 3.- The remaining carrot has juiciness 5. When *k* = 3, one possible optimal play is as follows: - Oleg eats the carrot with juiciness 1 beforehand.- Oleg eats the carrot with juiciness 2 beforehand.- Oleg eats the carrot with juiciness 3 beforehand.- The remaining carrot has juiciness 5. Thus, the answer is 3, 3, 5, 5. For the second sample, Oleg can always eat the carrot with juiciness 1 since he always moves first. So, the remaining carrot will always have juiciness 1000000000.
[ { "input": "4\n1 2 3 5", "output": "3 3 5 5" }, { "input": "5\n1000000000 1000000000 1000000000 1000000000 1", "output": "1000000000 1000000000 1000000000 1000000000 1000000000" }, { "input": "4\n1 12 3 5", "output": "12 3 12 12" }, { "input": "5\n1 3 2 2 4", "output": "2...
46
0
0
172,152
629
Famil Door and Roads
[ "combinatorics", "data structures", "dfs and similar", "dp", "probabilities", "trees" ]
null
null
Famil Door’s City map looks like a tree (undirected connected acyclic graph) so other people call it Treeland. There are *n* intersections in the city connected by *n*<=-<=1 bidirectional roads. There are *m* friends of Famil Door living in the city. The *i*-th friend lives at the intersection *u**i* and works at the intersection *v**i*. Everyone in the city is unhappy because there is exactly one simple path between their home and work. Famil Door plans to construct exactly one new road and he will randomly choose one among *n*Β·(*n*<=-<=1)<=/<=2 possibilities. Note, that he may even build a new road between two cities that are already connected by one. He knows, that each of his friends will become happy, if after Famil Door constructs a new road there is a path from this friend home to work and back that doesn't visit the same road twice. Formally, there is a simple cycle containing both *u**i* and *v**i*. Moreover, if the friend becomes happy, his pleasure is equal to the length of such path (it's easy to see that it's unique). For each of his friends Famil Door wants to know his expected pleasure, that is the expected length of the cycle containing both *u**i* and *v**i* if we consider only cases when such a cycle exists.
The first line of the input contains integers *n* and *m* (2<=≀<=*n*,<= *m*<=≀<=100<=000)Β β€” the number of the intersections in the Treeland and the number of Famil Door's friends. Then follow *n*<=-<=1 lines describing bidirectional roads. Each of them contains two integers *a**i* and *b**i* (1<=≀<=*a**i*,<=*b**i*<=≀<=*n*)Β β€” the indices of intersections connected by the *i*-th road. Last *m* lines of the input describe Famil Door's friends. The *i*-th of these lines contain two integers *u**i* and *v**i* (1<=≀<=*u**i*,<=*v**i*<=≀<=*n*,<=*u**i*<=β‰ <=*v**i*)Β β€” indices of intersections where the *i*-th friend lives and works.
For each friend you should print the expected value of pleasure if he will be happy. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6. Namely: let's assume that your answer is *a*, and the answer of the jury is *b*. The checker program will consider your answer correct, if .
[ "4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1\n", "3 3\n1 2\n1 3\n1 2\n1 3\n2 3\n" ]
[ "4.00000000\n3.00000000\n3.00000000\n", "2.50000000\n2.50000000\n3.00000000\n" ]
Consider the second sample. 1. Both roads (1, 2) and (2, 3) work, so the expected length if <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ec563337e40cadafa8449c9571eb5b8c7199e10c.png" style="max-width: 100.0%;max-height: 100.0%;"/> 1. Roads (1, 3) and (2, 3) make the second friend happy. Same as for friend 1 the answer is 2.5 1. The only way to make the third friend happy is to add road (2, 3), so the answer is 3
[ { "input": "4 3\n2 4\n4 1\n3 2\n3 1\n2 3\n4 1", "output": "4.00000000\n3.00000000\n3.00000000" }, { "input": "3 3\n1 2\n1 3\n1 2\n1 3\n2 3", "output": "2.50000000\n2.50000000\n3.00000000" }, { "input": "10 5\n8 10\n3 6\n7 3\n7 4\n8 9\n9 4\n5 1\n10 5\n6 2\n9 1\n7 6\n5 1\n6 9\n10 2", "...
30
0
0
172,249