problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
βŒ€
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
C. Superior Periodic Subarraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an infinite periodic array a0, a1, ..., an - 1, ... with the period of length n. Formally, . A periodic subarray (l, s) (0 ≀ l < n, 1 ≀ s < n) of array a is an infinite periodic array with a period of length s that is a subsegment of array a, starting with position l.A periodic subarray (l, s) is superior, if when attaching it to the array a, starting from index l, any element of the subarray is larger than or equal to the corresponding element of array a. An example of attaching is given on the figure (top β€” infinite array a, bottom β€” its periodic subarray (l, s)): Find the number of distinct pairs (l, s), corresponding to the superior periodic arrays.InputThe first line contains number n (1 ≀ n ≀ 2Β·105). The second line contains n numbers a0, a1, ..., an - 1 (1 ≀ ai ≀ 106), separated by a space.OutputPrint a single integer β€” the sought number of pairs.ExamplesInput47 1 2 3Output2Input22 1Output1Input31 1 1Output6NoteIn the first sample the superior subarrays are (0, 1) and (3, 2).Subarray (0, 1) is superior, as a0 β‰₯ a0, a0 β‰₯ a1, a0 β‰₯ a2, a0 β‰₯ a3, a0 β‰₯ a0, ...Subarray (3, 2) is superior a3 β‰₯ a3, a0 β‰₯ a0, a3 β‰₯ a1, a0 β‰₯ a2, a3 β‰₯ a3, ...In the third sample any pair of (l, s) corresponds to a superior subarray as all the elements of an array are distinct.
Input47 1 2 3
Output2
1 second
256 megabytes
['number theory', '*2400']
B. Once Again...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array.InputThe first line contains two space-separated integers: n, T (1 ≀ n ≀ 100, 1 ≀ T ≀ 107). The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 300).OutputPrint a single number β€” the length of a sought sequence.ExamplesInput4 33 1 4 2Output5NoteThe array given in the sample looks like that: 3, 1, 4, 2, 3, 1, 4, 2, 3, 1, 4, 2. The elements in bold form the largest non-decreasing subsequence.
Input4 33 1 4 2
Output5
1 second
256 megabytes
['constructive algorithms', 'dp', 'matrices', '*1900']
A. GCD Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe GCD table G of size n × n for an array of positive integers a of length n is defined by formula Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows: Given all the numbers of the GCD table G, restore array a.InputThe first line contains number n (1 ≀ n ≀ 500) β€” the length of array a. The second line contains n2 space-separated numbers β€” the elements of the GCD table of G for array a. All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.OutputIn the single line print n positive integers β€” the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.ExamplesInput42 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2Output4 3 6 2Input142Output42 Input21 1 1 1Output1 1
Input42 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
Output4 3 6 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'number theory', '*1700']
F. Zublicanes and Mumocratestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt's election time in Berland. The favorites are of course parties of zublicanes and mumocrates. The election campaigns of both parties include numerous demonstrations on n main squares of the capital of Berland. Each of the n squares certainly can have demonstrations of only one party, otherwise it could lead to riots. On the other hand, both parties have applied to host a huge number of demonstrations, so that on all squares demonstrations must be held. Now the capital management will distribute the area between the two parties.Some pairs of squares are connected by (n - 1) bidirectional roads such that between any pair of squares there is a unique way to get from one square to another. Some squares are on the outskirts of the capital meaning that they are connected by a road with only one other square, such squares are called dead end squares.The mayor of the capital instructed to distribute all the squares between the parties so that the dead end squares had the same number of demonstrations of the first and the second party. It is guaranteed that the number of dead end squares of the city is even.To prevent possible conflicts between the zublicanes and the mumocrates it was decided to minimize the number of roads connecting the squares with the distinct parties. You, as a developer of the department of distributing squares, should determine this smallest number.InputThe first line of the input contains a single integer n (2 ≀ n ≀ 5000) β€” the number of squares in the capital of Berland.Next n - 1 lines contain the pairs of integers x, y (1 ≀ x, y ≀ n, x ≠ y) β€” the numbers of the squares connected by the road. All squares are numbered with integers from 1 to n. It is guaranteed that the number of dead end squares of the city is even.OutputPrint a single number β€” the minimum number of roads connecting the squares with demonstrations of different parties.ExamplesInput81 42 43 46 57 58 54 5Output1Input51 21 31 41 5Output2
Input81 42 43 46 57 58 54 5
Output1
3 seconds
512 megabytes
['dp', 'trees', 'two pointers', '*2400']
E. Kojiro and Furraritime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMotorist Kojiro spent 10 years saving up for his favorite car brand, Furrari. Finally Kojiro's dream came true! Kojiro now wants to get to his girlfriend Johanna to show off his car to her.Kojiro wants to get to his girlfriend, so he will go to her along a coordinate line. For simplicity, we can assume that Kojiro is at the point f of a coordinate line, and Johanna is at point e. Some points of the coordinate line have gas stations. Every gas station fills with only one type of fuel: Regular-92, Premium-95 or Super-98. Thus, each gas station is characterized by a pair of integers ti and xi β€” the number of the gas type and its position.One liter of fuel is enough to drive for exactly 1 km (this value does not depend on the type of fuel). Fuels of three types differ only in quality, according to the research, that affects the lifetime of the vehicle motor. A Furrari tank holds exactly s liters of fuel (regardless of the type of fuel). At the moment of departure from point f Kojiro's tank is completely filled with fuel Super-98. At each gas station Kojiro can fill the tank with any amount of fuel, but of course, at no point in time, the amount of fuel in the tank can be more than s liters. Note that the tank can simultaneously have different types of fuel. The car can moves both left and right.To extend the lifetime of the engine Kojiro seeks primarily to minimize the amount of fuel of type Regular-92. If there are several strategies to go from f to e, using the minimum amount of fuel of type Regular-92, it is necessary to travel so as to minimize the amount of used fuel of type Premium-95.Write a program that can for the m possible positions of the start fi minimize firstly, the amount of used fuel of type Regular-92 and secondly, the amount of used fuel of type Premium-95.InputThe first line of the input contains four positive integers e, s, n, m (1 ≀ e, s ≀ 109, 1 ≀ n, m ≀ 2Β·105) β€” the coordinate of the point where Johanna is, the capacity of a Furrari tank, the number of gas stations and the number of starting points. Next n lines contain two integers each ti, xi (1 ≀ ti ≀ 3,  - 109 ≀ xi ≀ 109), representing the type of the i-th gas station (1 represents Regular-92, 2 β€” Premium-95 and 3 β€” Super-98) and the position on a coordinate line of the i-th gas station. Gas stations don't necessarily follow in order from left to right.The last line contains m integers fi ( - 109 ≀ fi < e). Start positions don't necessarily follow in order from left to right.No point of the coordinate line contains more than one gas station. It is possible that some of points fi or point e coincide with a gas station.OutputPrint exactly m lines. The i-th of them should contain two integers β€” the minimum amount of gas of type Regular-92 and type Premium-95, if Kojiro starts at point fi. First you need to minimize the first value. If there are multiple ways to do it, you need to also minimize the second value.If there is no way to get to Johanna from point fi, the i-th line should look like that "-1 -1" (two numbers minus one without the quotes).ExamplesInput8 4 1 12 40Output0 4Input9 3 2 32 31 6-1 0 1Output-1 -13 33 2Input20 9 2 41 52 10-1 0 1 2Output-1 -1-1 -1-1 -1-1 -1
Input8 4 1 12 40
Output0 4
2 seconds
256 megabytes
['dp', 'greedy', '*2800']
D. Three Logostime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThree companies decided to order a billboard with pictures of their logos. A billboard is a big square board. A logo of each company is a rectangle of a non-zero area. Advertisers will put up the ad only if it is possible to place all three logos on the billboard so that they do not overlap and the billboard has no empty space left. When you put a logo on the billboard, you should rotate it so that the sides were parallel to the sides of the billboard.Your task is to determine if it is possible to put the logos of all the three companies on some square billboard without breaking any of the described rules.InputThe first line of the input contains six positive integers x1, y1, x2, y2, x3, y3 (1 ≀ x1, y1, x2, y2, x3, y3 ≀ 100), where xi and yi determine the length and width of the logo of the i-th company respectively.OutputIf it is impossible to place all the three logos on a square shield, print a single integer "-1" (without the quotes).If it is possible, print in the first line the length of a side of square n, where you can place all the three logos. Each of the next n lines should contain n uppercase English letters "A", "B" or "C". The sets of the same letters should form solid rectangles, provided that: the sizes of the rectangle composed from letters "A" should be equal to the sizes of the logo of the first company, the sizes of the rectangle composed from letters "B" should be equal to the sizes of the logo of the second company, the sizes of the rectangle composed from letters "C" should be equal to the sizes of the logo of the third company, Note that the logos of the companies can be rotated for printing on the billboard. The billboard mustn't have any empty space. If a square billboard can be filled with the logos in multiple ways, you are allowed to print any of them.See the samples to better understand the statement.ExamplesInput5 1 2 5 5 2Output5AAAAABBBBBBBBBBCCCCCCCCCCInput4 4 2 6 4 2Output6BBBBBBBBBBBBAAAACCAAAACCAAAACCAAAACC
Input5 1 2 5 5 2
Output5AAAAABBBBBBBBBBCCCCCCCCCC
1 second
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'geometry', 'implementation', 'math', '*1700']
C. Developing Skillstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values ​​of for all i from 1 to n. The expression ⌊ xβŒ‹ denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.InputThe first line of the input contains two positive integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 107) β€” the number of skills of the character and the number of units of improvements at Petya's disposal.The second line of the input contains a sequence of n integers ai (0 ≀ ai ≀ 100), where ai characterizes the level of the i-th skill of the character.OutputThe first line of the output should contain a single non-negative integer β€” the maximum total rating of the character that Petya can get using k or less improvement units.ExamplesInput2 47 9Output2Input3 817 15 19Output5Input2 299 100Output20NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to lfloor frac{100}{10} rfloor +  lfloor frac{100}{10} rfloor = 10 + 10 =  20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to .
Input2 47 9
Output2
1 second
256 megabytes
['implementation', 'math', 'sortings', '*1400']
B. Luxurious Housestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all the houses with larger numbers. In other words, a house is luxurious if the number of floors in it is strictly greater than in all the houses, which are located to the right from it. In this task it is assumed that the heights of floors in the houses are the same.The new architect is interested in n questions, i-th of them is about the following: "how many floors should be added to the i-th house to make it luxurious?" (for all i from 1 to n, inclusive). You need to help him cope with this task.Note that all these questions are independent from each other β€” the answer to the question for house i does not affect other answers (i.e., the floors to the houses are not actually added).InputThe first line of the input contains a single number n (1 ≀ n ≀ 105) β€” the number of houses in the capital of Berland.The second line contains n space-separated positive integers hi (1 ≀ hi ≀ 109), where hi equals the number of floors in the i-th house. OutputPrint n integers a1, a2, ..., an, where number ai is the number of floors that need to be added to the house number i to make it luxurious. If the house is already luxurious and nothing needs to be added to it, then ai should be equal to zero.All houses are numbered from left to right, starting from one.ExamplesInput51 2 3 1 2Output3 2 0 2 0 Input43 2 1 4Output2 3 4 0
Input51 2 3 1 2
Output3 2 0 2 0
1 second
256 megabytes
['implementation', 'math', '*1100']
A. Vasya the Hipstertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.Can you help him?InputThe single line of the input contains two positive integers a and b (1 ≀ a, b ≀ 100) β€” the number of red and blue socks that Vasya's got.OutputPrint two space-separated integers β€” the maximum number of days when Vasya can wear different socks and the number of days when he can wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.Keep in mind that at the end of the day Vasya throws away the socks that he's been wearing on that day.ExamplesInput3 1Output1 1Input2 3Output2 0Input7 3Output3 2NoteIn the first sample Vasya can first put on one pair of different socks, after that he has two red socks left to wear on the second day.
Input3 1
Output1 1
1 second
256 megabytes
['implementation', 'math', '*800']
E. Kefa and Watchtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Kefa the parrot was walking down the street as he was on the way home from the restaurant when he saw something glittering by the road. As he came nearer he understood that it was a watch. He decided to take it to the pawnbroker to earn some money. The pawnbroker said that each watch contains a serial number represented by a string of digits from 0 to 9, and the more quality checks this number passes, the higher is the value of the watch. The check is defined by three positive integers l, r and d. The watches pass a check if a substring of the serial number from l to r has period d. Sometimes the pawnbroker gets distracted and Kefa changes in some substring of the serial number all digits to c in order to increase profit from the watch. The seller has a lot of things to do to begin with and with Kefa messing about, he gave you a task: to write a program that determines the value of the watch.Let us remind you that number x is called a period of string s (1 ≀ x ≀ |s|), if si  =  si + x for all i from 1 to |s|  -  x.InputThe first line of the input contains three positive integers n, m and k (1 ≀ n ≀ 105, 1 ≀ m + k ≀ 105) β€” the length of the serial number, the number of change made by Kefa and the number of quality checks.The second line contains a serial number consisting of n digits.Then m + k lines follow, containing either checks or changes. The changes are given as 1 l r c (1 ≀ l ≀ r ≀ n, 0 ≀ c ≀ 9). That means that Kefa changed all the digits from the l-th to the r-th to be c. The checks are given as 2 l r d (1 ≀ l ≀ r ≀ n, 1 ≀ d ≀ r - l + 1).OutputFor each check on a single line print "YES" if the watch passed it, otherwise print "NO".ExamplesInput3 1 21122 2 3 11 1 3 82 1 2 1OutputNOYESInput6 2 33349342 2 5 21 4 4 32 1 6 31 2 3 82 3 6 1OutputNOYESNONoteIn the first sample test two checks will be made. In the first one substring "12" is checked on whether or not it has period 1, so the answer is "NO". In the second one substring "88", is checked on whether or not it has period 1, and it has this period, so the answer is "YES".In the second statement test three checks will be made. The first check processes substring "3493", which doesn't have period 2. Before the second check the string looks as "334334", so the answer to it is "YES". And finally, the third check processes substring "8334", which does not have period 1.
Input3 1 21122 2 3 11 1 3 82 1 2 1
OutputNOYES
1.5 seconds
256 megabytes
['data structures', 'hashing', 'strings', '*2500']
D. Kefa and Dishestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type β€” if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!InputThe first line of the input contains three space-separated numbers, n, m and k (1 ≀ m ≀ n ≀ 18, 0 ≀ k ≀ n * (n - 1)) β€” the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules.The second line contains n space-separated numbers ai, (0 ≀ ai ≀ 109) β€” the satisfaction he gets from the i-th dish.Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≀ xi, yi ≀ n, 0 ≀ ci ≀ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≀ i < j ≀ k), that xi = xj and yi = yj.OutputIn the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.ExamplesInput2 2 11 12 1 1Output3Input4 3 21 2 3 42 1 53 4 2Output12NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.
Input2 2 11 12 1 1
Output3
2 seconds
256 megabytes
['bitmasks', 'dp', '*1800']
C. Kefa and Parktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.InputThe first line contains two integers, n and m (2 ≀ n ≀ 105, 1 ≀ m ≀ n) β€” the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≀ xi, yi ≀ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge. It is guaranteed that the given set of edges specifies a tree.OutputA single integer β€” the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.ExamplesInput4 11 1 0 01 21 31 4Output2Input7 11 0 1 1 0 0 01 21 32 42 53 63 7Output2NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test: The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test: The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Input4 11 1 0 01 21 31 4
Output2
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*1500']
B. Kefa and Companytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!InputThe first line of the input contains two space-separated integers, n and d (1 ≀ n ≀ 105, ) β€” the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≀ mi, si ≀ 109) β€” the amount of money and the friendship factor, respectively. OutputPrint the maximum total friendship factir that can be reached.ExamplesInput4 575 50 100150 2075 1Output100Input5 1000 711 3299 1046 887 54Output111NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends.
Input4 575 50 100150 2075 1
Output100
2 seconds
256 megabytes
['binary search', 'sortings', 'two pointers', '*1500']
A. Kefa and First Stepstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!InputThe first line contains integer n (1 ≀ n ≀ 105).The second line contains n integers a1,  a2,  ...,  an (1 ≀ ai ≀ 109).OutputPrint a single integer β€” the length of the maximum non-decreasing subsegment of sequence a.ExamplesInput62 2 1 3 4 1Output3Input32 2 9Output3NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.
Input62 2 1 3 4 1
Output3
2 seconds
256 megabytes
['brute force', 'dp', 'implementation', '*900']
B. Finding Team Membertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?InputThere are 2n lines in the input. The first line contains an integer n (1 ≀ n ≀ 400) β€” the number of teams to be formed.The i-th line (i > 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≀ aij ≀ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)OutputOutput a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.ExamplesInput261 23 4 5Output2 1 4 3Input34870603831 161856845957 794650 97697783847 50566 691206 498447698377 156232 59015 382455 626960Output6 5 4 3 2 1NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.
Input261 23 4 5
Output2 1 4 3
2 seconds
256 megabytes
['brute force', 'implementation', 'sortings', '*1300']
A. Raising Bacteriatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are a lover of bacteria. You want to raise some bacteria in a box. Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment. What is the minimum number of bacteria you need to put into the box across those days?InputThe only line containing one integer x (1 ≀ x ≀ 109).OutputThe only line containing one integer: the answer.ExamplesInput5Output2Input8Output1NoteFor the first sample, we can add one bacterium in the box in the first day morning and at the third morning there will be 4 bacteria in the box. Now we put one more resulting 5 in the box. We added 2 bacteria in the process so the answer is 2.For the second sample, we can put one in the first morning and in the 4-th morning there will be 8 in the box. So the answer is 1.
Input5
Output2
1 second
256 megabytes
['bitmasks', '*1000']
F. Mirror Boxtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a box full of mirrors. Box consists of grid of size n × m. Each cell of the grid contains a mirror put in the shape of '\' or ' / ' (45 degree to the horizontal or vertical line). But mirrors in some cells have been destroyed. You want to put new mirrors into these grids so that the following two conditions are satisfied: If you put a light ray horizontally/vertically into the middle of any unit segment that is side of some border cell, the light will go out from the neighboring unit segment to the segment you put the ray in. each unit segment of the grid of the mirror box can be penetrated by at least one light ray horizontally/vertically put into the box according to the rules of the previous paragraph After you tried putting some mirrors, you find out that there are many ways of doing so. How many possible ways are there? The answer might be large, so please find the result modulo prime number MOD.InputThe first line contains three integers n, m, MOD (1 ≀ n, m ≀ 100, 3 ≀ MOD ≀ 109 + 7, MOD is prime), m, n indicates the dimensions of a box and MOD is the number to module the answer.The following n lines each contains a string of length m. Each string contains only ' / ', '\', '*', where '*' denotes that the mirror in that grid has been destroyed. It is guaranteed that the number of '*' is no more than 200.OutputOutput the answer modulo MOD.ExamplesInput2 2 1000000007*//*Output1Input2 2 1000000007**\\Output1Input2 2 3****Output2NoteThe only way for sample 1 is shown on the left picture from the statement.The only way for sample 2 is shown on the right picture from the statement.For the third sample, there are 5 possibilities that are listed below: 1.2.3.4.5.The answer is then module by 3 so the output should be 2.
Input2 2 1000000007*//*
Output1
2 seconds
256 megabytes
['matrices', 'trees', '*3200']
E. Walking!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a sand trail in front of Alice's home.In daytime, people walk over it and leave a footprint on the trail for their every single step. Alice cannot distinguish the order of the footprints, but she can tell whether each footprint is made by left foot or right foot. Also she's certain that all people are walking by alternating left foot and right foot.For example, suppose that one person walked through the trail and left some footprints. The footprints are RRLRL in order along the trail ('R' means right foot and 'L' means left foot). You might think the outcome of the footprints is strange. But in fact, some steps are resulting from walking backwards!There are some possible order of steps that produce these footprints such as 1 → 3 → 2 → 5 → 4 or 2 → 3 → 4 → 5 → 1 (we suppose that the distance between two consecutive steps can be arbitrarily long). The number of backward steps from above two examples are 2 and 1 separately.Alice is interested in these footprints. Whenever there is a person walking trough the trail, she takes a picture of all these footprints along the trail and erase all of them so that next person will leave a new set of footprints. We know that people walk by alternating right foot and left foot, but we don't know if the first step is made by left foot or right foot.Alice wants to know the minimum possible number of backward steps made by a person. But it's a little hard. Please help Alice to calculate it. You also need to construct one possible history of these footprints.InputOnly one line containing the string S (1 ≀ |S| ≀ 100 000) containing all footprints in order along the trail from entrance to exit.It is guaranteed that there is at least one possible footprint history.OutputYou should output 2 lines.The first line should contain a number denoting the minimum number of backward steps.The second line should contain a permutation of integers from 1 to |S|. This permutation should denote the order of footprints that may possible be used by person walked there.If there are several possible answers, you may output any of them.ExamplesInputRRLRLOutput12 5 1 3 4InputRLRLRLRLROutput01 2 3 4 5 6 7 8 9InputRRRRRLLLLOutput44 9 3 8 2 7 1 6 5NoteFor the first sample, one possible order is 2 → 5 → 1 → 3 → 4, among them only the step 5 → 1 is backward step so the answer is 1. For the second example one possible order is just to follow the order of input, thus there are no backward steps. For the third sample, there will be 4 backward steps because every step from L to R will be a backward step.
InputRRLRL
Output12 5 1 3 4
1 second
256 megabytes
['constructive algorithms', 'greedy', '*2700']
D. LCS Againtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.Recall that LCS of two strings S and T is the longest string C such that C both in S and T as a subsequence.InputThe first line contains two numbers n and m denoting the length of string S and number of first English lowercase characters forming the character set for strings (1 ≀ n ≀ 100 000, 2 ≀ m ≀ 26).The second line contains string S.OutputPrint the only line containing the answer.ExamplesInput3 3aaaOutput6Input3 3aabOutput11Input1 2aOutput1Input10 9abacadefghOutput789NoteFor the first sample, the 6 possible strings T are: aab, aac, aba, aca, baa, caa. For the second sample, the 11 possible strings T are: aaa, aac, aba, abb, abc, aca, acb, baa, bab, caa, cab.For the third sample, the only possible string T is b.
Input3 3aaa
Output6
2 seconds
256 megabytes
['dp', 'greedy', '*2700']
C. Weakness and Poornesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible.The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence.The poorness of a segment is defined as the absolute value of sum of the elements of segment.InputThe first line contains one integer n (1 ≀ n ≀ 200 000), the length of a sequence.The second line contains n integers a1, a2, ..., an (|ai| ≀ 10 000).OutputOutput a real number denoting the minimum possible weakness of a1 - x, a2 - x, ..., an - x. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.ExamplesInput31 2 3Output1.000000000000000Input41 2 3 4Output2.000000000000000Input101 10 2 9 3 8 4 7 5 6Output4.500000000000000NoteFor the first case, the optimal value of x is 2 so the sequence becomes  - 1, 0, 1 and the max poorness occurs at the segment "-1" or segment "1". The poorness value (answer) equals to 1 in this case. For the second sample the optimal value of x is 2.5 so the sequence becomes  - 1.5,  - 0.5, 0.5, 1.5 and the max poorness occurs on segment "-1.5 -0.5" or "0.5 1.5". The poorness value (answer) equals to 2 in this case.
Input31 2 3
Output1.000000000000000
2 seconds
256 megabytes
['ternary search', '*2000']
B. "Or" Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make as large as possible, where denotes the bitwise OR. Find the maximum possible value of after performing at most k operations optimally.InputThe first line contains three integers n, k and x (1 ≀ n ≀ 200 000, 1 ≀ k ≀ 10, 2 ≀ x ≀ 8).The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 109).OutputOutput the maximum value of a bitwise OR of sequence elements after performing operations.ExamplesInput3 1 21 1 1Output3Input4 2 31 2 4 8Output79NoteFor the first sample, any possible choice of doing one operation will result the same three numbers 1, 1, 2 so the result is . For the second sample if we multiply 8 by 3 two times we'll get 72. In this case the numbers will become 1, 2, 4, 72 so the OR value will be 79 and is the largest possible result.
Input3 1 21 1 1
Output3
2 seconds
256 megabytes
['brute force', 'greedy', '*1700']
A. A Problem about Polylinetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.InputOnly one line containing two positive integers a and b (1 ≀ a, b ≀ 109).OutputOutput the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output  - 1 as the answer.ExamplesInput3 1Output1.000000000000Input1 3Output-1Input4 1Output1.250000000000NoteYou can see following graphs for sample 1 and sample 3.
Input3 1
Output1.000000000000
1 second
256 megabytes
['geometry', 'math', '*1700']
B. Modulo Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of numbers a1, a2, ..., an, and a number m.Check if it is possible to choose a non-empty subsequence aij such that the sum of numbers in this subsequence is divisible by m.InputThe first line contains two numbers, n and m (1 ≀ n ≀ 106, 2 ≀ m ≀ 103) β€” the size of the original sequence and the number such that sum should be divisible by it.The second line contains n integers a1, a2, ..., an (0 ≀ ai ≀ 109).OutputIn the single line print either "YES" (without the quotes) if there exists the sought subsequence, or "NO" (without the quotes), if such subsequence doesn't exist.ExamplesInput3 51 2 3OutputYESInput1 65OutputNOInput4 63 1 1 3OutputYESInput6 65 5 5 5 5 5OutputYESNoteIn the first sample test you can choose numbers 2 and 3, the sum of which is divisible by 5.In the second sample test the single non-empty subsequence of numbers is a single number 5. Number 5 is not divisible by 6, that is, the sought subsequence doesn't exist.In the third sample test you need to choose two numbers 3 on the ends.In the fourth sample test you can take the whole subsequence.
Input3 51 2 3
OutputYES
2 seconds
256 megabytes
['combinatorics', 'data structures', 'dp', 'two pointers', '*1900']
A. Multiplication Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1.You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.InputThe single line contains numbers n and x (1 ≀ n ≀ 105, 1 ≀ x ≀ 109) β€” the size of the table and the number that we are looking for in the table.OutputPrint a single number: the number of times x occurs in the table.ExamplesInput10 5Output2Input6 12Output4Input5 13Output0NoteA table for the second sample test is given below. The occurrences of number 12 are marked bold.
Input10 5
Output2
1 second
256 megabytes
['implementation', 'number theory', '*1000']
E. Painting Edgestime limit per test6 secondsmemory limit per test600 megabytesinputstandard inputoutputstandard outputNote the unusual memory limit for this problem.You are given an undirected graph consisting of n vertices and m edges. The vertices are numbered with integers from 1 to n, the edges are numbered with integers from 1 to m. Each edge can be unpainted or be painted in one of the k colors, which are numbered with integers from 1 to k. Initially, none of the edges is painted in any of the colors.You get queries of the form "Repaint edge ei to color ci". At any time the graph formed by the edges of the same color must be bipartite. If after the repaint this condition is violated, then the query is considered to be invalid and edge ei keeps its color. Otherwise, edge ei is repainted in color ci, and the query is considered to valid.Recall that the graph is called bipartite if the set of its vertices can be divided into two parts so that no edge connected vertices of the same parts.For example, suppose you are given a triangle graph, that is a graph with three vertices and edges (1, 2), (2, 3) and (3, 1). Suppose that the first two edges are painted color 1, and the third one is painted color 2. Then the query of "repaint the third edge in color 1" will be incorrect because after its execution the graph formed by the edges of color 1 will not be bipartite. On the other hand, it is possible to repaint the second edge in color 2.You receive q queries. For each query, you should either apply it, and report that the query is valid, or report that the query is invalid.InputThe first line contains integers n, m, k, q (2 ≀ n ≀ 5Β·105, 1 ≀ m, q ≀ 5Β·105, 1 ≀ k ≀ 50) β€” the number of vertices, the number of edges, the number of colors and the number of queries. Then follow m edges of the graph in the form ai, bi (1 ≀ ai, bi ≀ n). Then follow q queries of the form ei, ci (1 ≀ ei ≀ m, 1 ≀ ci ≀ k).It is guaranteed that the graph doesn't contain multiple edges and loops.OutputFor each query print "YES" (without the quotes), if it is valid, or "NO" (without the quotes), if this query destroys the bipartivity of the graph formed by the edges of some color.ExamplesInput3 3 2 51 22 31 31 12 13 23 12 2OutputYESYESYESNOYES
Input3 3 2 51 22 31 31 12 13 23 12 2
OutputYESYESYESNOYES
6 seconds
600 megabytes
['binary search', 'data structures', '*3300']
D. Flights for Regular Customerstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the country there are exactly n cities numbered with positive integers from 1 to n. In each city there is an airport is located.Also, there is the only one airline, which makes m flights. Unfortunately, to use them, you need to be a regular customer of this company, namely, you have the opportunity to enjoy flight i from city ai to city bi only if you have already made at least di flights before that.Please note that flight i flies exactly from city ai to city bi. It can not be used to fly from city bi to city ai. An interesting fact is that there may possibly be recreational flights with a beautiful view of the sky, which begin and end in the same city.You need to get from city 1 to city n. Unfortunately, you've never traveled by plane before. What minimum number of flights you have to perform in order to get to city n?Note that the same flight can be used multiple times.InputThe first line contains two integers, n and m (2 ≀ n ≀ 150, 1 ≀ m ≀ 150) β€” the number of cities in the country and the number of flights the company provides.Next m lines contain numbers ai, bi, di (1 ≀ ai, bi ≀ n, 0 ≀ di ≀ 109), representing flight number i from city ai to city bi, accessible to only the clients who have made at least di flights. OutputPrint "Impossible" (without the quotes), if it is impossible to get from city 1 to city n using the airways.But if there is at least one way, print a single integer β€” the minimum number of flights you need to make to get to the destination point.ExamplesInput3 21 2 02 3 1Output2Input2 11 2 100500OutputImpossibleInput3 32 1 02 3 61 2 0Output8
Input3 21 2 02 3 1
Output2
4 seconds
256 megabytes
['dp', 'matrices', '*2700']
C. Points on Planetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a plane are n points (xi, yi) 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 pi 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.InputThe first line contains integer n (1 ≀ n ≀ 106).The i + 1-th line contains the coordinates of the i-th point: xi and yi (0 ≀ xi, yi ≀ 106).It is guaranteed that no two points coincide.OutputPrint the permutation of numbers pi 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.ExamplesInput50 78 103 45 09 12Output4 3 1 2 5 NoteIn the sample test the total distance is:(|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
Input50 78 103 45 09 12
Output4 3 1 2 5
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'geometry', 'greedy', 'sortings', '*2100']
B. Invariance of Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree of size n is an undirected connected graph consisting of n vertices without cycles.Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vertices pu and pv are connected by an edge".You are given permutation p of size n. Find some tree size n, invariant relative to the given permutation.InputThe first line contains number n (1 ≀ n ≀ 105) β€” the size of the permutation (also equal to the size of the sought tree).The second line contains permutation pi (1 ≀ pi ≀ n).OutputIf the sought tree does not exist, print "NO" (without the quotes).Otherwise, print "YES", and then print n - 1 lines, each of which contains two integers β€” the numbers of vertices connected by an edge of the tree you found. The vertices are numbered from 1, the order of the edges and the order of the vertices within the edges does not matter.If there are multiple solutions, output any of them.ExamplesInput44 3 2 1OutputYES4 14 21 3Input33 1 2OutputNONoteIn the first sample test a permutation transforms edge (4, 1) into edge (1, 4), edge (4, 2) into edge (1, 3) and edge (1, 3) into edge (4, 2). These edges all appear in the resulting tree.It can be shown that in the second sample test no tree satisfies the given condition.
Input44 3 2 1
OutputYES4 14 21 3
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'greedy', 'trees', '*2100']
A. Vasya and Petya's Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.Petya can ask questions like: "Is the unknown number divisible by number y?".The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no questions), and then Vasya responds to each question with a 'yes' or a 'no'. After receiving all the answers Petya should determine the number that Vasya thought of.Unfortunately, Petya is not familiar with the number theory. Help him find the minimum number of questions he should ask to make a guaranteed guess of Vasya's number, and the numbers yi, he should ask the questions about.InputA single line contains number n (1 ≀ n ≀ 103).OutputPrint the length of the sequence of questions k (0 ≀ k ≀ n), followed by k numbers β€” the questions yi (1 ≀ yi ≀ n).If there are several correct sequences of questions of the minimum length, you are allowed to print any of them.ExamplesInput4Output32 4 3 Input6Output42 4 3 5 NoteThe sequence from the answer to the first sample test is actually correct.If the unknown number is not divisible by one of the sequence numbers, it is equal to 1.If the unknown number is divisible by 4, it is 4.If the unknown number is divisible by 3, then the unknown number is 3.Otherwise, it is equal to 2. Therefore, the sequence of questions allows you to guess the unknown number. It can be shown that there is no correct sequence of questions of length 2 or shorter.
Input4
Output32 4 3
1 second
256 megabytes
['math', 'number theory', '*1500']
I. Robots protectiontime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCompany "Robots industries" produces robots for territory protection. Robots protect triangle territories β€” right isosceles triangles with catheti parallel to North-South and East-West directions.Owner of some land buys and sets robots on his territory to protect it. From time to time, businessmen want to build offices on that land and want to know how many robots will guard it. You are to handle these queries. InputThe first line contains integer N β€” width and height of the land, and integer Q β€” number of queries to handle.Next Q lines contain queries you need to process.Two types of queries: 1 dir x y len β€” add a robot to protect a triangle. Depending on the value of dir, the values of x, y and len represent a different triangle: dir = 1: Triangle is defined by the points (x, y), (x + len, y), (x, y + len) dir = 2: Triangle is defined by the points (x, y), (x + len, y), (x, y - len) dir = 3: Triangle is defined by the points (x, y), (x - len, y), (x, y + len) dir = 4: Triangle is defined by the points (x, y), (x - len, y), (x, y - len) 2 x y β€” output how many robots guard this point (robot guards a point if the point is inside or on the border of its triangle) 1 ≀ N ≀ 5000 1 ≀ Q ≀ 105 1 ≀ dir ≀ 4 All points of triangles are within range [1, N] All numbers are positive integers OutputFor each second type query output how many robots guard this point. Each answer should be in a separate line.ExamplesInput17 101 1 3 2 41 3 10 3 71 2 6 8 21 3 9 4 22 4 41 4 15 10 62 7 72 9 42 12 22 13 8Output22201
Input17 101 1 3 2 41 3 10 3 71 2 6 8 21 3 9 4 22 4 41 4 15 10 62 7 72 9 42 12 22 13 8
Output22201
1.5 seconds
512 megabytes
['data structures', '*2800']
H. Botstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha and Ira are two best friends. But they aren’t just friends, they are software engineers and experts in artificial intelligence. They are developing an algorithm for two bots playing a two-player game. The game is cooperative and turn based. In each turn, one of the players makes a move (it doesn’t matter which player, it's possible that players turns do not alternate). Algorithm for bots that Sasha and Ira are developing works by keeping track of the state the game is in. Each time either bot makes a move, the state changes. And, since the game is very dynamic, it will never go back to the state it was already in at any point in the past.Sasha and Ira are perfectionists and want their algorithm to have an optimal winning strategy. They have noticed that in the optimal winning strategy, both bots make exactly N moves each. But, in order to find the optimal strategy, their algorithm needs to analyze all possible states of the game (they haven’t learned about alpha-beta pruning yet) and pick the best sequence of moves.They are worried about the efficiency of their algorithm and are wondering what is the total number of states of the game that need to be analyzed? InputThe first and only line contains integer N. 1 ≀ N ≀ 106 OutputOutput should contain a single integer – number of possible states modulo 109 + 7.ExamplesInput2Output19NoteStart: Game is in state A. Turn 1: Either bot can make a move (first bot is red and second bot is blue), so there are two possible states after the first turn – B and C. Turn 2: In both states B and C, either bot can again make a turn, so the list of possible states is expanded to include D, E, F and G. Turn 3: Red bot already did N=2 moves when in state D, so it cannot make any more moves there. It can make moves when in state E, F and G, so states I, K and M are added to the list. Similarly, blue bot cannot make a move when in state G, but can when in D, E and F, so states H, J and L are added. Turn 4: Red bot already did N=2 moves when in states H, I and K, so it can only make moves when in J, L and M, so states P, R and S are added. Blue bot cannot make a move when in states J, L and M, but only when in H, I and K, so states N, O and Q are added. Overall, there are 19 possible states of the game their algorithm needs to analyze.
Input2
Output19
1.5 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*1800']
G. Run for beertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeople in BubbleLand like to drink beer. Little do you know, beer here is so good and strong that every time you drink it your speed goes 10 times slower than before you drank it.Birko lives in city Beergrade, but wants to go to city Beerburg. You are given a road map of BubbleLand and you need to find the fastest way for him. When he starts his journey in Beergrade his speed is 1. When he comes to a new city he always tries a glass of local beer, which divides his speed by 10. The question here is what the minimal time for him to reach Beerburg is. If there are several paths with the same minimal time, pick the one that has least roads on it. If there is still more than one path, pick any.It is guaranteed that there will be at least one path from Beergrade to Beerburg.InputThe first line of input contains integer N β€” the number of cities in Bubbleland and integer M β€” the number of roads in this country. Cities are enumerated from 0 to N - 1, with city 0 being Beergrade, and city N - 1 being Beerburg. Each of the following M lines contains three integers a, b (a ≠ b) and len. These numbers indicate that there is a bidirectional road between cities a and b with length len. 2 ≀ N ≀ 105 1 ≀ M ≀ 105 0 ≀ len ≀ 9 There is at most one road between two cities OutputThe first line of output should contain minimal time needed to go from Beergrade to Beerburg.The second line of the output should contain the number of cities on the path from Beergrade to Beerburg that takes minimal time. The third line of output should contain the numbers of cities on this path in the order they are visited, separated by spaces.ExamplesInput8 100 1 11 2 52 7 60 3 23 7 30 4 04 5 05 7 20 6 06 7 7Output3230 3 7
Input8 100 1 11 2 52 7 60 3 23 7 30 4 04 5 05 7 20 6 06 7 7
Output3230 3 7
1 second
256 megabytes
['dfs and similar', 'shortest paths', '*2200']
F. Bulbotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |posnew - posold|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.InputThe first line contains number of turns n and initial position x. Next n lines contain two numbers lstart and lend, which represent that all bulbs from interval [lstart, lend] are shining this turn. 1 ≀ n ≀ 5000 1 ≀ x ≀ 109 1 ≀ lstart ≀ lend ≀ 109 OutputOutput should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.ExamplesInput5 42 79 168 109 171 6Output8NoteBefore 1. turn move to position 5Before 2. turn move to position 9Before 5. turn move to position 8
Input5 42 79 168 109 171 6
Output8
1 second
256 megabytes
['dp', 'greedy', '*2100']
E. Spectator Riotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt’s riot time on football stadium Ramacana! Raging fans have entered the field and the police find themselves in a difficult situation. The field can be represented as a square in the coordinate system defined by two diagonal vertices in (0,0) and (105, 105). The sides of that square are also considered to be inside the field, everything else is outside.In the beginning, there are N fans on the field. For each fan we are given his speed, an integer vi as well as his integer coordinates (xi, yi). A fan with those coordinates might move and after one second he might be at any point (xi + p, yi + q) where 0 ≀ |p| + |q| ≀ vi. p, q are both integers.Points that go outside of the square that represents the field are excluded and all others have equal probability of being the location of that specific fan after one second.Andrej, a young and promising police officer, has sent a flying drone to take a photo of the riot from above. The drone’s camera works like this: It selects three points with integer coordinates such that there is a chance of a fan appearing there after one second. They must not be collinear or the camera won’t work. It is guaranteed that not all of the initial positions of fans will be on the same line. Camera focuses those points and creates a circle that passes through those three points. A photo is taken after one second (one second after the initial state). Everything that is on the circle or inside it at the moment of taking the photo (one second after focusing the points) will be on the photo. Your goal is to select those three points so that the expected number of fans seen on the photo is maximized. If there are more such selections, select those three points that give the circle with largest radius among them. If there are still more suitable selections, any one of them will be accepted. If your answer follows conditions above and radius of circle you return is smaller then the optimal one by 0.01, your output will be considered as correct.No test will have optimal radius bigger than 1010.InputThe first line contains the number of fans on the field, N. The next N lines contain three integers: xi ,yi, vi. They are the x-coordinate, y-coordinate and speed of fan i at the beginning of the one second interval considered in the task. 3 ≀ N ≀ 105 0 ≀ xi, yi ≀ 105 0 ≀ vi ≀ 1000 All numbers are integers OutputYou need to output the three points that camera needs to select. Print them in three lines, with every line containing the x-coordinate, then y-coordinate, separated by a single space. The order of points does not matter.ExamplesInput31 1 11 1 11 2 1Output2 22 11 0
Input31 1 11 1 11 2 1
Output2 22 11 0
1 second
256 megabytes
['geometry', '*2800']
D. Tablecitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Each district has its own unique name β€œ(X, Y)”, where X and Y are the coordinates of the district in the grid. The thief’s movement is as Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity. Below is an example of thief’s possible movements if he is located in district (7,1):Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.InputThere is no input for this problem. OutputThe first line of output contains integer N – duration of police search in hours. Each of the following N lines contains exactly 4 integers Xi1, Yi1, Xi2, Yi2 separated by spaces, that represent 2 districts (Xi1, Yi1), (Xi2, Yi2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement. N ≀ 2015 1 ≀ X ≀ 1000 1 ≀ Y ≀ 2 ExamplesInputΠ’ этой Π·Π°Π΄Π°Ρ‡Π΅ Π½Π΅Ρ‚ ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠ² Π²Π²ΠΎΠ΄Π°-Π²Ρ‹Π²ΠΎΠ΄Π°.This problem doesn't have sample input and output.OutputΠ‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Π·Π°ΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅ Π½ΠΈΠΆΠ΅.See the note below.NoteLet's consider the following output:25 1 50 28 1 80 2This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.Consider the following initial position and thief’s movement:In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.Since there is no further investigation by the police, the thief escaped!
InputΠ’ этой Π·Π°Π΄Π°Ρ‡Π΅ Π½Π΅Ρ‚ ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠ² Π²Π²ΠΎΠ΄Π°-Π²Ρ‹Π²ΠΎΠ΄Π°.This problem doesn't have sample input and output.
OutputΠ‘ΠΌΠΎΡ‚Ρ€ΠΈΡ‚Π΅ Π·Π°ΠΌΠ΅Ρ‡Π°Π½ΠΈΠ΅ Π½ΠΈΠΆΠ΅.See the note below.
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1700']
C. Partytime limit per test2 secondsmemory limit per test4 megabytesinputstandard inputoutputstandard outputNote the unusual memory limit for the problem.People working in MDCS (Microsoft Development Center Serbia) like partying. They usually go to night clubs on Friday and Saturday.There are N people working in MDCS and there are N clubs in the city. Unfortunately, if there is more than one Microsoft employee in night club, level of coolness goes infinitely high and party is over, so club owners will never let more than one Microsoft employee enter their club in the same week (just to be sure).You are organizing night life for Microsoft employees and you have statistics about how much every employee likes Friday and Saturday parties for all clubs.You need to match people with clubs maximizing overall sum of their happiness (they are happy as much as they like the club), while half of people should go clubbing on Friday and the other half on Saturday.InputThe first line contains integer N β€” number of employees in MDCS.Then an N × N matrix follows, where element in i-th row and j-th column is an integer number that represents how much i-th person likes j-th club’s Friday party.Then another N × N matrix follows, where element in i-th row and j-th column is an integer number that represents how much i-th person likes j-th club’s Saturday party. 2 ≀ N ≀ 20 N is even 0 ≀  level of likeness  ≀ 106 All values are integers OutputOutput should contain a single integer β€” maximum sum of happiness possible.ExamplesInput41 2 3 42 3 4 13 4 1 24 1 2 35 8 7 16 9 81 355 78 1 61 1 1 1Output167NoteHere is how we matched people with clubs:Friday: 1st person with 4th club (4 happiness) and 4th person with 1st club (4 happiness). Saturday: 2nd person with 3rd club (81 happiness) and 3rd person with 2nd club (78 happiness).4+4+81+78 = 167
Input41 2 3 42 3 4 13 4 1 24 1 2 35 8 7 16 9 81 355 78 1 61 1 1 1
Output167
2 seconds
4 megabytes
['bitmasks', 'brute force', 'graph matchings', '*2700']
B. Bribestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRuritania is a country with a very badly maintained road network, which is not exactly good news for lorry drivers that constantly have to do deliveries. In fact, when roads are maintained, they become one-way. It turns out that it is sometimes impossible to get from one town to another in a legal way – however, we know that all towns are reachable, though illegally!Fortunately for us, the police tend to be very corrupt and they will allow a lorry driver to break the rules and drive in the wrong direction provided they receive β€˜a small gift’. There is one patrol car for every road and they will request 1000 Ruritanian dinars when a driver drives in the wrong direction. However, being greedy, every time a patrol car notices the same driver breaking the rule, they will charge double the amount of money they requested the previous time on that particular road.Borna is a lorry driver that managed to figure out this bribing pattern. As part of his job, he has to make K stops in some towns all over Ruritania and he has to make these stops in a certain order. There are N towns (enumerated from 1 to N) in Ruritania and Borna’s initial location is the capital city i.e. town 1. He happens to know which ones out of the N - 1 roads in Ruritania are currently unidirectional, but he is unable to compute the least amount of money he needs to prepare for bribing the police. Help Borna by providing him with an answer and you will be richly rewarded.InputThe first line contains N, the number of towns in Ruritania. The following N - 1 lines contain information regarding individual roads between towns. A road is represented by a tuple of integers (a,b,x), which are separated with a single whitespace character. The numbers a and b represent the cities connected by this particular road, and x is either 0 or 1: 0 means that the road is bidirectional, 1 means that only the a → b direction is legal. The next line contains K, the number of stops Borna has to make. The final line of input contains K positive integers s1, …, sK: the towns Borna has to visit. 1 ≀ N ≀ 105 1 ≀ K ≀ 106 1 ≀ a, b ≀ N for all roads for all roads 1 ≀ si ≀ N for all 1 ≀ i ≀ K OutputThe output should contain a single number: the least amount of thousands of Ruritanian dinars Borna should allocate for bribes, modulo 109 + 7.ExamplesInput51 2 02 3 05 1 13 4 155 4 5 2 2Output4NoteBorna first takes the route 1 → 5 and has to pay 1000 dinars. After that, he takes the route 5 → 1 → 2 → 3 → 4 and pays nothing this time. However, when he has to return via 4 → 3 → 2 → 1 → 5, he needs to prepare 3000 (1000+2000) dinars. Afterwards, getting to 2 via 5 → 1 → 2 will cost him nothing. Finally, he doesn't even have to leave town 2 to get to 2, so there is no need to prepare any additional bribe money. Hence he has to prepare 4000 dinars in total.
Input51 2 02 3 05 1 13 4 155 4 5 2 2
Output4
1 second
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2200']
A. Fibonotcitime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFibonotci sequence is an integer recursive sequence defined by the recurrence relation Fn = sn - 1Β·Fn - 1 + sn - 2Β·Fn - 2 with F0 = 0, F1 = 1 Sequence s is an infinite and almost cyclic sequence with a cycle of length N. A sequence s is called almost cyclic with a cycle of length N if , for i β‰₯ N, except for a finite number of values si, for which (i β‰₯ N).Following is an example of an almost cyclic sequence with a cycle of length 4: s = (5,3,8,11,5,3,7,11,5,3,8,11,…) Notice that the only value of s for which the equality does not hold is s6 (s6 = 7 and s2 = 8). You are given s0, s1, ...sN - 1 and all the values of sequence s for which (i β‰₯ N).Find .InputThe first line contains two numbers K and P. The second line contains a single number N. The third line contains N numbers separated by spaces, that represent the first N numbers of the sequence s. The fourth line contains a single number M, the number of values of sequence s for which . Each of the following M lines contains two numbers j and v, indicating that and sj = v. All j-s are distinct. 1 ≀ N, M ≀ 50000 0 ≀ K ≀ 1018 1 ≀ P ≀ 109 1 ≀ si ≀ 109, for all i = 0, 1, ...N - 1 N ≀ j ≀ 1018 1 ≀ v ≀ 109 All values are integers OutputOutput should contain a single integer equal to .ExamplesInput10 831 2 127 35 4Output4
Input10 831 2 127 35 4
Output4
2 seconds
256 megabytes
['data structures', 'math', 'matrices', '*2700']
B. Bear and Three Musketeerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDo you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.InputThe first line contains two space-separated integers, n and m (3 ≀ n ≀ 4000, 0 ≀ m ≀ 4000) β€” respectively number of warriors and number of pairs of warriors knowing each other.i-th of the following m lines contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.OutputIf Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).ExamplesInput5 61 21 32 32 43 44 5Output2Input7 42 13 65 11 7Output-1NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.
Input5 61 21 32 32 43 44 5
Output2
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'graphs', 'hashing', '*1500']
A. Bear and Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a grizzly bear who desires power and adoration. He wants to win in upcoming elections and rule over the Bearland.There are n candidates, including Limak. We know how many citizens are going to vote for each candidate. Now i-th candidate would get ai votes. Limak is candidate number 1. To win in elections, he must get strictly more votes than any other candidate.Victory is more important than everything else so Limak decided to cheat. He will steal votes from his opponents by bribing some citizens. To bribe a citizen, Limak must give him or her one candy - citizens are bears and bears like candies. Limak doesn't have many candies and wonders - how many citizens does he have to bribe?InputThe first line contains single integer n (2 ≀ n ≀ 100) - number of candidates.The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 1000) - number of votes for each candidate. Limak is candidate number 1.Note that after bribing number of votes for some candidate might be zero or might be greater than 1000.OutputPrint the minimum number of citizens Limak must bribe to have strictly more votes than any other candidate.ExamplesInput55 1 11 2 8Output4Input41 8 8 8Output6Input27 6Output0NoteIn the first sample Limak has 5 votes. One of the ways to achieve victory is to bribe 4 citizens who want to vote for the third candidate. Then numbers of votes would be 9, 1, 7, 2, 8 (Limak would have 9 votes). Alternatively, Limak could steal only 3 votes from the third candidate and 1 vote from the second candidate to get situation 9, 0, 8, 2, 8.In the second sample Limak will steal 2 votes from each candidate. Situation will be 7, 6, 6, 6.In the third sample Limak is a winner without bribing any citizen.
Input55 1 11 2 8
Output4
1 second
256 megabytes
['greedy', 'implementation', '*1200']
E. Bear and Bowlingtime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is an old brown bear. He often goes bowling with his friends. Today he feels really good and tries to beat his own record!For rolling a ball one gets a score β€” an integer (maybe negative) number of points. Score for i-th roll is multiplied by i and scores are summed up. So, for k rolls with scores s1, s2, ..., sk, total score is . Total score is 0 if there were no rolls.Limak made n rolls and got score ai for i-th of them. He wants to maximize his total score and he came up with an interesting idea. He will cancel some rolls, saying that something distracted him or there was a strong wind.Limak is able to cancel any number of rolls, maybe even all or none of them. Total score is calculated as if there were only non-canceled rolls. Look at the sample tests for clarification. What maximum total score can Limak get?InputThe first line contains single integer n (1 ≀ n ≀ 105).The second line contains n space-separated integers a1, a2, ..., an (|ai| ≀ 107) - scores for Limak's rolls.OutputPrint the maximum possible total score after choosing rolls to cancel.ExamplesInput5-2 -8 0 5 -3Output13Input6-10 20 -30 40 -50 60Output400NoteIn first sample Limak should cancel rolls with scores  - 8 and  - 3. Then he is left with three rolls with scores  - 2, 0, 5. Total score is 1Β·( - 2) + 2Β·0 + 3Β·5 = 13.In second sample Limak should cancel roll with score  - 50. Total score is 1Β·( - 10) + 2Β·20 + 3Β·( - 30) + 4Β·40 + 5Β·60 = 400.
Input5-2 -8 0 5 -3
Output13
6 seconds
256 megabytes
['data structures', 'greedy', '*3200']
D. Bear and Cavalrytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWould you want to fight against bears riding horses? Me neither.Limak is a grizzly bear. He is general of the dreadful army of Bearland. The most important part of an army is cavalry of course.Cavalry of Bearland consists of n warriors and n horses. i-th warrior has strength wi and i-th horse has strength hi. Warrior together with his horse is called a unit. Strength of a unit is equal to multiplied strengths of warrior and horse. Total strength of cavalry is equal to sum of strengths of all n units. Good assignment of warriors and horses makes cavalry truly powerful.Initially, i-th warrior has i-th horse. You are given q queries. In each query two warriors swap their horses with each other.General Limak must be ready for every possible situation. What if warriors weren't allowed to ride their own horses? After each query find the maximum possible strength of cavalry if we consider assignments of all warriors to all horses that no warrior is assigned to his own horse (it can be proven that for n β‰₯ 2 there is always at least one correct assignment).Note that we can't leave a warrior without a horse.InputThe first line contains two space-separated integers, n and q (2 ≀ n ≀ 30 000, 1 ≀ q ≀ 10 000).The second line contains n space-separated integers, w1, w2, ..., wn (1 ≀ wi ≀ 106) β€” strengths of warriors.The third line contains n space-separated integers, h1, h2, ..., hn (1 ≀ hi ≀ 106) β€” strengths of horses.Next q lines describe queries. i-th of them contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi), indices of warriors who swap their horses with each other.OutputPrint q lines with answers to queries. In i-th line print the maximum possible strength of cavalry after first i queries.ExamplesInput4 21 10 100 10003 7 2 52 42 4Output57327532Input3 37 11 53 2 11 21 32 3Output444852Input7 41 2 4 8 16 32 6487 40 77 29 50 11 181 52 76 25 6Output9315930893159315NoteClarification for the first sample: Warriors:Β 1Β 10Β 100Β 1000Horses:Β Β Β 3Β Β 7Β Β 2Β Β Β Β 5Β  After first query situation looks like the following: Warriors:Β 1Β 10Β 100Β 1000Horses:Β Β Β 3Β Β 5Β Β 2Β Β Β Β 7Β  We can get 1Β·2 + 10Β·3 + 100Β·7 + 1000Β·5 = 5732 (note that no hussar takes his own horse in this assignment).After second query we get back to initial situation and optimal assignment is 1Β·2 + 10Β·3 + 100Β·5 + 1000Β·7 = 7532.Clarification for the second sample. After first query: Warriors:Β Β 7Β 11Β 5Horses:Β Β Β Β 2Β Β 3Β 1 Optimal assignment is 7Β·1 + 11Β·2 + 5Β·3 = 44.Then after second query 7Β·3 + 11Β·2 + 5Β·1 = 48.Finally 7Β·2 + 11Β·3 + 5Β·1 = 52.
Input4 21 10 100 10003 7 2 52 42 4
Output57327532
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', '*3000']
C. Bear and Drawingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little bear who learns to draw. People usually start with houses, fences and flowers but why would bears do it? Limak lives in the forest and he decides to draw a tree.Recall that tree is a connected graph consisting of n vertices and n - 1 edges.Limak chose a tree with n vertices. He has infinite strip of paper with two parallel rows of dots. Little bear wants to assign vertices of a tree to some n distinct dots on a paper so that edges would intersect only at their endpoints β€” drawn tree must be planar. Below you can see one of correct drawings for the first sample test. Is it possible for Limak to draw chosen tree?InputThe first line contains single integer n (1 ≀ n ≀ 105).Next n - 1 lines contain description of a tree. i-th of them contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n, ai ≠ bi) denoting an edge between vertices ai and bi. It's guaranteed that given description forms a tree.OutputPrint "Yes" (without the quotes) if Limak can draw chosen tree. Otherwise, print "No" (without the quotes).ExamplesInput81 21 31 66 46 76 57 8OutputYesInput131 21 31 42 52 62 73 83 93 104 114 124 13OutputNo
Input81 21 31 66 46 76 57 8
OutputYes
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'trees', '*2300']
B. Bear and Blockstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.InputThe first line contains single integer n (1 ≀ n ≀ 105).The second line contains n space-separated integers h1, h2, ..., hn (1 ≀ hi ≀ 109) β€” sizes of towers.OutputPrint the number of operations needed to destroy all towers.ExamplesInput62 1 4 6 2 2Output3Input73 3 3 1 3 3 3Output2NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color. After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.
Input62 1 4 6 2 2
Output3
1 second
256 megabytes
['binary search', 'data structures', 'dp', 'math', '*1600']
A. Bear and Pokertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?InputFirst line of input contains an integer n (2 ≀ n ≀ 105), the number of players.The second line contains n integer numbers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the bids of players.OutputPrint "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.ExamplesInput475 150 75 50OutputYesInput3100 150 250OutputNoNoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.
Input475 150 75 50
OutputYes
2 seconds
256 megabytes
['implementation', 'math', 'number theory', '*1300']
B. Order Booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di β€” buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.InputThe input starts with two positive integers n and s (1 ≀ n ≀ 1000, 1 ≀ s ≀ 50), the number of orders and the book depth.Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≀ pi ≀ 105) and an integer qi (1 ≀ qi ≀ 104) β€” direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.OutputPrint no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.ExamplesInput6 2B 10 3S 50 2S 40 1S 50 6B 20 4B 25 10OutputS 50 8S 40 1B 25 10B 20 4NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Input6 2B 10 3S 50 2S 40 1S 50 6B 20 4B 25 10
OutputS 50 8S 40 1B 25 10B 20 4
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', 'sortings', '*1300']
A. Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.InputThe first line contains two integers nA, nB (1 ≀ nA, nB ≀ 105), separated by a space β€” the sizes of arrays A and B, correspondingly.The second line contains two integers k and m (1 ≀ k ≀ nA, 1 ≀ m ≀ nB), separated by a space.The third line contains nA numbers a1, a2, ... anA ( - 109 ≀ a1 ≀ a2 ≀ ... ≀ anA ≀ 109), separated by spaces β€” elements of array A.The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≀ b1 ≀ b2 ≀ ... ≀ bnB ≀ 109), separated by spaces β€” elements of array B.OutputPrint "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).ExamplesInput3 32 11 2 33 4 5OutputYESInput3 33 31 2 33 4 5OutputNOInput5 23 11 1 1 1 12 2OutputYESNoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .
Input3 32 11 2 33 4 5
OutputYES
2 seconds
256 megabytes
['sortings', '*900']
E. Geometric Progressionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGeometric progression with the first element a and common ratio b is a sequence of numbers a, ab, ab2, ab3, ....You are given n integer geometric progressions. Your task is to find the smallest integer x, that is the element of all the given progressions, or else state that such integer does not exist.InputThe first line contains integer (1 ≀ n ≀ 100) β€” the number of geometric progressions. Next n lines contain pairs of integers a, b (1 ≀ a, b ≀ 109), that are the first element and the common ratio of the corresponding geometric progression.OutputIf the intersection of all progressions is empty, then print  - 1, otherwise print the remainder of the minimal positive integer number belonging to all progressions modulo 1000000007 (109 + 7).ExamplesInput22 24 1Output4Input22 23 3Output-1NoteIn the second sample test one of the progressions contains only powers of two, the other one contains only powers of three.
Input22 24 1
Output4
1 second
256 megabytes
['math', '*3200']
D. Campustime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOscolcovo city has a campus consisting of n student dormitories, n universities and n military offices. Initially, the i-th dormitory belongs to the i-th university and is assigned to the i-th military office.Life goes on and the campus is continuously going through some changes. The changes can be of four types: University aj merges with university bj. After that all the dormitories that belonged to university bj are assigned to to university aj, and university bj disappears. Military office cj merges with military office dj. After that all the dormitories that were assigned to military office dj, are assigned to military office cj, and military office dj disappears. Students of university xj move in dormitories. Lets kxj is the number of dormitories that belong to this university at the time when the students move in. Then the number of students in each dormitory of university xj increases by kxj (note that the more dormitories belong to the university, the more students move in each dormitory of the university). Military office number yj conducts raids on all the dormitories assigned to it and takes all students from there. Thus, at each moment of time each dormitory is assigned to exactly one university and one military office. Initially, all the dormitory are empty.Your task is to process the changes that take place in the campus and answer the queries, how many people currently live in dormitory qj.InputThe first line contains two integers, n and m (1 ≀ n, m ≀ 5Β·105) β€” the number of dormitories and the number of queries, respectively.Next m lines contain the queries, each of them is given in one of the following formats: Β«U aj bjΒ» β€” merging universities; Β«M cj djΒ» β€” merging military offices; Β«A xjΒ» β€” students of university xj moving in the dormitories; Β«Z yjΒ» β€” a raid in military office yj; Β«Q qjΒ» β€” a query asking the number of people in dormitory qj. All the numbers in the queries are positive integers and do not exceed n. It is guaranteed that at the moment of the query the universities and military offices, that are present in the query, exist.OutputIn the i-th line print the answer to the i-th query asking the number of people in the dormitory.ExamplesInput2 7A 1Q 1U 1 2A 1Z 1Q 1Q 2Output102Input5 12U 1 2M 4 5A 1Q 1A 3A 4Q 3Q 4Z 4Q 4A 5Q 5Output21101NoteConsider the first sample test: In the first query university 1 owns only dormitory 1, so after the query dormitory 1 will have 1 student. After the third query university 1 owns dormitories 1 and 2. The fourth query increases by 2 the number of students living in dormitories 1 and 2 that belong to university number 1. After that 3 students live in the first dormitory and 2 students live in the second dormitory. At the fifth query the number of students living in dormitory 1, assigned to the military office 1, becomes zero.
Input2 7A 1Q 1U 1 2A 1Z 1Q 1Q 2
Output102
2 seconds
256 megabytes
['binary search', 'data structures', 'dsu', 'trees', '*3100']
C. CNF 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output'In Boolean logic, a formula is in conjunctive normal form (CNF) or clausal normal form if it is a conjunction of clauses, where a clause is a disjunction of literals' (cited from https://en.wikipedia.org/wiki/Conjunctive_normal_form)In the other words, CNF is a formula of type , where & represents a logical "AND" (conjunction), represents a logical "OR" (disjunction), and vij are some boolean variables or their negations. Each statement in brackets is called a clause, and vij are called literals.You are given a CNF containing variables x1, ..., xm and their negations. We know that each variable occurs in at most two clauses (with negation and without negation in total). Your task is to determine whether this CNF is satisfiable, that is, whether there are such values of variables where the CNF value is true. If CNF is satisfiable, then you also need to determine the values of the variables at which the CNF is true. It is guaranteed that each variable occurs at most once in each clause.InputThe first line contains integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of clauses and the number variables, correspondingly.Next n lines contain the descriptions of each clause. The i-th line first contains first number ki (ki β‰₯ 1) β€” the number of literals in the i-th clauses. Then follow space-separated literals vij (1 ≀ |vij| ≀ m). A literal that corresponds to vij is x|vij| either with negation, if vij is negative, or without negation otherwise.OutputIf CNF is not satisfiable, print a single line "NO" (without the quotes), otherwise print two strings: string "YES" (without the quotes), and then a string of m numbers zero or one β€” the values of variables in satisfying assignment in the order from x1 to xm.ExamplesInput2 22 1 -22 2 -1OutputYES11Input4 31 11 23 -1 -2 31 -3OutputNOInput5 62 1 23 1 -2 34 -3 5 4 62 -6 -41 5OutputYES100010NoteIn the first sample test formula is . One of possible answer is x1 = TRUE, x2 = TRUE.
Input2 22 1 -22 2 -1
OutputYES11
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*2500']
B. Minimizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got array A, consisting of n integers and a positive integer k. Array A is indexed by integers from 1 to n.You need to permute the array elements so that value became minimal possible. In particular, it is allowed not to change order of elements at all.InputThe first line contains two integers n, k (2 ≀ n ≀ 3Β·105, 1 ≀ k ≀ min(5000, n - 1)). The second line contains n integers A[1], A[2], ..., A[n] ( - 109 ≀ A[i] ≀ 109), separate by spaces β€” elements of the array A.OutputPrint the minimum possible value of the sum described in the statement.ExamplesInput3 21 2 4Output1Input5 23 -5 3 -5 3Output0Input6 34 3 4 3 2 5Output3NoteIn the first test one of the optimal permutations is 1Β 4Β 2. In the second test the initial order is optimal. In the third test one of the optimal permutations is 2Β 3Β 4Β 4Β 3Β 5.
Input3 21 2 4
Output1
2 seconds
256 megabytes
['dp', 'greedy', 'sortings', '*2000']
A. Lengthening Stickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the length of any stick.Determine the number of ways to increase the lengths of some sticks so that you can form from them a non-degenerate (that is, having a positive area) triangle. Two ways are considered different, if the length of some stick is increased by different number of centimeters in them.InputThe single line contains 4 integers a, b, c, l (1 ≀ a, b, c ≀ 3Β·105, 0 ≀ l ≀ 3Β·105).OutputPrint a single integer β€” the number of ways to increase the sizes of the sticks by the total of at most l centimeters, so that you can make a non-degenerate triangle from it.ExamplesInput1 1 1 2Output4Input1 2 3 1Output2Input10 2 1 7Output0NoteIn the first sample test you can either not increase any stick or increase any two sticks by 1 centimeter.In the second sample test you can increase either the first or the second stick by one centimeter. Note that the triangle made from the initial sticks is degenerate and thus, doesn't meet the conditions.
Input1 1 1 2
Output4
1 second
256 megabytes
['combinatorics', 'implementation', 'math', '*2100']
E. Pig and Palindromestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeppa the Pig was walking and walked into the forest. What a strange coincidence! The forest has the shape of a rectangle, consisting of n rows and m columns. We enumerate the rows of the rectangle from top to bottom with numbers from 1 to n, and the columns β€” from left to right with numbers from 1 to m. Let's denote the cell at the intersection of the r-th row and the c-th column as (r, c).Initially the pig stands in cell (1, 1), and in the end she wants to be in cell (n, m). Since the pig is in a hurry to get home, she can go from cell (r, c), only to either cell (r + 1, c) or (r, c + 1). She cannot leave the forest.The forest, where the pig is, is very unusual. Some cells of the forest similar to each other, and some look very different. Peppa enjoys taking pictures and at every step she takes a picture of the cell where she is now. The path through the forest is considered to be beautiful if photographs taken on her way, can be viewed in both forward and in reverse order, showing the same sequence of photos. More formally, the line formed by the cells in order of visiting should be a palindrome (you can read a formal definition of a palindrome in the previous problem).Count the number of beautiful paths from cell (1, 1) to cell (n, m). Since this number can be very large, determine the remainder after dividing it by 109 + 7.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 500) β€” the height and width of the field.Each of the following n lines contains m lowercase English letters identifying the types of cells of the forest. Identical cells are represented by identical letters, different cells are represented by different letters.OutputPrint a single integer β€” the number of beautiful paths modulo 109 + 7.ExamplesInput3 4aaabbaaaabbaOutput3NotePicture illustrating possibilities for the sample test.
Input3 4aaabbaaaabba
Output3
4 seconds
256 megabytes
['combinatorics', 'dp', '*2300']
D. Tree Requeststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 500 000) β€” the number of nodes in the tree and queries, respectively.The following line contains n - 1 integers p2, p3, ..., pn β€” the parents of vertices from the second to the n-th (1 ≀ pi < i).The next line contains n lowercase English letters, the i-th of these letters is written on vertex i.Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≀ vi, hi ≀ n) β€” the vertex and the depth that appear in the i-th query.OutputPrint m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).ExamplesInput6 51 1 1 3 3zacccd1 13 34 16 11 2OutputYesNoYesYesYesNoteString s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.Clarification for the sample test.In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them.In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".
Input6 51 1 1 3 3zacccd1 13 34 16 11 2
OutputYesNoYesYesYes
2 seconds
256 megabytes
['binary search', 'bitmasks', 'constructive algorithms', 'dfs and similar', 'graphs', 'trees', '*2200']
C. Replacementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDaniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≀ xi ≀ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 300 000) the length of the string and the number of queries.The second line contains string s, consisting of n lowercase English letters and period signs.The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≀ xi ≀ n, ci β€” a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.OutputPrint m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.ExamplesInput10 3.b..bz....1 h3 c9 fOutput431Input4 4.cc.2 .3 .2 a1 aOutput1311NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4Β Β Β Β ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3Β Β Β Β ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1Β Β Β Β ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1Β Β Β Β ("[..]c."  →  ".c.") after the second query: f(....) = 3Β Β Β Β ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1Β Β Β Β (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1Β Β Β Β ("aa[..]"  →  "aa.")
Input10 3.b..bz....1 h3 c9 f
Output431
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'implementation', '*1600']
B. Simple Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a.Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen with the same probability), after which the winner is the player, whose number was closer to c. The boys agreed that if m and a are located on the same distance from c, Misha wins.Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number n. You need to determine which value of a Andrew must choose, so that the probability of his victory is the highest possible.More formally, you need to find such integer a (1 ≀ a ≀ n), that the probability that is maximal, where c is the equiprobably chosen integer from 1 to n (inclusive).InputThe first line contains two integers n and m (1 ≀ m ≀ n ≀ 109) β€” the range of numbers in the game, and the number selected by Misha respectively.OutputPrint a single number β€” such value a, that probability that Andrew wins is the highest. If there are multiple such values, print the minimum of them.ExamplesInput3 1Output2Input4 3Output2NoteIn the first sample test: Andrew wins if c is equal to 2 or 3. The probability that Andrew wins is 2 / 3. If Andrew chooses a = 3, the probability of winning will be 1 / 3. If a = 1, the probability of winning is 0.In the second sample test: Andrew wins if c is equal to 1 and 2. The probability that Andrew wins is 1 / 2. For other choices of a the probability of winning is less.
Input3 1
Output2
1 second
256 megabytes
['constructive algorithms', 'games', 'greedy', 'implementation', 'math', '*1300']
A. Electionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.InputThe first line of the input contains two integers n, m (1 ≀ n, m ≀ 100) β€” the number of candidates and of cities, respectively.Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≀ j ≀ n, 1 ≀ i ≀ m, 0 ≀ aij ≀ 109) denotes the number of votes for candidate j in city i.It is guaranteed that the total number of people in all the cities does not exceed 109.OutputPrint a single number β€” the index of the candidate who won the elections. The candidates are indexed starting from one.ExamplesInput3 31 2 32 3 11 2 1Output2Input3 410 10 35 1 62 2 21 5 7Output1NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.
Input3 31 2 32 3 11 2 1
Output2
1 second
256 megabytes
['implementation', '*1100']
B. Inventorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCompanies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.InputThe first line contains a single integer nΒ β€” the number of items (1 ≀ n ≀ 105).The second line contains n numbers a1, a2, ..., an (1 ≀ ai ≀ 105)Β β€” the initial inventory numbers of the items.OutputPrint n numbersΒ β€” the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.ExamplesInput31 3 2Output1 3 2 Input42 2 3 3Output2 1 3 4 Input12Output1 NoteIn the first test the numeration is already a permutation, so there is no need to change anything.In the second test there are two pairs of equal numbers, in each pair you need to replace one number.In the third test you need to replace 2 by 1, as the numbering should start from one.
Input31 3 2
Output1 3 2
1 second
256 megabytes
['greedy', 'math', '*1200']
A. Musictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Lesha loves listening to music via his smartphone. But the smartphone doesn't have much memory, so Lesha listens to his favorite songs in a well-known social network InTalk.Unfortunately, internet is not that fast in the city of Ekaterinozavodsk and the song takes a lot of time to download. But Lesha is quite impatient. The song's duration is T seconds. Lesha downloads the first S seconds of the song and plays it. When the playback reaches the point that has not yet been downloaded, Lesha immediately plays the song from the start (the loaded part of the song stays in his phone, and the download is continued from the same place), and it happens until the song is downloaded completely and Lesha listens to it to the end. For q seconds of real time the Internet allows you to download q - 1 seconds of the track.Tell Lesha, for how many times he will start the song, including the very first start.InputThe single line contains three integers T, S, q (2 ≀ q ≀ 104, 1 ≀ S < T ≀ 105).OutputPrint a single integerΒ β€” the number of times the song will be restarted.ExamplesInput5 2 2Output2Input5 4 7Output1Input6 2 3Output1NoteIn the first test, the song is played twice faster than it is downloaded, which means that during four first seconds Lesha reaches the moment that has not been downloaded, and starts the song again. After another two seconds, the song is downloaded completely, and thus, Lesha starts the song twice.In the second test, the song is almost downloaded, and Lesha will start it only once.In the third sample test the download finishes and Lesha finishes listening at the same moment. Note that song isn't restarted in this case.
Input5 2 2
Output2
2 seconds
256 megabytes
['implementation', 'math', '*1500']
E. Longest Increasing Subsequencetime limit per test1.5 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputNote that the memory limit in this problem is less than usual.Let's consider an array consisting of positive integers, some positions of which contain gaps.We have a collection of numbers that can be used to fill the gaps. Each number from the given collection can be used at most once.Your task is to determine such way of filling gaps that the longest increasing subsequence in the formed array has a maximum size.InputThe first line contains a single integer nΒ β€” the length of the array (1 ≀ n ≀ 105).The second line contains n space-separated integersΒ β€” the elements of the sequence. A gap is marked as "-1". The elements that are not gaps are positive integers not exceeding 109. It is guaranteed that the sequence contains 0 ≀ k ≀ 1000 gaps.The third line contains a single positive integer mΒ β€” the number of elements to fill the gaps (k ≀ m ≀ 105).The fourth line contains m positive integersΒ β€” the numbers to fill gaps. Each number is a positive integer not exceeding 109. Some numbers may be equal. OutputPrint n space-separated numbers in a single lineΒ β€” the resulting sequence. If there are multiple possible answers, print any of them.ExamplesInput31 2 3110Output1 2 3 Input31 -1 331 2 3Output1 2 3 Input2-1 222 4Output2 2 Input3-1 -1 -151 1 1 1 2Output1 1 2 Input4-1 -1 -1 241 1 2 2Output1 2 1 2 NoteIn the first sample there are no gaps, so the correct answer is the initial sequence.In the second sample there is only one way to get an increasing subsequence of length 3.In the third sample answer "4 2" would also be correct. Note that only strictly increasing subsequences are considered.In the fifth sample the answer "1 1 1 2" is not considered correct, as number 1 can be used in replacing only two times.
Input31 2 3110
Output1 2 3
1.5 seconds
128 megabytes
['data structures', 'dp', '*3000']
D. Sign Poststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne Khanate had a lot of roads and very little wood. Riding along the roads was inconvenient, because the roads did not have road signs indicating the direction to important cities.The Han decided that it's time to fix the issue, and ordered to put signs on every road. The Minister of Transport has to do that, but he has only k signs. Help the minister to solve his problem, otherwise the poor guy can lose not only his position, but also his head.More formally, every road in the Khanate is a line on the Oxy plane, given by an equation of the form Ax + By + C = 0 (A and B are not equal to 0 at the same time). You are required to determine whether you can put signs in at most k points so that each road had at least one sign installed.InputThe input starts with two positive integers n, k (1 ≀ n ≀ 105, 1 ≀ k ≀ 5)Next n lines contain three integers each, Ai, Bi, Ci, the coefficients of the equation that determines the road (|Ai|, |Bi|, |Ci| ≀ 105, Ai2 + Bi2 ≠ 0).It is guaranteed that no two roads coincide.OutputIf there is no solution, print "NO" in the single line (without the quotes).Otherwise, print in the first line "YES" (without the quotes).In the second line print a single number m (m ≀ k) β€” the number of used signs. In the next m lines print the descriptions of their locations.Description of a location of one sign is two integers v, u. If u and v are two distinct integers between 1 and n, we assume that sign is at the point of intersection of roads number v and u. If u =  - 1, and v is an integer between 1 and n, then the sign is on the road number v in the point not lying on any other road. In any other case the description of a sign will be assumed invalid and your answer will be considered incorrect. In case if v = u, or if v and u are the numbers of two non-intersecting roads, your answer will also be considered incorrect.The roads are numbered starting from 1 in the order in which they follow in the input.ExamplesInput3 11 0 00 -1 07 -93 0OutputYES11 2Input3 11 0 00 1 01 1 3OutputNOInput2 33 4 55 6 7OutputYES21 -12 -1NoteNote that you do not have to minimize m, but it shouldn't be more than k.In the first test all three roads intersect at point (0,0).In the second test all three roads form a triangle and there is no way to place one sign so that it would stand on all three roads at once.
Input3 11 0 00 -1 07 -93 0
OutputYES11 2
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*2800']
C. New Languagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLiving in Byteland was good enough to begin with, but the good king decided to please his subjects and to introduce a national language. He gathered the best of wise men, and sent an expedition to faraway countries, so that they would find out all about how a language should be designed.After some time, the wise men returned from the trip even wiser. They locked up for six months in the dining room, after which they said to the king: "there are a lot of different languages, but almost all of them have letters that are divided into vowels and consonants; in a word, vowels and consonants must be combined correctly."There are very many rules, all of them have exceptions, but our language will be deprived of such defects! We propose to introduce a set of formal rules of combining vowels and consonants, and include in the language all the words that satisfy them.The rules of composing words are: The letters are divided into vowels and consonants in some certain way; All words have a length of exactly n; There are m rules of the form (pos1, t1, pos2, t2). Each rule is: if the position pos1 has a letter of type t1, then the position pos2 has a letter of type t2.You are given some string s of length n, it is not necessarily a correct word of the new language. Among all the words of the language that lexicographically not smaller than the string s, find the minimal one in lexicographic order.InputThe first line contains a single line consisting of letters 'V' (Vowel) and 'C' (Consonant), determining which letters are vowels and which letters are consonants. The length of this string l is the size of the alphabet of the new language (1 ≀ l ≀ 26). The first l letters of the English alphabet are used as the letters of the alphabet of the new language. If the i-th character of the string equals to 'V', then the corresponding letter is a vowel, otherwise it is a consonant.The second line contains two integers n, m (1 ≀ n ≀ 200, 0 ≀ m ≀ 4n(n - 1))Β β€” the number of letters in a single word and the number of rules, correspondingly.Next m lines describe m rules of the language in the following format: pos1, t1, pos2, t2 (1 ≀ pos1, pos2 ≀ n, pos1 ≠ pos2, 'V', 'C' }).The last line contains string s of length n, consisting of the first l small letters of the English alphabet.It is guaranteed that no two rules are the same.OutputPrint a smallest word of a language that is lexicographically not smaller than s. If such words does not exist (for example, if the language has no words at all), print "-1" (without the quotes).ExamplesInputVC2 11 V 2 CaaOutputabInputVC2 11 C 2 VbbOutput-1InputVCC4 31 C 2 V2 C 3 V3 V 4 VabacOutputacaaNoteIn the first test word "aa" is not a word of the language, but word "ab" is.In the second test out of all four possibilities only word "bb" is not a word of a language, but all other words are lexicographically less, so there is no answer.In the third test, due to the last rule, "abac" doesn't belong to the language ("a" is a vowel, "c" is a consonant). The only word with prefix "ab" that meets the given rules is "abaa". But it is less than "abac", so the answer will be "acaa"
InputVC2 11 V 2 Caa
Outputab
2 seconds
256 megabytes
['2-sat', 'greedy', '*2600']
B. Symmetric and Transitivetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.A set ρ of pairs (a, b) of elements of some set A is called a binary relation on set A. For two elements a and b of the set A we say that they are in relation ρ, if pair , in this case we use a notation .Binary relation is equivalence relation, if: It is reflexive (for any a it is true that ); It is symmetric (for any a, b it is true that if , then ); It is transitive (if and , than ).Little Johnny is not completely a fool and he noticed that the first condition is not necessary! Here is his "proof":Take any two elements, a and b. If , then (according to property (2)), which means (according to property (3)).It's very simple, isn't it? However, you noticed that Johnny's "proof" is wrong, and decided to show him a lot of examples that prove him wrong.Here's your task: count the number of binary relations over a set of size n such that they are symmetric, transitive, but not an equivalence relations (i.e. they are not reflexive).Since their number may be very large (not 0, according to Little Johnny), print the remainder of integer division of this number by 109 + 7.InputA single line contains a single integer n (1 ≀ n ≀ 4000).OutputIn a single line print the answer to the problem modulo 109 + 7.ExamplesInput1Output1Input2Output3Input3Output10NoteIf n = 1 there is only one such relationΒ β€” an empty one, i.e. . In other words, for a single element x of set A the following is hold: .If n = 2 there are three such relations. Let's assume that set A consists of two elements, x and y. Then the valid relations are , ρ = {(x, x)}, ρ = {(y, y)}. It is easy to see that the three listed binary relations are symmetric and transitive relations, but they are not equivalence relations.
Input1
Output1
1.5 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*1900']
A. Primes or Palindromes?time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRikhail Mubinchik believes that the current definition of prime numbers is obsolete as they are too complex and unpredictable. A palindromic number is another matter. It is aesthetically pleasing, and it has a number of remarkable properties. Help Rikhail to convince the scientific community in this!Let us remind you that a number is called prime if it is integer larger than one, and is not divisible by any positive integer other than itself and one.Rikhail calls a number a palindromic if it is integer, positive, and its decimal representation without leading zeros is a palindrome, i.e. reads the same from left to right and right to left.One problem with prime numbers is that there are too many of them. Let's introduce the following notation: Ο€(n)Β β€” the number of primes no larger than n, rub(n)Β β€” the number of palindromic numbers no larger than n. Rikhail wants to prove that there are a lot more primes than palindromic ones.He asked you to solve the following problem: for a given value of the coefficient A find the maximum n, such that Ο€(n) ≀ AΒ·rub(n).InputThe input consists of two positive integers p, q, the numerator and denominator of the fraction that is the value of AΒ (,Β ).OutputIf such maximum number exists, then print it. Otherwise, print "Palindromic tree is better than splay tree" (without the quotes).ExamplesInput1 1Output40Input1 42Output1Input6 4Output172
Input1 1
Output40
3 seconds
256 megabytes
['brute force', 'implementation', 'math', 'number theory', '*1600']
F. Mausoleumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKing of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then β€” non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement: [1, 2, 2, 3, 4, 4, 3, 1]; [1, 1]; [2, 2, 1, 1]; [1, 2, 3, 3, 2, 1]. Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≀ xi, yi ≀ 2n) and sign signi.Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.InputThe first line of the input contains integers n and k (1 ≀ n ≀ 35, 0 ≀ k ≀ 100) β€” the number of pairs of blocks and the number of additional requirements.Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≀ xi, yi ≀ 2n), and the sign is on of the list of the five possible signs.OutputPrint the sought number of ways.ExamplesInput3 0Output9Input3 12 > 3Output1Input4 13 = 6Output3
Input3 0
Output9
1 second
256 megabytes
['dp', '*2400']
E. President and Roadstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer.Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest.The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer.InputThe first lines contain four integers n, m, s and t (2 ≀ n ≀ 105;Β 1 ≀ m ≀ 105;Β 1 ≀ s, t ≀ n) β€” the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t).Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≀ ai, bi ≀ n;Β ai ≠ bi;Β 1 ≀ li ≀ 106) β€” the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi.The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads.OutputPrint m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input).If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes).Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing.If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes).ExamplesInput6 7 1 61 2 21 3 102 3 72 4 83 5 34 5 25 6 1OutputYESCAN 2CAN 1CAN 1CAN 1CAN 1YESInput3 3 1 31 2 102 3 101 3 100OutputYESYESCAN 81Input2 2 1 21 2 11 2 2OutputYESNONoteThe cost of repairing the road is the difference between the time needed to ride along it before and after the repairing.In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
Input6 7 1 61 2 21 3 102 3 72 4 83 5 34 5 25 6 1
OutputYESCAN 2CAN 1CAN 1CAN 1CAN 1YES
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'hashing', 'shortest paths', '*2200']
D. One-Dimensional Battle Shipstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob love playing one-dimensional battle ships. They play on the field in the form of a line consisting of n square cells (that is, on a 1 × n table).At the beginning of the game Alice puts k ships on the field without telling their positions to Bob. Each ship looks as a 1 × a rectangle (that is, it occupies a sequence of a consecutive squares of the field). The ships cannot intersect and even touch each other.After that Bob makes a sequence of "shots". He names cells of the field and Alice either says that the cell is empty ("miss"), or that the cell belongs to some ship ("hit").But here's the problem! Alice like to cheat. May be that is why she responds to each Bob's move with a "miss". Help Bob catch Alice cheating β€” find Bob's first move, such that after it you can be sure that Alice cheated.InputThe first line of the input contains three integers: n, k and a (1 ≀ n, k, a ≀ 2Β·105) β€” the size of the field, the number of the ships and the size of each ship. It is guaranteed that the n, k and a are such that you can put k ships of size a on the field, so that no two ships intersect or touch each other.The second line contains integer m (1 ≀ m ≀ n) β€” the number of Bob's moves.The third line contains m distinct integers x1, x2, ..., xm, where xi is the number of the cell where Bob made the i-th shot. The cells are numbered from left to right from 1 to n.OutputPrint a single integer β€” the number of such Bob's first move, after which you can be sure that Alice lied. Bob's moves are numbered from 1 to m in the order the were made. If the sought move doesn't exist, then print "-1".ExamplesInput11 3 354 8 6 1 11Output3Input5 1 321 5Output-1Input5 1 313Output1
Input11 3 354 8 6 1 11
Output3
1 second
256 megabytes
['binary search', 'data structures', 'greedy', 'sortings', '*1700']
C. Geometric Progressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≀ i1 < i2 < i3 ≀ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form bΒ·k0, bΒ·k1, ..., bΒ·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.InputThe first line of the input contains two integers, n and k (1 ≀ n, k ≀ 2Β·105), showing how many numbers Polycarp's sequence has and his favorite number.The second line contains n integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109) β€” elements of the sequence.OutputOutput a single number β€” the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.ExamplesInput5 21 1 2 2 4Output4Input3 11 1 1Output1Input10 31 2 6 2 3 6 9 18 3 9Output6NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Input5 21 1 2 2 4
Output4
1 second
256 megabytes
['binary search', 'data structures', 'dp', '*1700']
B. Berland National Librarytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.InputThe first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers).It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.OutputPrint a single integer β€” the minimum possible capacity of the reading room.ExamplesInput6+ 12001- 12001- 1- 1200+ 1+ 7Output3Input2- 1- 2Output2Input2+ 1- 1Output1NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Input6+ 12001- 12001- 1- 1200+ 1+ 7
Output3
1 second
256 megabytes
['implementation', '*1300']
A. Lineland Mailtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β€” a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values ​​mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other cityInputThe first line of the input contains integer n (2 ≀ n ≀ 105) β€” the number of cities in Lineland. The second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109), where xi is the x-coordinate of the i-th city. All the xi's are distinct and follow in ascending order.OutputPrint n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, and maxi is the maximum cost of sending a letter from the i-th city.ExamplesInput4-5 -2 2 7Output3 123 94 75 12Input2-1 1Output2 22 2
Input4-5 -2 2 7
Output3 123 94 75 12
3 seconds
256 megabytes
['greedy', 'implementation', '*900']
G. Max and Mintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo kittens, Max and Min, play with a pair of non-negative integers x and y. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, x and y became negative at the same time, and kitten Max tries to prevent him from doing so.Each kitten has a set of pairs of integers available to it. Kitten Max has n pairs of non-negative integers (ai, bi) (1 ≀ i ≀ n), and kitten Min has m pairs of non-negative integers (cj, dj) (1 ≀ j ≀ m). As kitten Max makes a move, it can take any available pair (ai, bi) and add ai to x and bi to y, and kitten Min can take any available pair (cj, dj) and subtract cj from x and dj from y. Each kitten can use each pair multiple times during distinct moves.Max moves first. Kitten Min is winning if at some moment both numbers a, b are negative simultaneously. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.InputThe first line contains two integers, n and m (1 ≀ n, m ≀ 100 000) β€” the number of pairs of numbers available to Max and Min, correspondingly.The second line contains two integers x, y (1 ≀ x, y ≀ 109) β€” the initial values of numbers with which the kittens are playing.Next n lines contain the pairs of numbers ai, bi (1 ≀ ai, bi ≀ 109) β€” the pairs available to Max.The last m lines contain pairs of numbers cj, dj (1 ≀ cj, dj ≀ 109) β€” the pairs available to Min.OutputPrint Β«MaxΒ» (without the quotes), if kitten Max wins, or "Min" (without the quotes), if kitten Min wins.ExamplesInput2 242 432 33 23 1010 3OutputMinInput1 11 13 41 1OutputMaxNoteIn the first test from the statement Min can respond to move (2, 3) by move (3, 10), and to move (3, 2) by move (10, 3). Thus, for each pair of Max and Min's moves the values of both numbers x and y will strictly decrease, ergo, Min will win sooner or later.In the second sample test after each pair of Max and Min's moves both numbers x and y only increase, thus none of them will become negative.
Input2 242 432 33 23 1010 3
OutputMin
2 seconds
256 megabytes
['geometry', '*2500']
F. Clique in the Divisibility Graphtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively.Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connected by an edge. In particular, an empty set of vertexes and a set consisting of a single vertex, are cliques.Let's define a divisibility graph for a set of positive integers A = {a1, a2, ..., an} as follows. The vertices of the given graph are numbers from set A, and two numbers ai and aj (i ≠ j) are connected by an edge if and only if either ai is divisible by aj, or aj is divisible by ai.You are given a set of non-negative integers A. Determine the size of a maximum clique in a divisibility graph for set A.InputThe first line contains integer n (1 ≀ n ≀ 106), that sets the size of set A.The second line contains n distinct positive integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” elements of subset A. The numbers in the line follow in the ascending order.OutputPrint a single number β€” the maximum size of a clique in a divisibility graph for set A.ExamplesInput83 4 6 8 10 18 21 24Output3NoteIn the first sample test a clique of size 3 is, for example, a subset of vertexes {3, 6, 18}. A clique of a larger size doesn't exist in this graph.
Input83 4 6 8 10 18 21 24
Output3
1 second
256 megabytes
['dp', 'math', 'number theory', '*1500']
E. Restoring Maptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArchaeologists found some information about an ancient land of Treeland. We know for sure that the Treeland consisted of n cities connected by the n - 1 road, such that you can get from each city to any other one along the roads. However, the information about the specific design of roads in Treeland has been lost. The only thing that the archaeologists can use is the preserved information about near cities.Two cities of Treeland were called near, if it were possible to move from one city to the other one by moving through at most two roads. Also, a city is considered near to itself. During the recent excavations archaeologists found a set of n notes, each of them represents a list of cities, near to some of the n cities of the country. However, unfortunately, none of the found records lets you understand in what order the cities go in the list and for which city in the list the near to it cities were listed. Help the archaeologists and restore any variant of the map of Treeland that meets the found information.InputThe first line contains integer n (2 ≀ n ≀ 1000) β€” the number of cities in the country. Next n lines describe the found lists of near cities. Each list starts from number k (1 ≀ k ≀ n), representing the number of cities in the list followed by k city numbers. All numbers in each list are distinct.It is guaranteed that the given information determines at least one possible road map.OutputPrint n - 1 pairs of numbers representing the roads of the country. The i-th line must contain two integers ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi), showing that there is a road between cities ai and bi.The answer you print must satisfy the description of close cities from the input. You may print the roads of the countries in any order. The cities that are connected by a road may also be printed in any order.If there are multiple good answers, you may print any of them.ExamplesInput54 3 2 4 15 5 3 2 4 15 4 2 1 5 34 2 1 4 33 1 4 5Output1 41 21 34 5Input65 6 1 3 4 25 2 1 3 4 66 3 6 2 5 4 16 6 1 2 5 3 43 5 2 45 3 1 2 4 6Output2 41 22 32 64 5
Input54 3 2 4 15 5 3 2 4 15 4 2 1 5 34 2 1 4 33 1 4 5
Output1 41 21 34 5
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'trees', '*3200']
D. Restructuring Companytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEven the most successful company can go through a crisis period when you have to make a hard decision β€” to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types: Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≀ x, y ≀ n) β€” are numbers of two of some company employees. If team(x) matches team(y), then nothing happens. Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≀ x ≀ y ≀ n) β€” the numbers of some two employees of the company. At that the crisis manager can sometimes wonder whether employees x and y (1 ≀ x, y ≀ n) work at the same department.Help the crisis manager and answer all of his queries.InputThe first line of the input contains two integers n and q (1 ≀ n ≀ 200 000, 1 ≀ q ≀ 500 000) β€” the number of the employees of the company and the number of queries the crisis manager has.Next q lines contain the queries of the crisis manager. Each query looks like typeΒ xΒ y, where . If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.OutputFor each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.ExamplesInput8 63 2 51 2 53 2 52 4 72 1 23 1 7OutputNOYESYES
Input8 63 2 51 2 53 2 52 4 72 1 23 1 7
OutputNOYESYES
2 seconds
256 megabytes
['data structures', 'dsu', '*1900']
C. Logistical Questionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome country consists of n cities, connected by a railroad network. The transport communication of the country is so advanced that the network consists of a minimum required number of (n - 1) bidirectional roads (in the other words, the graph of roads is a tree). The i-th road that directly connects cities ai and bi, has the length of li kilometers.The transport network is served by a state transporting company FRR (Fabulous Rail Roads). In order to simplify the price policy, it offers a single ride fare on the train. In order to follow the route of length t kilometers, you need to pay burles. Note that it is forbidden to split a long route into short segments and pay them separately (a special railroad police, or RRP, controls that the law doesn't get violated).A Large Software Company decided to organize a programming tournament. Having conducted several online rounds, the company employees determined a list of finalists and sent it to the logistical department to find a place where to conduct finals. The Large Software Company can easily organize the tournament finals in any of the n cities of the country, so the the main factor in choosing the city for the last stage of the tournament is the total cost of buying tickets for all the finalists. We know that the i-th city of the country has wi cup finalists living there.Help the company employees find the city such that the total cost of travel of all the participants to it is minimum.InputThe first line of the input contains number n (1 ≀ n ≀ 200 000) β€” the number of cities in the country.The next line contains n integers w1, w2, ..., wn (0 ≀ wi ≀ 108) β€” the number of finalists living in each city of the country.Next (n - 1) lines contain the descriptions of the railroad, the i-th line contains three integers, ai, bi, li (1 ≀ ai, bi ≀ n, ai ≠ bi, 1 ≀ li ≀ 1000).OutputPrint two numbers β€” an integer f that is the number of the optimal city to conduct the competition, and the real number c, equal to the minimum total cost of transporting all the finalists to the competition. Your answer will be considered correct if two conditions are fulfilled at the same time: The absolute or relative error of the printed number c in comparison with the cost of setting up a final in city f doesn't exceed 10 - 6; Absolute or relative error of the printed number c in comparison to the answer of the jury doesn't exceed 10 - 6. If there are multiple answers, you are allowed to print any of them.ExamplesInput53 1 2 6 51 2 32 3 14 3 95 3 1Output3 192.0Input25 51 2 2Output1 14.142135623730951000NoteIn the sample test an optimal variant of choosing a city to conduct the finals of the competition is 3. At such choice the cost of conducting is burles.In the second sample test, whatever city you would choose, you will need to pay for the transport for five participants, so you will need to pay burles for each one of them.
Input53 1 2 6 51 2 32 3 14 3 95 3 1
Output3 192.0
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'trees', '*3000']
B. Replicating Processestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure.As part of this task, we assume that the social network is 4n processes running on the n servers. All servers are absolutely identical machines, each of which has a volume of RAM of 1 GB = 1024 MB (1). Each process takes 100 MB of RAM on the server. At the same time, the needs of maintaining the viability of the server takes about 100 more megabytes of RAM. Thus, each server may have up to 9 different processes of social network.Now each of the n servers is running exactly 4 processes. However, at the moment of peak load it is sometimes necessary to replicate the existing 4n processes by creating 8n new processes instead of the old ones. More formally, there is a set of replication rules, the i-th (1 ≀ i ≀ 4n) of which has the form of ai → (bi, ci), where ai, bi and ci (1 ≀ ai, bi, ci ≀ n) are the numbers of servers. This means that instead of an old process running on server ai, there should appear two new copies of the process running on servers bi and ci. The two new replicated processes can be on the same server (i.e., bi may be equal to ci) or even on the same server where the original process was (i.e. ai may be equal to bi or ci). During the implementation of the rule ai → (bi, ci) first the process from the server ai is destroyed, then appears a process on the server bi, then appears a process on the server ci.There is a set of 4n rules, destroying all the original 4n processes from n servers, and creating after their application 8n replicated processes, besides, on each of the n servers will be exactly 8 processes. However, the rules can only be applied consecutively, and therefore the amount of RAM of the servers imposes limitations on the procedure for the application of the rules.According to this set of rules determine the order in which you want to apply all the 4n rules so that at any given time the memory of each of the servers contained at most 9 processes (old and new together), or tell that it is impossible.InputThe first line of the input contains integer n (1 ≀ n ≀ 30 000) β€” the number of servers of the social network.Next 4n lines contain the rules of replicating processes, the i-th (1 ≀ i ≀ 4n) of these lines as form ai, bi, ci (1 ≀ ai, bi, ci ≀ n) and describes rule ai → (bi, ci).It is guaranteed that each number of a server from 1 to n occurs four times in the set of all ai, and eight times among a set that unites all bi and ci.OutputIf the required order of performing rules does not exist, print "NO" (without the quotes).Otherwise, print in the first line "YES" (without the quotes), and in the second line β€” a sequence of 4n numbers from 1 to 4n, giving the numbers of the rules in the order they are applied. The sequence should be a permutation, that is, include each number from 1 to 4n exactly once.If there are multiple possible variants, you are allowed to print any of them.ExamplesInput21 2 21 2 21 2 21 2 22 1 12 1 12 1 12 1 1OutputYES1 2 5 6 3 7 4 8Input31 2 31 1 11 1 11 1 12 1 32 2 22 2 22 2 23 1 23 3 33 3 33 3 3OutputYES2 3 4 6 7 8 10 11 12 1 5 9Note(1) To be extremely accurate, we should note that the amount of server memory is 1 GiB = 1024 MiB and processes require 100 MiB RAM where a gibibyte (GiB) is the amount of RAM of 230 bytes and a mebibyte (MiB) is the amount of RAM of 220 bytes.In the first sample test the network uses two servers, each of which initially has four launched processes. In accordance with the rules of replication, each of the processes must be destroyed and twice run on another server. One of the possible answers is given in the statement: after applying rules 1 and 2 the first server will have 2 old running processes, and the second server will have 8 (4 old and 4 new) processes. After we apply rules 5 and 6, both servers will have 6 running processes (2 old and 4 new). After we apply rules 3 and 7, both servers will have 7 running processes (1 old and 6 new), and after we apply rules 4 and 8, each server will have 8 running processes. At no time the number of processes on a single server exceeds 9.In the second sample test the network uses three servers. On each server, three processes are replicated into two processes on the same server, and the fourth one is replicated in one process for each of the two remaining servers. As a result of applying rules 2, 3, 4, 6, 7, 8, 10, 11, 12 each server would have 7 processes (6 old and 1 new), as a result of applying rules 1, 5, 9 each server will have 8 processes. At no time the number of processes on a single server exceeds 9.
Input21 2 21 2 21 2 21 2 22 1 12 1 12 1 12 1 1
OutputYES1 2 5 6 3 7 4 8
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2600']
A. Matching Namestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTeachers of one programming summer school decided to make a surprise for the students by giving them names in the style of the "Hobbit" movie. Each student must get a pseudonym maximally similar to his own name. The pseudonym must be a name of some character of the popular saga and now the teachers are busy matching pseudonyms to student names.There are n students in a summer school. Teachers chose exactly n pseudonyms for them. Each student must get exactly one pseudonym corresponding to him. Let us determine the relevance of a pseudonym b to a student with name a as the length of the largest common prefix a and b. We will represent such value as . Then we can determine the quality of matching of the pseudonyms to students as a sum of relevances of all pseudonyms to the corresponding students.Find the matching between students and pseudonyms with the maximum quality.InputThe first line contains number n (1 ≀ n ≀ 100 000) β€” the number of students in the summer school.Next n lines contain the name of the students. Each name is a non-empty word consisting of lowercase English letters. Some names can be repeating.The last n lines contain the given pseudonyms. Each pseudonym is a non-empty word consisting of small English letters. Some pseudonyms can be repeating.The total length of all the names and pseudonyms doesn't exceed 800 000 characters.OutputIn the first line print the maximum possible quality of matching pseudonyms to students.In the next n lines describe the optimal matching. Each line must have the form a b (1 ≀ a, b ≀ n), that means that the student who was number a in the input, must match to the pseudonym number b in the input.The matching should be a one-to-one correspondence, that is, each student and each pseudonym should occur exactly once in your output. If there are several optimal answers, output any.ExamplesInput5gennadygalyaborisbilltoshikbilbotoringendalfsmauggaladrielOutput114 12 51 35 23 4NoteThe first test from the statement the match looks as follows: bill  →  bilbo (lcp = 3) galya  →  galadriel (lcp = 3) gennady  →  gendalf (lcp = 3) toshik  →  torin (lcp = 2) boris  →  smaug (lcp = 0)
Input5gennadygalyaborisbilltoshikbilbotoringendalfsmauggaladriel
Output114 12 51 35 23 4
2 seconds
256 megabytes
['dfs and similar', 'strings', 'trees', '*2300']
B. Gerald is into Arttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald bought two very rare paintings at the Sotheby's auction and he now wants to hang them on the wall. For that he bought a special board to attach it to the wall and place the paintings on the board. The board has shape of an a1 × b1 rectangle, the paintings have shape of a a2 × b2 and a3 × b3 rectangles.Since the paintings are painted in the style of abstract art, it does not matter exactly how they will be rotated, but still, one side of both the board, and each of the paintings must be parallel to the floor. The paintings can touch each other and the edges of the board, but can not overlap or go beyond the edge of the board. Gerald asks whether it is possible to place the paintings on the board, or is the board he bought not large enough?InputThe first line contains two space-separated numbers a1 and b1 β€” the sides of the board. Next two lines contain numbers a2, b2, a3 and b3 β€” the sides of the paintings. All numbers ai, bi in the input are integers and fit into the range from 1 to 1000.OutputIf the paintings can be placed on the wall, print "YES" (without the quotes), and if they cannot, print "NO" (without the quotes).ExamplesInput3 21 32 1OutputYESInput5 53 33 3OutputNOInput4 22 31 2OutputYESNoteThat's how we can place the pictures in the first test:And that's how we can do it in the third one.
Input3 21 32 1
OutputYES
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1200']
A. Currency System in Geraldiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?InputThe first line contains number n (1 ≀ n ≀ 1000) β€” the number of values of the banknotes that used in Geraldion. The second line contains n distinct space-separated numbers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the values of the banknotes.OutputPrint a single line β€” the minimum unfortunate sum. If there are no unfortunate sums, print  - 1.ExamplesInput51 2 3 4 5Output-1
Input51 2 3 4 5
Output-1
2 seconds
256 megabytes
['implementation', 'sortings', '*1000']
E. Gerald and Pathtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main walking trail in Geraldion is absolutely straight, and it passes strictly from the north to the south, it is so long that no one has ever reached its ends in either of the two directions. The Geraldionians love to walk on this path at any time, so the mayor of the city asked the Herald to illuminate this path with a few spotlights. The spotlights have already been delivered to certain places and Gerald will not be able to move them. Each spotlight illuminates a specific segment of the path of the given length, one end of the segment is the location of the spotlight, and it can be directed so that it covers the segment to the south or to the north of spotlight.The trail contains a monument to the mayor of the island, and although you can walk in either directions from the monument, no spotlight is south of the monument.You are given the positions of the spotlights and their power. Help Gerald direct all the spotlights so that the total length of the illuminated part of the path is as much as possible.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of spotlights. Each of the n lines contains two space-separated integers, ai and li (0 ≀ ai ≀ 108, 1 ≀ li ≀ 108). Number ai shows how much further the i-th spotlight to the north, and number li shows the length of the segment it illuminates.It is guaranteed that all the ai's are distinct.OutputPrint a single integer β€” the maximum total length of the illuminated part of the path.ExamplesInput31 12 23 3Output5Input41 23 34 36 2Output9
Input31 12 23 3
Output5
4 seconds
256 megabytes
['dp', 'sortings', '*3000']
D. Randomizertime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald got tired of playing board games with the usual six-sided die, and he bought a toy called Randomizer. It functions as follows.A Randomizer has its own coordinate plane on which a strictly convex polygon is painted, the polygon is called a basic polygon. If you shake a Randomizer, it draws some nondegenerate (i.e. having a non-zero area) convex polygon with vertices at some vertices of the basic polygon. The result of the roll (more precisely, the result of the shaking) is considered to be the number of points with integer coordinates, which were strictly inside (the points on the border are not considered) the selected polygon. Now Gerald is wondering: what is the expected result of shaking the Randomizer?During the shaking the Randomizer considers all the possible non-degenerate convex polygons with vertices at the vertices of the basic polygon. Let's assume that there are k versions of the polygons. Then the Randomizer chooses each of them with probability .InputThe first line of the input contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of vertices of the basic polygon. Next n lines contain the coordinates of the vertices of the basic polygon. The i-th of these lines contain two integers xi and yi ( - 109 ≀ xi, yi ≀ 109) β€” the coordinates of the i-th vertex of the polygon. The vertices are given in the counter-clockwise order.OutputPrint the sought expected value with absolute or relative error at most 10 - 9.ExamplesInput40 02 02 20 2Output0.2Input50 02 02 21 30 2Output0.8125NoteA polygon is called strictly convex if it is convex and no its vertices lie on the same line.Let's assume that a random variable takes values x1, ..., xn with probabilities p1, ..., pn, correspondingly. Then the expected value of this variable equals to .
Input40 02 02 20 2
Output0.2
2.5 seconds
256 megabytes
['combinatorics', 'geometry', 'probabilities', '*2800']
C. Gerald and Giant Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiant chess is quite common in Geraldion. We will not delve into the rules of the game, we'll just say that the game takes place on an h × w field, and it is painted in two colors, but not like in chess. Almost all cells of the field are white and only some of them are black. Currently Gerald is finishing a game of giant chess against his friend Pollard. Gerald has almost won, and the only thing he needs to win is to bring the pawn from the upper left corner of the board, where it is now standing, to the lower right corner. Gerald is so confident of victory that he became interested, in how many ways can he win?The pawn, which Gerald has got left can go in two ways: one cell down or one cell to the right. In addition, it can not go to the black cells, otherwise the Gerald still loses. There are no other pawns or pieces left on the field, so that, according to the rules of giant chess Gerald moves his pawn until the game is over, and Pollard is just watching this process.InputThe first line of the input contains three integers: h, w, n β€” the sides of the board and the number of black cells (1 ≀ h, w ≀ 105, 1 ≀ n ≀ 2000). Next n lines contain the description of black cells. The i-th of these lines contains numbers ri, ci (1 ≀ ri ≀ h, 1 ≀ ci ≀ w) β€” the number of the row and column of the i-th cell.It is guaranteed that the upper left and lower right cell are white and all cells in the description are distinct.OutputPrint a single line β€” the remainder of the number of ways to move Gerald's pawn from the upper left to the lower right corner modulo 109 + 7.ExamplesInput3 4 22 22 3Output2Input100 100 315 1616 1599 88Output545732279
Input3 4 22 22 3
Output2
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*2200']
B. Equivalent Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: They are equal. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2, then one of the following is correct: a1 is equivalent to b1, and a2 is equivalent to b2 a1 is equivalent to b2, and a2 is equivalent to b1 As a home task, the teacher gave two strings to his students and asked to determine if they are equivalent.Gerald has already completed this home task. Now it's your turn!InputThe first two lines of the input contain two strings given by the teacher. Each of them has the length from 1 to 200 000 and consists of lowercase English letters. The strings have the same length.OutputPrint "YES" (without the quotes), if these two strings are equivalent, and "NO" (without the quotes) otherwise.ExamplesInputaabaabaaOutputYESInputaabbababOutputNONoteIn the first sample you should split the first string into strings "aa" and "ba", the second one β€” into strings "ab" and "aa". "aa" is equivalent to "aa"; "ab" is equivalent to "ba" as "ab" = "a" + "b", "ba" = "b" + "a".In the second sample the first string can be splitted into strings "aa" and "bb", that are equivalent only to themselves. That's why string "aabb" is equivalent only to itself and to string "bbaa".
Inputaabaabaa
OutputYES
2 seconds
256 megabytes
['divide and conquer', 'hashing', 'sortings', 'strings', '*1700']
A. Gerald's Hexagontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to . Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.He painted a few lines, parallel to the sides of the hexagon. The lines split the hexagon into regular triangles with sides of 1 centimeter. Now Gerald wonders how many triangles he has got. But there were so many of them that Gerald lost the track of his counting. Help the boy count the triangles.InputThe first and the single line of the input contains 6 space-separated integers a1, a2, a3, a4, a5 and a6 (1 ≀ ai ≀ 1000) β€” the lengths of the sides of the hexagons in centimeters in the clockwise order. It is guaranteed that the hexagon with the indicated properties and the exactly such sides exists.OutputPrint a single integer β€” the number of triangles with the sides of one 1 centimeter, into which the hexagon is split.ExamplesInput1 1 1 1 1 1Output6Input1 2 1 2 1 2Output13NoteThis is what Gerald's hexagon looks like in the first sample:And that's what it looks like in the second sample:
Input1 1 1 1 1 1
Output6
2 seconds
256 megabytes
['brute force', 'geometry', 'math', '*1600']
E. A Simple Tasktime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis task is very simple. Given a string S of length n and q queries each query is on the format i j k which means sort the substring consisting of the characters from i to j in non-decreasing order if k = 1 or in non-increasing order if k = 0.Output the final string after applying the queries.InputThe first line will contain two integers n, q (1 ≀ n ≀ 105, 0 ≀ q ≀ 50 000), the length of the string and the number of queries respectively. Next line contains a string S itself. It contains only lowercase English letters.Next q lines will contain three integers each i, j, k (1 ≀ i ≀ j ≀ n, ).OutputOutput one line, the string S after applying the queries.ExamplesInput10 5abacdabcda7 10 05 8 11 4 03 6 07 10 1OutputcbcaaaabddInput10 1agjucbvdfk1 10 1OutputabcdfgjkuvNoteFirst sample test explanation:
Input10 5abacdabcda7 10 05 8 11 4 03 6 07 10 1
Outputcbcaaaabdd
5 seconds
512 megabytes
['data structures', 'sortings', 'strings', '*2300']
D. Guess Your Way Out! IItime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node.Let's index all the nodes of the tree such that The root is number 1 Each internal node i (i ≀ 2h - 1 - 1) will have a left child with index = 2i and a right child with index = 2i + 1 The level of a node is defined as 1 for a root, or 1 + level of parent of the node otherwise. The vertices of the level h are called leaves. The exit to the maze is located at some leaf node n, the player doesn't know where the exit is so he has to guess his way out! In the new version of the game the player is allowed to ask questions on the format "Does the ancestor(exit, i) node number belong to the range [L, R]?". Here ancestor(v, i) is the ancestor of a node v that located in the level i. The game will answer with "Yes" or "No" only. The game is designed such that it doesn't always answer correctly, and sometimes it cheats to confuse the player!.Amr asked a lot of questions and got confused by all these answers, so he asked you to help him. Given the questions and its answers, can you identify whether the game is telling contradictory information or not? If the information is not contradictory and the exit node can be determined uniquely, output its number. If the information is not contradictory, but the exit node isn't defined uniquely, output that the number of questions is not sufficient. Otherwise output that the information is contradictory.InputThe first line contains two integers h, q (1 ≀ h ≀ 50, 0 ≀ q ≀ 105), the height of the tree and the number of questions respectively.The next q lines will contain four integers each i, L, R, ans (1 ≀ i ≀ h, 2i - 1 ≀ L ≀ R ≀ 2i - 1, ), representing a question as described in the statement with its answer (ans = 1 if the answer is "Yes" and ans = 0 if the answer is "No").OutputIf the information provided by the game is contradictory output "Game cheated!" without the quotes.Else if you can uniquely identify the exit to the maze output its index. Otherwise output "Data not sufficient!" without the quotes.ExamplesInput3 13 4 6 0Output7Input4 34 10 14 13 6 6 02 3 3 1Output14Input4 23 4 6 14 12 15 1OutputData not sufficient!Input4 23 4 5 12 3 3 1OutputGame cheated!NoteNode u is an ancestor of node v if and only if u is the same node as v, u is the parent of node v, or u is an ancestor of the parent of node v. In the first sample test there are 4 leaf nodes 4, 5, 6, 7. The first question says that the node isn't in the range [4, 6] so the exit is node number 7.In the second sample test there are 8 leaf nodes. After the first question the exit is in the range [10, 14]. After the second and the third questions only node number 14 is correct. Check the picture below to fully understand.
Input3 13 4 6 0
Output7
2 seconds
256 megabytes
['data structures', 'implementation', 'sortings', '*2300']
C. Amr and Chemistrytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.To do this, Amr can do two different kind of operations. Choose some chemical i and double its current volume so the new volume will be 2ai Choose some chemical i and divide its volume by two (integer division) so the new volume will be Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?InputThe first line contains one number n (1 ≀ n ≀ 105), the number of chemicals.The second line contains n space separated integers ai (1 ≀ ai ≀ 105), representing the initial volume of the i-th chemical in liters.OutputOutput one integer the minimum number of operations required to make all the chemicals volumes equal.ExamplesInput34 8 2Output2Input33 5 6Output5NoteIn the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.
Input34 8 2
Output2
1 second
256 megabytes
['brute force', 'graphs', 'greedy', 'math', 'shortest paths', '*1900']
B. Amr and The Large Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.Help Amr by choosing the smallest subsegment possible.InputThe first line contains one number n (1 ≀ n ≀ 105), the size of the array.The second line contains n integers ai (1 ≀ ai ≀ 106), representing elements of the array.OutputOutput two integers l, r (1 ≀ l ≀ r ≀ n), the beginning and the end of the subsegment chosen respectively.If there are several possible answers you may output any of them. ExamplesInput51 1 2 2 1Output1 5Input51 2 2 3 1Output2 3Input61 2 2 1 1 2Output1 5NoteA subsegment B of an array A from l to r is an array of size r - l + 1 where Bi = Al + i - 1 for all 1 ≀ i ≀ r - l + 1
Input51 1 2 2 1
Output1 5
1 second
256 megabytes
['implementation', '*1300']
A. Lala Land and Apple Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere.Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple trees. Amr currently stands in x = 0 position. At the beginning, he can choose whether to go right or left. He'll continue in his direction until he meets an apple tree he didn't visit before. He'll take all of its apples and then reverse his direction, continue walking in this direction until he meets another apple tree he didn't visit before and so on. In the other words, Amr reverses his direction when visiting each new apple tree. Amr will stop collecting apples when there are no more trees he didn't visit in the direction he is facing.What is the maximum number of apples he can collect?InputThe first line contains one number n (1 ≀ n ≀ 100), the number of apple trees in Lala Land.The following n lines contains two integers each xi, ai ( - 105 ≀ xi ≀ 105, xi ≠ 0, 1 ≀ ai ≀ 105), representing the position of the i-th tree and number of apples on it.It's guaranteed that there is at most one apple tree at each coordinate. It's guaranteed that no tree grows in point 0.OutputOutput the maximum number of apples Amr can collect.ExamplesInput2-1 51 5Output10Input3-2 21 4-1 3Output9Input31 93 57 10Output9NoteIn the first sample test it doesn't matter if Amr chose at first to go left or right. In both cases he'll get all the apples.In the second sample test the optimal solution is to go left to x =  - 1, collect apples from there, then the direction will be reversed, Amr has to go to x = 1, collect apples from there, then the direction will be reversed and Amr goes to the final tree x =  - 2.In the third sample test the optimal solution is to go right to x = 1, collect apples from there, then the direction will be reversed and Amr will not be able to collect anymore apples because there are no apple trees to his left.
Input2-1 51 5
Output10
1 second
256 megabytes
['brute force', 'implementation', 'sortings', '*1100']
E. Ann and Half-Palindrometime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputTomorrow Ann takes the hardest exam of programming where she should get an excellent mark. On the last theoretical class the teacher introduced the notion of a half-palindrome. String t is a half-palindrome, if for all the odd positions i () the following condition is held: ti = t|t| - i + 1, where |t| is the length of string t if positions are indexed from 1. For example, strings "abaa", "a", "bb", "abbbaa" are half-palindromes and strings "ab", "bba" and "aaabaa" are not.Ann knows that on the exam she will get string s, consisting only of letters a and b, and number k. To get an excellent mark she has to find the k-th in the lexicographical order string among all substrings of s that are half-palyndromes. Note that each substring in this order is considered as many times as many times it occurs in s.The teachers guarantees that the given number k doesn't exceed the number of substrings of the given string that are half-palindromes.Can you cope with this problem?InputThe first line of the input contains string s (1 ≀ |s| ≀ 5000), consisting only of characters 'a' and 'b', where |s| is the length of string s.The second line contains a positive integer kΒ β€”Β  the lexicographical number of the requested string among all the half-palindrome substrings of the given string s. The strings are numbered starting from one. It is guaranteed that number k doesn't exceed the number of substrings of the given string that are half-palindromes.OutputPrint a substring of the given string that is the k-th in the lexicographical order of all substrings of the given string that are half-palindromes.ExamplesInputabbabaab7OutputabaaInputaaaaa10OutputaaaInputbbaabb13OutputbbaabbNoteBy definition, string a = a1a2... an is lexicographically less than string b = b1b2... bm, if either a is a prefix of b and doesn't coincide with b, or there exists such i, that a1 = b1, a2 = b2, ... ai - 1 = bi - 1, ai < bi.In the first sample half-palindrome substrings are the following stringsΒ β€”Β a, a, a, a, aa, aba, abaa, abba, abbabaa, b, b, b, b, baab, bab, bb, bbab, bbabaab (the list is given in the lexicographical order).
Inputabbabaab7
Outputabaa
1.5 seconds
512 megabytes
['data structures', 'dp', 'graphs', 'string suffix structures', 'strings', 'trees', '*2300']
D. Vitaly and Cycletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter Vitaly was expelled from the university, he became interested in the graph theory.Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not necessarily connected, without parallel edges and loops. You need to find t β€” the minimum number of edges that must be added to the given graph in order to form a simple cycle of an odd length, consisting of more than one vertex. Moreover, he must find w β€” the number of ways to add t edges in order to form a cycle of an odd length (consisting of more than one vertex). It is prohibited to add loops or parallel edges.Two ways to add edges to the graph are considered equal if they have the same sets of added edges.Since Vitaly does not study at the university, he asked you to help him with this task.InputThe first line of the input contains two integers n and m (Β β€”Β the number of vertices in the graph and the number of edges in the graph.Next m lines contain the descriptions of the edges of the graph, one edge per line. Each edge is given by a pair of integers ai, bi (1 ≀ ai, bi ≀ n)Β β€”Β the vertices that are connected by the i-th edge. All numbers in the lines are separated by a single space.It is guaranteed that the given graph doesn't contain any loops and parallel edges. The graph isn't necessarily connected.OutputPrint in the first line of the output two space-separated integers t and wΒ β€”Β the minimum number of edges that should be added to the graph to form a simple cycle of an odd length consisting of more than one vertex where each vertex occurs at most once, and the number of ways to do this.ExamplesInput4 41 21 34 24 3Output1 2Input3 31 22 33 1Output0 1Input3 0Output3 1NoteThe simple cycle is a cycle that doesn't contain any vertex twice.
Input4 41 21 34 24 3
Output1 2
1 second
256 megabytes
['combinatorics', 'dfs and similar', 'graphs', 'math', '*2000']
C. Arthur and Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArthur has bought a beautiful big table into his new flat. When he came home, Arthur noticed that the new table is unstable.In total the table Arthur bought has n legs, the length of the i-th leg is li.Arthur decided to make the table stable and remove some legs. For each of them Arthur determined number diΒ β€”Β the amount of energy that he spends to remove the i-th leg.A table with k legs is assumed to be stable if there are more than half legs of the maximum length. For example, to make a table with 5 legs stable, you need to make sure it has at least three (out of these five) legs of the maximum length. Also, a table with one leg is always stable and a table with two legs is stable if and only if they have the same lengths.Your task is to help Arthur and count the minimum number of energy units Arthur should spend on making the table stable.InputThe first line of the input contains integer n (1 ≀ n ≀ 105)Β β€”Β the initial number of legs in the table Arthur bought.The second line of the input contains a sequence of n integers li (1 ≀ li ≀ 105), where li is equal to the length of the i-th leg of the table.The third line of the input contains a sequence of n integers di (1 ≀ di ≀ 200), where di is the number of energy units that Arthur spends on removing the i-th leg off the table.OutputPrint a single integer β€” the minimum number of energy units that Arthur needs to spend in order to make the table stable.ExamplesInput21 53 2Output2Input32 4 41 1 1Output0Input62 2 1 1 3 34 3 5 5 2 1Output8
Input21 53 2
Output2
1 second
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', 'math', 'sortings', '*1900']
B. Pasha and Teatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows: Pasha can boil the teapot exactly once by pouring there at most w milliliters of water; Pasha pours the same amount of water to each girl; Pasha pours the same amount of water to each boy; if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.InputThe first line of the input contains two integers, n and w (1 ≀ n ≀ 105, 1 ≀ w ≀ 109)Β β€” the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters.The second line of the input contains the sequence of integers ai (1 ≀ ai ≀ 109, 1 ≀ i ≀ 2n)Β β€”Β the capacities of Pasha's tea cups in milliliters.OutputPrint a single real number β€” the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.ExamplesInput2 41 1 1 1Output3Input3 184 4 4 2 2 2Output18Input1 52 3Output4.5NotePasha also has candies that he is going to give to girls but that is another task...
Input2 41 1 1 1
Output3
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', 'sortings', '*1500']
A. Ilya and Diplomastime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSoon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one diploma.They also decided that there must be given at least min1 and at most max1 diplomas of the first degree, at least min2 and at most max2 diplomas of the second degree, and at least min3 and at most max3 diplomas of the third degree.After some discussion it was decided to choose from all the options of distributing diplomas satisfying these limitations the one that maximizes the number of participants who receive diplomas of the first degree. Of all these options they select the one which maximizes the number of the participants who receive diplomas of the second degree. If there are multiple of these options, they select the option that maximizes the number of diplomas of the third degree.Choosing the best option of distributing certificates was entrusted to Ilya, one of the best programmers of Berland. However, he found more important things to do, so it is your task now to choose the best option of distributing of diplomas, based on the described limitations.It is guaranteed that the described limitations are such that there is a way to choose such an option of distributing diplomas that all n participants of the Olympiad will receive a diploma of some degree.InputThe first line of the input contains a single integer n (3 ≀ n ≀ 3Β·106)Β β€”Β the number of schoolchildren who will participate in the Olympiad.The next line of the input contains two integers min1 and max1 (1 ≀ min1 ≀ max1 ≀ 106)Β β€”Β the minimum and maximum limits on the number of diplomas of the first degree that can be distributed.The third line of the input contains two integers min2 and max2 (1 ≀ min2 ≀ max2 ≀ 106)Β β€”Β the minimum and maximum limits on the number of diplomas of the second degree that can be distributed. The next line of the input contains two integers min3 and max3 (1 ≀ min3 ≀ max3 ≀ 106)Β β€”Β the minimum and maximum limits on the number of diplomas of the third degree that can be distributed. It is guaranteed that min1 + min2 + min3 ≀ n ≀ max1 + max2 + max3.OutputIn the first line of the output print three numbers, showing how many diplomas of the first, second and third degree will be given to students in the optimal variant of distributing diplomas.The optimal variant of distributing diplomas is the one that maximizes the number of students who receive diplomas of the first degree. Of all the suitable options, the best one is the one which maximizes the number of participants who receive diplomas of the second degree. If there are several of these options, the best one is the one that maximizes the number of diplomas of the third degree.ExamplesInput61 52 63 7Output1 2 3 Input101 21 31 5Output2 3 5 Input61 32 22 2Output2 2 2
Input61 52 63 7
Output1 2 3
1 second
256 megabytes
['greedy', 'implementation', 'math', '*1100']
B. Case of Fake Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid 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.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” the number of gears.The second line contains n digits a1, a2, ..., an (0 ≀ ai ≀ n - 1) β€” the sequence of active teeth: the active tooth of the i-th gear contains number ai.OutputIn a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.ExamplesInput31 0 0OutputYesInput54 2 1 4 3OutputYesInput40 2 3 1OutputNoNoteIn 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.
Input31 0 0
OutputYes
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
A. Case of the Zeros and Onestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.InputFirst line of the input contains a single integer n (1 ≀ n ≀ 2Β·105), the length of the string that Andreid has.The second line contains the string of length n consisting only from zeros and ones.OutputOutput the minimum length of the string that may remain after applying the described operations several times.ExamplesInput41100Output0Input501010Output1Input811101111Output6NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .
Input41100
Output0
1 second
256 megabytes
['greedy', '*900']
E. Case of Computer Networktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-known detective. Now he is preparing a defense against a possible attack by hackers on a major computer network.In this network are n vertices, some pairs of vertices are connected by m undirected channels. It is planned to transfer q important messages via this network, the i-th of which must be sent from vertex si to vertex di via one or more channels, perhaps through some intermediate vertices.To protect against attacks a special algorithm was developed. Unfortunately it can be applied only to the network containing directed channels. Therefore, as new channels can't be created, it was decided for each of the existing undirected channels to enable them to transmit data only in one of the two directions.Your task is to determine whether it is possible so to choose the direction for each channel so that each of the q messages could be successfully transmitted.InputThe first line contains three integers n, m and q (1 ≀ n, m, q ≀ 2Β·105) β€” the number of nodes, channels and important messages.Next m lines contain two integers each, vi and ui (1 ≀ vi, ui ≀ n, vi ≠ ui), that means that between nodes vi and ui is a channel. Between a pair of nodes can exist more than one channel.Next q lines contain two integers si and di (1 ≀ si, di ≀ n, si ≠ di) β€” the numbers of the nodes of the source and destination of the corresponding message.It is not guaranteed that in it initially possible to transmit all the messages.OutputIf a solution exists, print on a single line "Yes" (without the quotes). Otherwise, print "No" (without the quotes).ExamplesInput4 4 21 21 32 33 41 34 2OutputYesInput3 2 21 23 21 32 1OutputNoInput3 3 21 21 23 21 32 1OutputYesNoteIn the first sample test you can assign directions, for example, as follows: 1 → 2, 1 → 3, 3 → 2, 4 → 3. Then the path for for the first message will be 1 → 3, and for the second one β€” 4 → 3 → 2.In the third sample test you can assign directions, for example, as follows: 1 → 2, 2 → 1, 2 → 3. Then the path for the first message will be 1 → 2 → 3, and for the second one β€” 2 → 1.
Input4 4 21 21 32 33 41 34 2
OutputYes
3 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2800']
D. Case of a Top Secrettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-famous detective. Now he is busy with a top secret case, the details of which are not subject to disclosure.However, he needs help conducting one of the investigative experiment. There are n pegs put on a plane, they are numbered from 1 to n, the coordinates of the i-th of them are (xi, 0). Then, we tie to the bottom of one of the pegs a weight on a tight rope of length l (thus, its coordinates will be equal to (xi,  - l), where i is the number of the used peg). Then the weight is pushed to the right, so that it starts to rotate counterclockwise. At the same time, if the weight during rotation touches some of the other pegs, it then begins to rotate around that peg. Suppose that each peg itself is very thin and does not affect the rope length while weight is rotating around it. More formally, if at some moment the segment of the rope contains one or more pegs in addition to the peg around which the weight is rotating, the weight will then rotate around the farthermost one of them on a shorter segment of a rope. In particular, if the segment of the rope touches some peg by its endpoint, it is considered that the weight starts to rotate around that peg on a segment of the rope of length 0.At some moment the weight will begin to rotate around some peg, without affecting the rest of the pegs. Andrewid interested in determining the number of this peg.Andrewid prepared m queries containing initial conditions for pushing the weight, help him to determine for each of them, around what peg the weight will eventually rotate.InputThe first line contains integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of pegs and queries.The next line contains n integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the pegs. It is guaranteed that the coordinates of all the pegs are distinct integers.Next m lines contain the descriptions of the queries of pushing the weight, each consists of two integers ai (1 ≀ ai ≀ n) and li (1 ≀ li ≀ 109) β€” the number of the starting peg and the length of the rope.OutputPrint m lines, the i-th line should contain the number of the peg around which the weight will eventually rotate after the i-th push.ExamplesInput3 20 3 52 31 8Output32Input4 41 5 7 151 42 153 161 28Output2431NotePicture to the first sample test: Picture to the second sample test:Note that in the last query weight starts to rotate around the peg 1 attached to a rope segment of length 0.
Input3 20 3 52 31 8
Output32
2 seconds
256 megabytes
['binary search', 'implementation', 'math', '*2500']
C. Case of Chocolatetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-known detective. Now he does not investigate any case and is eating chocolate out of boredom.A bar of chocolate can be presented as an n × n table, where each cell represents one piece of chocolate. The columns of the table are numbered from 1 to n from left to right and the rows are numbered from top to bottom. Let's call the anti-diagonal to be a diagonal that goes the lower left corner to the upper right corner of the table. First Andrewid eats all the pieces lying below the anti-diagonal. Then he performs the following q actions with the remaining triangular part: first, he chooses a piece on the anti-diagonal and either direction 'up' or 'left', and then he begins to eat all the pieces starting from the selected cell, moving in the selected direction until he reaches the already eaten piece or chocolate bar edge.After each action, he wants to know how many pieces he ate as a result of this action.InputThe first line contains integers n (1 ≀ n ≀ 109) and q (1 ≀ q ≀ 2Β·105) β€” the size of the chocolate bar and the number of actions.Next q lines contain the descriptions of the actions: the i-th of them contains numbers xi and yi (1 ≀ xi, yi ≀ n, xi + yi = n + 1) β€” the numbers of the column and row of the chosen cell and the character that represents the direction (L β€” left, U β€” up).OutputPrint q lines, the i-th of them should contain the number of eaten pieces as a result of the i-th action.ExamplesInput6 53 4 U6 1 L2 5 L1 6 U4 3 UOutput43212Input10 62 9 U10 1 U1 10 U8 3 L10 1 L6 5 UOutput9110602NotePictures to the sample tests:The pieces that were eaten in the same action are painted the same color. The pieces lying on the anti-diagonal contain the numbers of the action as a result of which these pieces were eaten.In the second sample test the Andrewid tries to start eating chocolate for the second time during his fifth action, starting from the cell at the intersection of the 10-th column and the 1-st row, but this cell is already empty, so he does not eat anything.
Input6 53 4 U6 1 L2 5 L1 6 U4 3 U
Output43212
3 seconds
256 megabytes
['data structures', '*2200']
B. Case of Fugitivetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≀ i ≀ n - 1.To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≀ x ≀ ri, li + 1 ≀ y ≀ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.InputThe first line contains integers n (2 ≀ n ≀ 2Β·105) and m (1 ≀ m ≀ 2Β·105) β€” the number of islands and bridges.Next n lines each contain two integers li and ri (1 ≀ li ≀ ri ≀ 1018) β€” the coordinates of the island endpoints.The last line contains m integer numbers a1, a2, ..., am (1 ≀ ai ≀ 1018) β€” the lengths of the bridges that Andrewid got.OutputIf it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi. If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.ExamplesInput4 41 47 89 1012 144 5 3 8OutputYes2 3 1 Input2 211 1417 182 9OutputNoInput2 11 11000000000000000000 1000000000000000000999999999999999999OutputYes1 NoteIn the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.
Input4 41 47 89 1012 144 5 3 8
OutputYes2 3 1
3 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2000']