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
12
Start of the session
[ "constructive algorithms" ]
E. Start of the season
2
256
Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size *n*<=×<=*n* (*n* is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to *n*<=-<=1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.
The first line contains one integer *n* (2<=≤<=*n*<=≤<=1000), *n* is even.
Output *n* lines with *n* numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any.
[ "2\n", "4\n" ]
[ "0 1\n1 0\n", "0 1 3 2\n1 0 2 3\n3 2 0 1\n2 3 1 0\n" ]
none
[ { "input": "2", "output": "0 1\n1 0" }, { "input": "4", "output": "0 1 3 2\n1 0 2 3\n3 2 0 1\n2 3 1 0" }, { "input": "6", "output": "0 1 4 2 5 3\n1 0 2 5 3 4\n4 2 0 3 1 5\n2 5 3 0 4 1\n5 3 1 4 0 2\n3 4 5 1 2 0" }, { "input": "8", "output": "0 1 5 2 6 3 7 4\n1 0 2 6 3 7 4 ...
2,000
22,118,400
0
20,163
235
Let's Play Osu!
[ "dp", "math", "probabilities" ]
null
null
You're playing a game called Osu! Here's a simplified version of it. There are *n* clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of *n* characters "O" and "X". Using the play sequence you can calculate the score for the play as follows: for every maximal consecutive "O"s block, add the square of its length (the number of characters "O") to the score. For example, if your play can be encoded as "OOXOOOXXOO", then there's three maximal consecutive "O"s block "OO", "OOO", "OO", so your score will be 22<=+<=32<=+<=22<==<=17. If there are no correct clicks in a play then the score for the play equals to 0. You know that the probability to click the *i*-th (1<=≤<=*i*<=≤<=*n*) click correctly is *p**i*. In other words, the *i*-th character in the play sequence has *p**i* probability to be "O", 1<=-<=*p**i* to be "X". You task is to calculate the expected score for your play.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=105) — the number of clicks. The second line contains *n* space-separated real numbers *p*1,<=*p*2,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=1). There will be at most six digits after the decimal point in the given *p**i*.
Print a single real number — the expected score for your play. Your answer will be considered correct if its absolute or relative error does not exceed 10<=-<=6.
[ "3\n0.5 0.5 0.5\n", "4\n0.7 0.2 0.1 0.9\n", "5\n1 1 1 1 1\n" ]
[ "2.750000000000000\n", "2.489200000000000\n", "25.000000000000000\n" ]
For the first example. There are 8 possible outcomes. Each has a probability of 0.125. - "OOO"  →  3<sup class="upper-index">2</sup> = 9; - "OOX"  →  2<sup class="upper-index">2</sup> = 4; - "OXO"  →  1<sup class="upper-index">2</sup> + 1<sup class="upper-index">2</sup> = 2; - "OXX"  →  1<sup class="upper-index">2</sup> = 1; - "XOO"  →  2<sup class="upper-index">2</sup> = 4; - "XOX"  →  1<sup class="upper-index">2</sup> = 1; - "XXO"  →  1<sup class="upper-index">2</sup> = 1; - "XXX"  →  0. So the expected score is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/9aa477286058d4dd02d6f78cad11a658e4f37440.png" style="max-width: 100.0%;max-height: 100.0%;"/>
[ { "input": "3\n0.5 0.5 0.5", "output": "2.750000000000000" }, { "input": "4\n0.7 0.2 0.1 0.9", "output": "2.489200000000000" }, { "input": "5\n1 1 1 1 1", "output": "25.000000000000000" }, { "input": "10\n0.684846 0.156794 0.153696 0.714526 0.281868 0.628256 0.745339 0.123854...
374
9,318,400
3
20,164
960
Full Binary Tree Queries
[ "brute force", "implementation", "trees" ]
null
null
You have a full binary tree having infinite levels. Each node has an initial value. If a node has value *x*, then its left child has value 2·*x* and its right child has value 2·*x*<=+<=1. The value of the root is 1. You need to answer *Q* queries. There are 3 types of queries: 1. Cyclically shift the values of all nodes on the same level as node with value *X* by *K* units. (The values/nodes of any other level are not affected).1. Cyclically shift the nodes on the same level as node with value *X* by *K* units. (The subtrees of these nodes will move along with them).1. Print the value of every node encountered on the simple path from the node with value *X* to the root. Positive *K* implies right cyclic shift and negative *K* implies left cyclic shift. It is guaranteed that atleast one type 3 query is present.
The first line contains a single integer *Q* (1<=≤<=*Q*<=≤<=105). Then *Q* queries follow, one per line: - Queries of type 1 and 2 have the following format: *T* *X* *K* (1<=≤<=*T*<=≤<=2; 1<=≤<=*X*<=≤<=1018; 0<=≤<=|*K*|<=≤<=1018), where *T* is type of the query.- Queries of type 3 have the following format: 3 *X* (1<=≤<=*X*<=≤<=1018).
For each query of type 3, print the values of all nodes encountered in descending order.
[ "5\n3 12\n1 2 1\n3 12\n2 4 -1\n3 8\n", "5\n3 14\n1 5 -3\n3 14\n1 3 1\n3 14\n" ]
[ "12 6 3 1 \n12 6 2 1 \n8 4 2 1 \n", "14 7 3 1 \n14 6 3 1 \n14 6 2 1 \n" ]
Following are the images of the first 4 levels of the tree in the first test case: Original: After query 1 2 1: After query 2 4 -1:
[ { "input": "5\n3 12\n1 2 1\n3 12\n2 4 -1\n3 8", "output": "12 6 3 1 \n12 6 2 1 \n8 4 2 1 " }, { "input": "5\n3 14\n1 5 -3\n3 14\n1 3 1\n3 14", "output": "14 7 3 1 \n14 6 3 1 \n14 6 2 1 " }, { "input": "6\n3 1\n2 1 0\n3 10\n2 1 -4\n3 10\n2 10 -5", "output": "1 \n10 5 2 1 \n10 5 2 1 " ...
0
0
-1
20,204
0
none
[ "none" ]
null
null
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large version of a letter *x* is denoted by *x*'. BSCII encoding, which is used everywhere in Bookland, is made in that way so that large letters are presented in the order of the numbers they are denoted by, and small letters are presented in the order of the numbers they are denoted by, but all large letters are before all small letters. For example, the following conditions hold: 2<=&lt;<=3, 2'<=&lt;<=3', 3'<=&lt;<=2. A word *x*1,<=*x*2,<=...,<=*x**a* is not lexicographically greater than *y*1,<=*y*2,<=...,<=*y**b* if one of the two following conditions holds: - *a*<=≤<=*b* and *x*1<==<=*y*1,<=...,<=*x**a*<==<=*y**a*, i.e. the first word is the prefix of the second word; - there is a position 1<=≤<=*j*<=≤<=*min*(*a*,<=*b*), such that *x*1<==<=*y*1,<=...,<=*x**j*<=-<=1<==<=*y**j*<=-<=1 and *x**j*<=&lt;<=*y**j*, i.e. at the first position where the words differ the first word has a smaller letter than the second word has. For example, the word "3' 7 5" is before the word "2 4' 6" in lexicographical order. It is said that sequence of words is in lexicographical order if each word is not lexicographically greater than the next word in the sequence. Denis has a sequence of words consisting of small letters only. He wants to change some letters to large (let's call this process a capitalization) in such a way that the sequence of words is in lexicographical order. However, he soon realized that for some reason he can't change a single letter in a single word. He only can choose a letter and change all of its occurrences in all words to large letters. He can perform this operation any number of times with arbitrary letters of Bookland's alphabet. Help Denis to choose which letters he needs to capitalize (make large) in order to make the sequence of words lexicographically ordered, or determine that it is impossible. Note that some words can be equal.
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=100<=000, 1<=≤<=*m*<=≤<=100<=000) — the number of words and the number of letters in Bookland's alphabet, respectively. The letters of Bookland's alphabet are denoted by integers from 1 to *m*. Each of the next *n* lines contains a description of one word in format *l**i*,<=*s**i*,<=1,<=*s**i*,<=2,<=...,<=*s**i*,<=*l**i* (1<=≤<=*l**i*<=≤<=100<=000, 1<=≤<=*s**i*,<=*j*<=≤<=*m*), where *l**i* is the length of the word, and *s**i*,<=*j* is the sequence of letters in the word. The words are given in the order Denis has them in the sequence. It is guaranteed that the total length of all words is not greater than 100<=000.
In the first line print "Yes" (without quotes), if it is possible to capitalize some set of letters in such a way that the sequence of words becomes lexicographically ordered. Otherwise, print "No" (without quotes). If the required is possible, in the second line print *k* — the number of letters Denis has to capitalize (make large), and in the third line print *k* distinct integers — these letters. Note that you don't need to minimize the value *k*. You can print the letters in any order. If there are multiple answers, print any of them.
[ "4 3\n1 2\n1 1\n3 1 3 2\n2 1 1\n", "6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4\n", "4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1\n" ]
[ "Yes\n2\n2 3 ", "Yes\n0\n", "No\n" ]
In the first example after Denis makes letters 2 and 3 large, the sequence looks like the following: - 2' - 1 - 1 3' 2' - 1 1 The condition 2' &lt; 1 holds, so the first word is not lexicographically larger than the second word. The second word is the prefix of the third word, so the are in lexicographical order. As the first letters of the third and the fourth words are the same, and 3' &lt; 1, then the third word is not lexicographically larger than the fourth word. In the second example the words are in lexicographical order from the beginning, so Denis can do nothing. In the third example there is no set of letters such that if Denis capitalizes them, the sequence becomes lexicographically ordered.
[ { "input": "4 3\n1 2\n1 1\n3 1 3 2\n2 1 1", "output": "Yes\n2\n2 3 " }, { "input": "6 5\n2 1 2\n2 1 2\n3 1 2 3\n2 1 5\n2 4 4\n2 4 4", "output": "Yes\n0" }, { "input": "4 3\n4 3 2 2 1\n3 1 1 3\n3 2 3 3\n2 3 1", "output": "No" }, { "input": "4 4\n3 3 4 1\n4 3 4 2 2\n4 2 1 2 3\n...
30
0
0
20,232
113
Grammar Lessons
[ "implementation", "strings" ]
A. Grammar Lessons
5
256
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: - There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb. - There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine. - Masculine adjectives end with -lios, and feminine adjectives end with -liala. - Masculine nouns end with -etr, and feminime nouns end with -etra. - Masculine verbs end with -initis, and feminime verbs end with -inites. - Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language. - It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language. - There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications. - A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: - Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs. - All words in the statement should have the same gender. After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.
The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.
If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).
[ "petr\n", "etis atis animatis etis atis amatis\n", "nataliala kataliala vetra feinites\n" ]
[ "YES\n", "NO\n", "YES\n" ]
none
[ { "input": "petr", "output": "YES" }, { "input": "etis atis animatis etis atis amatis", "output": "NO" }, { "input": "nataliala kataliala vetra feinites", "output": "YES" }, { "input": "qweasbvflios", "output": "YES" }, { "input": "lios lios petr initis qwe", ...
60
0
-1
20,260
404
Restore Graph
[ "dfs and similar", "graphs", "sortings" ]
null
null
Valera had an undirected connected graph without self-loops and multiple edges consisting of *n* vertices. The graph had an interesting property: there were at most *k* edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to *n*. One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array *d*. Thus, element *d*[*i*] of the array shows the shortest distance from the vertex Valera chose to vertex number *i*. Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array *d*. Help him restore the lost graph.
The first line contains two space-separated integers *n* and *k* (1<=≤<=*k*<=&lt;<=*n*<=≤<=105). Number *n* shows the number of vertices in the original graph. Number *k* shows that at most *k* edges were adjacent to each vertex in the original graph. The second line contains space-separated integers *d*[1],<=*d*[2],<=...,<=*d*[*n*] (0<=≤<=*d*[*i*]<=&lt;<=*n*). Number *d*[*i*] shows the shortest distance from the vertex Valera chose to the vertex number *i*.
If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer *m* (0<=≤<=*m*<=≤<=106) — the number of edges in the found graph. In each of the next *m* lines print two space-separated integers *a**i* and *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*), denoting the edge that connects vertices with numbers *a**i* and *b**i*. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.
[ "3 2\n0 1 1\n", "4 2\n2 0 1 3\n", "3 1\n0 0 0\n" ]
[ "3\n1 2\n1 3\n3 2\n", "3\n1 3\n1 4\n2 3\n", "-1\n" ]
none
[ { "input": "3 2\n0 1 1", "output": "2\n1 2\n1 3" }, { "input": "4 2\n2 0 1 3", "output": "3\n1 3\n1 4\n2 3" }, { "input": "3 1\n0 0 0", "output": "-1" }, { "input": "5 3\n0 2 1 2 1", "output": "4\n1 3\n1 5\n2 5\n4 5" }, { "input": "7 3\n2 2 0 1 3 2 1", "output...
483
36,044,800
3
20,266
576
Points on Plane
[ "constructive algorithms", "divide and conquer", "geometry", "greedy", "sortings" ]
null
null
On a plane are *n* points (*x**i*, *y**i*) with integer coordinates between 0 and 106. The distance between the two points with numbers *a* and *b* is said to be the following value: (the distance calculated by such formula is called Manhattan distance). We call a hamiltonian path to be some permutation *p**i* of numbers from 1 to *n*. We say that the length of this path is value . Find some hamiltonian path with a length of no more than 25<=×<=108. Note that you do not have to minimize the path length.
The first line contains integer *n* (1<=≤<=*n*<=≤<=106). The *i*<=+<=1-th line contains the coordinates of the *i*-th point: *x**i* and *y**i* (0<=≤<=*x**i*,<=*y**i*<=≤<=106). It is guaranteed that no two points coincide.
Print the permutation of numbers *p**i* from 1 to *n* — the sought Hamiltonian path. The permutation must meet the inequality . If there are multiple possible answers, print any of them. It is guaranteed that the answer exists.
[ "5\n0 7\n8 10\n3 4\n5 0\n9 12\n" ]
[ "4 3 1 2 5 \n" ]
In the sample test the total distance is: <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c772e61c616e1c27114e3facb9e6db6c5cf93b82.png" style="max-width: 100.0%;max-height: 100.0%;"/> (|5 - 3| + |0 - 4|) + (|3 - 0| + |4 - 7|) + (|0 - 8| + |7 - 10|) + (|8 - 9| + |10 - 12|) = 2 + 4 + 3 + 3 + 8 + 3 + 1 + 2 = 26
[]
2,000
116,531,200
0
20,344
936
World of Tank
[ "dp", "greedy" ]
null
null
Vitya loves programming and problem solving, but sometimes, to distract himself a little, he plays computer games. Once he found a new interesting game about tanks, and he liked it so much that he went through almost all levels in one day. Remained only the last level, which was too tricky. Then Vitya remembered that he is a programmer, and wrote a program that helped him to pass this difficult level. Try do the same. The game is organized as follows. There is a long road, two cells wide and *n* cells long. Some cells have obstacles. You control a tank that occupies one cell. Initially, the tank is located before the start of the road, in a cell with coordinates (0,<=1). Your task is to move the tank to the end of the road, to the cell (*n*<=+<=1,<=1) or (*n*<=+<=1,<=2). Every second the tank moves one cell to the right: the coordinate *x* is increased by one. When you press the up or down arrow keys, the tank instantly changes the lane, that is, the *y* coordinate. When you press the spacebar, the tank shoots, and the nearest obstacle along the lane in which the tank rides is instantly destroyed. In order to load a gun, the tank needs *t* seconds. Initially, the gun is not loaded, that means, the first shot can be made only after *t* seconds after the tank starts to move. If at some point the tank is in the same cell with an obstacle not yet destroyed, it burns out. If you press the arrow exactly at the moment when the tank moves forward, the tank will first move forward, and then change the lane, so it will not be possible to move diagonally. Your task is to find out whether it is possible to pass the level, and if possible, to find the order of actions the player need to make.
The first line contains four integers *n*, *m*1, *m*2 and *t*, the length of the field, the number of obstacles in the first lane, the number of obstacles in the second lane and the number of tank steps before reloading, respectively (1<=≤<=*n*<=≤<=109; 0<=≤<=*m*1,<=*m*2<=≤<=*n*; 0<=≤<=*m*1<=+<=*m*2<=≤<=106; 1<=≤<=*t*<=≤<=*n*). The next two lines contain a description of the obstacles. The first of these lines contains *m*1 numbers *x**i* — the obstacle coordinates in the first lane (1<=≤<=*x**i*<=≤<=*n*; *x**i*<=&lt;<=*x**i*<=+<=1). The *y* coordinate for all these obstacles will be 1. The second line contains *m*2 numbers describing the obstacles of the second lane in the same format. The *y* coordinate of all these obstacles will be 2.
In the first line print «Yes», if it is possible to pass the level, or «No», otherwise. If it is possible, then in the second line print the number of times the tank moves from one lane to another, and in the next line print the coordinates of the transitions, one number per transition: the coordinate *x* (0<=≤<=*x*<=≤<=*n*<=+<=1). All transition coordinates coordinates must be distinct and should be output in strictly increasing order.The number of transitions should not exceed 2·106. If the tank can pass the level, then it can do it using no more than 2·106 transitions. In the fourth line print the number of shots that the tank makes during the movement, in the following lines print two numbers, *x* and *y* coordinates of the point (1<=≤<=*x*<=≤<=*n*, 1<=≤<=*y*<=≤<=2), from which the tank fired a shot, the number of shots must not exceed *m*1<=+<=*m*2. Shots must be output in the order in which they are fired. If there are several solutions, output any one.
[ "6 2 3 2\n2 6\n3 5 6\n", "1 1 1 1\n1\n1\n", "9 5 2 5\n1 2 7 8 9\n4 6\n" ]
[ "Yes\n2\n0 3 \n2\n2 2\n4 1\n", "No\n", "Yes\n4\n0 3 5 10 \n1\n5 2\n" ]
Picture for the first sample test.
[]
77
0
0
20,350
710
Generate a String
[ "dfs and similar", "dp" ]
null
null
zscoder wants to generate an input file for some programming competition problem. His input is a string consisting of *n* letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor. Initially, the text editor is empty. It takes him *x* seconds to insert or delete a letter 'a' from the text file and *y* seconds to copy the contents of the entire text file, and duplicate it. zscoder wants to find the minimum amount of time needed for him to create the input file of exactly *n* letters 'a'. Help him to determine the amount of time needed to generate the input.
The only line contains three integers *n*, *x* and *y* (1<=≤<=*n*<=≤<=107, 1<=≤<=*x*,<=*y*<=≤<=109) — the number of letters 'a' in the input file and the parameters from the problem statement.
Print the only integer *t* — the minimum amount of time needed to generate the input file.
[ "8 1 1\n", "8 1 10\n" ]
[ "4\n", "8\n" ]
none
[ { "input": "8 1 1", "output": "4" }, { "input": "8 1 10", "output": "8" }, { "input": "10 62 99", "output": "384" }, { "input": "88 417 591", "output": "4623" }, { "input": "57 5289 8444", "output": "60221" }, { "input": "382 81437847 324871127", "...
0
0
-1
20,352
491
Up the hill
[ "constructive algorithms", "implementation" ]
null
null
Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through. It is known that there were *N* stops, all on different integer heights between 1 and *N* kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop *N*<=-<=1 to the stop *N* and successfully finished their expedition. They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill. Help them by suggesting some possible stop heights satisfying numbers from the travel journal.
In the first line there is an integer non-negative number *A* denoting the number of days of climbing up the hill. Second line contains an integer non-negative number *B* — the number of days of walking down the hill (*A*<=+<=*B*<=+<=1<==<=*N*, 1<=≤<=*N*<=≤<=100<=000).
Output *N* space-separated distinct integers from 1 to *N* inclusive, denoting possible heights of the stops in order of visiting.
[ "0\n1\n", "2\n1" ]
[ "2 1 \n", "1 3 4 2" ]
none
[ { "input": "0\n1", "output": "2 1 " }, { "input": "2\n1", "output": "2 3 4 1 " }, { "input": "0\n3", "output": "4 3 2 1 " }, { "input": "1\n1", "output": "2 3 1 " }, { "input": "3\n7", "output": "8 9 10 11 7 6 5 4 3 2 1 " }, { "input": "700\n300", ...
124
9,011,200
3
20,375
452
4-point polyline
[ "brute force", "constructive algorithms", "geometry", "trees" ]
null
null
You are given a rectangular grid of lattice points from (0,<=0) to (*n*,<=*m*) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible. A polyline defined by points *p*1,<=*p*2,<=*p*3,<=*p*4 consists of the line segments *p*1<=*p*2,<=*p*2<=*p*3,<=*p*3<=*p*4, and its length is the sum of the lengths of the individual line segments.
The only line of the input contains two integers *n* and *m* (0<=≤<=*n*,<=*m*<=≤<=1000). It is guaranteed that grid contains at least 4 different points.
Print 4 lines with two integers per line separated by space — coordinates of points *p*1,<=*p*2,<=*p*3,<=*p*4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10<=-<=6 precision.
[ "1 1\n", "0 10\n" ]
[ "1 1\n0 0\n1 0\n0 1\n", "0 1\n0 10\n0 0\n0 9\n" ]
none
[ { "input": "1 1", "output": "0 0\n1 1\n0 1\n1 0" }, { "input": "0 10", "output": "0 1\n0 10\n0 0\n0 9" }, { "input": "10 10", "output": "10 9\n0 0\n10 10\n1 0" }, { "input": "100 100", "output": "0 1\n100 100\n0 0\n99 100" }, { "input": "10 100", "output": "9 ...
61
0
0
20,401
10
Digital Root
[ "number theory" ]
C. Digital Root
2
256
Not long ago Billy came across such a problem, where there were given three natural numbers *A*, *B* and *C* from the range [1,<=*N*], and it was asked to check whether the equation *AB*<==<=*C* is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root *d*(*x*) of the number *x* is the sum *s*(*x*) of all the digits of this number, if *s*(*x*)<=≤<=9, otherwise it is *d*(*s*(*x*)). For example, a digital root of the number 6543 is calculated as follows: *d*(6543)<==<=*d*(6<=+<=5<=+<=4<=+<=3)<==<=*d*(18)<==<=9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. *d*(*xy*)<==<=*d*(*d*(*x*)*d*(*y*)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.
The first line contains the only number *N* (1<=≤<=*N*<=≤<=106).
Output one number — the amount of required *A*, *B* and *C* from the range [1,<=*N*].
[ "4\n", "5\n" ]
[ "2\n", "6\n" ]
For the first sample the required triples are (3, 4, 3) and (4, 3, 3).
[ { "input": "4", "output": "2" }, { "input": "5", "output": "6" }, { "input": "6", "output": "14" }, { "input": "7", "output": "25" }, { "input": "1", "output": "0" }, { "input": "8", "output": "40" }, { "input": "10", "output": "82" }...
60
0
-1
20,403
63
Settlers' Training
[ "implementation" ]
B. Settlers' Training
2
256
In a strategic computer game "Settlers II" one has to build defense structures to expand and protect the territory. Let's take one of these buildings. At the moment the defense structure accommodates exactly *n* soldiers. Within this task we can assume that the number of soldiers in the defense structure won't either increase or decrease. Every soldier has a rank — some natural number from 1 to *k*. 1 stands for a private and *k* stands for a general. The higher the rank of the soldier is, the better he fights. Therefore, the player profits from having the soldiers of the highest possible rank. To increase the ranks of soldiers they need to train. But the soldiers won't train for free, and each training session requires one golden coin. On each training session all the *n* soldiers are present. At the end of each training session the soldiers' ranks increase as follows. First all the soldiers are divided into groups with the same rank, so that the least possible number of groups is formed. Then, within each of the groups where the soldiers below the rank *k* are present, exactly one soldier increases his rank by one. You know the ranks of all *n* soldiers at the moment. Determine the number of golden coins that are needed to increase the ranks of all the soldiers to the rank *k*.
The first line contains two integers *n* and *k* (1<=≤<=*n*,<=*k*<=≤<=100). They represent the number of soldiers and the number of different ranks correspondingly. The second line contains *n* numbers in the non-decreasing order. The *i*-th of them, *a**i*, represents the rank of the *i*-th soldier in the defense building (1<=≤<=*i*<=≤<=*n*, 1<=≤<=*a**i*<=≤<=*k*).
Print a single integer — the number of golden coins needed to raise all the soldiers to the maximal rank.
[ "4 4\n1 2 2 3\n", "4 3\n1 1 1 1\n" ]
[ "4", "5" ]
In the first example the ranks will be raised in the following manner: 1 2 2 3  →  2 2 3 4  →  2 3 4 4  →  3 4 4 4  →  4 4 4 4 Thus totals to 4 training sessions that require 4 golden coins.
[ { "input": "4 4\n1 2 2 3", "output": "4" }, { "input": "4 3\n1 1 1 1", "output": "5" }, { "input": "3 3\n1 2 3", "output": "2" }, { "input": "1 1\n1", "output": "0" }, { "input": "1 5\n1", "output": "4" }, { "input": "1 5\n4", "output": "1" }, ...
310
21,606,400
3.882255
20,416
513
Second price auction
[ "bitmasks", "probabilities" ]
null
null
Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receives a request with details about the user, web page and ad slot and they have to respond within those 100 milliseconds with a bid they would pay for putting an advertisement on that ad slot. The company that suggests the highest bid wins the auction and gets to place its advertisement. If there are several companies tied for the highest bid, the winner gets picked at random. However, the company that won the auction does not have to pay the exact amount of its bid. In most of the cases, a second-price auction is used. This means that the amount paid by the company is equal to the maximum of all the other bids placed for this ad slot. Let's consider one such bidding. There are *n* companies competing for placing an ad. The *i*-th of these companies will bid an integer number of microdollars equiprobably randomly chosen from the range between *L**i* and *R**i*, inclusive. In the other words, the value of the *i*-th company bid can be any integer from the range [*L**i*,<=*R**i*] with the same probability. Determine the expected value that the winner will have to pay in a second-price auction.
The first line of input contains an integer number *n* (2<=≤<=*n*<=≤<=5). *n* lines follow, the *i*-th of them containing two numbers *L**i* and *R**i* (1<=≤<=*L**i*<=≤<=*R**i*<=≤<=10000) describing the *i*-th company's bid preferences. This problem doesn't have subproblems. You will get 8 points for the correct submission.
Output the answer with absolute or relative error no more than 1*e*<=-<=9.
[ "3\n4 7\n8 10\n5 5\n", "3\n2 5\n3 4\n1 6\n" ]
[ "5.7500000000\n", "3.5000000000\n" ]
Consider the first example. The first company bids a random integer number of microdollars in range [4, 7]; the second company bids between 8 and 10, and the third company bids 5 microdollars. The second company will win regardless of the exact value it bids, however the price it will pay depends on the value of first company's bid. With probability 0.5 the first company will bid at most 5 microdollars, and the second-highest price of the whole auction will be 5. With probability 0.25 it will bid 6 microdollars, and with probability 0.25 it will bid 7 microdollars. Thus, the expected value the second company will have to pay is 0.5·5 + 0.25·6 + 0.25·7 = 5.75.
[ { "input": "3\n4 7\n8 10\n5 5", "output": "5.7500000000" }, { "input": "3\n2 5\n3 4\n1 6", "output": "3.5000000000" }, { "input": "5\n1 10000\n1 10000\n1 10000\n1 10000\n1 10000", "output": "6667.1666666646" }, { "input": "2\n1 2\n1 2", "output": "1.2500000000" }, { ...
2,000
28,672,000
0
20,423
747
Comments
[ "dfs and similar", "expression parsing", "implementation", "strings" ]
null
null
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment. When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: - at first, the text of the comment is written; - after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); - after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). For example, if the comments look like: then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: - at first, print a integer *d* — the maximum depth of nesting comments; - after that print *d* lines, the *i*-th of them corresponds to nesting level *i*; - for the *i*-th row print comments of nesting level *i* in the order of their appearance in the Policarp's comments feed, separated by space.
The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros. The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid.
Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input.
[ "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\n", "a,5,A,0,a,0,A,0,a,0,A,0\n", "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0\n" ]
[ "3\nhello test one \nok bye two \na b \n", "2\na \nA a A a A \n", "4\nA K M \nB F H L N O \nC D G I P \nE J \n" ]
The first example is explained in the statements.
[ { "input": "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0", "output": "3\nhello test one \nok bye two \na b " }, { "input": "a,5,A,0,a,0,A,0,a,0,A,0", "output": "2\na \nA a A a A " }, { "input": "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0", "output": "4\nA K M \n...
592
98,099,200
-1
20,437
809
Glad to see you!
[ "binary search", "interactive" ]
null
null
This is an interactive problem. In the output section below you will see the information about flushing the output. On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in Vičkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building. In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of *n* dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to *n*. After a little thought, the girl ordered exactly *k* different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better. The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*). After that Noora chooses some dish *a* for the number *x* such that, at first, *a* is among the dishes Noora ordered (*x* can be equal to *a*), and, secondly, the value is the minimum possible. By the same rules the girl chooses dish *b* for *y*. After that Noora says «TAK» to Leha, if , and «NIE» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered. Help Leha to solve this problem!
There are two numbers *n* and *k* (2<=≤<=*k*<=≤<=*n*<=≤<=105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.
If you want to provide an answer, output a string of the form 2 *x* *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*), if you think the dishes *x* and *y* was among dishes ordered by Noora. After that, flush the output and terminate your program.
[ "3 2\nNIE\nTAK\nNIE\nTAK\nTAK\nTAK\n" ]
[ "1 1 2\n1 2 1\n1 1 3\n1 3 1\n1 2 3\n1 3 2\n2 2 3\n" ]
There are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (*x* = 1), then she'll choose the second dish (*a* = 2) as the dish with the minimum value <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e5a4a1705bc256e413564795cc8b70857f0ae44c.png" style="max-width: 100.0%;max-height: 100.0%;"/>. For the second (*x* = 2) and the third (*x* = 3) dishes themselves will be optimal, because in that case <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/79add195d023131e992b60a354fec89501759e75.png" style="max-width: 100.0%;max-height: 100.0%;"/>. Let Leha asks Noora about the next couple of dishes: - *x* = 1, *y* = 2, then he'll recieve «NIE» answer, because |1 - 2| &gt; |2 - 2| - *x* = 2, *y* = 1, then he'll recieve «TAK» answer, because |2 - 2| ≤ |1 - 2| - *x* = 1, *y* = 3, then he'll recieve «NIE» answer, because |1 - 2| &gt; |3 - 3| - *x* = 3, *y* = 1, then he'll recieve «TAK» answer, because |3 - 3| ≤ |1 - 2| - *x* = 2, *y* = 3, then he'll recieve «TAK» answer, because |2 - 2| ≤ |3 - 3| - *x* = 3, *y* = 2, then he'll recieve «TAK» answer, because |3 - 3| ≤ |2 - 2| According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3.
[]
46
5,632,000
0
20,442
350
Wrong Floyd
[ "brute force", "constructive algorithms", "dfs and similar", "graphs" ]
null
null
Valera conducts experiments with algorithms that search for shortest paths. He has recently studied the Floyd's algorithm, so it's time to work with it. Valera's already written the code that counts the shortest distance between any pair of vertexes in a non-directed connected graph from *n* vertexes and *m* edges, containing no loops and multiple edges. Besides, Valera's decided to mark part of the vertexes. He's marked exactly *k* vertexes *a*1,<=*a*2,<=...,<=*a**k*. Valera's code is given below. Valera has seen that his code is wrong. Help the boy. Given the set of marked vertexes *a*1,<=*a*2,<=...,<=*a**k*, find such non-directed connected graph, consisting of *n* vertexes and *m* edges, for which Valera's code counts the wrong shortest distance for at least one pair of vertexes (*i*,<=*j*). Valera is really keen to get a graph without any loops and multiple edges. If no such graph exists, print -1.
The first line of the input contains three integers *n*,<=*m*,<=*k* (3<=≤<=*n*<=≤<=300, 2<=≤<=*k*<=≤<=*n* , ) — the number of vertexes, the number of edges and the number of marked vertexes. The second line of the input contains *k* space-separated integers *a*1,<=*a*2,<=... *a**k* (1<=≤<=*a**i*<=≤<=*n*) — the numbers of the marked vertexes. It is guaranteed that all numbers *a**i* are distinct.
If the graph doesn't exist, print -1 on a single line. Otherwise, print *m* lines, each containing two integers *u*,<=*v* — the description of the edges of the graph Valera's been looking for.
[ "3 2 2\n1 2\n", "3 3 2\n1 2\n" ]
[ "1 3\n2 3\n", "-1\n" ]
none
[ { "input": "3 2 2\n1 2", "output": "1 3\n2 3" }, { "input": "3 3 2\n1 2", "output": "-1" }, { "input": "300 43056 2\n5 6", "output": "1 2\n2 3\n3 4\n4 7\n5 300\n6 300\n7 8\n8 9\n9 10\n10 11\n11 12\n12 13\n13 14\n14 15\n15 16\n16 17\n17 18\n18 19\n19 20\n20 21\n21 22\n22 23\n23 24\n24...
592
102,400
0
20,457
961
Pair Of Lines
[ "geometry" ]
null
null
You are given *n* points on Cartesian plane. Every point is a lattice point (i.<=e. both of its coordinates are integers), and all points are distinct. You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?
The first line contains one integer *n* (1<=≤<=*n*<=≤<=105) — the number of points you are given. Then *n* lines follow, each line containing two integers *x**i* and *y**i* (|*x**i*|,<=|*y**i*|<=≤<=109)— coordinates of *i*-th point. All *n* points are distinct.
If it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.
[ "5\n0 0\n0 1\n1 1\n1 -1\n2 2\n", "5\n0 0\n1 0\n2 1\n1 1\n2 3\n" ]
[ "YES\n", "NO\n" ]
In the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points.
[ { "input": "5\n0 0\n0 1\n1 1\n1 -1\n2 2", "output": "YES" }, { "input": "5\n0 0\n1 0\n2 1\n1 1\n2 3", "output": "NO" }, { "input": "1\n-1000000000 1000000000", "output": "YES" }, { "input": "5\n2 -1\n-4 1\n0 -9\n5 -9\n9 -10", "output": "NO" }, { "input": "5\n6 1\n...
514
71,680,000
3
20,468
920
SUM and REPLACE
[ "brute force", "data structures", "dsu", "number theory" ]
null
null
Let *D*(*x*) be the number of positive divisors of a positive integer *x*. For example, *D*(2)<==<=2 (2 is divisible by 1 and 2), *D*(6)<==<=4 (6 is divisible by 1, 2, 3 and 6). You are given an array *a* of *n* integers. You have to process two types of queries: 1. REPLACE *l* *r* — for every replace *a**i* with *D*(*a**i*); 1. SUM *l* *r* — calculate . Print the answer for each SUM query.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=3·105) — the number of elements in the array and the number of queries to process, respectively. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) — the elements of the array. Then *m* lines follow, each containing 3 integers *t**i*, *l**i*, *r**i* denoting *i*-th query. If *t**i*<==<=1, then *i*-th query is REPLACE *l**i* *r**i*, otherwise it's SUM *l**i* *r**i* (1<=≤<=*t**i*<=≤<=2, 1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). There is at least one SUM query.
For each SUM query print the answer to it.
[ "7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7\n" ]
[ "30\n13\n4\n22\n" ]
none
[ { "input": "7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7", "output": "30\n13\n4\n22" }, { "input": "4 2\n1 1 1 3\n1 1 4\n2 1 4", "output": "5" }, { "input": "10 2\n1 1 1 1 1 1 1 1 1 9\n1 1 10\n2 1 10", "output": "12" }, { "input": "4 2\n1 1 3 1\n1 1 4\n2 1 4"...
2,000
15,462,400
0
20,495
976
Degree Set
[ "constructive algorithms", "graphs", "implementation" ]
null
null
You are given a sequence of *n* positive integers *d*1,<=*d*2,<=...,<=*d**n* (*d*1<=&lt;<=*d*2<=&lt;<=...<=&lt;<=*d**n*). Your task is to construct an undirected graph such that: - there are exactly *d**n*<=+<=1 vertices; - there are no self-loops; - there are no multiple edges; - there are no more than 106 edges; - its degree set is equal to *d*. Vertices should be numbered 1 through (*d**n*<=+<=1). Degree sequence is an array *a* with length equal to the number of vertices in a graph such that *a**i* is the number of vertices adjacent to *i*-th vertex. Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence. It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 106 edges. Print the resulting graph.
The first line contains one integer *n* (1<=≤<=*n*<=≤<=300) — the size of the degree set. The second line contains *n* integers *d*1,<=*d*2,<=...,<=*d**n* (1<=≤<=*d**i*<=≤<=1000, *d*1<=&lt;<=*d*2<=&lt;<=...<=&lt;<=*d**n*) — the degree set.
In the first line print one integer *m* (1<=≤<=*m*<=≤<=106) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 106 edges. Each of the next *m* lines should contain two integers *v**i* and *u**i* (1<=≤<=*v**i*,<=*u**i*<=≤<=*d**n*<=+<=1) — the description of the *i*-th edge.
[ "3\n2 3 4\n", "3\n1 2 3\n" ]
[ "8\n3 1\n4 2\n4 5\n2 5\n5 1\n3 2\n2 1\n5 3\n", "4\n1 2\n1 3\n1 4\n2 3\n" ]
none
[ { "input": "3\n2 3 4", "output": "8\n1 2\n1 3\n1 4\n1 5\n2 3\n2 4\n2 5\n3 4" }, { "input": "3\n1 2 3", "output": "4\n1 2\n1 3\n1 4\n2 3" }, { "input": "4\n1 3 4 6", "output": "11\n1 2\n1 3\n1 4\n1 5\n1 6\n1 7\n2 3\n2 4\n2 5\n3 4\n3 5" }, { "input": "1\n1", "output": "1\n1...
780
58,470,400
0
20,498
466
Information Graph
[ "dfs and similar", "dsu", "graphs", "trees" ]
null
null
There are *n* employees working in company "X" (let's number them from 1 to *n* for convenience). Initially the employees didn't have any relationships among each other. On each of *m* next days one of the following events took place: - either employee *y* became the boss of employee *x* (at that, employee *x* didn't have a boss before); - or employee *x* gets a packet of documents and signs them; then he gives the packet to his boss. The boss signs the documents and gives them to his boss and so on (the last person to sign the documents sends them to the archive); - or comes a request of type "determine whether employee *x* signs certain documents". Your task is to write a program that will, given the events, answer the queries of the described type. At that, it is guaranteed that throughout the whole working time the company didn't have cyclic dependencies.
The first line contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=105) — the number of employees and the number of events. Each of the next *m* lines contains the description of one event (the events are given in the chronological order). The first number of the line determines the type of event *t* (1<=≤<=*t*<=≤<=3). - If *t*<==<=1, then next follow two integers *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*) — numbers of the company employees. It is guaranteed that employee *x* doesn't have the boss currently. - If *t*<==<=2, then next follow integer *x* (1<=≤<=*x*<=≤<=*n*) — the number of the employee who got a document packet. - If *t*<==<=3, then next follow two integers *x* and *i* (1<=≤<=*x*<=≤<=*n*; 1<=≤<=*i*<=≤<=[number of packets that have already been given]) — the employee and the number of the document packet for which you need to find out information. The document packets are numbered started from 1 in the chronological order. It is guaranteed that the input has at least one query of the third type.
For each query of the third type print "YES" if the employee signed the document package and "NO" otherwise. Print all the words without the quotes.
[ "4 9\n1 4 3\n2 4\n3 3 1\n1 2 3\n2 2\n3 1 2\n1 3 1\n2 2\n3 1 3\n" ]
[ "YES\nNO\nYES\n" ]
none
[]
30
0
0
20,532
929
Пограничные врата
[]
null
null
Герой Аркадий находится на узкой полоске земли, разделенной на *n* зон, пронумерованных от 1 до *n*. Из *i*-й зоны можно пройти лишь в (*i*<=-<=1)-ю зону и в (*i*<=+<=1)-ю зону, если они существуют. При этом между каждой парой соседних зон находятся пограничные врата, которые могут быть разных цветов, цвет врат между *i*-й и (*i*<=+<=1)-й зоной равен *g**i*. Аркадий может пройти пограничные врата некоторого цвета, только если он перед этим побывал в одном из шатров хранителей ключей этого цвета и взял ключ. В каждой зоне находится ровно один шатер хранителя ключей некоторого цвета, цвет шатра в *i*-й зоне равен *k**i*. После посещения шатра определенного цвета Аркадий может неограниченное число раз проходить через любые врата этого цвета. На проход через одни врата Аркадий тратит один ход, на посещение шатра и другие перемещения ходы не требуются. За какое минимальное число ходов Аркадий может попасть из зоны *a* в зону *b*, если изначально у него нет никаких ключей?
Первая строка содержит три целых числа *n*, *a*, *b* (2<=≤<=*n*<=≤<=100<=000, 1<=≤<=*a*,<=*b*<=≤<=*n*, *a*<=≠<=*b*) — число зон, номер начальной зоны и номер конечной зоны, соответственно. Вторая строка содержит *n*<=-<=1 целое число *g*1,<=*g*2,<=...,<=*g**n*<=-<=1 (1<=≤<=*g**i*<=≤<=100<=000), где *g**i* означает цвет пограничных врат между зонами *i* и *i*<=+<=1. Третья строка содержит *n* целых чисел *k*1,<=*k*2,<=...,<=*k**n* (1<=≤<=*k**i*<=≤<=100<=000), где *k**i* означает цвет шатра хранителя ключей в *i*-й зоне.
Если Аркадий не может попасть из зоны *a* в зону *b*, не имея изначально ключей, выведите -1. Иначе выведите минимальное количество ходов, которое потребуется Аркадию.
[ "5 4 1\n3 1 1 2\n7 1 2 1 3\n", "5 1 5\n4 3 2 1\n4 3 2 5 5\n" ]
[ "7\n", "-1\n" ]
В первом примере, чтобы попасть из зоны 4 в зону 1, Аркадию нужно сначала взять ключ цвета 1, пройти в зону 3, там взять ключ цвета 2 и пройти обратно в зону 4 и затем в зону 5, взять там ключ цвета 3 и дойти до зоны 1 за четыре хода. Во втором примере Аркадий может дойти лишь до четвертой зоны, так как шатров хранителей ключей цвета 1 нет совсем.
[]
46
5,632,000
-1
20,534
758
Blown Garland
[ "brute force", "implementation", "number theory" ]
null
null
Nothing is eternal in the world, Kostya understood it on the 7-th of January when he saw partially dead four-color garland. Now he has a goal to replace dead light bulbs, however he doesn't know how many light bulbs for each color are required. It is guaranteed that for each of four colors at least one light is working. It is known that the garland contains light bulbs of four colors: red, blue, yellow and green. The garland is made as follows: if you take any four consecutive light bulbs then there will not be light bulbs with the same color among them. For example, the garland can look like "RYBGRYBGRY", "YBGRYBGRYBG", "BGRYB", but can not look like "BGRYG", "YBGRYBYGR" or "BGYBGY". Letters denote colors: 'R' — red, 'B' — blue, 'Y' — yellow, 'G' — green. Using the information that for each color at least one light bulb still works count the number of dead light bulbs of each four colors.
The first and the only line contains the string *s* (4<=≤<=|*s*|<=≤<=100), which describes the garland, the *i*-th symbol of which describes the color of the *i*-th light bulb in the order from the beginning of garland: - 'R' — the light bulb is red, - 'B' — the light bulb is blue, - 'Y' — the light bulb is yellow, - 'G' — the light bulb is green, - '!' — the light bulb is dead. The string *s* can not contain other symbols except those five which were described. It is guaranteed that in the given string at least once there is each of four letters 'R', 'B', 'Y' and 'G'. It is guaranteed that the string *s* is correct garland with some blown light bulbs, it means that for example the line "GRBY!!!B" can not be in the input data.
In the only line print four integers *k**r*,<=*k**b*,<=*k**y*,<=*k**g* — the number of dead light bulbs of red, blue, yellow and green colors accordingly.
[ "RYBGRYBGR\n", "!RGYB\n", "!!!!YGRB\n", "!GB!RG!Y!\n" ]
[ "0 0 0 0", "0 1 0 0", "1 1 1 1", "2 1 1 0" ]
In the first example there are no dead light bulbs. In the second example it is obvious that one blue bulb is blown, because it could not be light bulbs of other colors on its place according to the statements.
[ { "input": "RYBGRYBGR", "output": "0 0 0 0" }, { "input": "!RGYB", "output": "0 1 0 0" }, { "input": "!!!!YGRB", "output": "1 1 1 1" }, { "input": "!GB!RG!Y!", "output": "2 1 1 0" }, { "input": "RYBG", "output": "0 0 0 0" }, { "input": "!Y!!!Y!!G!!!G!!...
46
4,505,600
3
20,541
144
Meeting
[ "implementation" ]
null
null
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at the integer points of the plane. At each integer point which belongs to the table perimeter there is a chair in which a general sits. Some points on the plane contain radiators for the generals not to freeze in winter. Each radiator is characterized by the number *r**i* — the radius of the area this radiator can heat. That is, if the distance between some general and the given radiator is less than or equal to *r**i*, than the general feels comfortable and warm. Here distance is defined as Euclidean distance, so the distance between points (*x*1,<=*y*1) and (*x*2,<=*y*2) is Each general who is located outside the radiators' heating area can get sick. Thus, you should bring him a warm blanket. Your task is to count the number of warm blankets you should bring to the Super Duper Secret Place. The generals who are already comfortable do not need a blanket. Also the generals never overheat, ever if they are located in the heating area of several radiators. The radiators can be located at any integer points on the plane, even inside the rectangle (under the table) or on the perimeter (directly under some general). Even in this case their radius does not change.
The first input line contains coordinates of two opposite table corners *x**a*, *y**a*, *x**b*, *y**b* (*x**a*<=≠<=*x**b*,<=*y**a*<=≠<=*y**b*). The second line contains integer *n* — the number of radiators (1<=≤<=*n*<=≤<=103). Then *n* lines contain the heaters' coordinates as "*x**i* *y**i* *r**i*", the numbers are separated by spaces. All input data numbers are integers. The absolute value of all coordinates does not exceed 1000, 1<=≤<=*r**i*<=≤<=1000. Several radiators can be located at the same point.
Print the only number — the number of blankets you should bring.
[ "2 5 4 2\n3\n3 1 2\n5 3 1\n1 3 2\n", "5 2 6 3\n2\n6 2 2\n6 5 3\n" ]
[ "4\n", "0\n" ]
In the first sample the generals are sitting at points: (2, 2), (2, 3), (2, 4), (2, 5), (3, 2), (3, 5), (4, 2), (4, 3), (4, 4), (4, 5). Among them, 4 generals are located outside the heating range. They are the generals at points: (2, 5), (3, 5), (4, 4), (4, 5). In the second sample the generals are sitting at points: (5, 2), (5, 3), (6, 2), (6, 3). All of them are located inside the heating range.
[ { "input": "2 5 4 2\n3\n3 1 2\n5 3 1\n1 3 2", "output": "4" }, { "input": "5 2 6 3\n2\n6 2 2\n6 5 3", "output": "0" }, { "input": "-705 595 -702 600\n1\n-589 365 261", "output": "4" }, { "input": "-555 674 -553 774\n5\n-656 128 631\n597 -220 999\n-399 793 155\n-293 -363 1000\...
2,000
204,800
0
20,574
623
Electric Charges
[ "binary search", "dp" ]
null
null
Programmer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals. A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis *X* is positive and axis *Y* is negative. Experienced laboratory worker marked *n* points with integer coordinates (*x**i*,<=*y**i*) on the plane and stopped the time. Sasha should use "atomic tweezers" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible. Since Sasha is a programmer, he naively thinks that all the particles will simply "fall" into their projections on the corresponding axes: electrons will fall on axis *X*, while protons will fall on axis *Y*. As we are programmers too, we will consider the same model as Sasha. That is, a particle gets from point (*x*,<=*y*) to point (*x*,<=0) if it is an electron and to point (0,<=*y*) if it is a proton. As the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him. Print a square of the minimum possible diameter of the set.
The first line of the input contains a single integer *n* (1<=≤<=*n*<=≤<=100<=000) — the number of points marked on the plane. Each of the next *n* lines contains two integers *x**i* and *y**i* (<=-<=108<=≤<=*x**i*,<=*y**i*<=≤<=108) — the coordinates of the *i*-th point. It is guaranteed that no two points coincide.
Print a single integer — the square of the minimum possible diameter of the set.
[ "3\n1 10\n1 20\n1 30\n", "2\n1 10\n10 1\n" ]
[ "0\n", "2\n" ]
In the first sample Sasha puts electrons at all points, all particles eventually fall at a single point (1, 0). In the second sample Sasha puts an electron at point (1, 10), and a proton at point (10, 1). The result is a set of two points (1, 0) and (0, 1), which has a diameter of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/bfe16f27ebc966df6f10ba356a1547b6e7242dd7.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
[ { "input": "3\n1 10\n1 20\n1 30", "output": "0" }, { "input": "2\n1 10\n10 1", "output": "2" }, { "input": "10\n1 6\n2 2\n-1 9\n-8 8\n-4 10\n-10 -6\n5 -1\n-3 -7\n-4 3\n9 4", "output": "100" }, { "input": "18\n-14 -745\n87 -4611\n89 -3748\n-77 273\n-21 -4654\n-86 -5108\n-70 32...
530
20,684,800
0
20,579
375
Tree and Queries
[ "data structures", "dfs and similar", "trees" ]
null
null
You have a rooted tree consisting of *n* vertices. Each vertex of the tree has some color. We will assume that the tree vertices are numbered by integers from 1 to *n*. Then we represent the color of vertex *v* as *c**v*. The tree root is a vertex with number 1. In this problem you need to answer to *m* queries. Each query is described by two integers *v**j*,<=*k**j*. The answer to query *v**j*,<=*k**j* is the number of such colors of vertices *x*, that the subtree of vertex *v**j* contains at least *k**j* vertices of color *x*. You can find the definition of a rooted tree by the following link: http://en.wikipedia.org/wiki/Tree_(graph_theory).
The first line contains two integers *n* and *m* (2<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=105). The next line contains a sequence of integers *c*1,<=*c*2,<=...,<=*c**n* (1<=≤<=*c**i*<=≤<=105). The next *n*<=-<=1 lines contain the edges of the tree. The *i*-th line contains the numbers *a**i*,<=*b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=*n*; *a**i*<=≠<=*b**i*) — the vertices connected by an edge of the tree. Next *m* lines contain the queries. The *j*-th line contains two integers *v**j*,<=*k**j* (1<=≤<=*v**j*<=≤<=*n*; 1<=≤<=*k**j*<=≤<=105).
Print *m* integers — the answers to the queries in the order the queries appear in the input.
[ "8 5\n1 2 2 3 3 2 3 3\n1 2\n1 5\n2 3\n2 4\n5 6\n5 7\n5 8\n1 2\n1 3\n1 4\n2 3\n5 3\n", "4 1\n1 2 3 4\n1 2\n2 3\n3 4\n1 1\n" ]
[ "2\n2\n1\n0\n1\n", "4\n" ]
A subtree of vertex *v* in a rooted tree with root *r* is a set of vertices {*u* : *dist*(*r*, *v*) + *dist*(*v*, *u*) = *dist*(*r*, *u*)}. Where *dist*(*x*, *y*) is the length (in edges) of the shortest path between vertices *x* and *y*.
[ { "input": "8 5\n1 2 2 3 3 2 3 3\n1 2\n1 5\n2 3\n2 4\n5 6\n5 7\n5 8\n1 2\n1 3\n1 4\n2 3\n5 3", "output": "2\n2\n1\n0\n1" }, { "input": "4 1\n1 2 3 4\n1 2\n2 3\n3 4\n1 1", "output": "4" } ]
1,000
5,120,000
0
20,632
518
Anya and Smartphone
[ "constructive algorithms", "data structures", "implementation" ]
null
null
Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly *n* applications, each application has its own icon. The icons are located on different screens, one screen contains *k* icons. The icons from the first to the *k*-th one are located on the first screen, from the (*k*<=+<=1)-th to the 2*k*-th ones are on the second screen and so on (the last screen may be partially empty). Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen *t*, Anya needs to make the following gestures: first she scrolls to the required screen number *t*, by making *t*<=-<=1 gestures (if the icon is on the screen *t*), and then make another gesture — press the icon of the required application exactly once to launch it. After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1. All applications are numbered from 1 to *n*. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change. Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.
The first line of the input contains three numbers *n*,<=*m*,<=*k* (1<=≤<=*n*,<=*m*,<=*k*<=≤<=105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains *n* integers, permutation *a*1,<=*a*2,<=...,<=*a**n* — the initial order of icons from left to right in the menu (from the first to the last one), *a**i* —  is the id of the application, whose icon goes *i*-th in the menu. Each integer from 1 to *n* occurs exactly once among *a**i*. The third line contains *m* integers *b*1,<=*b*2,<=...,<=*b**m*(1<=≤<=*b**i*<=≤<=*n*) — the ids of the launched applications in the planned order. One application may be launched multiple times.
Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.
[ "8 3 3\n1 2 3 4 5 6 7 8\n7 8 1\n", "5 4 2\n3 1 5 2 4\n4 4 4 4\n" ]
[ "7\n", "8\n" ]
In the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture. In total, Anya makes 7 gestures.
[ { "input": "8 3 3\n1 2 3 4 5 6 7 8\n7 8 1", "output": "7" }, { "input": "5 4 2\n3 1 5 2 4\n4 4 4 4", "output": "8" }, { "input": "10 10 3\n1 2 3 4 5 6 7 8 9 10\n2 3 4 5 6 7 8 9 10 1", "output": "25" }, { "input": "10 12 3\n6 1 2 9 3 10 8 5 7 4\n3 9 9 4 8 2 3 8 10 8 3 4", ...
358
15,769,600
3
20,639
374
Inna and Dima
[ "dfs and similar", "dp", "graphs", "implementation" ]
null
null
Inna and Dima bought a table of size *n*<=×<=*m* in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A". Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows: 1. initially, Inna chooses some cell of the table where letter "D" is written; 1. then Inna can move to some side-adjacent table cell that contains letter "I"; then from this cell she can go to one of the side-adjacent table cells that contains the written letter "M"; then she can go to a side-adjacent cell that contains letter "A". Then Inna assumes that she has gone through her sweetheart's name; 1. Inna's next move can be going to one of the side-adjacent table cells that contains letter "D" and then walk on through name DIMA in the similar manner. Inna never skips a letter. So, from the letter "D" she always goes to the letter "I", from the letter "I" she always goes the to letter "M", from the letter "M" she always goes to the letter "A", and from the letter "A" she always goes to the letter "D". Depending on the choice of the initial table cell, Inna can go through name DIMA either an infinite number of times or some positive finite number of times or she can't go through his name once. Help Inna find out what maximum number of times she can go through name DIMA.
The first line of the input contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=103). Then follow *n* lines that describe Inna and Dima's table. Each line contains *m* characters. Each character is one of the following four characters: "D", "I", "M", "A". Note that it is not guaranteed that the table contains at least one letter "D".
If Inna cannot go through name DIMA once, print on a single line "Poor Dima!" without the quotes. If there is the infinite number of names DIMA Inna can go through, print "Poor Inna!" without the quotes. Otherwise print a single integer — the maximum number of times Inna can go through name DIMA.
[ "1 2\nDI\n", "2 2\nMA\nID\n", "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID\n" ]
[ "Poor Dima!\n", "Poor Inna!\n", "4\n" ]
Notes to the samples: In the first test sample, Inna cannot go through name DIMA a single time. In the second test sample, Inna can go through the infinite number of words DIMA. For that, she should move in the clockwise direction starting from the lower right corner. In the third test sample the best strategy is to start from the cell in the upper left corner of the table. Starting from this cell, Inna can go through name DIMA four times.
[ { "input": "1 2\nDI", "output": "Poor Dima!" }, { "input": "2 2\nMA\nID", "output": "Poor Inna!" }, { "input": "5 5\nDIMAD\nDIMAI\nDIMAM\nDDMAA\nAAMID", "output": "4" }, { "input": "1 1\nI", "output": "Poor Dima!" }, { "input": "5 5\nDIMAD\nADDDI\nMDDDM\nIDDDA\nDA...
0
0
-1
20,657
757
Felicity is Coming!
[ "data structures", "hashing", "sortings", "strings" ]
null
null
It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has *n* gyms. The *i*-th gym has *g**i* Pokemon in it. There are *m* distinct Pokemon types in the Himalayan region numbered from 1 to *m*. There is a special evolution camp set up in the fest which claims to evolve any Pokemon. The type of a Pokemon could change after evolving, subject to the constraint that if two Pokemon have the same type before evolving, they will have the same type after evolving. Also, if two Pokemon have different types before evolving, they will have different types after evolving. It is also possible that a Pokemon has the same type before and after evolving. Formally, an evolution plan is a permutation *f* of {1,<=2,<=...,<=*m*}, such that *f*(*x*)<==<=*y* means that a Pokemon of type *x* evolves into a Pokemon of type *y*. The gym leaders are intrigued by the special evolution camp and all of them plan to evolve their Pokemons. The protocol of the mountain states that in each gym, for every type of Pokemon, the number of Pokemon of that type before evolving any Pokemon should be equal the number of Pokemon of that type after evolving all the Pokemons according to the evolution plan. They now want to find out how many distinct evolution plans exist which satisfy the protocol. Two evolution plans *f*1 and *f*2 are distinct, if they have at least one Pokemon type evolving into a different Pokemon type in the two plans, i. e. there exists an *i* such that *f*1(*i*)<=≠<=*f*2(*i*). Your task is to find how many distinct evolution plans are possible such that if all Pokemon in all the gyms are evolved, the number of Pokemon of each type in each of the gyms remains the same. As the answer can be large, output it modulo 109<=+<=7.
The first line contains two integers *n* and *m* (1<=≤<=*n*<=≤<=105, 1<=≤<=*m*<=≤<=106) — the number of gyms and the number of Pokemon types. The next *n* lines contain the description of Pokemons in the gyms. The *i*-th of these lines begins with the integer *g**i* (1<=≤<=*g**i*<=≤<=105) — the number of Pokemon in the *i*-th gym. After that *g**i* integers follow, denoting types of the Pokemons in the *i*-th gym. Each of these integers is between 1 and *m*. The total number of Pokemons (the sum of all *g**i*) does not exceed 5·105.
Output the number of valid evolution plans modulo 109<=+<=7.
[ "2 3\n2 1 2\n2 2 3\n", "1 3\n3 1 2 3\n", "2 4\n2 1 2\n3 2 3 4\n", "2 2\n3 2 2 1\n2 1 2\n", "3 7\n2 1 2\n2 3 4\n3 5 6 7\n" ]
[ "1\n", "6\n", "2\n", "1\n", "24\n" ]
In the first case, the only possible evolution plan is: In the second case, any permutation of (1,  2,  3) is valid. In the third case, there are two possible plans: In the fourth case, the only possible evolution plan is:
[ { "input": "2 3\n2 1 2\n2 2 3", "output": "1" }, { "input": "1 3\n3 1 2 3", "output": "6" }, { "input": "2 4\n2 1 2\n3 2 3 4", "output": "2" }, { "input": "2 2\n3 2 2 1\n2 1 2", "output": "1" }, { "input": "3 7\n2 1 2\n2 3 4\n3 5 6 7", "output": "24" }, { ...
1,372
111,001,600
-1
20,682
392
Three Arrays
[ "data structures" ]
null
null
There are three arrays *a*, *b* and *c*. Each of them consists of *n* integers. SmallY wants to find three integers *u*, *v*, *w* (0<=≤<=*u*,<=*v*,<=*w*<=≤<=*n*) such that the following condition holds: each number that appears in the union of *a*, *b* and *c*, appears either in the first *u* elements of *a*, or in the first *v* elements of *b*, or in the first *w* elements of *c*. Of course, SmallY doesn't want to have huge numbers *u*, *v* and *w*, so she wants sum *u*<=+<=*v*<=+<=*w* to be as small as possible. Please, help her to find the minimal possible sum of *u*<=+<=*v*<=+<=*w*.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=105). The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* — array *a*. The third line contains the description of array *b* in the same format. The fourth line contains the description of array *c* in the same format. The following constraint holds: 1<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=109.
Print a single integer — the minimum possible sum of *u*<=+<=*v*<=+<=*w*.
[ "3\n1 1 101\n1 2 1\n3 2 1\n", "5\n1 1 2 2 3\n2 2 4 3 3\n3 3 1 1 1\n" ]
[ "5", "5" ]
In the first example you should choose *u* = 3, *v* = 0, *w* = 2. In the second example you should choose *u* = 1, *v* = 3, *w* = 1.
[]
109
0
0
20,760
916
Jamie and Interesting Graph
[ "constructive algorithms", "graphs", "shortest paths" ]
null
null
Jamie has recently found undirected weighted graphs with the following properties very interesting: - The graph is connected and contains exactly *n* vertices and *m* edges. - All edge weights are integers and are in range [1,<=109] inclusive. - The length of shortest path from 1 to *n* is a prime number. - The sum of edges' weights in the minimum spanning tree (MST) of the graph is a prime number. - The graph contains no loops or multi-edges. If you are not familiar with some terms from the statement you can find definitions of them in notes section. Help Jamie construct any graph with given number of vertices and edges that is interesting!
First line of input contains 2 integers *n*, *m*  — the required number of vertices and edges.
In the first line output 2 integers *sp*, *mstw* (1<=≤<=*sp*,<=*mstw*<=≤<=1014) — the length of the shortest path and the sum of edges' weights in the minimum spanning tree. In the next *m* lines output the edges of the graph. In each line output 3 integers *u*, *v*, *w* (1<=≤<=*u*,<=*v*<=≤<=*n*,<=1<=≤<=*w*<=≤<=109) describing the edge connecting *u* and *v* and having weight *w*.
[ "4 4\n", "5 4\n" ]
[ "7 7\n1 2 3\n2 3 2\n3 4 2\n2 4 4\n", "7 13\n1 2 2\n1 3 4\n1 4 3\n4 5 4\n" ]
The graph of sample 1: <img class="tex-graphics" src="https://espresso.codeforces.com/42f9750de41b0d9a6b21e8615170113cfe19b0f2.png" style="max-width: 100.0%;max-height: 100.0%;"/> Shortest path sequence: {1, 2, 3, 4}. MST edges are marked with an asterisk (*). Definition of terms used in the problem statement: A shortest path in an undirected graph is a sequence of vertices (*v*<sub class="lower-index">1</sub>, *v*<sub class="lower-index">2</sub>, ... , *v*<sub class="lower-index">*k*</sub>) such that *v*<sub class="lower-index">*i*</sub> is adjacent to *v*<sub class="lower-index">*i* + 1</sub> 1 ≤ *i* &lt; *k* and the sum of weight <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e7f62cfd5c2c3b81dc80aaf2f512898495354f03.png" style="max-width: 100.0%;max-height: 100.0%;"/> is minimized where *w*(*i*, *j*) is the edge weight between *i* and *j*. ([https://en.wikipedia.org/wiki/Shortest_path_problem](https://en.wikipedia.org/wiki/Shortest_path_problem)) A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. ([https://en.wikipedia.org/wiki/Prime_number](https://en.wikipedia.org/wiki/Prime_number)) A minimum spanning tree (MST) is a subset of the edges of a connected, edge-weighted undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. ([https://en.wikipedia.org/wiki/Minimum_spanning_tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree)) [https://en.wikipedia.org/wiki/Multiple_edges](https://en.wikipedia.org/wiki/Multiple_edges)
[ { "input": "4 4", "output": "100003 100003\n1 2 100001\n2 3 1\n3 4 1\n1 3 1000000000" }, { "input": "5 4", "output": "100003 100003\n1 2 100000\n2 3 1\n3 4 1\n4 5 1" }, { "input": "2 1", "output": "100003 100003\n1 2 100003" }, { "input": "10 19", "output": "100003 100003...
30
5,632,000
0
20,802
116
Little Pigs and Wolves
[ "greedy", "implementation" ]
null
null
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size *n*<=×<=*m*. Each cell in this grid was either empty, containing one little pig, or containing one wolf. A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs. They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf. What is the maximum number of little pigs that may be eaten by the wolves?
The first line contains integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow *n* lines containing *m* characters each — that is the grid description. "." means that this cell is empty. "P" means that this cell contains a little pig. "W" means that this cell contains a wolf. It is guaranteed that there will be at most one wolf adjacent to any little pig.
Print a single number — the maximal number of little pigs that may be eaten by the wolves.
[ "2 3\nPPW\nW.P\n", "3 3\nP.W\n.P.\nW.P\n" ]
[ "2\n", "0\n" ]
In the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.
[ { "input": "2 3\nPPW\nW.P", "output": "2" }, { "input": "3 3\nP.W\n.P.\nW.P", "output": "0" }, { "input": "1 1\nP", "output": "0" }, { "input": "2 6\nWW..WW\n.PPPP.", "output": "2" }, { "input": "6 2\n.W\n.W\n.P\nWP\n.P\nPW", "output": "3" }, { "input"...
124
0
3
20,827
74
Train
[ "dp", "games", "greedy" ]
B. Train
2
256
A stowaway and a controller play the following game. The train is represented by *n* wagons which are numbered with positive integers from 1 to *n* from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions — moving or idle. Every minute the players move. The controller's move is as follows. The controller has the movement direction — to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the 1-st or the *n*-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move. The stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of *n* wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back. Let's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train. If at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again. At any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner.
The first line contains three integers *n*, *m* and *k*. They represent the number of wagons in the train, the stowaway's and the controller's initial positions correspondingly (2<=≤<=*n*<=≤<=50, 1<=≤<=*m*,<=*k*<=≤<=*n*, *m*<=≠<=*k*). The second line contains the direction in which a controller moves. "to head" means that the controller moves to the train's head and "to tail" means that the controller moves to its tail. It is guaranteed that in the direction in which the controller is moving, there is at least one wagon. Wagon 1 is the head, and wagon *n* is the tail. The third line has the length from 1 to 200 and consists of symbols "0" and "1". The *i*-th symbol contains information about the train's state at the *i*-th minute of time. "0" means that in this very minute the train moves and "1" means that the train in this very minute stands idle. The last symbol of the third line is always "1" — that's the terminal train station.
If the stowaway wins, print "Stowaway" without quotes. Otherwise, print "Controller" again without quotes, then, separated by a space, print the number of a minute, at which the stowaway will be caught.
[ "5 3 2\nto head\n0001001\n", "3 2 1\nto tail\n0001\n" ]
[ "Stowaway", "Controller 2" ]
none
[ { "input": "5 3 2\nto head\n0001001", "output": "Stowaway" }, { "input": "3 2 1\nto tail\n0001", "output": "Controller 2" }, { "input": "4 2 1\nto tail\n1000001", "output": "Controller 6" }, { "input": "2 1 2\nto head\n111111", "output": "Stowaway" }, { "input": "...
92
0
3.977
20,903
906
Reverses
[ "dp", "string suffix structures", "strings" ]
null
null
Hurricane came to Berland and to suburbs Stringsvill. You are going to it to check if it's all right with you favorite string. Hurrinace broke it a bit by reversing some of its non-intersecting substrings. You have a photo of this string before hurricane and you want to restore it to original state using reversing minimum possible number of its substrings and find out which substrings you should reverse. You are given a string *s* — original state of your string and string *t* — state of the string after hurricane. You should select *k* non-intersecting substrings of *t* in such a way that after reverse of these substrings string will be equal *s* and *k* is minimum possible.
First line of input contains string *s* and second line contains string *t*. Both strings have same length and consist of lowercase English letters. 1<=≤<=|*s*|<==<=|*t*|<=≤<=5·105
In first line print *k* — minimum number of substrings you should reverse. Next output *k* lines. Each line should contain two integers *l**i*, *r**i* meaning that you should reverse substring from symbol number *l**i* to symbol *r**i* (strings are 1-indexed). These substrings shouldn't intersect. If there are multiple answers print any. If it's impossible to restore string output -1.
[ "abcxxxdef\ncbaxxxfed\n" ]
[ "2\n7 9\n1 3\n" ]
none
[]
30
0
0
20,974
986
Perfect Encoding
[ "fft", "math" ]
null
null
You are working as an analyst in a company working on a new system for big data storage. This system will store $n$ different objects. Each object should have a unique ID. To create the system, you choose the parameters of the system — integers $m \ge 1$ and $b_{1}, b_{2}, \ldots, b_{m}$. With these parameters an ID of some object in the system is an array of integers $[a_{1}, a_{2}, \ldots, a_{m}]$ where $1 \le a_{i} \le b_{i}$ holds for every $1 \le i \le m$. Developers say that production costs are proportional to $\sum_{i=1}^{m} b_{i}$. You are asked to choose parameters $m$ and $b_{i}$ so that the system will be able to assign unique IDs to $n$ different objects and production costs are minimized. Note that you don't have to use all available IDs.
In the only line of input there is one positive integer $n$. The length of the decimal representation of $n$ is no greater than $1.5 \cdot 10^{6}$. The integer does not contain leading zeros.
Print one number — minimal value of $\sum_{i=1}^{m} b_{i}$.
[ "36\n", "37\n", "12345678901234567890123456789\n" ]
[ "10\n", "11\n", "177\n" ]
none
[ { "input": "36", "output": "10" }, { "input": "37", "output": "11" }, { "input": "12345678901234567890123456789", "output": "177" }, { "input": "1", "output": "1" }, { "input": "2", "output": "2" }, { "input": "3", "output": "3" }, { "input...
2,000
21,401,600
0
21,046
626
Group Projects
[ "dp" ]
null
null
There are *n* students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the *i*-th student *a**i* minutes to finish his/her independent piece. If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum *a**i* in the group minus the minimum *a**i* in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most *k*? Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.
The first line contains two space-separated integers *n* and *k* (1<=≤<=*n*<=≤<=200, 0<=≤<=*k*<=≤<=1000) — the number of students and the maximum total imbalance allowed, respectively. The second line contains *n* space-separated integers *a**i* (1<=≤<=*a**i*<=≤<=500) — the time it takes the *i*-th student to complete his/her independent piece of work.
Print a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109<=+<=7.
[ "3 2\n2 4 5\n", "4 3\n7 8 9 10\n", "4 0\n5 10 20 21\n" ]
[ "3\n", "13\n", "1\n" ]
In the first sample, we have three options: - The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2. - The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1. - All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.
[ { "input": "3 2\n2 4 5", "output": "3" }, { "input": "4 3\n7 8 9 10", "output": "13" }, { "input": "4 0\n5 10 20 21", "output": "1" }, { "input": "20 1000\n50 50 100 100 150 150 200 200 250 250 300 300 350 350 400 400 450 450 500 500", "output": "97456952" }, { "i...
1,762
25,190,400
3
21,065
786
Till I Collapse
[ "data structures", "divide and conquer" ]
null
null
Rick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated *n* Mr. Meeseeks, standing in a line numbered from 1 to *n*. Each of them has his own color. *i*-th Mr. Meeseeks' color is *a**i*. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most *k* different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each 1<=≤<=*i*<=≤<=*e*<=≤<=*j*<=≤<=*n*, if Mr. Meeseeks number *i* and Mr. Meeseeks number *j* are in the same squad then Mr. Meeseeks number *e* should be in that same squad. Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized. Rick and Morty haven't finalized the exact value of *k*, so in order to choose it, for each *k* between 1 and *n* (inclusive) need to know the minimum number of presidios needed.
The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=105) — number of Mr. Meeseeks. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* separated by spaces (1<=≤<=*a**i*<=≤<=*n*) — colors of Mr. Meeseeks in order they standing in a line.
In the first and only line of input print *n* integers separated by spaces. *i*-th integer should be the minimum number of presidios needed if the value of *k* is *i*.
[ "5\n1 3 4 3 3\n", "8\n1 5 7 8 1 7 6 1\n" ]
[ "4 2 1 1 1 \n", "8 4 3 2 1 1 1 1 \n" ]
For the first sample testcase, some optimal ways of dividing army into squads for each *k* are: 1. [1], [3], [4], [3, 3] 1. [1], [3, 4, 3, 3] 1. [1, 3, 4, 3, 3] 1. [1, 3, 4, 3, 3] 1. [1, 3, 4, 3, 3] For the second testcase, some optimal ways of dividing army into squads for each *k* are: 1. [1], [5], [7], [8], [1], [7], [6], [1] 1. [1, 5], [7, 8], [1, 7], [6, 1] 1. [1, 5, 7], [8], [1, 7, 6, 1] 1. [1, 5, 7, 8], [1, 7, 6, 1] 1. [1, 5, 7, 8, 1, 7, 6, 1] 1. [1, 5, 7, 8, 1, 7, 6, 1] 1. [1, 5, 7, 8, 1, 7, 6, 1] 1. [1, 5, 7, 8, 1, 7, 6, 1]
[ { "input": "5\n1 3 4 3 3", "output": "4 2 1 1 1 " }, { "input": "8\n1 5 7 8 1 7 6 1", "output": "8 4 3 2 1 1 1 1 " }, { "input": "10\n4 1 2 6 8 5 3 9 3 9", "output": "10 4 3 2 2 2 2 1 1 1 " }, { "input": "85\n23 11 69 1 49 10 7 13 66 35 81 4 51 2 62 55 31 18 85 34 59 44 20 28...
31
0
-1
21,088
543
Road Improvement
[ "dp", "trees" ]
null
null
The country has *n* cities and *n*<=-<=1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to *n* inclusive. All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city *x* to any other city contains at most one bad road. Your task is — for every possible *x* determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1<=000<=000<=007 (109<=+<=7).
The first line of the input contains a single integer *n* (2<=≤<=*n*<=≤<=2·105) — the number of cities in the country. Next line contains *n*<=-<=1 positive integers *p*2,<=*p*3,<=*p*4,<=...,<=*p**n* (1<=≤<=*p**i*<=≤<=*i*<=-<=1) — the description of the roads in the country. Number *p**i* means that the country has a road connecting city *p**i* and city *i*.
Print *n* integers *a*1,<=*a*2,<=...,<=*a**n*, where *a**i* is the sought number of ways to improve the quality of the roads modulo 1<=000<=000<=007 (109<=+<=7), if the capital of the country is at city number *i*.
[ "3\n1 1\n", "5\n1 2 3 4\n" ]
[ "4 3 3", "5 8 9 8 5" ]
none
[ { "input": "3\n1 1", "output": "4 3 3" }, { "input": "5\n1 2 3 4", "output": "5 8 9 8 5" }, { "input": "31\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1", "output": "73741817 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 536870913 5368...
514
72,294,400
3
21,108
515
Drazil and His Happy Friends
[ "brute force", "dsu", "meet-in-the-middle", "number theory" ]
null
null
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan. There are *n* boys and *m* girls among his friends. Let's number them from 0 to *n*<=-<=1 and 0 to *m*<=-<=1 separately. In *i*-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, *i* starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever. Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.
The first line contains two integer *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=100). The second line contains integer *b* (0<=≤<=*b*<=≤<=*n*), denoting the number of happy boys among friends of Drazil, and then follow *b* distinct integers *x*1,<=*x*2,<=...,<=*x**b* (0<=≤<=*x**i*<=&lt;<=*n*), denoting the list of indices of happy boys. The third line conatins integer *g* (0<=≤<=*g*<=≤<=*m*), denoting the number of happy girls among friends of Drazil, and then follow *g* distinct integers *y*1,<=*y*2,<=... ,<=*y**g* (0<=≤<=*y**j*<=&lt;<=*m*), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.
If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".
[ "2 3\n0\n1 0\n", "2 4\n1 0\n1 2\n", "2 3\n1 0\n1 1\n" ]
[ "Yes\n", "No\n", "Yes\n" ]
By <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/169ade208e6eb4f9263c57aaff716529d59c3288.png" style="max-width: 100.0%;max-height: 100.0%;"/> we define the remainder of integer division of *i* by *k*. In first sample case: - On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. - On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. - On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. - On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. - On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.
[ { "input": "2 3\n0\n1 0", "output": "Yes" }, { "input": "2 4\n1 0\n1 2", "output": "No" }, { "input": "2 3\n1 0\n1 1", "output": "Yes" }, { "input": "16 88\n6 5 14 2 0 12 7\n30 21 64 35 79 74 39 63 44 81 73 0 27 33 69 12 86 46 20 25 55 52 7 58 23 5 60 32 41 50 82", "outpu...
46
2,867,200
-1
21,206
0
none
[ "none" ]
null
null
In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest. Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible. There are *n* (*n* is always even) possible starting positions for characters marked along the *Ox* axis. The positions are given by their distinct coordinates *x*1,<=*x*2,<=...,<=*x**n*, two characters cannot end up at the same position. Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be *n*<=-<=2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting. Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.
The first line on the input contains a single integer *n* (2<=≤<=*n*<=≤<=200<=000, *n* is even) — the number of positions available initially. The second line contains *n* distinct integers *x*1,<=*x*2,<=...,<=*x**n* (0<=≤<=*x**i*<=≤<=109), giving the coordinates of the corresponding positions.
Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.
[ "6\n0 1 3 7 15 31\n", "2\n73 37\n" ]
[ "7\n", "36\n" ]
In the first sample one of the optimum behavior of the players looks like that: 1. Vova bans the position at coordinate 15; 1. Lesha bans the position at coordinate 3; 1. Vova bans the position at coordinate 31; 1. Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7. In the second sample there are only two possible positions, so there will be no bans.
[ { "input": "6\n0 1 3 7 15 31", "output": "7" }, { "input": "2\n73 37", "output": "36" }, { "input": "2\n0 1000000000", "output": "1000000000" }, { "input": "8\n729541013 135019377 88372488 319157478 682081360 558614617 258129110 790518782", "output": "470242129" }, { ...
46
102,400
0
21,235
860
Arkady and a Nobody-men
[ "data structures", "dfs and similar", "trees" ]
null
null
Arkady words in a large company. There are *n* employees working in a system of a strict hierarchy. Namely, each employee, with an exception of the CEO, has exactly one immediate manager. The CEO is a manager (through a chain of immediate managers) of all employees. Each employee has an integer rank. The CEO has rank equal to 1, each other employee has rank equal to the rank of his immediate manager plus 1. Arkady has a good post in the company, however, he feels that he is nobody in the company's structure, and there are a lot of people who can replace him. He introduced the value of replaceability. Consider an employee *a* and an employee *b*, the latter being manager of *a* (not necessarily immediate). Then the replaceability *r*(*a*,<=*b*) of *a* with respect to *b* is the number of subordinates (not necessarily immediate) of the manager *b*, whose rank is not greater than the rank of *a*. Apart from replaceability, Arkady introduced the value of negligibility. The negligibility *z**a* of employee *a* equals the sum of his replaceabilities with respect to all his managers, i.e. , where the sum is taken over all his managers *b*. Arkady is interested not only in negligibility of himself, but also in negligibility of all employees in the company. Find the negligibility of each employee for Arkady.
The first line contains single integer *n* (1<=≤<=*n*<=≤<=5·105) — the number of employees in the company. The second line contains *n* integers *p*1,<=*p*2,<=...,<=*p**n* (0<=≤<=*p**i*<=≤<=*n*), where *p**i*<==<=0 if the *i*-th employee is the CEO, otherwise *p**i* equals the id of the immediate manager of the employee with id *i*. The employees are numbered from 1 to *n*. It is guaranteed that there is exactly one 0 among these values, and also that the CEO is a manager (not necessarily immediate) for all the other employees.
Print *n* integers — the negligibilities of all employees in the order of their ids: *z*1,<=*z*2,<=...,<=*z**n*.
[ "4\n0 1 2 1\n", "5\n2 3 4 5 0\n", "5\n0 1 1 1 3\n" ]
[ "0 2 4 2 \n", "10 6 3 1 0 \n", "0 3 3 3 5 \n" ]
Consider the first example: - The CEO has no managers, thus *z*<sub class="lower-index">1</sub> = 0. - *r*(2, 1) = 2 (employees 2 and 4 suit the conditions, employee 3 has too large rank). Thus *z*<sub class="lower-index">2</sub> = *r*(2, 1) = 2. - Similarly, *z*<sub class="lower-index">4</sub> = *r*(4, 1) = 2. - *r*(3, 2) = 1 (employee 3 is a subordinate of 2 and has suitable rank). *r*(3, 1) = 3 (employees 2, 3, 4 suit the conditions). Thus *z*<sub class="lower-index">3</sub> = *r*(3, 2) + *r*(3, 1) = 4.
[]
46
0
0
21,237
15
Triangles
[ "combinatorics", "dp" ]
E. Triangles
1
64
Last summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has *n* levels, where *n* is an even number. In the local council you were given an area map, where the granny's house is marked by point *H*, parts of dense forest are marked grey (see the picture to understand better). After a long time at home Peter decided to yield to his granny's persuasions and step out for a breath of fresh air. Being prudent, Peter plans the route beforehand. The route, that Peter considers the most suitable, has the following characteristics: - it starts and ends in the same place — the granny's house; - the route goes along the forest paths only (these are the segments marked black in the picture); - the route has positive length (to step out for a breath of fresh air Peter has to cover some distance anyway); - the route cannot cross itself; - there shouldn't be any part of dense forest within the part marked out by this route; You should find the amount of such suitable oriented routes modulo 1000000009. The example of the area map for *n*<==<=12 is given in the picture. Since the map has a regular structure, you can construct it for other *n* by analogy using the example.
The input data contain the only even integer *n* (2<=≤<=*n*<=≤<=106).
Output the only number — the amount of Peter's routes modulo 1000000009.
[ "2\n", "4\n" ]
[ "10\n", "74\n" ]
none
[ { "input": "2", "output": "10" }, { "input": "4", "output": "74" }, { "input": "6", "output": "1354" }, { "input": "8", "output": "163594" }, { "input": "10", "output": "122492554" }, { "input": "966", "output": "154440215" }, { "input": "9...
92
0
-1
21,260
0
none
[ "none" ]
null
null
Поликарп мечтает стать программистом и фанатеет от степеней двойки. Среди двух чисел ему больше нравится то, которое делится на большую степень числа 2. По заданной последовательности целых положительных чисел *a*1,<=*a*2,<=...,<=*a**n* требуется найти *r* — максимальную степень числа 2, на которую делится хотя бы одно из чисел последовательности. Кроме того, требуется вывести количество чисел *a**i*, которые делятся на *r*.
В первой строке записано целое число *n* (1<=≤<=*n*<=≤<=100) — длина последовательности *a*. Во второй строке записана последовательность целых чисел *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109).
Выведите два числа: - *r* — максимальную степень двойки, на которую делится хотя бы одно из чисел заданной последовательности, - количество элементов последовательности, которые делятся на *r*.
[ "5\n80 7 16 4 48\n", "4\n21 5 3 33\n" ]
[ "16 3\n", "1 4\n" ]
В первом тестовом примере максимальная степень двойки, на которую делится хотя бы одно число, равна 16 = 2<sup class="upper-index">4</sup>, на неё делятся числа 80, 16 и 48. Во втором тестовом примере все четыре числа нечётные, поэтому делятся только на 1 = 2<sup class="upper-index">0</sup>. Это и будет максимальной степенью двойки для данного примера.
[ { "input": "5\n80 7 16 4 48", "output": "16 3" }, { "input": "4\n21 5 3 33", "output": "1 4" }, { "input": "10\n8 112 52 86 93 102 24 24 100 826791168", "output": "256 1" }, { "input": "3\n458297759 18 104", "output": "8 1" }, { "input": "7\n12 14 40 8 74 104 11",...
62
4,608,000
3
21,263
776
The Holmes Children
[ "math", "number theory" ]
null
null
The Holmes children are fighting over who amongst them is the cleverest. Mycroft asked Sherlock and Eurus to find value of *f*(*n*), where *f*(1)<==<=1 and for *n*<=≥<=2, *f*(*n*) is the number of distinct ordered positive integer pairs (*x*,<=*y*) that satisfy *x*<=+<=*y*<==<=*n* and *gcd*(*x*,<=*y*)<==<=1. The integer *gcd*(*a*,<=*b*) is the greatest common divisor of *a* and *b*. Sherlock said that solving this was child's play and asked Mycroft to instead get the value of . Summation is done over all positive integers *d* that divide *n*. Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft. She defined a *k*-composite function *F**k*(*n*) recursively as follows: She wants them to tell the value of *F**k*(*n*) modulo 1000000007.
A single line of input contains two space separated integers *n* (1<=≤<=*n*<=≤<=1012) and *k* (1<=≤<=*k*<=≤<=1012) indicating that Eurus asks Sherlock and Mycroft to find the value of *F**k*(*n*) modulo 1000000007.
Output a single integer — the value of *F**k*(*n*) modulo 1000000007.
[ "7 1\n", "10 2\n" ]
[ "6", "4" ]
In the first case, there are 6 distinct ordered pairs (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1) satisfying *x* + *y* = 7 and *gcd*(*x*, *y*) = 1. Hence, *f*(7) = 6. So, *F*<sub class="lower-index">1</sub>(7) = *f*(*g*(7)) = *f*(*f*(7) + *f*(1)) = *f*(6 + 1) = *f*(7) = 6.
[ { "input": "7 1", "output": "6" }, { "input": "10 2", "output": "4" }, { "input": "640 15", "output": "2" }, { "input": "641 17", "output": "2" }, { "input": "641 2000", "output": "1" }, { "input": "961 2", "output": "930" }, { "input": "52...
389
307,200
3
21,264
926
Choose Place
[]
null
null
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right. Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard. You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'. Find any of the most convenient vacant places for Petya.
The input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' — the description of the left desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the center desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the right desk in the current row. So, the length of each of the six lines is 8. It is guaranteed that there is at least one vacant place in the classroom.
Print the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input. If there are multiple answers, print any.
[ "..-**-..\n..-**-..\n..-..-..\n..-..-..\n..-..-..\n..-..-..\n", "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-..-..\n..-**-..\n", "**-**-*.\n*.-*.-**\n**-**-**\n**-**-**\n..-..-..\n..-**-..\n" ]
[ "..-**-..\n..-**-..\n..-..-..\n..-P.-..\n..-..-..\n..-..-..\n", "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-P.-..\n..-**-..\n", "**-**-*.\n*.-*P-**\n**-**-**\n**-**-**\n..-..-..\n..-**-..\n" ]
In the first example the maximum convenience is 3. In the second example the maximum convenience is 2. In the third example the maximum convenience is 4.
[ { "input": "..-**-..\n..-**-..\n..-..-..\n..-..-..\n..-..-..\n..-..-..", "output": "..-**-..\n..-**-..\n..-..-..\n..-P.-..\n..-..-..\n..-..-.." }, { "input": "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-..-..\n..-**-..", "output": "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-P.-..\n..-**-.." }, ...
93
7,065,600
3
21,291
835
Palindromic characteristics
[ "brute force", "dp", "hashing", "strings" ]
null
null
Palindromic characteristics of string *s* with length |*s*| is a sequence of |*s*| integers, where *k*-th number is the total number of non-empty substrings of *s* which are *k*-palindromes. A string is 1-palindrome if and only if it reads the same backward as forward. A string is *k*-palindrome (*k*<=&gt;<=1) if and only if: 1. Its left half equals to its right half. 1. Its left and right halfs are non-empty (*k*<=-<=1)-palindromes. The left half of string *t* is its prefix of length ⌊|*t*|<=/<=2⌋, and right half — the suffix of the same length. ⌊|*t*|<=/<=2⌋ denotes the length of string *t* divided by 2, rounded down. Note that each substring is counted as many times as it appears in the string. For example, in the string "aaa" the substring "a" appears 3 times.
The first line contains the string *s* (1<=≤<=|*s*|<=≤<=5000) consisting of lowercase English letters.
Print |*s*| integers — palindromic characteristics of string *s*.
[ "abba\n", "abacaba\n" ]
[ "6 1 0 0 \n", "12 4 1 0 0 0 0 \n" ]
In the first example 1-palindromes are substring «a», «b», «b», «a», «bb», «abba», the substring «bb» is 2-palindrome. There are no 3- and 4-palindromes here.
[ { "input": "abba", "output": "6 1 0 0 " }, { "input": "abacaba", "output": "12 4 1 0 0 0 0 " }, { "input": "qqqpvmgd", "output": "11 3 0 0 0 0 0 0 " }, { "input": "wyemcafatp", "output": "11 1 0 0 0 0 0 0 0 0 " } ]
15
0
0
21,299
670
Magic Powder - 2
[ "binary search", "implementation" ]
null
null
The term of this problem is the same as the previous one, the only exception — increased restrictions.
The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=100<=000,<=1<=≤<=*k*<=≤<=109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=109), where the *i*-th number is equal to the number of grams of the *i*-th ingredient, needed to bake one cookie. The third line contains the sequence *b*1,<=*b*2,<=...,<=*b**n* (1<=≤<=*b**i*<=≤<=109), where the *i*-th number is equal to the number of grams of the *i*-th ingredient, which Apollinaria has.
Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.
[ "1 1000000000\n1\n1000000000\n", "10 1\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1 1 1 1 1\n", "3 1\n2 1 4\n11 3 16\n", "4 3\n4 3 5 6\n11 12 14 20\n" ]
[ "2000000000\n", "0\n", "4\n", "3\n" ]
none
[ { "input": "1 1000000000\n1\n1000000000", "output": "2000000000" }, { "input": "10 1\n1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000\n1 1 1 1 1 1 1 1 1 1", "output": "0" }, { "input": "3 1\n2 1 4\n11 3 16", "output": "4" ...
171
17,612,800
3
21,309
815
Karen and Test
[ "brute force", "combinatorics", "constructive algorithms", "math" ]
null
null
Karen has just arrived at school, and she has a math test today! The test is about basic addition and subtraction. Unfortunately, the teachers were too busy writing tasks for Codeforces rounds, and had no time to make an actual test. So, they just put one question in the test that is worth all the points. There are *n* integers written on a row. Karen must alternately add and subtract each pair of adjacent integers, and write down the sums or differences on the next row. She must repeat this process on the values on the next row, and so on, until only one integer remains. The first operation should be addition. Note that, if she ended the previous row by adding the integers, she should start the next row by subtracting, and vice versa. The teachers will simply look at the last integer, and then if it is correct, Karen gets a perfect score, otherwise, she gets a zero for the test. Karen has studied well for this test, but she is scared that she might make a mistake somewhere and it will cause her final answer to be wrong. If the process is followed, what number can she expect to be written on the last row? Since this number can be quite large, output only the non-negative remainder after dividing it by 109<=+<=7.
The first line of input contains a single integer *n* (1<=≤<=*n*<=≤<=200000), the number of numbers written on the first row. The next line contains *n* integers. Specifically, the *i*-th one among these is *a**i* (1<=≤<=*a**i*<=≤<=109), the *i*-th number on the first row.
Output a single integer on a line by itself, the number on the final row after performing the process above. Since this number can be quite large, print only the non-negative remainder after dividing it by 109<=+<=7.
[ "5\n3 6 9 12 15\n", "4\n3 7 5 2\n" ]
[ "36\n", "1000000006\n" ]
In the first test case, the numbers written on the first row are 3, 6, 9, 12 and 15. Karen performs the operations as follows: The non-negative remainder after dividing the final number by 10<sup class="upper-index">9</sup> + 7 is still 36, so this is the correct output. In the second test case, the numbers written on the first row are 3, 7, 5 and 2. Karen performs the operations as follows: The non-negative remainder after dividing the final number by 10<sup class="upper-index">9</sup> + 7 is 10<sup class="upper-index">9</sup> + 6, so this is the correct output.
[ { "input": "5\n3 6 9 12 15", "output": "36" }, { "input": "4\n3 7 5 2", "output": "1000000006" }, { "input": "1\n1", "output": "1" }, { "input": "16\n985629174 189232688 48695377 692426437 952164554 243460498 173956955 210310239 237322183 96515847 678847559 682240199 49879255...
249
12,902,400
-1
21,322
958
Death Stars (medium)
[ "hashing", "strings" ]
null
null
The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star. The first map is an *N*<=×<=*M* grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an *M*<=×<=*N* grid. Heidi needs to align those two maps in such a way that they overlap over some *M*<=×<=*M* section in which all cosmic objects are identical. Help Heidi by identifying where such an *M*<=×<=*M* section lies within both maps.
The first line of the input contains two space-separated integers *N* and *M* (1<=≤<=*N*<=≤<=2000, 1<=≤<=*M*<=≤<=200, *M*<=≤<=*N*). The next *N* lines each contain *M* lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next *M* lines each contain *N* characters, describing the second map in the same format.
The only line of the output should contain two space-separated integers *i* and *j*, denoting that the section of size *M*<=×<=*M* in the first map that starts at the *i*-th row is equal to the section of the second map that starts at the *j*-th column. Rows and columns are numbered starting from 1. If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists.
[ "10 5\nsomer\nandom\nnoise\nmayth\neforc\nebewi\nthyou\nhctwo\nagain\nnoise\nsomermayth\nandomeforc\nnoiseebewi\nagainthyou\nnoisehctwo\n" ]
[ "4 6\n" ]
The 5-by-5 grid for the first test case looks like this:
[ { "input": "10 5\nsomer\nandom\nnoise\nmayth\neforc\nebewi\nthyou\nhctwo\nagain\nnoise\nsomermayth\nandomeforc\nnoiseebewi\nagainthyou\nnoisehctwo", "output": "4 6" }, { "input": "1 1\ng\ng", "output": "1 1" } ]
93
8,294,400
-1
21,359
97
Leaders
[ "dfs and similar", "dsu", "graphs", "trees" ]
E. Leaders
2
256
After a revolution in Berland the new dictator faced an unexpected challenge: the country has to be somehow ruled. The dictator is a very efficient manager, yet he can't personally give orders to each and every citizen. That's why he decided to pick some set of leaders he would control. Those leaders will directly order the citizens. However, leadership efficiency turned out to vary from person to person (i.e. while person A makes an efficient leader, person B may not be that good at it). That's why the dictator asked world-famous berland scientists for help. The scientists suggested an innovatory technology — to make the leaders work in pairs. A relationship graph is some undirected graph whose vertices correspond to people. A simple path is a path with no repeated vertices. Long and frighteningly expensive research showed that a pair of people has maximum leadership qualities if a graph of relationships has a simple path between them with an odd number of edges. The scientists decided to call such pairs of different people leader pairs. Secret services provided the scientists with the relationship graph so that the task is simple — we have to learn to tell the dictator whether the given pairs are leader pairs or not. Help the scientists cope with the task.
The first line contains integers *n* and *m* (1<=≤<=*n*<=≤<=105,<=0<=≤<=*m*<=≤<=105) — the number of vertices and edges in the relationship graph correspondingly. Next *m* lines contain pairs of integers *a* and *b* which mean that there is an edge between the *a*-th and the *b*-th vertices (the vertices are numbered starting from 1, 1<=≤<=*a*,<=*b*<=≤<=*n*). It is guaranteed that the graph has no loops or multiple edges. Next line contains number *q* (1<=≤<=*q*<=≤<=105) — the number of pairs the scientists are interested in. Next *q* lines contain these pairs (in the same format as the edges, the queries can be repeated, a query can contain a pair of the identical vertices).
For each query print on a single line "Yes" if there's a simple odd path between the pair of people; otherwise, print "No".
[ "7 7\n1 3\n1 4\n2 3\n2 4\n5 6\n6 7\n7 5\n8\n1 2\n1 3\n1 4\n2 4\n1 5\n5 6\n5 7\n6 7\n" ]
[ "No\nYes\nYes\nYes\nNo\nYes\nYes\nYes\n" ]
Notes to the samples: 1) Between vertices 1 and 2 there are 2 different simple paths in total: 1-3-2 and 1-4-2. Both of them consist of an even number of edges. 2) Vertices 1 and 3 are connected by an edge, that's why a simple odd path for them is 1-3. 5) Vertices 1 and 5 are located in different connected components, there's no path between them.
[]
218
0
-1
21,399
0
none
[ "none" ]
null
null
Vasya has *n* items lying in a line. The items are consecutively numbered by numbers from 1 to *n* in such a way that the leftmost item has number 1, the rightmost item has number *n*. Each item has a weight, the *i*-th item weights *w**i* kilograms. Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions: 1. Take the leftmost item with the left hand and spend *w**i*<=·<=*l* energy units (*w**i* is a weight of the leftmost item, *l* is some parameter). If the previous action was the same (left-hand), then the robot spends extra *Q**l* energy units; 1. Take the rightmost item with the right hand and spend *w**j*<=·<=*r* energy units (*w**j* is a weight of the rightmost item, *r* is some parameter). If the previous action was the same (right-hand), then the robot spends extra *Q**r* energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.
The first line contains five integers *n*,<=*l*,<=*r*,<=*Q**l*,<=*Q**r* (1<=≤<=*n*<=≤<=105;<=1<=≤<=*l*,<=*r*<=≤<=100;<=1<=≤<=*Q**l*,<=*Q**r*<=≤<=104). The second line contains *n* integers *w*1,<=*w*2,<=...,<=*w**n* (1<=≤<=*w**i*<=≤<=100).
In the single line print a single number — the answer to the problem.
[ "3 4 4 19 1\n42 3 99\n", "4 7 2 3 9\n1 2 3 4\n" ]
[ "576\n", "34\n" ]
Consider the first sample. As *l* = *r*, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units. The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.
[ { "input": "3 4 4 19 1\n42 3 99", "output": "576" }, { "input": "4 7 2 3 9\n1 2 3 4", "output": "34" }, { "input": "2 100 100 10000 10000\n100 100", "output": "20000" }, { "input": "2 3 4 5 6\n1 2", "output": "11" }, { "input": "1 78 94 369 10000\n93", "output...
0
0
-1
21,419
756
Long number
[ "expression parsing", "math", "number theory" ]
null
null
Consider the following grammar: - &lt;expression&gt; ::= &lt;term&gt; | &lt;expression&gt; '+' &lt;term&gt;- &lt;term&gt; ::= &lt;number&gt; | &lt;number&gt; '-' &lt;number&gt; | &lt;number&gt; '(' &lt;expression&gt; ')'- &lt;number&gt; ::= &lt;pos_digit&gt; | &lt;number&gt; &lt;digit&gt;- &lt;digit&gt; ::= '0' | &lt;pos_digit&gt;- &lt;pos_digit&gt; ::= '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' This grammar describes a number in decimal system using the following rules: - &lt;number&gt; describes itself,- &lt;number&gt;-&lt;number&gt; (l-r, *l*<=≤<=*r*) describes integer which is concatenation of all integers from *l* to *r*, written without leading zeros. For example, 8-11 describes 891011,- &lt;number&gt;(&lt;expression&gt;) describes integer which is concatenation of &lt;number&gt; copies of integer described by &lt;expression&gt;,- &lt;expression&gt;+&lt;term&gt; describes integer which is concatenation of integers described by &lt;expression&gt; and &lt;term&gt;. For example, 2(2-4+1)+2(2(17)) describes the integer 2341234117171717. You are given an expression in the given grammar. Print the integer described by it modulo 109<=+<=7.
The only line contains a non-empty string at most 105 characters long which is valid according to the given grammar. In particular, it means that in terms l-r *l*<=≤<=*r* holds.
Print single integer — the number described by the expression modulo 109<=+<=7.
[ "8-11\n", "2(2-4+1)+2(2(17))\n", "1234-5678\n", "1+2+3+4-5+6+7-9\n" ]
[ "891011\n", "100783079\n", "745428774\n", "123456789\n" ]
none
[ { "input": "8-11", "output": "891011" }, { "input": "2(2-4+1)+2(2(17))", "output": "100783079" }, { "input": "1234-5678", "output": "745428774" }, { "input": "1+2+3+4-5+6+7-9", "output": "123456789" }, { "input": "598777", "output": "598777" }, { "inpu...
30
0
-1
21,429
370
Berland Bingo
[ "implementation" ]
null
null
Lately, a national version of a bingo game has become very popular in Berland. There are *n* players playing the game, each player has a card with numbers. The numbers on each card are distinct, but distinct cards can have equal numbers. The card of the *i*-th player contains *m**i* numbers. During the game the host takes numbered balls one by one from a bag. He reads the number aloud in a high and clear voice and then puts the ball away. All participants cross out the number if it occurs on their cards. The person who crosses out all numbers from his card first, wins. If multiple people cross out all numbers from their cards at the same time, there are no winners in the game. At the beginning of the game the bag contains 100 balls numbered 1 through 100, the numbers of all balls are distinct. You are given the cards for each player. Write a program that determines whether a player can win the game at the most favorable for him scenario or not.
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of the players. Then follow *n* lines, each line describes a player's card. The line that describes a card starts from integer *m**i* (1<=≤<=*m**i*<=≤<=100) that shows how many numbers the *i*-th player's card has. Then follows a sequence of integers *a**i*,<=1,<=*a**i*,<=2,<=...,<=*a**i*,<=*m**i* (1<=≤<=*a**i*,<=*k*<=≤<=100) — the numbers on the *i*-th player's card. The numbers in the lines are separated by single spaces. It is guaranteed that all the numbers on each card are distinct.
Print *n* lines, the *i*-th line must contain word "YES" (without the quotes), if the *i*-th player can win, and "NO" (without the quotes) otherwise.
[ "3\n1 1\n3 2 4 1\n2 10 11\n", "2\n1 1\n1 1\n" ]
[ "YES\nNO\nYES\n", "NO\nNO\n" ]
none
[ { "input": "3\n1 1\n3 2 4 1\n2 10 11", "output": "YES\nNO\nYES" }, { "input": "2\n1 1\n1 1", "output": "NO\nNO" }, { "input": "1\n1 1", "output": "YES" }, { "input": "2\n1 2\n1 3", "output": "YES\nYES" }, { "input": "2\n1 1\n2 1 2", "output": "YES\nNO" }, ...
93
0
0
21,528
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
[]
92
0
0
21,580
792
Mages and Monsters
[ "data structures", "geometry" ]
null
null
Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells. Vova's character can learn new spells during the game. Every spell is characterized by two values *x**i* and *y**i* — damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage *x* and mana cost *y* for *z* seconds, then he will deal *x*·*z* damage and spend *y*·*z* mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously. Also Vova can fight monsters. Every monster is characterized by two values *t**j* and *h**j* — monster kills Vova's character in *t**j* seconds and has *h**j* health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones. Vova's character kills a monster, if he deals *h**j* damage to it in no more than *t**j* seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in *t**j* seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight. You have to write a program which can answer two types of queries: - 1 *x* *y* — Vova's character learns new spell which deals *x* damage per second and costs *y* mana per second. - 2 *t* *h* — Vova fights the monster which kills his character in *t* seconds and has *h* health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game. For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.
The first line contains two integer numbers *q* and *m* (2<=≤<=*q*<=≤<=105,<=1<=≤<=*m*<=≤<=1012) — the number of queries and the amount of mana at the beginning of every fight. *i*-th of each next *q* lines contains three numbers *k**i*, *a**i* and *b**i* (1<=≤<=*k**i*<=≤<=2,<=1<=≤<=*a**i*,<=*b**i*<=≤<=106). Using them you can restore queries this way: let *j* be the index of the last query of second type with positive answer (*j*<==<=0 if there were none of these). - If *k**i*<==<=1, then character learns spell with *x*<==<=(*a**i*<=+<=*j*) *mod* 106<=+<=1, *y*<==<=(*b**i*<=+<=*j*) *mod* 106<=+<=1. - If *k**i*<==<=2, then you have to determine if Vova is able to win the fight against monster with *t*<==<=(*a**i*<=+<=*j*) *mod* 106<=+<=1, *h*<==<=(*b**i*<=+<=*j*) *mod* 106<=+<=1.
For every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.
[ "3 100\n1 4 9\n2 19 49\n2 19 49\n" ]
[ "YES\nNO\n" ]
In first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana.
[ { "input": "3 100\n1 4 9\n2 19 49\n2 19 49", "output": "YES\nNO" }, { "input": "10 442006988299\n2 10 47\n1 9 83\n1 15 24\n2 19 47\n2 75 99\n2 85 23\n2 8 33\n2 9 82\n1 86 49\n2 71 49", "output": "NO\nYES\nYES\nYES\nYES\nYES\nYES" }, { "input": "2 424978864039\n2 7 3\n2 10 8", "output...
873
15,564,800
3
21,586
0
none
[ "none" ]
null
null
...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu... Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super weapon. Due to high seismic activity and poor weather conditions the satellites haven't yet been able to make clear shots of the monster. The analysis of the first shot resulted in an undirected graph with *n* vertices and *m* edges. Now the world's best minds are about to determine whether this graph can be regarded as Cthulhu or not. To add simplicity, let's suppose that Cthulhu looks from the space like some spherical body with tentacles attached to it. Formally, we shall regard as Cthulhu such an undirected graph that can be represented as a set of three or more rooted trees, whose roots are connected by a simple cycle. It is guaranteed that the graph contains no multiple edges and self-loops.
The first line contains two integers — the number of vertices *n* and the number of edges *m* of the graph (1<=≤<=*n*<=≤<=100, 0<=≤<=*m*<=≤<=). Each of the following *m* lines contains a pair of integers *x* and *y*, that show that an edge exists between vertices *x* and *y* (1<=≤<=*x*,<=*y*<=≤<=*n*,<=*x*<=≠<=*y*). For each pair of vertices there will be at most one edge between them, no edge connects a vertex to itself.
Print "NO", if the graph is not Cthulhu and "FHTAGN!" if it is.
[ "6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4\n", "6 5\n5 6\n4 6\n3 1\n5 1\n1 2\n" ]
[ "FHTAGN!", "NO" ]
Let us denote as a simple cycle a set of *v* vertices that can be numbered so that the edges will only exist between vertices number 1 and 2, 2 and 3, ..., *v* - 1 and *v*, *v* and 1. A tree is a connected undirected graph consisting of *n* vertices and *n* - 1 edges (*n* &gt; 0). A rooted tree is a tree where one vertex is selected to be the root.
[ { "input": "6 6\n6 3\n6 4\n5 1\n2 5\n1 4\n5 4", "output": "FHTAGN!" }, { "input": "6 5\n5 6\n4 6\n3 1\n5 1\n1 2", "output": "NO" }, { "input": "10 10\n4 10\n8 5\n2 8\n4 9\n9 3\n2 7\n10 6\n10 2\n9 8\n1 8", "output": "FHTAGN!" }, { "input": "5 4\n1 5\n1 3\n1 4\n3 2", "outpu...
248
2,048,000
3
21,614
387
George and Number
[ "greedy", "implementation" ]
null
null
George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers *b*. During the game, George modifies the array by using special changes. Let's mark George's current array as *b*1,<=*b*2,<=...,<=*b*|*b*| (record |*b*| denotes the current length of the array). Then one change is a sequence of actions: - Choose two distinct indexes *i* and *j* (1<=≤<=*i*,<=*j*<=≤<=|*b*|; *i*<=≠<=*j*), such that *b**i*<=≥<=*b**j*. - Get number *v*<==<=*concat*(*b**i*,<=*b**j*), where *concat*(*x*,<=*y*) is a number obtained by adding number *y* to the end of the decimal record of number *x*. For example, *concat*(500,<=10)<==<=50010, *concat*(2,<=2)<==<=22. - Add number *v* to the end of the array. The length of the array will increase by one. - Remove from the array numbers with indexes *i* and *j*. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array. George played for a long time with his array *b* and received from array *b* an array consisting of exactly one number *p*. Now George wants to know: what is the maximum number of elements array *b* could contain originally? Help him find this number. Note that originally the array could contain only positive integers.
The first line of the input contains a single integer *p* (1<=≤<=*p*<=&lt;<=10100000). It is guaranteed that number *p* doesn't contain any leading zeroes.
Print an integer — the maximum number of elements array *b* could contain originally.
[ "9555\n", "10000000005\n", "800101\n", "45\n", "1000000000000001223300003342220044555\n", "19992000\n", "310200\n" ]
[ "4", "2", "3", "1", "17", "1", "2" ]
Let's consider the test examples: - Originally array *b* can be equal to {5, 9, 5, 5}. The sequence of George's changes could have been: {5, 9, 5, 5} → {5, 5, 95} → {95, 55} → {9555}. - Originally array *b* could be equal to {1000000000, 5}. Please note that the array *b* cannot contain zeros. - Originally array *b* could be equal to {800, 10, 1}. - Originally array *b* could be equal to {45}. It cannot be equal to {4, 5}, because George can get only array {54} from this array in one operation. Note that the numbers can be very large.
[ { "input": "9555", "output": "4" }, { "input": "10000000005", "output": "2" }, { "input": "800101", "output": "3" }, { "input": "45", "output": "1" }, { "input": "1000000000000001223300003342220044555", "output": "17" }, { "input": "19992000", "out...
124
0
0
21,642
80
Depression
[ "geometry", "math" ]
B. Depression
1
256
Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels! There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock. Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll. Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00. You can only rotate the hands forward, that is, as is shown in the picture: As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction. Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.
The only line of input contains current time according to the digital clock, formatted as HH:MM (00<=≤<=HH<=≤<=23, 00<=≤<=MM<=≤<=59). The mantel clock initially shows 12:00. Pretests contain times of the beginning of some morning TV programs of the Channel One Russia.
Print two numbers *x* and *y* — the angles of turning the hour and minute hands, respectively (0<=≤<=*x*,<=*y*<=&lt;<=360). The absolute or relative error in the answer should not exceed 10<=-<=9.
[ "12:00\n", "04:30\n", "08:17\n" ]
[ "0 0", "135 180", "248.5 102" ]
A note to the second example: the hour hand will be positioned exactly in the middle, between 4 and 5.
[ { "input": "12:00", "output": "0 0" }, { "input": "04:30", "output": "135 180" }, { "input": "08:17", "output": "248.5 102" }, { "input": "07:20", "output": "220 120" }, { "input": "09:55", "output": "297.5 330" }, { "input": "11:59", "output": "35...
46
0
3.977
21,656
258
Little Elephant and LCM
[ "binary search", "combinatorics", "dp", "math" ]
null
null
The Little Elephant loves the LCM (least common multiple) operation of a non-empty set of positive integers. The result of the LCM operation of *k* positive integers *x*1,<=*x*2,<=...,<=*x**k* is the minimum positive integer that is divisible by each of numbers *x**i*. Let's assume that there is a sequence of integers *b*1,<=*b*2,<=...,<=*b**n*. Let's denote their LCMs as *lcm*(*b*1,<=*b*2,<=...,<=*b**n*) and the maximum of them as *max*(*b*1,<=*b*2,<=...,<=*b**n*). The Little Elephant considers a sequence *b* good, if *lcm*(*b*1,<=*b*2,<=...,<=*b**n*)<==<=*max*(*b*1,<=*b*2,<=...,<=*b**n*). The Little Elephant has a sequence of integers *a*1,<=*a*2,<=...,<=*a**n*. Help him find the number of good sequences of integers *b*1,<=*b*2,<=...,<=*b**n*, such that for all *i* (1<=≤<=*i*<=≤<=*n*) the following condition fulfills: 1<=≤<=*b**i*<=≤<=*a**i*. As the answer can be rather large, print the remainder from dividing it by 1000000007 (109<=+<=7).
The first line contains a single positive integer *n* (1<=≤<=*n*<=≤<=105) — the number of integers in the sequence *a*. The second line contains *n* space-separated integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=105) — sequence *a*.
In the single line print a single integer — the answer to the problem modulo 1000000007 (109<=+<=7).
[ "4\n1 4 3 2\n", "2\n6 3\n" ]
[ "15\n", "13\n" ]
none
[ { "input": "4\n1 4 3 2", "output": "15" }, { "input": "2\n6 3", "output": "13" }, { "input": "7\n1 2 1 2 3 4 1", "output": "27" }, { "input": "4\n6 7 2 3", "output": "89" }, { "input": "7\n2 1 1 1 2 2 2", "output": "16" }, { "input": "7\n7 1 9 9 10 4 4...
4,000
19,251,200
0
21,675
617
Chocolate
[ "combinatorics" ]
null
null
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't. Please note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.
The first line of the input contains integer *n* (1<=≤<=*n*<=≤<=100) — the number of pieces in the chocolate bar. The second line contains *n* integers *a**i* (0<=≤<=*a**i*<=≤<=1), where 0 represents a piece without the nut and 1 stands for a piece with the nut.
Print the number of ways to break the chocolate into multiple parts so that each part would contain exactly one nut.
[ "3\n0 1 0\n", "5\n1 0 1 0 1\n" ]
[ "1\n", "4\n" ]
In the first sample there is exactly one nut, so the number of ways equals 1 — Bob shouldn't make any breaks. In the second sample you can break the bar in four ways: 10|10|1 1|010|1 10|1|01 1|01|01
[ { "input": "3\n0 1 0", "output": "1" }, { "input": "5\n1 0 1 0 1", "output": "4" }, { "input": "10\n0 0 1 0 0 0 1 1 0 1", "output": "8" }, { "input": "20\n0 0 0 0 1 1 1 0 1 0 0 1 0 1 1 0 1 1 1 0", "output": "24" }, { "input": "50\n0 1 1 1 1 1 1 0 1 1 0 1 1 1 0 0 1...
124
1,638,400
3
21,716
0
none
[ "none" ]
null
null
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, *m* icons can fit in a horizontal row in any window. Igor K.'s computer contains *n* folders in the D: disk's root catalog. The folders are numbered from 1 to *n* in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from *a* to *b* inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from *a* to *b* and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.
The only line contains four integers *n*, *m*, *a*, *b* (1<=≤<=*n*,<=*m*<=≤<=109, 1<=≤<=*a*<=≤<=*b*<=≤<=*n*). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.
Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from *a* to *b*.
[ "11 4 3 9\n", "20 5 2 20\n" ]
[ "3\n", "2\n" ]
The images below illustrate statement tests. The first test: <img class="tex-graphics" src="https://espresso.codeforces.com/a0e4ba690dd16e3c68210a28afd82020b23fb605.png" style="max-width: 100.0%;max-height: 100.0%;"/> In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection. The second test: <img class="tex-graphics" src="https://espresso.codeforces.com/289e2666a3d8b3dfe5b22ff3d88976df711640f7.png" style="max-width: 100.0%;max-height: 100.0%;"/> In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.
[ { "input": "11 4 3 9", "output": "3" }, { "input": "20 5 2 20", "output": "2" }, { "input": "1 1 1 1", "output": "1" }, { "input": "26 5 2 18", "output": "3" }, { "input": "21 5 1 15", "output": "1" }, { "input": "21 5 1 21", "output": "1" }, {...
124
0
0
21,744
710
Two Arithmetic Progressions
[ "math", "number theory" ]
null
null
You are given two arithmetic progressions: *a*1*k*<=+<=*b*1 and *a*2*l*<=+<=*b*2. Find the number of integers *x* such that *L*<=≤<=*x*<=≤<=*R* and *x*<==<=*a*1*k*'<=+<=*b*1<==<=*a*2*l*'<=+<=*b*2, for some integers *k*',<=*l*'<=≥<=0.
The only line contains six integers *a*1,<=*b*1,<=*a*2,<=*b*2,<=*L*,<=*R* (0<=&lt;<=*a*1,<=*a*2<=≤<=2·109,<=<=-<=2·109<=≤<=*b*1,<=*b*2,<=*L*,<=*R*<=≤<=2·109,<=*L*<=≤<=*R*).
Print the desired number of integers *x*.
[ "2 0 3 3 5 21\n", "2 4 3 0 6 17\n" ]
[ "3\n", "2\n" ]
none
[ { "input": "2 0 3 3 5 21", "output": "3" }, { "input": "2 4 3 0 6 17", "output": "2" }, { "input": "2 0 4 2 -39 -37", "output": "0" }, { "input": "1 9 3 11 49 109", "output": "20" }, { "input": "3 81 5 72 -1761 501", "output": "28" }, { "input": "8 -89...
62
0
0
21,745
161
Discounts
[ "constructive algorithms", "greedy", "sortings" ]
null
null
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheaper). If there are several items with the same minimum price, the discount is available for only one of them! Polycarpus has *k* carts, and he wants to buy up all stools and pencils from the supermarket. Help him distribute the stools and the pencils among the shopping carts, so that the items' total price (including the discounts) is the least possible. Polycarpus must use all *k* carts to purchase the items, no shopping cart can remain empty. Each shopping cart can contain an arbitrary number of stools and/or pencils.
The first input line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=103) — the number of items in the supermarket and the number of carts, correspondingly. Next *n* lines describe the items as "*c**i* *t**i*" (without the quotes), where *c**i* (1<=≤<=*c**i*<=≤<=109) is an integer denoting the price of the *i*-th item, *t**i* (1<=≤<=*t**i*<=≤<=2) is an integer representing the type of item *i* (1 for a stool and 2 for a pencil). The numbers in the lines are separated by single spaces.
In the first line print a single real number with exactly one decimal place — the minimum total price of the items, including the discounts. In the following *k* lines print the descriptions of the items in the carts. In the *i*-th line print the description of the *i*-th cart as "*t* *b*1 *b*2 ... *b**t*" (without the quotes), where *t* is the number of items in the *i*-th cart, and the sequence *b*1,<=*b*2,<=...,<=*b**t* (1<=≤<=*b**j*<=≤<=*n*) gives the indices of items to put in this cart in the optimal distribution. All indices of items in all carts should be pairwise different, each item must belong to exactly one cart. You can print the items in carts and the carts themselves in any order. The items are numbered from 1 to *n* in the order in which they are specified in the input. If there are multiple optimal distributions, you are allowed to print any of them.
[ "3 2\n2 1\n3 2\n3 1\n", "4 3\n4 1\n1 2\n2 2\n3 2\n" ]
[ "5.5\n2 1 2\n1 3\n", "8.0\n1 1\n2 4 2\n1 3\n" ]
In the first sample case the first cart should contain the 1st and 2nd items, and the second cart should contain the 3rd item. This way each cart has a stool and each cart has a 50% discount for the cheapest item. The total price of all items will be: 2·0.5 + (3 + 3·0.5) = 1 + 4.5 = 5.5.
[ { "input": "3 2\n2 1\n3 2\n3 1", "output": "5.5\n2 1 2\n1 3" }, { "input": "4 3\n4 1\n1 2\n2 2\n3 2", "output": "8.0\n1 1\n1 2\n2 3 4" }, { "input": "1 1\n1 1", "output": "0.5\n1 1" }, { "input": "1 1\n1 2", "output": "1.0\n1 1" }, { "input": "10 1\n1 1\n2 2\n1 1\...
248
20,172,800
0
21,788
518
Arthur and Questions
[ "greedy", "implementation", "math", "ternary search" ]
null
null
After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length *n* (*a*1,<=*a*2,<=...,<=*a**n*), consisting of integers and integer *k*, not exceeding *n*. This sequence had the following property: if you write out the sums of all its segments consisting of *k* consecutive elements (*a*1 <=+<= *a*2 ... <=+<= *a**k*,<= *a*2 <=+<= *a*3 <=+<= ... <=+<= *a**k*<=+<=1,<= ...,<= *a**n*<=-<=*k*<=+<=1 <=+<= *a**n*<=-<=*k*<=+<=2 <=+<= ... <=+<= *a**n*), then those numbers will form strictly increasing sequence. For example, for the following sample: *n*<==<=5,<= *k*<==<=3,<= *a*<==<=(1,<= 2,<= 4,<= 5,<= 6) the sequence of numbers will look as follows: (1 <=+<= 2 <=+<= 4,<= 2 <=+<= 4 <=+<= 5,<= 4 <=+<= 5 <=+<= 6) = (7,<= 11,<= 15), that means that sequence *a* meets the described property. Obviously the sequence of sums will have *n*<=-<=*k*<=+<=1 elements. Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |*a**i*|, where |*a**i*| is the absolute value of *a**i*.
The first line contains two integers *n* and *k* (1<=≤<=*k*<=≤<=*n*<=≤<=105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains *n* space-separated elements *a**i* (1<=≤<=*i*<=≤<=*n*). If *a**i* <==<= ?, then the *i*-th element of Arthur's sequence was replaced by a question mark. Otherwise, *a**i* (<=-<=109<=≤<=*a**i*<=≤<=109) is the *i*-th element of Arthur's sequence.
If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print *n* integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |*a**i*|, where |*a**i*| is the absolute value of *a**i*. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.
[ "3 2\n? 1 2\n", "5 1\n-10 -9 ? -7 -6\n", "5 3\n4 6 7 2 9\n" ]
[ "0 1 2 \n", "-10 -9 -8 -7 -6 \n", "Incorrect sequence\n" ]
none
[ { "input": "3 2\n? 1 2", "output": "0 1 2 " }, { "input": "5 1\n-10 -9 ? -7 -6", "output": "-10 -9 -8 -7 -6 " }, { "input": "5 3\n4 6 7 2 9", "output": "Incorrect sequence" }, { "input": "9 3\n? ? ? ? ? ? ? ? ?", "output": "-1 -1 -1 0 0 0 1 1 1 " }, { "input": "5 ...
217
12,595,200
3
21,852
453
Little Pony and Harmony Chest
[ "bitmasks", "brute force", "dp" ]
null
null
Princess Twilight went to Celestia and Luna's old castle to research the chest from the Elements of Harmony. A sequence of positive integers *b**i* is harmony if and only if for every two elements of the sequence their greatest common divisor equals 1. According to an ancient book, the key of the chest is a harmony sequence *b**i* which minimizes the following expression: You are given sequence *a**i*, help Princess Twilight to find the key.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=100) — the number of elements of the sequences *a* and *b*. The next line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=30).
Output the key — sequence *b**i* that minimizes the sum described above. If there are multiple optimal sequences, you can output any of them.
[ "5\n1 1 1 1 1\n", "5\n1 6 4 2 8\n" ]
[ "1 1 1 1 1 ", "1 5 3 1 8 " ]
none
[ { "input": "5\n1 1 1 1 1", "output": "1 1 1 1 1 " }, { "input": "5\n1 6 4 2 8", "output": "1 5 3 1 8 " }, { "input": "10\n16 3 16 10 12 5 14 14 15 27", "output": "19 1 17 7 11 1 16 13 15 29 " }, { "input": "10\n8 7 11 5 17 24 28 18 7 8", "output": "9 7 11 5 17 23 29 19 1 ...
0
0
-1
21,878
556
Case of Fake Numbers
[ "brute force", "implementation" ]
null
null
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was. Its most important components are a button and a line of *n* similar gears. Each gear has *n* teeth containing all numbers from 0 to *n*<=-<=1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on. Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if *n*<==<=5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active. Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0,<=1,<=2,<=...,<=*n*<=-<=1. Write a program that determines whether the given puzzle is real or fake.
The first line contains integer *n* (1<=≤<=*n*<=≤<=1000) — the number of gears. The second line contains *n* digits *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=*n*<=-<=1) — the sequence of active teeth: the active tooth of the *i*-th gear contains number *a**i*.
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
[ "3\n1 0 0\n", "5\n4 2 1 4 3\n", "4\n0 2 3 1\n" ]
[ "Yes\n", "Yes\n", "No\n" ]
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
[ { "input": "3\n1 0 0", "output": "Yes" }, { "input": "5\n4 2 1 4 3", "output": "Yes" }, { "input": "4\n0 2 3 1", "output": "No" }, { "input": "1\n0", "output": "Yes" }, { "input": "2\n1 0", "output": "Yes" }, { "input": "5\n2 4 4 1 1", "output": "Y...
15
0
0
21,943
149
Division into Teams
[ "greedy", "math", "sortings" ]
null
null
Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers). The key in football is to divide into teams fairly before the game begins. There are *n* boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic *a**i* (the larger it is, the better the boy plays). Let's denote the number of players in the first team as *x*, the number of players in the second team as *y*, the individual numbers of boys who play for the first team as *p**i* and the individual numbers of boys who play for the second team as *q**i*. Division *n* boys into two teams is considered fair if three conditions are fulfilled: - Each boy plays for exactly one team (*x*<=+<=*y*<==<=*n*). - The sizes of teams differ in no more than one (|*x*<=-<=*y*|<=≤<=1). - The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.
The first line contains the only integer *n* (2<=≤<=*n*<=≤<=105) which represents the number of guys in the yard. The next line contains *n* positive space-separated integers, *a**i* (1<=≤<=*a**i*<=≤<=104), the *i*-th number represents the *i*-th boy's playing skills.
On the first line print an integer *x* — the number of boys playing for the first team. On the second line print *x* integers — the individual numbers of boys playing for the first team. On the third line print an integer *y* — the number of boys playing for the second team, on the fourth line print *y* integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: *x*<=+<=*y*<==<=*n*, |*x*<=-<=*y*|<=≤<=1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.
[ "3\n1 2 1\n", "5\n2 3 3 1 1\n" ]
[ "2\n1 2 \n1\n3 \n", "3\n4 1 3 \n2\n5 2 \n" ]
Let's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.
[ { "input": "3\n1 2 1", "output": "2\n1 2 \n1\n3 " }, { "input": "5\n2 3 3 1 1", "output": "3\n4 1 3 \n2\n5 2 " }, { "input": "10\n2 2 2 2 2 2 2 1 2 2", "output": "5\n8 2 4 6 9 \n5\n1 3 5 7 10 " }, { "input": "10\n2 3 3 1 3 1 1 1 2 2", "output": "5\n4 7 1 10 3 \n5\n6 8 9 2...
0
0
-1
21,948
630
Area of a Star
[ "geometry" ]
null
null
It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star. A "star" figure having *n*<=≥<=5 corners where *n* is a prime number is constructed the following way. On the circle of radius *r* *n* points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.
The only line of the input contains two integers *n* (5<=≤<=*n*<=&lt;<=109, *n* is prime) and *r* (1<=≤<=*r*<=≤<=109) — the number of the star corners and the radius of the circumcircle correspondingly.
Output one number — the star area. The relative error of your answer should not be greater than 10<=-<=7.
[ "7 10\n" ]
[ "108.395919545675" ]
none
[ { "input": "7 10", "output": "108.395919545675" }, { "input": "5 1", "output": "1.122569941449" }, { "input": "7 1000", "output": "1083959.195456745256" }, { "input": "11 1000000000", "output": "1061689977712182980.125000000000" }, { "input": "999999937 1", "o...
61
0
0
22,035
0
none
[ "none" ]
null
null
You are an assistant director in a new musical play. The play consists of *n* musical parts, each part must be performed by exactly one actor. After the casting the director chose *m* actors who can take part in the play. Your task is to assign the parts to actors. However, there are several limitations. First, each actor has a certain voice range and there are some parts that he cannot sing. Formally, there are two integers for each actor, *c**i* and *d**i* (*c**i*<=≤<=*d**i*) — the pitch of the lowest and the highest note that the actor can sing. There also are two integers for each part — *a**j* and *b**j* (*a**j*<=≤<=*b**j*) — the pitch of the lowest and the highest notes that are present in the part. The *i*-th actor can perform the *j*-th part if and only if *c**i*<=≤<=*a**j*<=≤<=*b**j*<=≤<=*d**i*, i.e. each note of the part is in the actor's voice range. According to the contract, the *i*-th actor can perform at most *k**i* parts. Besides, you are allowed not to give any part to some actors (then they take part in crowd scenes). The rehearsal starts in two hours and you need to do the assignment quickly!
The first line contains a single integer *n* — the number of parts in the play (1<=≤<=*n*<=≤<=105). Next *n* lines contain two space-separated integers each, *a**j* and *b**j* — the range of notes for the *j*-th part (1<=≤<=*a**j*<=≤<=*b**j*<=≤<=109). The next line contains a single integer *m* — the number of actors (1<=≤<=*m*<=≤<=105). Next *m* lines contain three space-separated integers each, *c**i*, *d**i* and *k**i* — the range of the *i*-th actor and the number of parts that he can perform (1<=≤<=*c**i*<=≤<=*d**i*<=≤<=109, 1<=≤<=*k**i*<=≤<=109).
If there is an assignment that meets all the criteria aboce, print a single word "YES" (without the quotes) in the first line. In the next line print *n* space-separated integers. The *i*-th integer should be the number of the actor who should perform the *i*-th part. If there are multiple correct assignments, print any of them. If there is no correct assignment, print a single word "NO" (without the quotes).
[ "3\n1 3\n2 4\n3 5\n2\n1 4 2\n2 5 1\n", "3\n1 3\n2 4\n3 5\n2\n1 3 2\n2 5 1\n" ]
[ "YES\n1 1 2\n", "NO\n" ]
none
[]
124
307,200
0
22,054
436
Feed with Candy
[ "greedy" ]
null
null
The hero of the Cut the Rope game is a little monster named Om Nom. He loves candies. And what a coincidence! He also is the hero of today's problem. One day, Om Nom visited his friend Evan. Evan has *n* candies of two types (fruit drops and caramel drops), the *i*-th candy hangs at the height of *h**i* centimeters above the floor of the house, its mass is *m**i*. Om Nom wants to eat as many candies as possible. At the beginning Om Nom can make at most *x* centimeter high jumps. When Om Nom eats a candy of mass *y*, he gets stronger and the height of his jump increases by *y* centimeters. What maximum number of candies can Om Nom eat if he never eats two candies of the same type in a row (Om Nom finds it too boring)?
The first line contains two integers, *n* and *x* (1<=≤<=*n*,<=*x*<=≤<=2000) — the number of sweets Evan has and the initial height of Om Nom's jump. Each of the following *n* lines contains three integers *t**i*,<=*h**i*,<=*m**i* (0<=≤<=*t**i*<=≤<=1; 1<=≤<=*h**i*,<=*m**i*<=≤<=2000) — the type, height and the mass of the *i*-th candy. If number *t**i* equals 0, then the current candy is a caramel drop, otherwise it is a fruit drop.
Print a single integer — the maximum number of candies Om Nom can eat.
[ "5 3\n0 2 4\n1 3 1\n0 8 3\n0 20 10\n1 5 5\n" ]
[ "4\n" ]
One of the possible ways to eat 4 candies is to eat them in the order: 1, 5, 3, 2. Let's assume the following scenario: 1. Initially, the height of Om Nom's jump equals 3. He can reach candies 1 and 2. Let's assume that he eats candy 1. As the mass of this candy equals 4, the height of his jump will rise to 3 + 4 = 7. 1. Now Om Nom can reach candies 2 and 5. Let's assume that he eats candy 5. Then the height of his jump will be 7 + 5 = 12. 1. At this moment, Om Nom can reach two candies, 2 and 3. He won't eat candy 2 as its type matches the type of the previously eaten candy. Om Nom eats candy 3, the height of his jump is 12 + 3 = 15. 1. Om Nom eats candy 2, the height of his jump is 15 + 1 = 16. He cannot reach candy 4.
[ { "input": "5 3\n0 2 4\n1 3 1\n0 8 3\n0 20 10\n1 5 5", "output": "4" }, { "input": "5 2\n1 15 2\n1 11 2\n0 17 2\n0 16 1\n1 18 2", "output": "0" }, { "input": "6 2\n1 17 3\n1 6 1\n0 4 2\n1 10 1\n1 7 3\n1 5 1", "output": "0" }, { "input": "7 2\n1 14 1\n1 9 2\n0 6 3\n0 20 2\n0 4...
77
0
0
22,056
748
Santa Claus and Tangerines
[ "binary search", "data structures", "greedy", "two pointers" ]
null
null
Santa Claus has *n* tangerines, and the *i*-th of them consists of exactly *a**i* slices. Santa Claus came to a school which has *k* pupils. Santa decided to treat them with tangerines. However, there can be too few tangerines to present at least one tangerine to each pupil. So Santa decided to divide tangerines into parts so that no one will be offended. In order to do this, he can divide a tangerine or any existing part into two smaller equal parts. If the number of slices in the part he wants to split is odd, then one of the resulting parts will have one slice more than the other. It's forbidden to divide a part consisting of only one slice. Santa Claus wants to present to everyone either a whole tangerine or exactly one part of it (that also means that everyone must get a positive number of slices). One or several tangerines or their parts may stay with Santa. Let *b**i* be the number of slices the *i*-th pupil has in the end. Let Santa's joy be the minimum among all *b**i*'s. Your task is to find the maximum possible joy Santa can have after he treats everyone with tangerines (or their parts).
The first line contains two positive integers *n* and *k* (1<=≤<=*n*<=≤<=106, 1<=≤<=*k*<=≤<=2·109) denoting the number of tangerines and the number of pupils, respectively. The second line consists of *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=≤<=*a**i*<=≤<=107), where *a**i* stands for the number of slices the *i*-th tangerine consists of.
If there's no way to present a tangerine or a part of tangerine to everyone, print -1. Otherwise, print the maximum possible joy that Santa can have.
[ "3 2\n5 9 3\n", "2 4\n12 14\n", "2 3\n1 1\n" ]
[ "5\n", "6\n", "-1\n" ]
In the first example Santa should divide the second tangerine into two parts with 5 and 4 slices. After that he can present the part with 5 slices to the first pupil and the whole first tangerine (with 5 slices, too) to the second pupil. In the second example Santa should divide both tangerines, so that he'll be able to present two parts with 6 slices and two parts with 7 slices. In the third example Santa Claus can't present 2 slices to 3 pupils in such a way that everyone will have anything.
[]
46
4,608,000
0
22,071
45
Event Dates
[ "greedy", "meet-in-the-middle", "sortings" ]
D. Event Dates
2
256
On a history lesson the teacher asked Vasya to name the dates when *n* famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [*l**i*,<=*r**i*] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such *n* dates of famous events that will fulfill both conditions. It is guaranteed that it is possible.
The first line contains one integer *n* (1<=≤<=*n*<=≤<=100) — the number of known events. Then follow *n* lines containing two integers *l**i* and *r**i* each (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=107) — the earliest acceptable date and the latest acceptable date of the *i*-th event.
Print *n* numbers — the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists.
[ "3\n1 2\n2 3\n3 4\n", "2\n1 3\n1 3\n" ]
[ "1 2 3 \n", "1 2 \n" ]
none
[ { "input": "3\n1 2\n2 3\n3 4", "output": "1 2 3 " }, { "input": "2\n1 3\n1 3", "output": "1 2 " }, { "input": "10\n1 10\n3 4\n8 10\n3 4\n5 9\n1 4\n7 10\n1 9\n1 8\n4 10", "output": "7 3 10 4 6 1 9 5 2 8 " }, { "input": "10\n1 1\n8 10\n1 7\n6 8\n5 7\n1 9\n8 8\n6 10\n1 4\n3 4", ...
92
0
0
22,072
89
Fire and Ice
[ "greedy" ]
E. Fire and Ice
0
256
The Fire Lord attacked the Frost Kingdom. He has already got to the Ice Fortress, where the Snow Queen dwells. He arranged his army on a segment *n* in length not far from the city walls. And only the frost magician Solomon can save the Frost Kingdom. The *n*-long segment is located at a distance equal exactly to 1 from the castle walls. It can be imaginarily divided into unit segments. On some of the unit segments fire demons are located — no more than one demon per position. Each demon is characterised by his strength - by some positive integer. We can regard the fire demons being idle. Initially Solomon is positioned on the fortress wall. He can perform the following actions several times in a row: - "L" — Solomon shifts one unit to the left. This movement cannot be performed on the castle wall.- "R" — Solomon shifts one unit to the left. This movement cannot be performed if there's no ice block to the right.- "A" — If there's nothing to the right of Solomon, then Solomon creates an ice block that immediately freezes to the block that Solomon is currently standing on. If there already is an ice block, then Solomon destroys it. At that the ice blocks to the right of the destroyed one can remain but they are left unsupported. Those ice blocks fall down. Solomon spends exactly a second on each of these actions. As the result of Solomon's actions, ice blocks' segments fall down. When an ice block falls on a fire demon, the block evaporates and the demon's strength is reduced by 1. When the demons' strength is equal to 0, the fire demon vanishes. The picture below shows how it happens. The ice block that falls on the position with no demon, breaks into lots of tiny pieces and vanishes without hurting anybody. Help Solomon destroy all the Fire Lord's army in minimum time.
The first line contains an integer *n* (1<=≤<=*n*<=≤<=1000). The next line contains *n* numbers, the *i*-th of them represents the strength of the fire demon standing of the *i*-th position, an integer from 1 to 100. If there's no demon on the *i*-th position, then the *i*-th number equals to 0. It is guaranteed that the input data have at least one fire demon.
Print a string of minimum length, containing characters "L", "R" and "A" — the succession of actions leading to the required result. If there are several possible answers, print any of them.
[ "3\n1 0 1\n", "3\n0 2 0\n" ]
[ "ARARARALLLA", "ARARALAARALA" ]
none
[ { "input": "3\n1 0 1", "output": "ARARARALLLA" }, { "input": "3\n0 2 0", "output": "ARARALAARALA" }, { "input": "5\n3 1 2 2 4", "output": "ARALAARALAARARARARARALLLAARARARALAARALAARALLLLLA" }, { "input": "4\n2 2 2 2", "output": "ARARARARALLLLAARARARARALLLLA" }, { "...
139
20,172,800
0
22,076
949
Curfew
[ "binary search", "brute force", "greedy", "sortings" ]
null
null
Instructors of Some Informatics School make students go to bed. The house contains *n* rooms, in each room exactly *b* students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to *n*. Initially, in *i*-th room there are *a**i* students. All students are currently somewhere in the house, therefore *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*. Also 2 instructors live in this house. The process of curfew enforcement is the following. One instructor starts near room 1 and moves toward room *n*, while the second instructor starts near room *n* and moves toward room 1. After processing current room, each instructor moves on to the next one. Both instructors enter rooms and move simultaneously, if *n* is odd, then only the first instructor processes the middle room. When all rooms are processed, the process ends. When an instructor processes a room, she counts the number of students in the room, then turns off the light, and locks the room. Also, if the number of students inside the processed room is not equal to *b*, the instructor writes down the number of this room into her notebook (and turns off the light, and locks the room). Instructors are in a hurry (to prepare the study plan for the next day), so they don't care about who is in the room, but only about the number of students. While instructors are inside the rooms, students can run between rooms that are not locked and not being processed. A student can run by at most *d* rooms, that is she can move to a room with number that differs my at most *d*. Also, after (or instead of) running each student can hide under a bed in a room she is in. In this case the instructor will not count her during the processing. In each room any number of students can hide simultaneously. Formally, here is what's happening: - A curfew is announced, at this point in room *i* there are *a**i* students. - Each student can run to another room but not further than *d* rooms away from her initial room, or stay in place. After that each student can optionally hide under a bed. - Instructors enter room 1 and room *n*, they count students there and lock the room (after it no one can enter or leave this room). - Each student from rooms with numbers from 2 to *n*<=-<=1 can run to another room but not further than *d* rooms away from her current room, or stay in place. Each student can optionally hide under a bed. - Instructors move from room 1 to room 2 and from room *n* to room *n*<=-<=1. - This process continues until all rooms are processed. Let *x*1 denote the number of rooms in which the first instructor counted the number of non-hidden students different from *b*, and *x*2 be the same number for the second instructor. Students know that the principal will only listen to one complaint, therefore they want to minimize the maximum of numbers *x**i*. Help them find this value if they use the optimal strategy.
The first line contains three integers *n*, *d* and *b* (2<=≤<=*n*<=≤<=100<=000, 1<=≤<=*d*<=≤<=*n*<=-<=1, 1<=≤<=*b*<=≤<=10<=000), number of rooms in the house, running distance of a student, official number of students in a room. The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (0<=≤<=*a**i*<=≤<=109), *i*-th of which stands for the number of students in the *i*-th room before curfew announcement. It is guaranteed that *a*1<=+<=*a*2<=+<=...<=+<=*a**n*<==<=*nb*.
Output one integer, the minimal possible value of the maximum of *x**i*.
[ "5 1 1\n1 0 0 0 4\n", "6 1 2\n3 8 0 1 0 0\n" ]
[ "1\n", "2\n" ]
In the first sample the first three rooms are processed by the first instructor, and the last two are processed by the second instructor. One of the optimal strategies is the following: firstly three students run from room 5 to room 4, on the next stage two of them run to room 3, and one of those two hides under a bed. This way, the first instructor writes down room 2, and the second writes down nothing. In the second sample one of the optimal strategies is the following: firstly all students in room 1 hide, all students from room 2 run to room 3. On the next stage one student runs from room 3 to room 4, and 5 students hide. This way, the first instructor writes down rooms 1 and 2, the second instructor writes down rooms 5 and 6.
[ { "input": "5 1 1\n1 0 0 0 4", "output": "1" }, { "input": "6 1 2\n3 8 0 1 0 0", "output": "2" }, { "input": "5 1 1\n1 1 0 3 0", "output": "0" }, { "input": "5 1 1\n4 0 0 1 0", "output": "1" }, { "input": "2 1 1\n0 2", "output": "0" }, { "input": "100 ...
109
13,516,800
3
22,092
0
none
[ "none" ]
null
null
Now Fox Ciel becomes a commander of Tree Land. Tree Land, like its name said, has *n* cities connected by *n*<=-<=1 undirected roads, and for any two cities there always exists a path between them. Fox Ciel needs to assign an officer to each city. Each officer has a rank — a letter from 'A' to 'Z'. So there will be 26 different ranks, and 'A' is the topmost, so 'Z' is the bottommost. There are enough officers of each rank. But there is a special rule must obey: if *x* and *y* are two distinct cities and their officers have the same rank, then on the simple path between *x* and *y* there must be a city *z* that has an officer with higher rank. The rule guarantee that a communications between same rank officers will be monitored by higher rank officer. Help Ciel to make a valid plan, and if it's impossible, output "Impossible!".
The first line contains an integer *n* (2<=≤<=*n*<=≤<=105) — the number of cities in Tree Land. Each of the following *n*<=-<=1 lines contains two integers *a* and *b* (1<=≤<=*a*,<=*b*<=≤<=*n*,<=*a*<=≠<=*b*) — they mean that there will be an undirected road between *a* and *b*. Consider all the cities are numbered from 1 to *n*. It guaranteed that the given graph will be a tree.
If there is a valid plane, output *n* space-separated characters in a line — *i*-th character is the rank of officer in the city with number *i*. Otherwise output "Impossible!".
[ "4\n1 2\n1 3\n1 4\n", "10\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n7 8\n8 9\n9 10\n" ]
[ "A B B B\n", "D C B A D C B D C D\n" ]
In the first example, for any two officers of rank 'B', an officer with rank 'A' will be on the path between them. So it is a valid solution.
[]
1,000
27,136,000
0
22,166
469
Chat Online
[ "implementation" ]
null
null
Little X and Little Z are good friends. They always chat online. But both of them have schedules. Little Z has fixed schedule. He always online at any moment of time between *a*1 and *b*1, between *a*2 and *b*2, ..., between *a**p* and *b**p* (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between *c*1 and *d*1, between *c*2 and *d*2, ..., between *c**q* and *d**q* (all borders inclusive). But if he gets up at time *t*, these segments will be shifted by *t*. They become [*c**i*<=+<=*t*,<=*d**i*<=+<=*t*] (for all *i*). If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between *l* and *r* (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [*l*,<=*r*] suit for that?
The first line contains four space-separated integers *p*,<=*q*,<=*l*,<=*r* (1<=≤<=<=*p*,<=*q*<=≤<=50; 0<=≤<=*l*<=≤<=*r*<=≤<=1000). Each of the next *p* lines contains two space-separated integers *a**i*,<=*b**i* (0<=≤<=*a**i*<=&lt;<=*b**i*<=≤<=1000). Each of the next *q* lines contains two space-separated integers *c**j*,<=*d**j* (0<=≤<=*c**j*<=&lt;<=*d**j*<=≤<=1000). It's guaranteed that *b**i*<=&lt;<=*a**i*<=+<=1 and *d**j*<=&lt;<=*c**j*<=+<=1 for all valid *i* and *j*.
Output a single integer — the number of moments of time from the segment [*l*,<=*r*] which suit for online conversation.
[ "1 1 0 4\n2 3\n0 1\n", "2 3 0 20\n15 17\n23 26\n1 4\n7 11\n15 17\n" ]
[ "3\n", "20\n" ]
none
[ { "input": "1 1 0 4\n2 3\n0 1", "output": "3" }, { "input": "2 3 0 20\n15 17\n23 26\n1 4\n7 11\n15 17", "output": "20" }, { "input": "5 2 27 452\n148 154\n421 427\n462 470\n777 786\n969 978\n245 247\n313 322", "output": "54" }, { "input": "3 6 25 785\n273 275\n391 397\n775 78...
31
0
0
22,196
443
Kolya and Tandem Repeat
[ "brute force", "implementation", "strings" ]
null
null
Kolya got string *s* for his birthday, the string consists of small English letters. He immediately added *k* more characters to the right of the string. Then Borya came and said that the new string contained a tandem repeat of length *l* as a substring. How large could *l* be? See notes for definition of a tandem repeat.
The first line contains *s* (1<=≤<=|*s*|<=≤<=200). This string contains only small English letters. The second line contains number *k* (1<=≤<=*k*<=≤<=200) — the number of the added characters.
Print a single number — the maximum length of the tandem repeat that could have occurred in the new string.
[ "aaba\n2\n", "aaabbbb\n2\n", "abracadabra\n10\n" ]
[ "6\n", "6\n", "20\n" ]
A tandem repeat of length 2*n* is string *s*, where for any position *i* (1 ≤ *i* ≤ *n*) the following condition fulfills: *s*<sub class="lower-index">*i*</sub> = *s*<sub class="lower-index">*i* + *n*</sub>. In the first sample Kolya could obtain a string aabaab, in the second — aaabbbbbb, in the third — abracadabrabracadabra.
[ { "input": "aaba\n2", "output": "6" }, { "input": "aaabbbb\n2", "output": "6" }, { "input": "abracadabra\n10", "output": "20" }, { "input": "zwvrx\n3", "output": "6" }, { "input": "ayi\n10", "output": "12" }, { "input": "eexlzphiay\n1", "output": "...
78
3,584,000
0
22,200
0
none
[ "none" ]
null
null
Вася купил стол, у которого *n* ножек. Каждая ножка состоит из двух частей, которые соединяются друг с другом. Каждая часть может быть произвольной положительной длины, но гарантируется, что из всех 2*n* частей возможно составить *n* ножек одинаковой длины. При составлении ножки любые две части могут быть соединены друг с другом. Изначально все ножки стола разобраны, а вам заданы длины 2*n* частей в произвольном порядке. Помогите Васе собрать все ножки стола так, чтобы все они были одинаковой длины, разбив заданные 2*n* части на пары правильным образом. Каждая ножка обязательно должна быть составлена ровно из двух частей, не разрешается использовать как ножку только одну часть.
В первой строке задано число *n* (1<=≤<=*n*<=≤<=1000) — количество ножек у стола, купленного Васей. Во второй строке следует последовательность из 2*n* целых положительных чисел *a*1,<=*a*2,<=...,<=*a*2*n* (1<=≤<=*a**i*<=≤<=100<=000) — длины частей ножек стола в произвольном порядке.
Выведите *n* строк по два целых числа в каждой — длины частей ножек, которые надо соединить друг с другом. Гарантируется, что всегда возможно собрать *n* ножек одинаковой длины. Если ответов несколько, разрешается вывести любой из них.
[ "3\n1 3 2 4 5 3\n", "3\n1 1 1 2 2 2\n" ]
[ "1 5\n2 4\n3 3\n", "1 2\n2 1\n1 2\n" ]
none
[ { "input": "3\n1 3 2 4 5 3", "output": "1 5\n2 4\n3 3" }, { "input": "3\n1 1 1 2 2 2", "output": "1 2\n1 2\n1 2" }, { "input": "1\n3 7", "output": "3 7" }, { "input": "10\n9 13 18 7 18 13 2 2 5 16 3 17 5 4 18 2 15 11 7 15", "output": "2 18\n2 18\n2 18\n3 17\n4 16\n5 15\n5...
62
4,608,000
0
22,207
733
Kostya the Sculptor
[ "data structures", "hashing" ]
null
null
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has *n* stones which are rectangular parallelepipeds. The edges sizes of the *i*-th of them are *a**i*, *b**i* and *c**i*. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
The first line contains the integer *n* (1<=≤<=*n*<=≤<=105). *n* lines follow, in the *i*-th of which there are three integers *a**i*,<=*b**i* and *c**i* (1<=≤<=*a**i*,<=*b**i*,<=*c**i*<=≤<=109) — the lengths of edges of the *i*-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
In the first line print *k* (1<=≤<=*k*<=≤<=2) the number of stones which Zahar has chosen. In the second line print *k* distinct integers from 1 to *n* — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to *n* in the order as they are given in the input data. You can print the stones in arbitrary order. If there are several answers print any of them.
[ "6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4\n", "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7\n" ]
[ "1\n1\n", "2\n1 5\n" ]
In the first example we can connect the pairs of stones: - 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. - 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 - 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 - 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: - 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 - 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 - 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 - 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 - 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone.
[ { "input": "6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4", "output": "1\n1" }, { "input": "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7", "output": "2\n1 5" }, { "input": "1\n1 1 1", "output": "1\n1" }, { "input": "2\n2 3 1\n2 2 3", "output": "2\n2 1" }, { ...
124
0
0
22,229
899
Letters Removing
[ "data structures", "strings" ]
null
null
Petya has a string of length *n* consisting of small and large English letters and digits. He performs *m* operations. Each operation is described with two integers *l* and *r* and a character *c*: Petya removes from the string all characters *c* on positions between *l* and *r*, inclusive. It's obvious that the length of the string remains the same or decreases after each operation. Find how the string will look like after Petya performs all *m* operations.
The first string contains two integers *n* and *m* (1<=≤<=*n*,<=*m*<=≤<=2·105) — the length of the string and the number of operations. The second line contains the string of length *n*, consisting of small and large English letters and digits. Positions in the string are enumerated from 1. Each of the next *m* lines contains two integers *l* and *r* (1<=≤<=*l*<=≤<=*r*), followed by a character *c*, which is a small or large English letter or a digit. This line describes one operation. It is guaranteed that *r* doesn't exceed the length of the string *s* before current operation.
Print the string Petya will obtain after performing all *m* operations. If the strings becomes empty after all operations, print an empty line.
[ "4 2\nabac\n1 3 a\n2 2 c\n", "3 2\nA0z\n1 3 0\n1 1 z\n", "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a\n", "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A\n" ]
[ "b\n", "Az\n", "tFrg4\n", "AB\n" ]
In the first example during the first operation both letters 'a' are removed, so the string becomes "bc". During the second operation the letter 'c' (on the second position) is removed, and the string becomes "b". In the second example during the first operation Petya removes '0' from the second position. After that the string becomes "Az". During the second operations the string doesn't change.
[ { "input": "4 2\nabac\n1 3 a\n2 2 c", "output": "b" }, { "input": "3 2\nA0z\n1 3 0\n1 1 z", "output": "Az" }, { "input": "10 4\nagtFrgF4aF\n2 5 g\n4 9 F\n1 5 4\n1 7 a", "output": "tFrg4" }, { "input": "9 5\naAAaBBccD\n1 4 a\n5 6 c\n2 3 B\n4 4 D\n2 3 A", "output": "AB" }...
2,000
7,680,000
0
22,298
438
The Child and Binary Tree
[ "combinatorics", "divide and conquer", "fft", "number theory" ]
null
null
Our child likes computer science very much, especially he likes binary trees. Consider the sequence of *n* distinct positive integers: *c*1,<=*c*2,<=...,<=*c**n*. The child calls a vertex-weighted rooted binary tree good if and only if for every vertex *v*, the weight of *v* is in the set {*c*1,<=*c*2,<=...,<=*c**n*}. Also our child thinks that the weight of a vertex-weighted tree is the sum of all vertices' weights. Given an integer *m*, can you for all *s* (1<=≤<=*s*<=≤<=*m*) calculate the number of good vertex-weighted rooted binary trees with weight *s*? Please, check the samples for better understanding what trees are considered different. We only want to know the answer modulo 998244353 (7<=×<=17<=×<=223<=+<=1, a prime number).
The first line contains two integers *n*,<=*m* (1<=≤<=*n*<=≤<=105; 1<=≤<=*m*<=≤<=105). The second line contains *n* space-separated pairwise distinct integers *c*1,<=*c*2,<=...,<=*c**n*. (1<=≤<=*c**i*<=≤<=105).
Print *m* lines, each line containing a single integer. The *i*-th line must contain the number of good vertex-weighted rooted binary trees whose weight exactly equal to *i*. Print the answers modulo 998244353 (7<=×<=17<=×<=223<=+<=1, a prime number).
[ "2 3\n1 2\n", "3 10\n9 4 3\n", "5 10\n13 10 6 4 15\n" ]
[ "1\n3\n9\n", "0\n0\n1\n1\n0\n2\n4\n2\n6\n15\n", "0\n0\n0\n1\n0\n1\n0\n2\n0\n5\n" ]
In the first example, there are 9 good vertex-weighted rooted binary trees whose weight exactly equal to 3:
[ { "input": "2 3\n1 2", "output": "1\n3\n9" }, { "input": "3 10\n9 4 3", "output": "0\n0\n1\n1\n0\n2\n4\n2\n6\n15" }, { "input": "5 10\n13 10 6 4 15", "output": "0\n0\n0\n1\n0\n1\n0\n2\n0\n5" }, { "input": "1 1\n1", "output": "1" }, { "input": "10 100\n9 95 37 56 3...
0
0
-1
22,313
939
Maximize!
[ "binary search", "greedy", "ternary search", "two pointers" ]
null
null
You are given a multiset *S* consisting of positive integers (initially empty). There are two kind of queries: 1. Add a positive integer to *S*, the newly added integer is not less than any number in it. 1. Find a subset *s* of the set *S* such that the value is maximum possible. Here *max*(*s*) means maximum value of elements in *s*,  — the average value of numbers in *s*. Output this maximum possible value of .
The first line contains a single integer *Q* (1<=≤<=*Q*<=≤<=5·105) — the number of queries. Each of the next *Q* lines contains a description of query. For queries of type 1 two integers 1 and *x* are given, where *x* (1<=≤<=*x*<=≤<=109) is a number that you should add to *S*. It's guaranteed that *x* is not less than any number in *S*. For queries of type 2, a single integer 2 is given. It's guaranteed that the first query has type 1, i. e. *S* is not empty when a query of type 2 comes.
Output the answer for each query of the second type in the order these queries are given in input. Each number should be printed in separate line. Your answer is considered correct, if each of your answers has absolute or relative error not greater than 10<=-<=6. Formally, let your answer be *a*, and the jury's answer be *b*. Your answer is considered correct if .
[ "6\n1 3\n2\n1 4\n2\n1 8\n2\n", "4\n1 1\n1 4\n1 5\n2\n" ]
[ "0.0000000000\n0.5000000000\n3.0000000000\n", "2.0000000000\n" ]
none
[ { "input": "6\n1 3\n2\n1 4\n2\n1 8\n2", "output": "0.0000000000\n0.5000000000\n3.0000000000" }, { "input": "4\n1 1\n1 4\n1 5\n2", "output": "2.0000000000" }, { "input": "8\n1 7\n1 26\n1 40\n1 45\n1 64\n2\n1 88\n1 94", "output": "31.6666666667" }, { "input": "9\n1 35\n2\n2\n1 ...
77
102,400
0
22,323
958
Hyperspace Jump (hard)
[]
null
null
It is now 125 years later, but humanity is still on the run from a humanoid-cyborg race determined to destroy it. Or perhaps we are getting some stories mixed up here... In any case, the fleet is now smaller. However, in a recent upgrade, all the navigation systems have been outfitted with higher-dimensional, linear-algebraic jump processors. Now, in order to make a jump, a ship's captain needs to specify a subspace of the *d*-dimensional space in which the events are taking place. She does so by providing a generating set of vectors for that subspace. Princess Heidi has received such a set from the captain of each of *m* ships. Again, she would like to group up those ships whose hyperspace jump subspaces are equal. To do so, she wants to assign a group number between 1 and *m* to each of the ships, so that two ships have the same group number if and only if their corresponding subspaces are equal (even though they might be given using different sets of vectors). Help Heidi!
The first line of the input contains two space-separated integers *m* and *d* (2<=≤<=*m*<=≤<=30<=000, 1<=≤<=*d*<=≤<=5) – the number of ships and the dimension of the full underlying vector space, respectively. Next, the *m* subspaces are described, one after another. The *i*-th subspace, which corresponds to the *i*-th ship, is described as follows: The first line contains one integer *k**i* (1<=≤<=*k**i*<=≤<=*d*). Then *k**i* lines follow, the *j*-th of them describing the *j*-th vector sent by the *i*-th ship. Each of the *j* lines consists of *d* space-separated integers *a**j*, *j*<==<=1,<=...,<=*d*, that describe the vector ; it holds that |*a**j*|<=≤<=250. The *i*-th subspace is the linear span of these *k**i* vectors.
Output *m* space-separated integers *g*1,<=...,<=*g**m*, where denotes the group number assigned to the *i*-th ship. That is, for any 1<=≤<=*i*<=&lt;<=*j*<=≤<=*m*, the following should hold: *g**i*<==<=*g**j* if and only if the *i*-th and the *j*-th subspaces are equal. In addition, the sequence (*g*1,<=*g*2,<=...,<=*g**m*) should be lexicographically minimal among all sequences with that property.
[ "8 2\n1\n5 0\n1\n0 1\n1\n0 1\n2\n0 6\n0 1\n2\n0 1\n1 0\n2\n-5 -5\n4 3\n2\n1 1\n0 1\n2\n1 0\n1 0\n" ]
[ "1 2 2 2 3 3 3 1 " ]
In the sample testcase, the first and the last subspace are equal, subspaces 2 to 4 are equal, and subspaces 5 to 7 are equal. Recall that two subspaces, one given as the span of vectors <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e8dc56705315ce4b334dd46dbc9c8c51fffb0036.png" style="max-width: 100.0%;max-height: 100.0%;"/> and another given as the span of vectors <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/99fd3b5233ff3b6f4989df43e2f60edb184bee11.png" style="max-width: 100.0%;max-height: 100.0%;"/>, are equal if each vector *v*<sub class="lower-index">*i*</sub> can be written as a linear combination of vectors *w*<sub class="lower-index">1</sub>, ..., *w*<sub class="lower-index">*k*</sub> (that is, there exist coefficients <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ae69b90a53c26d24b0b4a40a6970f6d5903cd568.png" style="max-width: 100.0%;max-height: 100.0%;"/> such that *v*<sub class="lower-index">*i*</sub> = α<sub class="lower-index">1</sub>*w*<sub class="lower-index">1</sub> + ... + α<sub class="lower-index">*k*</sub>*w*<sub class="lower-index">*k*</sub>) and, similarly, each vector *w*<sub class="lower-index">*i*</sub> can be written as a linear combination of vectors *v*<sub class="lower-index">1</sub>, ..., *v*<sub class="lower-index">*n*</sub>. Recall that a sequence (*g*<sub class="lower-index">1</sub>, *g*<sub class="lower-index">2</sub>, ..., *g*<sub class="lower-index">*m*</sub>) is lexicographically smaller than a sequence (*h*<sub class="lower-index">1</sub>, *h*<sub class="lower-index">2</sub>, ..., *h*<sub class="lower-index">*m*</sub>) if there exists an index *i*, 1 ≤ *i* ≤ *m*, such that *g*<sub class="lower-index">*i*</sub> &lt; *h*<sub class="lower-index">*i*</sub> and *g*<sub class="lower-index">*j*</sub> = *h*<sub class="lower-index">*j*</sub> for all *j* &lt; *i*.
[]
3,000
39,833,600
0
22,350
186
Growing Mushrooms
[ "greedy", "sortings" ]
null
null
Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch. Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts *t*1 seconds and the second part lasts *t*2 seconds. The first and the second part are separated by a little break. After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of *v**i* meters per second. After *t*1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by *k* percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of *u**i* meters per second. After a *t*2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary. Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds *a**i* and *b**i*, then there are two strategies: he either uses speed *a**i* before the break and speed *b**i* after it, or vice versa. Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results. The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).
The first input line contains four integer numbers *n*, *t*1, *t*2, *k* (1<=≤<=*n*,<=*t*1,<=*t*2<=≤<=1000; 1<=≤<=*k*<=≤<=100) — the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following *n* lines contains two integers. The *i*-th (1<=≤<=*i*<=≤<=*n*) line contains space-separated integers *a**i*, *b**i* (1<=≤<=*a**i*,<=*b**i*<=≤<=1000) — the speeds which the participant number *i* chose.
Print the final results' table: *n* lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.
[ "2 3 3 50\n2 4\n4 2\n", "4 1 1 1\n544 397\n280 101\n280 101\n693 970\n" ]
[ "1 15.00\n2 15.00\n", "4 1656.07\n1 937.03\n2 379.99\n3 379.99\n" ]
- First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2·3·0.5 + 4·3 &gt; 4·3·0.5 + 2·3.
[ { "input": "2 3 3 50\n2 4\n4 2", "output": "1 15.00\n2 15.00" }, { "input": "4 1 1 1\n544 397\n280 101\n280 101\n693 970", "output": "4 1656.07\n1 937.03\n2 379.99\n3 379.99" }, { "input": "10 1 1 25\n981 1\n352 276\n164 691\n203 853\n599 97\n901 688\n934 579\n910 959\n317 624\n440 737",...
62
0
0
22,353
0
none
[ "none" ]
null
null
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe, the *m* friends found *n* different kinds of milk on the menu, that's why they ordered *n* bottles — one bottle of each kind. We know that the volume of milk in each bottle equals *w*. When the bottles were brought in, they decided to pour all the milk evenly among the *m* cups, so that each got a cup. As a punishment for not passing the test Igor was appointed the person to pour the milk. He protested that he was afraid to mix something up and suggested to distribute the drink so that the milk from each bottle was in no more than two different cups. His friends agreed but they suddenly faced the following problem — and what is actually the way to do it? Help them and write the program that will help to distribute the milk among the cups and drink it as quickly as possible! Note that due to Igor K.'s perfectly accurate eye and unswerving hands, he can pour any fractional amount of milk from any bottle to any cup.
The only input data file contains three integers *n*, *w* and *m* (1<=≤<=*n*<=≤<=50, 100<=≤<=*w*<=≤<=1000, 2<=≤<=*m*<=≤<=50), where *n* stands for the number of ordered bottles, *w* stands for the volume of each of them and *m* stands for the number of friends in the company.
Print on the first line "YES" if it is possible to pour the milk so that the milk from each bottle was in no more than two different cups. If there's no solution, print "NO". If there is a solution, then print *m* more lines, where the *i*-th of them describes the content of the *i*-th student's cup. The line should consist of one or more pairs that would look like "*b* *v*". Each such pair means that *v* (*v*<=&gt;<=0) units of milk were poured into the *i*-th cup from bottle *b* (1<=≤<=*b*<=≤<=*n*). All numbers *b* on each line should be different. If there are several variants to solve the problem, print any of them. Print the real numbers with no less than 6 digits after the decimal point.
[ "2 500 3\n", "4 100 5\n", "4 100 7\n", "5 500 2\n" ]
[ "YES\n1 333.333333\n2 333.333333\n2 166.666667 1 166.666667\n", "YES\n3 20.000000 4 60.000000\n1 80.000000\n4 40.000000 2 40.000000\n3 80.000000\n2 60.000000 1 20.000000\n", "NO\n", "YES\n4 250.000000 5 500.000000 2 500.000000\n3 500.000000 1 500.000000 4 250.000000\n" ]
none
[ { "input": "2 500 3", "output": "YES\n1 333.333333\n2 333.333333\n2 166.666667 1 166.666667" }, { "input": "4 100 5", "output": "YES\n3 20.000000 4 60.000000\n1 80.000000\n4 40.000000 2 40.000000\n3 80.000000\n2 60.000000 1 20.000000" }, { "input": "4 100 7", "output": "NO" }, { ...
93
17,715,200
3
22,366
401
Sereja and Contests
[ "greedy", "implementation", "math" ]
null
null
Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds. Codesorfes has rounds of two types: *Div*1 (for advanced coders) and *Div*2 (for beginner coders). Two rounds, *Div*1 and *Div*2, can go simultaneously, (*Div*1 round cannot be held without *Div*2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the *Div*1 round is always greater. Sereja is a beginner coder, so he can take part only in rounds of *Div*2 type. At the moment he is taking part in a *Div*2 round, its identifier equals to *x*. Sereja remembers very well that he has taken part in exactly *k* rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed. Sereja is wondering: what minimum and what maximum number of *Div*2 rounds could he have missed? Help him find these two numbers.
The first line contains two integers: *x* (1<=≤<=*x*<=≤<=4000) — the round Sereja is taking part in today, and *k* (0<=≤<=*k*<=&lt;<=4000) — the number of rounds he took part in. Next *k* lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 *num*2 *num*1" (where *num*2 is the identifier of this *Div*2 round, *num*1 is the identifier of the *Div*1 round). It is guaranteed that *num*1<=-<=*num*2<==<=1. If Sereja took part in a usual *Div*2 round, then the corresponding line looks like: "2 *num*" (where *num* is the identifier of this *Div*2 round). It is guaranteed that the identifiers of all given rounds are less than *x*.
Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.
[ "3 2\n2 1\n2 2\n", "9 3\n1 2 3\n2 8\n1 4 5\n", "10 0\n" ]
[ "0 0", "2 3", "5 9" ]
In the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual *Div*2 round and the round with identifier 6 will be synchronous with the *Div*1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual *Div*2 rounds.
[ { "input": "3 2\n2 1\n2 2", "output": "0 0" }, { "input": "9 3\n1 2 3\n2 8\n1 4 5", "output": "2 3" }, { "input": "10 0", "output": "5 9" }, { "input": "10 2\n1 1 2\n1 8 9", "output": "3 5" }, { "input": "9 3\n1 4 5\n1 1 2\n1 6 7", "output": "2 2" }, { ...
187
3,481,600
3
22,392
56
Corporation Mail
[ "data structures", "expression parsing", "implementation" ]
C. Corporation Mail
2
256
The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows: - *employee* ::= *name*. | *name*:*employee*1,*employee*2, ... ,*employee**k*. - *name* ::= name of an employee That is, the description of each employee consists of his name, a colon (:), the descriptions of all his subordinates separated by commas, and, finally, a dot. If an employee has no subordinates, then the colon is not present in his description. For example, line MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY... is the correct way of recording the structure of a corporation where the director MIKE has subordinates MAX, ARTEM and DMITRY. ARTEM has a subordinate whose name is MIKE, just as the name of his boss and two subordinates of DMITRY are called DMITRY, just like himself. In the Beroil corporation every employee can only correspond with his subordinates, at that the subordinates are not necessarily direct. Let's call an uncomfortable situation the situation when a person whose name is *s* writes a letter to another person whose name is also *s*. In the example given above are two such pairs: a pair involving MIKE, and two pairs for DMITRY (a pair for each of his subordinates). Your task is by the given structure of the corporation to find the number of uncomfortable pairs in it.
The first and single line contains the corporation structure which is a string of length from 1 to 1000 characters. It is guaranteed that the description is correct. Every name is a string consisting of capital Latin letters from 1 to 10 symbols in length.
Print a single number — the number of uncomfortable situations in the company.
[ "MIKE:MAX.,ARTEM:MIKE..,DMITRY:DMITRY.,DMITRY...\n", "A:A..\n", "A:C:C:C:C.....\n" ]
[ "3\n", "1\n", "6\n" ]
none
[ { "input": "A:A..", "output": "1" }, { "input": "CK:CK.,CK.,CK..", "output": "3" }, { "input": "RHLGWEVBJ:KAWUINWEI:KAWUINWEI..,ZQATMW.,KAWUINWEI.,RSWN..", "output": "1" }, { "input": "GIRRY.", "output": "0" }, { "input": "XGB:QJNGARRAZV:DWGDCCU:ARDKJV:P:MXBLZKLPY...
498
30,515,200
3.818661
22,412
962
Simple Cycles Edges
[ "dfs and similar", "graphs", "trees" ]
null
null
You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself). A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle. Determine the edges, which belong to exactly on one simple cycle.
The first line contain two integers $n$ and $m$ $(1 \le n \le 100\,000$, $0 \le m \le \min(n \cdot (n - 1) / 2, 100\,000))$ — the number of vertices and the number of edges. Each of the following $m$ lines contain two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$) — the description of the edges.
In the first line print the number of edges, which belong to exactly one simple cycle. In the second line print the indices of edges, which belong to exactly one simple cycle, in increasing order. The edges are numbered from one in the same order as they are given in the input.
[ "3 3\n1 2\n2 3\n3 1\n", "6 7\n2 3\n3 4\n4 2\n1 2\n1 5\n5 6\n6 1\n", "5 6\n1 2\n2 3\n2 4\n4 3\n2 5\n5 3\n" ]
[ "3\n1 2 3 \n", "6\n1 2 3 5 6 7 \n", "0\n\n" ]
none
[ { "input": "3 3\n1 2\n2 3\n3 1", "output": "3\n1 2 3 " }, { "input": "6 7\n2 3\n3 4\n4 2\n1 2\n1 5\n5 6\n6 1", "output": "6\n1 2 3 5 6 7 " }, { "input": "5 6\n1 2\n2 3\n2 4\n4 3\n2 5\n5 3", "output": "0" }, { "input": "4 5\n1 2\n2 3\n3 4\n4 1\n1 3", "output": "0" }, {...
46
0
0
22,509
425
Sereja and Two Sequences
[ "data structures", "dp" ]
null
null
Sereja has two sequences *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**m*, consisting of integers. One day Sereja got bored and he decided two play with them. The rules of the game was very simple. Sereja makes several moves, in one move he can perform one of the following actions: 1. Choose several (at least one) first elements of sequence *a* (non-empty prefix of *a*), choose several (at least one) first elements of sequence *b* (non-empty prefix of *b*); the element of sequence *a* with the maximum index among the chosen ones must be equal to the element of sequence *b* with the maximum index among the chosen ones; remove the chosen elements from the sequences. 1. Remove all elements of both sequences. The first action is worth *e* energy units and adds one dollar to Sereja's electronic account. The second action is worth the number of energy units equal to the number of elements Sereja removed from the sequences before performing this action. After Sereja performed the second action, he gets all the money that he earned on his electronic account during the game. Initially Sereja has *s* energy units and no money on his account. What maximum number of money can Sereja get? Note, the amount of Seraja's energy mustn't be negative at any time moment.
The first line contains integers *n*, *m*, *s*, *e* (1<=≤<=*n*,<=*m*<=≤<=105; 1<=≤<=*s*<=≤<=3·105; 103<=≤<=*e*<=≤<=104). The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=105). The third line contains *m* integers *b*1, *b*2, ..., *b**m* (1<=≤<=*b**i*<=≤<=105).
Print a single integer — maximum number of money in dollars that Sereja can get.
[ "5 5 100000 1000\n1 2 3 4 5\n3 2 4 5 1\n", "3 4 3006 1000\n1 2 3\n1 2 4 3\n" ]
[ "3\n", "2\n" ]
none
[]
46
7,987,200
0
22,527
311
Biologist
[ "flows" ]
null
null
SmallR is a biologist. Her latest research finding is how to change the sex of dogs. In other words, she can change female dogs into male dogs and vice versa. She is going to demonstrate this technique. Now SmallR has *n* dogs, the costs of each dog's change may be different. The dogs are numbered from 1 to *n*. The cost of change for dog *i* is *v**i* RMB. By the way, this technique needs a kind of medicine which can be valid for only one day. So the experiment should be taken in one day and each dog can be changed at most once. This experiment has aroused extensive attention from all sectors of society. There are *m* rich folks which are suspicious of this experiment. They all want to bet with SmallR forcibly. If SmallR succeeds, the *i*-th rich folk will pay SmallR *w**i* RMB. But it's strange that they have a special method to determine whether SmallR succeeds. For *i*-th rich folk, in advance, he will appoint certain *k**i* dogs and certain one gender. He will think SmallR succeeds if and only if on some day the *k**i* appointed dogs are all of the appointed gender. Otherwise, he will think SmallR fails. If SmallR can't satisfy some folk that isn't her friend, she need not pay him, but if someone she can't satisfy is her good friend, she must pay *g* RMB to him as apologies for her fail. Then, SmallR hope to acquire money as much as possible by this experiment. Please figure out the maximum money SmallR can acquire. By the way, it is possible that she can't obtain any money, even will lose money. Then, please give out the minimum money she should lose.
The first line contains three integers *n*, *m*, *g* (1<=≤<=*n*<=≤<=104,<=0<=≤<=*m*<=≤<=2000,<=0<=≤<=*g*<=≤<=104). The second line contains *n* integers, each is 0 or 1, the sex of each dog, 0 represent the female and 1 represent the male. The third line contains *n* integers *v*1,<=*v*2,<=...,<=*v**n* (0<=≤<=*v**i*<=≤<=104). Each of the next *m* lines describes a rich folk. On the *i*-th line the first number is the appointed sex of *i*-th folk (0 or 1), the next two integers are *w**i* and *k**i* (0<=≤<=*w**i*<=≤<=104,<=1<=≤<=*k**i*<=≤<=10), next *k**i* distinct integers are the indexes of appointed dogs (each index is between 1 and *n*). The last number of this line represents whether *i*-th folk is SmallR's good friend (0 — no or 1 — yes).
Print a single integer, the maximum money SmallR can gain. Note that the integer is negative if SmallR will lose money.
[ "5 5 9\n0 1 1 1 0\n1 8 6 2 3\n0 7 3 3 2 1 1\n1 8 1 5 1\n1 0 3 2 1 4 1\n0 8 3 4 2 1 0\n1 7 2 4 1 1\n", "5 5 8\n1 0 1 1 1\n6 5 4 2 8\n0 6 3 2 3 4 0\n0 8 3 3 2 4 0\n0 0 3 3 4 1 1\n0 10 3 4 3 1 1\n0 4 3 3 4 1 1\n" ]
[ "2\n", "16\n" ]
none
[ { "input": "5 5 9\n0 1 1 1 0\n1 8 6 2 3\n0 7 3 3 2 1 1\n1 8 1 5 1\n1 0 3 2 1 4 1\n0 8 3 4 2 1 0\n1 7 2 4 1 1", "output": "2" }, { "input": "5 5 8\n1 0 1 1 1\n6 5 4 2 8\n0 6 3 2 3 4 0\n0 8 3 3 2 4 0\n0 0 3 3 4 1 1\n0 10 3 4 3 1 1\n0 4 3 3 4 1 1", "output": "16" }, { "input": "5 5 8\n0 1 0...
30
0
0
22,544
487
Conveyor Belts
[ "data structures" ]
null
null
Automatic Bakery of Cyberland (ABC) recently bought an *n*<=×<=*m* rectangle table. To serve the diners, ABC placed seats around the table. The size of each seat is equal to a unit square, so there are 2(*n*<=+<=*m*) seats in total. ABC placed conveyor belts on each unit square on the table. There are three types of conveyor belts: "^", "&lt;" and "&gt;". A "^" belt can bring things upwards. "&lt;" can bring leftwards and "&gt;" can bring rightwards. Let's number the rows with 1 to *n* from top to bottom, the columns with 1 to *m* from left to right. We consider the seats above and below the top of the table are rows 0 and *n*<=+<=1 respectively. Also we define seats to the left of the table and to the right of the table to be column 0 and *m*<=+<=1. Due to the conveyor belts direction restriction there are currently no way for a diner sitting in the row *n*<=+<=1 to be served. Given the initial table, there will be *q* events in order. There are two types of events: - "A *x* *y*" means, a piece of bread will appear at row *x* and column *y* (we will denote such position as (*x*,<=*y*)). The bread will follow the conveyor belt, until arriving at a seat of a diner. It is possible that the bread gets stuck in an infinite loop. Your task is to simulate the process, and output the final position of the bread, or determine that there will be an infinite loop. - "C *x* *y* *c*" means that the type of the conveyor belt at (*x*,<=*y*) is changed to *c*. Queries are performed separately meaning that even if the bread got stuck in an infinite loop, it won't affect further queries.
The first line of input contains three integers *n*, *m* and *q* (1<=≤<=*n*<=≤<=105,<=1<=≤<=*m*<=≤<=10,<=1<=≤<=*q*<=≤<=105), separated by a space. Next *n* lines, each line contains *m* characters, describing the table. The characters can only be one of "&lt;^&gt;". Next *q* lines, each line describes an event. The format is "C x y c" or "A x y" (Consecutive elements are separated by a space). It's guaranteed that 1<=≤<=*x*<=≤<=*n*,<=1<=≤<=*y*<=≤<=*m*. *c* is a character from the set "&lt;^&gt;". There are at most 10000 queries of "C" type.
For each event of type "A", output two integers *tx*, *ty* in a line, separated by a space, denoting the destination of (*x*,<=*y*) is (*tx*,<=*ty*). If there is an infinite loop, you should output *tx*<==<=*ty*<==<=<=-<=1.
[ "2 2 3\n&gt;&gt;\n^^\nA 2 1\nC 1 2 &lt;\nA 2 1\n", "4 5 7\n&gt;&lt;&lt;^&lt;\n^&lt;^^&gt;\n&gt;&gt;&gt;^&gt;\n&gt;^&gt;&gt;^\nA 3 1\nA 2 2\nC 1 4 &lt;\nA 3 1\nC 1 2 ^\nA 3 1\nA 2 2" ]
[ "1 3\n-1 -1\n", "0 4\n-1 -1\n-1 -1\n0 2\n0 2\n" ]
For the first sample: If the bread goes from (2, 1), it will go out of the table at (1, 3). After changing the conveyor belt of (1, 2) to "&lt;", when the bread goes from (2, 1) again, it will get stuck at "&gt;&lt;", so output is ( - 1,  - 1).
[]
31
0
0
22,558
436
Cardboard Box
[ "data structures", "greedy" ]
null
null
Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: *a**i* — how long it takes to complete the level for one star, *b**i* — how long it takes to complete the level for two stars (*a**i*<=&lt;<=*b**i*). You want to open the next box as quickly as possible. So, you need to earn at least *w* stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels.
The first line contains two integers *n* and *w* (1<=≤<=*n*<=≤<=3·105; 1<=≤<=*w*<=≤<=2*n*) — the number of levels in the first box and the number of stars you need to open another box. Each of the following *n* lines contains two integers *a**i* and *b**i* (1<=≤<=*a**i*<=&lt;<=*b**i*<=≤<=109) — the attributes of the *i*-th level.
In the first line print integer *t* — the minimum time you need to open the next box. In the next line, print *n* digits without spaces — the description of the optimal scenario: - if you need to pass the *i*-th level for one star, the *i*-th digit should equal 1; - if you need to pass the *i*-th level for two stars, the *i*-th digit should equal 2; - if you do not need to pass the *i*-th level at all, the *i*-th digit should equal 0.
[ "2 3\n1 2\n1 2\n", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30\n" ]
[ "3\n12\n", "14\n01020\n" ]
In the first test sample, answer 21 is also assumed correct.
[]
30
0
0
22,569
883
Berland Army
[ "constructive algorithms", "graphs", "greedy" ]
null
null
There are *n* military men in the Berland army. Some of them have given orders to other military men by now. Given *m* pairs (*x**i*, *y**i*), meaning that the military man *x**i* gave the *i*-th order to another military man *y**i*. It is time for reform! The Berland Ministry of Defence plans to introduce ranks in the Berland army. Each military man should be assigned a rank — integer number between 1 and *k*, inclusive. Some of them have been already assigned a rank, but the rest of them should get a rank soon. Help the ministry to assign ranks to the rest of the army so that: - for each of *m* orders it is true that the rank of a person giving the order (military man *x**i*) is strictly greater than the rank of a person receiving the order (military man *y**i*); - for each rank from 1 to *k* there is at least one military man with this rank.
The first line contains three integers *n*, *m* and *k* (1<=≤<=*n*<=≤<=2·105, 0<=≤<=*m*<=≤<=2·105, 1<=≤<=*k*<=≤<=2·105) — number of military men in the Berland army, number of orders and number of ranks. The second line contains *n* integers *r*1,<=*r*2,<=...,<=*r**n*, where *r**i*<=&gt;<=0 (in this case 1<=≤<=*r**i*<=≤<=*k*) means that the *i*-th military man has been already assigned the rank *r**i*; *r**i*<==<=0 means the *i*-th military man doesn't have a rank yet. The following *m* lines contain orders one per line. Each order is described with a line containing two integers *x**i*, *y**i* (1<=≤<=*x**i*,<=*y**i*<=≤<=*n*, *x**i*<=≠<=*y**i*). This line means that the *i*-th order was given by the military man *x**i* to the military man *y**i*. For each pair (*x*,<=*y*) of military men there could be several orders from *x* to *y*.
Print *n* integers, where the *i*-th number is the rank of the *i*-th military man. If there are many solutions, print any of them. If there is no solution, print the only number -1.
[ "5 3 3\n0 3 0 0 2\n2 4\n3 4\n3 5\n", "7 6 5\n0 4 5 4 1 0 0\n6 1\n3 6\n3 1\n7 5\n7 1\n7 4\n", "2 2 2\n2 1\n1 2\n2 1\n" ]
[ "1 3 3 2 2 \n", "2 4 5 4 1 3 5 \n", "-1\n" ]
none
[]
46
0
0
22,581
990
Flow Control
[ "dfs and similar", "dp", "greedy", "trees" ]
null
null
You have to handle a very complex water distribution system. The system consists of $n$ junctions and $m$ pipes, $i$-th pipe connects junctions $x_i$ and $y_i$. The only thing you can do is adjusting the pipes. You have to choose $m$ integer numbers $f_1$, $f_2$, ..., $f_m$ and use them as pipe settings. $i$-th pipe will distribute $f_i$ units of water per second from junction $x_i$ to junction $y_i$ (if $f_i$ is negative, then the pipe will distribute $|f_i|$ units of water per second from junction $y_i$ to junction $x_i$). It is allowed to set $f_i$ to any integer from $-2 \cdot 10^9$ to $2 \cdot 10^9$. In order for the system to work properly, there are some constraints: for every $i \in [1, n]$, $i$-th junction has a number $s_i$ associated with it meaning that the difference between incoming and outcoming flow for $i$-th junction must be exactly $s_i$ (if $s_i$ is not negative, then $i$-th junction must receive $s_i$ units of water per second; if it is negative, then $i$-th junction must transfer $|s_i|$ units of water per second to other junctions). Can you choose the integers $f_1$, $f_2$, ..., $f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied?
The first line contains an integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the number of junctions. The second line contains $n$ integers $s_1, s_2, \dots, s_n$ ($-10^4 \le s_i \le 10^4$) — constraints for the junctions. The third line contains an integer $m$ ($0 \le m \le 2 \cdot 10^5$) — the number of pipes. $i$-th of the next $m$ lines contains two integers $x_i$ and $y_i$ ($1 \le x_i, y_i \le n$, $x_i \ne y_i$) — the description of $i$-th pipe. It is guaranteed that each unordered pair $(x, y)$ will appear no more than once in the input (it means that there won't be any pairs $(x, y)$ or $(y, x)$ after the first occurrence of $(x, y)$). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them.
If you can choose such integer numbers $f_1, f_2, \dots, f_m$ in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output $m$ lines, $i$-th line should contain $f_i$ — the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input. Otherwise output "Impossible" in the only line.
[ "4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n", "4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1\n" ]
[ "Possible\n4\n-6\n8\n-7\n7\n", "Impossible\n" ]
none
[ { "input": "4\n3 -10 6 1\n5\n1 2\n3 2\n2 4\n3 4\n3 1", "output": "Possible\n-3\n-6\n1\n0\n0" }, { "input": "4\n3 -10 6 4\n5\n1 2\n3 2\n2 4\n3 4\n3 1", "output": "Impossible" }, { "input": "1\n0\n0", "output": "Possible" }, { "input": "1\n123\n0", "output": "Impossible" ...
31
0
0
22,603
154
Double Profiles
[ "graphs", "hashing", "sortings" ]
null
null
You have been offered a job in a company developing a large social network. Your first task is connected with searching profiles that most probably belong to the same user. The social network contains *n* registered profiles, numbered from 1 to *n*. Some pairs there are friends (the "friendship" relationship is mutual, that is, if *i* is friends with *j*, then *j* is also friends with *i*). Let's say that profiles *i* and *j* (*i*<=≠<=*j*) are doubles, if for any profile *k* (*k*<=≠<=*i*, *k*<=≠<=*j*) one of the two statements is true: either *k* is friends with *i* and *j*, or *k* isn't friends with either of them. Also, *i* and *j* can be friends or not be friends. Your task is to count the number of different unordered pairs (*i*,<=*j*), such that the profiles *i* and *j* are doubles. Note that the pairs are unordered, that is, pairs (*a*,<=*b*) and (*b*,<=*a*) are considered identical.
The first line contains two space-separated integers *n* and *m* (1<=≤<=*n*<=≤<=106, 0<=≤<=*m*<=≤<=106), — the number of profiles and the number of pairs of friends, correspondingly. Next *m* lines contains descriptions of pairs of friends in the format "*v* *u*", where *v* and *u* (1<=≤<=*v*,<=*u*<=≤<=*n*,<=*v*<=≠<=*u*) are numbers of profiles that are friends with each other. It is guaranteed that each unordered pair of friends occurs no more than once and no profile is friends with itself.
Print the single integer — the number of unordered pairs of profiles that are doubles. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the %I64d specificator.
[ "3 3\n1 2\n2 3\n1 3\n", "3 0\n", "4 1\n1 3\n" ]
[ "3\n", "3\n", "2\n" ]
In the first and second sample any two profiles are doubles. In the third sample the doubles are pairs of profiles (1, 3) and (2, 4).
[ { "input": "3 3\n1 2\n2 3\n1 3", "output": "3" }, { "input": "3 0", "output": "3" }, { "input": "4 1\n1 3", "output": "2" }, { "input": "1 0", "output": "0" }, { "input": "2 0", "output": "1" }, { "input": "2 1\n1 2", "output": "1" }, { "in...
46
0
0
22,620
132
Turing Tape
[ "implementation" ]
null
null
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one by one, starting from the first. Processing *i*-th element of the array is done in three steps: 1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0. 2. The *i*-th element of the array is subtracted from the result of the previous step modulo 256. 3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the *i*-th character to be printed. You are given the text printed using this method. Restore the array used to produce this text.
The input will consist of a single line *text* which contains the message printed using the described method. String *text* will contain between 1 and 100 characters, inclusive. ASCII-code of each character of *text* will be between 32 (space) and 126 (tilde), inclusive.
Output the initial array, which was used to produce *text*, one integer per line.
[ "Hello, World!\n" ]
[ "238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162\n" ]
Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 01001000<sub class="lower-index">2</sub>. Its reverse is 00010010<sub class="lower-index">2</sub> = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where *a* mod *b* is the remainder of division of *a* by *b*.
[ { "input": "Hello, World!", "output": "238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162" }, { "input": "N", "output": "142" }, { "input": "!{|aPUBKs[k\"HE;>O&(Nf}N4,*#g*<3sQXFJ'?Z/H9L[xx Rc5\"8~v}84+wv]w[oO0e':MaNy&6*]jRkYomz[o?=13Y?!fzA3eC\\", "output": "124\n166\n160\n184\n...
154
307,200
-1
22,658
67
Partial Teacher
[ "dp", "graphs", "greedy", "implementation" ]
A. Partial Teacher
1
256
A teacher decides to give toffees to his students. He asks *n* students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees. He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one. It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.
The first line of input contains the number of students *n* (2<=≤<=*n*<=≤<=1000). The second line gives (*n*<=-<=1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks.
Output consists of *n* integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.
[ "5\nLRLR\n", "5\n=RRR\n" ]
[ "2 1 2 1 2\n", "1 1 2 3 4\n" ]
none
[ { "input": "5\nLRLR", "output": "2 1 2 1 2" }, { "input": "5\n=RRR", "output": "1 1 2 3 4" }, { "input": "6\nRLRL=", "output": "1 2 1 2 1 1" }, { "input": "3\nR=", "output": "1 2 2" }, { "input": "7\nRR==RR", "output": "1 2 3 3 3 4 5" }, { "input": "16...
310
1,945,600
3.841376
22,671
954
Water Taps
[ "binary search", "greedy", "sortings" ]
null
null
Consider a system of *n* water taps all pouring water into the same container. The *i*-th water tap can be set to deliver any amount of water from 0 to *a**i* ml per second (this amount may be a real number). The water delivered by *i*-th tap has temperature *t**i*. If for every you set *i*-th tap to deliver exactly *x**i* ml of water per second, then the resulting temperature of water will be (if , then to avoid division by zero we state that the resulting water temperature is 0). You have to set all the water taps in such a way that the resulting temperature is exactly *T*. What is the maximum amount of water you may get per second if its temperature has to be *T*?
The first line contains two integers *n* and *T* (1<=≤<=*n*<=≤<=200000, 1<=≤<=*T*<=≤<=106) — the number of water taps and the desired temperature of water, respectively. The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=≤<=*a**i*<=≤<=106) where *a**i* is the maximum amount of water *i*-th tap can deliver per second. The third line contains *n* integers *t*1, *t*2, ..., *t**n* (1<=≤<=*t**i*<=≤<=106) — the temperature of water each tap delivers.
Print the maximum possible amount of water with temperature exactly *T* you can get per second (if it is impossible to obtain water with such temperature, then the answer is considered to be 0). Your answer is considered correct if its absolute or relative error doesn't exceed 10<=-<=6.
[ "2 100\n3 10\n50 150\n", "3 9\n5 5 30\n6 6 10\n", "2 12\n1 3\n10 15\n" ]
[ "6.000000000000000\n", "40.000000000000000\n", "1.666666666666667\n" ]
none
[ { "input": "2 100\n3 10\n50 150", "output": "6.000000000000000" }, { "input": "3 9\n5 5 30\n6 6 10", "output": "40.000000000000000" }, { "input": "2 12\n1 3\n10 15", "output": "1.666666666666667" }, { "input": "20 30\n70 97 14 31 83 22 83 56 19 87 59 7 7 89 24 82 34 40 6 24\n...
0
0
-1
22,684
482
Game with Strings
[ "bitmasks", "dp", "probabilities" ]
null
null
You play the game with your friend. The description of this game is listed below. Your friend creates *n* distinct strings of the same length *m* and tells you all the strings. Then he randomly chooses one of them. He chooses strings equiprobably, i.e. the probability of choosing each of the *n* strings equals . You want to guess which string was chosen by your friend. In order to guess what string your friend has chosen, you are allowed to ask him questions. Each question has the following form: «What character stands on position *pos* in the string you have chosen?» A string is considered guessed when the answers to the given questions uniquely identify the string. After the string is guessed, you stop asking questions. You do not have a particular strategy, so as each question you equiprobably ask about a position that hasn't been yet mentioned. Your task is to determine the expected number of questions needed to guess the string chosen by your friend.
The first line contains a single integer *n* (1<=≤<=*n*<=≤<=50) — the number of strings your friend came up with. The next *n* lines contain the strings that your friend has created. It is guaranteed that all the strings are distinct and only consist of large and small English letters. Besides, the lengths of all strings are the same and are between 1 to 20 inclusive.
Print the single number — the expected value. Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=9.
[ "2\naab\naac\n", "3\naaA\naBa\nCaa\n", "3\naca\nvac\nwqq\n" ]
[ "2.000000000000000\n", "1.666666666666667\n", "1.000000000000000\n" ]
In the first sample the strings only differ in the character in the third position. So only the following situations are possible: - you guess the string in one question. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>; - you guess the string in two questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> · <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/> (as in this case the first question should ask about the position that is other than the third one); - you guess the string in three questions. The event's probability is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/caddcdaf0d707d9e4ffa41e63e462a3c90474546.png" style="max-width: 100.0%;max-height: 100.0%;"/> · <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/6bb1686dc4a3e6a10e00b92d434455668cb330a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> · <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/a53d50910d43b79b6602f97f9fde950c9d1bdf77.png" style="max-width: 100.0%;max-height: 100.0%;"/> = <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/adaad783a304f9e72218e6e79114c6551a112aad.png" style="max-width: 100.0%;max-height: 100.0%;"/>; Thus, the expected value is equal to <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/5f789afab0601bacf9123c73584184ef358740fb.png" style="max-width: 100.0%;max-height: 100.0%;"/> In the second sample we need at most two questions as any pair of questions uniquely identifies the string. So the expected number of questions is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/208df5d4b6316ba263eede5d4cf4b844075718f1.png" style="max-width: 100.0%;max-height: 100.0%;"/>. In the third sample whatever position we ask about in the first question, we immediately identify the string.
[]
1,000
183,398,400
0
22,751
294
Shaass and Bookshelf
[ "dp", "greedy" ]
null
null
Shaass has *n* books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the *i*-th book is *t**i* and its pages' width is equal to *w**i*. The thickness of each book is either 1 or 2. All books have the same page heights. Shaass puts the books on the bookshelf in the following way. First he selects some of the books and put them vertically. Then he puts the rest of the books horizontally above the vertical books. The sum of the widths of the horizontal books must be no more than the total thickness of the vertical books. A sample arrangement of the books is depicted in the figure. Help Shaass to find the minimum total thickness of the vertical books that we can achieve.
The first line of the input contains an integer *n*, (1<=≤<=*n*<=≤<=100). Each of the next *n* lines contains two integers *t**i* and *w**i* denoting the thickness and width of the *i*-th book correspondingly, (1<=≤<=*t**i*<=≤<=2,<=1<=≤<=*w**i*<=≤<=100).
On the only line of the output print the minimum total thickness of the vertical books that we can achieve.
[ "5\n1 12\n1 3\n2 15\n2 5\n2 1\n", "3\n1 10\n2 1\n2 4\n" ]
[ "5\n", "3\n" ]
none
[ { "input": "5\n1 12\n1 3\n2 15\n2 5\n2 1", "output": "5" }, { "input": "3\n1 10\n2 1\n2 4", "output": "3" }, { "input": "10\n2 10\n2 4\n2 8\n2 3\n2 5\n2 6\n1 2\n1 10\n1 10\n2 5", "output": "12" }, { "input": "1\n2 7", "output": "2" }, { "input": "50\n1 24\n1 16\n1...
139
0
0
22,755