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. Biathlontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPerhaps many have heard that the World Biathlon Championship has finished. Although our hero Valera was not present at this spectacular event himself and only watched it on TV, it excited him so much that he decided to enroll in a biathlon section.Of course, biathlon as any sport, proved very difficult in practice. It takes much time and effort. Workouts, workouts, and workouts, β€” that's what awaited Valera on his way to great achievements in biathlon.As for the workouts, you all probably know that every professional biathlete should ski fast and shoot precisely at the shooting range. Only in this case you can hope to be successful, because running and shooting are the two main components of biathlon. Valera has been diligent in his ski trainings, which is why he runs really fast, however, his shooting accuracy is nothing to write home about.On a biathlon base where Valera is preparing for the competition, there is a huge rifle range with n targets. Each target have shape of a circle, and the center of each circle is located on the Ox axis. At the last training session Valera made the total of m shots. To make monitoring of his own results easier for him, one rather well-known programmer (of course it is you) was commissioned to write a program that would reveal how many and which targets Valera hit. More specifically, for each target the program must print the number of the first successful shot (in the target), or "-1" if this was not hit. The target is considered hit if the shot is inside the circle or on its boundary. Valera is counting on you and perhaps, thanks to you he will one day win international competitions.InputThe first line of the input file contains the integer n (1 ≀ n ≀ 104), which is the number of targets. The next n lines contain descriptions of the targets. Each target is a circle whose center is located on the Ox axis. Each circle is given by its coordinate of the center x ( - 2Β·104 ≀ x ≀ 2Β·104) and its radius r (1 ≀ r ≀ 1000). It is guaranteed that no two targets coincide, intersect or are nested into each other, but they can touch each other. The next line contains integer m (1 ≀ m ≀ 2Β·105), which is the number of shots. Next m lines contain descriptions of the shots, which are points on the plane, given by their coordinates x and y ( - 2Β·104 ≀ x, y ≀ 2Β·104).All the numbers in the input are integers. Targets and shots are numbered starting from one in the order of the input.OutputPrint on the first line a single number, the number of targets hit by Valera. Print on the second line for each of the targets the number of its first hit or "-1" (without quotes) if this number does not exist. Separate numbers with spaces.ExamplesInput32 15 210 150 11 33 04 04 0Output23 3 -1 Input33 27 111 242 16 06 411 2Output31 2 4
Input32 15 210 150 11 33 04 04 0
Output23 3 -1
1 second
256 megabytes
['binary search', 'implementation', '*1700']
A. Toy Armytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy "GAGA: Go And Go Again". The gameplay is as follows. There are two armies on the playing field each of which consists of n men (n is always even). The current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. This is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die. It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore. The game "GAGA" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends. You are asked to calculate the maximum total number of soldiers that may be killed during the game. InputThe input data consist of a single integer n (2 ≀ n ≀ 108, n is even). Please note that before the game starts there are 2n soldiers on the fields. OutputPrint a single number β€” a maximum total number of soldiers that could be killed in the course of the game in three turns.ExamplesInput2Output3Input4Output6NoteThe first sample test:1) Valera's soldiers 1 and 2 shoot at Arcady's soldier 1.2) Arcady's soldier 2 shoots at Valera's soldier 1.3) Valera's soldier 1 shoots at Arcady's soldier 2.There are 3 soldiers killed in total: Valera's soldier 1 and Arcady's soldiers 1 and 2.
Input2
Output3
2 seconds
256 megabytes
['math', 'number theory', '*900']
E. Two Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn an IT lesson Valera studied data compression. The teacher told about a new method, which we shall now describe to you.Let {a1, a2, ..., an} be the given sequence of lines needed to be compressed. Here and below we shall assume that all lines are of the same length and consist only of the digits 0 and 1. Let's define the compression function: f(empty sequence) = empty string f(s) = s. f(s1, s2) =  the smallest in length string, which has one of the prefixes equal to s1 and one of the suffixes equal to s2. For example, f(001, 011) = 0011, f(111, 011) = 111011. f(a1, a2, ..., an) = f(f(a1, a2, an - 1), an). For example, f(000, 000, 111) = f(f(000, 000), 111) = f(000, 111) = 000111. Valera faces a real challenge: he should divide the given sequence {a1, a2, ..., an} into two subsequences {b1, b2, ..., bk} and {c1, c2, ..., cm}, m + k = n, so that the value of S = |f(b1, b2, ..., bk)| + |f(c1, c2, ..., cm)| took the minimum possible value. Here |p| denotes the length of the string p.Note that it is not allowed to change the relative order of lines in the subsequences. It is allowed to make one of the subsequences empty. Each string from the initial sequence should belong to exactly one subsequence. Elements of subsequences b and c don't have to be consecutive in the original sequence a, i. e. elements of b and c can alternate in a (see samples 2 and 3).Help Valera to find the minimum possible value of S.InputThe first line of input data contains an integer n β€” the number of strings (1 ≀ n ≀ 2Β·105). Then on n lines follow elements of the sequence β€” strings whose lengths are from 1 to 20 characters, consisting only of digits 0 and 1. The i + 1-th input line contains the i-th element of the sequence. Elements of the sequence are separated only by a newline. It is guaranteed that all lines have the same length.OutputPrint a single number β€” the minimum possible value of S.ExamplesInput3011001Output4Input4000111110001Output8Input51010101010111110100010010Output17NoteDetailed answers to the tests: The best option is to make one of the subsequences empty, and the second one equal to the whole given sequence. |f(01, 10, 01)| = |f(f(01, 10), 01)| = |f(010, 01)| = |0101| = 4. The best option is: b = {000, 001}, c = {111, 110}. S = |f(000, 001)| + |f(111, 110)| = |0001| + |1110| = 8. The best option is: b = {10101, 01010, 01000}, c = {11111, 10010}. S = |10101000| + |111110010| = 17.
Input3011001
Output4
2 seconds
256 megabytes
['bitmasks', 'dp', '*2800']
D. Numberstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne quite ordinary day Valera went to school (there's nowhere else he should go on a week day). In a maths lesson his favorite teacher Ms. Evans told students about divisors. Despite the fact that Valera loved math, he didn't find this particular topic interesting. Even more, it seemed so boring that he fell asleep in the middle of a lesson. And only a loud ringing of a school bell could interrupt his sweet dream. Of course, the valuable material and the teacher's explanations were lost. However, Valera will one way or another have to do the homework. As he does not know the new material absolutely, he cannot do the job himself. That's why he asked you to help. You're his best friend after all, you just cannot refuse to help. Valera's home task has only one problem, which, though formulated in a very simple way, has not a trivial solution. Its statement looks as follows: if we consider all positive integers in the interval [a;b] then it is required to count the amount of such numbers in this interval that their smallest divisor will be a certain integer k (you do not have to consider divisor equal to one). In other words, you should count the amount of such numbers from the interval [a;b], that are not divisible by any number between 2 and k - 1 and yet are divisible by k. InputThe first and only line contains three positive integers a, b, k (1 ≀ a ≀ b ≀ 2Β·109, 2 ≀ k ≀ 2Β·109). OutputPrint on a single line the answer to the given problem. ExamplesInput1 10 2Output5Input12 23 3Output2Input6 19 5Output0NoteComments to the samples from the statement: In the first sample the answer is numbers 2, 4, 6, 8, 10.In the second one β€” 15, 21In the third one there are no such numbers.
Input1 10 2
Output5
3 seconds
256 megabytes
['dp', 'math', 'number theory', '*2400']
C. Tracktime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest.The track's map is represented by a rectangle n × m in size divided into squares. Each square is marked with a lowercase Latin letter (which means the type of the plot), with the exception of the starting square (it is marked with a capital Latin letters S) and the terminating square (it is marked with a capital Latin letter T). The time of movement from one square to another is equal to 1 minute. The time of movement within the cell can be neglected. We can move from the cell only to side-adjacent ones, but it is forbidden to go beyond the map edges. Also the following restriction is imposed on the path: it is not allowed to visit more than k different types of squares (squares of one type can be visited an infinite number of times). Squares marked with S and T have no type, so they are not counted. But S must be visited exactly once β€” at the very beginning, and T must be visited exactly once β€” at the very end.Your task is to find the path from the square S to the square T that takes minimum time. Among all shortest paths you should choose the lexicographically minimal one. When comparing paths you should lexicographically represent them as a sequence of characters, that is, of plot types.InputThe first input line contains three integers n, m and k (1 ≀ n, m ≀ 50, nΒ·m β‰₯ 2, 1 ≀ k ≀ 4). Then n lines contain the map. Each line has the length of exactly m characters and consists of lowercase Latin letters and characters S and T. It is guaranteed that the map contains exactly one character S and exactly one character T.Pretest 12 is one of the maximal tests for this problem.OutputIf there is a path that satisfies the condition, print it as a sequence of letters β€” the plot types. Otherwise, print "-1" (without quotes). You shouldn't print the character S in the beginning and T in the end.Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.ExamplesInput5 3 2SbacccaaccccabTOutputbccccInput3 4 1SxyyyxxxyyyTOutputxxxxInput1 3 3TySOutputyInput1 4 1SxyTOutput-1
Input5 3 2SbacccaaccccabT
Outputbcccc
5 seconds
256 megabytes
['graphs', 'greedy', 'shortest paths', '*2400']
B. Doctortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n animals in the queue to Dr. Dolittle. When an animal comes into the office, the doctor examines him, gives prescriptions, appoints tests and may appoint extra examination. Doc knows all the forest animals perfectly well and therefore knows exactly that the animal number i in the queue will have to visit his office exactly ai times. We will assume that an examination takes much more time than making tests and other extra procedures, and therefore we will assume that once an animal leaves the room, it immediately gets to the end of the queue to the doctor. Of course, if the animal has visited the doctor as many times as necessary, then it doesn't have to stand at the end of the queue and it immediately goes home. Doctor plans to go home after receiving k animals, and therefore what the queue will look like at that moment is important for him. Since the doctor works long hours and she can't get distracted like that after all, she asked you to figure it out. InputThe first line of input data contains two space-separated integers n and k (1 ≀ n ≀ 105, 0 ≀ k ≀ 1014). In the second line are given space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109).Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator). OutputIf the doctor will overall carry out less than k examinations, print a single number "-1" (without quotes). Otherwise, print the sequence of numbers β€” number of animals in the order in which they stand in the queue. Note that this sequence may be empty. This case is present in pretests. You can just print nothing or print one "End of line"-character. Both will be accepted.ExamplesInput3 31 2 1Output2 Input4 103 3 2 1Output-1Input7 101 3 3 1 2 3 1Output6 2 3 NoteIn the first sample test: Before examination: {1, 2, 3} After the first examination: {2, 3} After the second examination: {3, 2} After the third examination: {2} In the second sample test: Before examination: {1, 2, 3, 4, 5, 6, 7} After the first examination: {2, 3, 4, 5, 6, 7} After the second examination: {3, 4, 5, 6, 7, 2} After the third examination: {4, 5, 6, 7, 2, 3} After the fourth examination: {5, 6, 7, 2, 3} After the fifth examination: {6, 7, 2, 3, 5} After the sixth examination: {7, 2, 3, 5, 6} After the seventh examination: {2, 3, 5, 6} After the eighth examination: {3, 5, 6, 2} After the ninth examination: {5, 6, 2, 3} After the tenth examination: {6, 2, 3}
Input3 31 2 1
Output2
2 seconds
256 megabytes
['binary search', 'math', 'sortings', '*1800']
A. Magical Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputValery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.InputThe first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). OutputPrint on the single line the answer to the problem: the amount of subarrays, which are magical.Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).ExamplesInput42 1 1 4Output5Input5-2 -2 -2 0 1Output8NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Input42 1 1 4
Output5
2 seconds
256 megabytes
['math', '*1300']
E. Corridortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a house plan. Let the house be represented by an infinite horizontal strip defined by the inequality  - h ≀ y ≀ h. Strictly outside the house there are two light sources at the points (0, f) and (0,  - f). Windows are located in the walls, the windows are represented by segments on the lines y = h and y =  - h. Also, the windows are arranged symmetrically about the line y = 0.Your task is to find the area of the floor at the home, which will be lighted by the sources of light. InputThe first line of the input file contains three integers n, h and f (1 ≀ n ≀ 500, 1 ≀ h ≀ 10, h < f ≀ 1000). Next, n lines contain two integers each li, ri ( - 5000 ≀ li < ri ≀ 5000), each entry indicates two segments. Endpoints of the first segment are (li, h)-(ri, h), and endpoints of the second segment are (li,  - h)-(ri,  - h). These segments describe location of windows. Numbers in the lines are space-separated. It is guaranteed that no two distinct segments have common points. OutputPrint the single real number β€” the area of the illuminated part of the floor with an absolute or relative error of no more than 10 - 4.ExamplesInput1 1 2-1 1Output10.0000000000Input2 2 4-1 01 2Output23.3333333333NoteThe second sample test is shown on the figure. Green area is the desired area of the illuminated part of the floor. Violet segments indicate windows.
Input1 1 2-1 1
Output10.0000000000
2 seconds
256 megabytes
['geometry', '*2600']
D. Two out of Threetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.Let the queue to the cashier contain n people, at that each of them is characterized by a positive integer ai β€” that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need ai and aj of time to be served, the time needed to work with both of them customers is equal to max(ai, aj). Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).Vasya used in his algorithm an ingenious heuristic β€” as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number i, then he goes to the cashier, and is served within ai of time. Note that the total number of phases of serving a customer will always be equal to ⌈n / 2βŒ‰.Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.InputThe first line of the input file contains a single number n (1 ≀ n ≀ 1000), which is the number of people in the sequence. The second line contains space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 106). The people are numbered starting from the cashier to the end of the queue.OutputPrint on the first line a single number β€” the minimum time needed to process all n people. Then on ⌈n / 2βŒ‰ lines print the order in which customers will be served. Each line (probably, except for the last one) must contain two numbers separated by a space β€” the numbers of customers who will be served at the current stage of processing. If n is odd, then the last line must contain a single number β€” the number of the last served customer in the queue. The customers are numbered starting from 1.ExamplesInput41 2 3 4Output61 23 4Input52 4 3 1 4Output81 32 54
Input41 2 3 4
Output61 23 4
2 seconds
256 megabytes
['dp', '*2000']
C. General Mobilizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland Kingdom is a set of n cities connected with each other with n - 1 railways. Each road connects exactly two different cities. The capital is located in city 1. For each city there is a way to get from there to the capital by rail.In the i-th city there is a soldier division number i, each division is characterized by a number of ai. It represents the priority, the smaller the number, the higher the priority of this division. All values of ai are different.One day the Berland King Berl Great declared a general mobilization, and for that, each division should arrive in the capital. Every day from every city except the capital a train departs. So there are exactly n - 1 departing trains each day. Each train moves toward the capital and finishes movement on the opposite endpoint of the railway on the next day. It has some finite capacity of cj, expressed in the maximum number of divisions, which this train can transport in one go. Each train moves in the direction of reducing the distance to the capital. So each train passes exactly one railway moving from a city to the neighboring (where it stops) toward the capital.In the first place among the divisions that are in the city, division with the smallest number of ai get on the train, then with the next smallest and so on, until either the train is full or all the divisions are be loaded. So it is possible for a division to stay in a city for a several days.The duration of train's progress from one city to another is always equal to 1 day. All divisions start moving at the same time and end up in the capital, from where they don't go anywhere else any more. Each division moves along a simple path from its city to the capital, regardless of how much time this journey will take.Your goal is to find for each division, in how many days it will arrive to the capital of Berland. The countdown begins from day 0.InputThe first line contains the single integer n (1 ≀ n ≀ 5000). It is the number of cities in Berland. The second line contains n space-separated integers a1, a2, ..., an, where ai represents the priority of the division, located in the city number i. All numbers a1, a2, ..., an are different (1 ≀ ai ≀ 109). Then n - 1 lines contain the descriptions of the railway roads. Each description consists of three integers vj, uj, cj, where vj, uj are number of cities connected by the j-th rail, and cj stands for the maximum capacity of a train riding on this road (1 ≀ vj, uj ≀ n, vj ≠ uj, 1 ≀ cj ≀ n). OutputPrint sequence t1, t2, ..., tn, where ti stands for the number of days it takes for the division of city i to arrive to the capital. Separate numbers with spaces.ExamplesInput440 10 30 201 2 12 3 14 2 1Output0 1 3 2 Input55 4 3 2 11 2 12 3 12 4 14 5 1Output0 1 4 2 3
Input440 10 30 201 2 12 3 14 2 1
Output0 1 3 2
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'sortings', '*2000']
B. Setstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vasya likes very much to play with sets consisting of positive integers. To make the game more interesting, Vasya chose n non-empty sets in such a way, that no two of them have common elements.One day he wanted to show his friends just how interesting playing with numbers is. For that he wrote out all possible unions of two different sets on nΒ·(n - 1) / 2 pieces of paper. Then he shuffled the pieces of paper. He had written out the numbers in the unions in an arbitrary order.For example, if n = 4, and the actual sets have the following form {1, 3}, {5}, {2, 4}, {7}, then the number of set pairs equals to six. The six pieces of paper can contain the following numbers: 2, 7, 4. 1, 7, 3; 5, 4, 2; 1, 3, 5; 3, 1, 2, 4; 5, 7. Then Vasya showed the pieces of paper to his friends, but kept the n sets secret from them. His friends managed to calculate which sets Vasya had thought of in the first place. And how about you, can you restore the sets by the given pieces of paper?InputThe first input file line contains a number n (2 ≀ n ≀ 200), n is the number of sets at Vasya's disposal. Then follow sets of numbers from the pieces of paper written on nΒ·(n - 1) / 2 lines. Each set starts with the number ki (2 ≀ ki ≀ 200), which is the number of numbers written of the i-th piece of paper, and then follow ki numbers aij (1 ≀ aij ≀ 200). All the numbers on the lines are separated by exactly one space. It is guaranteed that the input data is constructed according to the above given rules from n non-intersecting sets.OutputPrint on n lines Vasya's sets' description. The first number on the line shows how many numbers the current set has. Then the set should be recorded by listing its elements. Separate the numbers by spaces. Each number and each set should be printed exactly once. Print the sets and the numbers in the sets in any order. If there are several answers to that problem, print any of them.It is guaranteed that there is a solution.ExamplesInput43 2 7 43 1 7 33 5 4 23 1 3 54 3 1 2 42 5 7Output1 7 2 2 4 2 1 3 1 5 Input45 6 7 8 9 1004 7 8 9 14 7 8 9 23 1 6 1003 2 6 1002 1 2Output3 7 8 9 2 6 100 1 1 1 2 Input32 1 22 1 32 2 3Output1 1 1 2 1 3
Input43 2 7 43 1 7 33 5 4 23 1 3 54 3 1 2 42 5 7
Output1 7 2 2 4 2 1 3 1 5
2 seconds
256 megabytes
['constructive algorithms', 'hashing', 'implementation', '*1700']
A. Double Colatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, drinks it and gets to the end of the queue as two Leonards, and so on. This process continues ad infinitum.For example, Penny drinks the third can of cola and the queue will look like this: Rajesh, Howard, Sheldon, Sheldon, Leonard, Leonard, Penny, Penny.Write a program that will print the name of a man who will drink the n-th can.Note that in the very beginning the queue looks like that: Sheldon, Leonard, Penny, Rajesh, Howard. The first person is Sheldon.InputThe input data consist of a single integer n (1 ≀ n ≀ 109).It is guaranteed that the pretests check the spelling of all the five names, that is, that they contain all the five possible answers.OutputPrint the single line β€” the name of the person who drinks the n-th can of cola. The cans are numbered starting from 1. Please note that you should spell the names like this: "Sheldon", "Leonard", "Penny", "Rajesh", "Howard" (without the quotes). In that order precisely the friends are in the queue initially.ExamplesInput1OutputSheldonInput6OutputSheldonInput1802OutputPenny
Input1
OutputSheldon
1 second
256 megabytes
['implementation', 'math', '*1100']
E. Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students in Polycarp's class (including himself). A few days ago all students wrote an essay "My best friend". Each student's essay was dedicated to one of the students of class, to his/her best friend. Note that student b's best friend is not necessarily student a, if a's best friend is b.And now the teacher leads the whole class to the museum of the history of sports programming. Exciting stories of legendary heroes await the students: tourist, Petr, tomek, SnapDragon β€” that's who they will hear about!The teacher decided to divide students into pairs so that each pair consisted of a student and his best friend. She may not be able to split all the students into pairs, it's not a problem β€” she wants to pick out the maximum number of such pairs. If there is more than one variant of doing so, she wants to pick out the pairs so that there were as much boy-girl pairs as possible. Of course, each student must not be included in more than one pair.InputThe first line contains an integer n (2 ≀ n ≀ 105), n is the number of students per class. Next, n lines contain information about the students, one per line. Each line contains two integers fi, si (1 ≀ fi ≀ n, fi ≠ i, 1 ≀ si ≀ 2), where fi is the number of i-th student's best friend and si denotes the i-th pupil's sex (si = 1 for a boy and si = 2 for a girl).OutputPrint on the first line two numbers t, e, where t is the maximum number of formed pairs, and e is the maximum number of boy-girl type pairs among them. Then print t lines, each line must contain a pair ai, bi (1 ≀ ai, bi ≀ n), they are numbers of pupils in the i-th pair. Print the pairs in any order. Print the numbers in pairs in any order. If there are several solutions, output any of them.ExamplesInput55 23 25 12 14 2Output2 25 34 2Input65 23 25 12 14 23 1Output3 14 25 13 6Input82 23 25 13 16 15 18 27 1Output4 15 63 42 17 8NoteThe picture corresponds to the first sample. On the picture rhomb stand for boys, squares stand for girls, arrows lead from a pupil to his/her best friend. Bold non-dashed arrows stand for pairs in the answer.
Input55 23 25 12 14 2
Output2 25 34 2
1 second
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'implementation', 'trees', '*2700']
D. Polycarp's Picture Gallerytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp loves not only to take pictures, but also to show his photos to friends. On his personal website he has recently installed a widget that can display n photos with the scroll option. At each moment of time the widget displays exactly one photograph with the option showing the previous/next one. From the first photo, you can switch to the second one or to the n-th one, from the second photo you can switch to the third one or to the first one, etc. Thus, navigation is performed in a cycle.Polycarp's collection consists of m photo albums, the i-th album contains ai photos. Polycarp wants to choose n photos and put them on a new widget. To make watching the photos interesting to the visitors, he is going to post pictures so that no two photos from one album were neighboring (each photo will have exactly two neighbors, the first photo's neighbors are the second and the n-th one).Help Polycarp compile a photo gallery. Select n photos from his collection and put them in such order that no two photos from one album went one after the other.InputThe first line contains two integers n and m (3 ≀ n ≀ 1000, 1 ≀ m ≀ 40), where n is the number of photos on the widget, and m is the number of albums. The second line contains m integers a1, a2, ..., am (1 ≀ ai ≀ 1000), where ai is the number of photos in the i-th album.OutputPrint the single number -1 if there is no solution. Otherwise, print n numbers t1, t2, ..., tn, where ti represents the number of the album of the i-th picture in the widget. The albums are numbered from 1 in the order of their appearance in the input. If there are several solutions, print any of them.ExamplesInput4 31 3 5Output3 1 3 2Input10 25 5Output2 1 2 1 2 1 2 1 2 1Input10 31 10 3Output-1
Input4 31 3 5
Output3 1 3 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2100']
C. Average Scoretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark.Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a + b = n). Now Polycarp wants to write a subject's name in front of each mark so that: there are exactly a Safety Studies marks, there are exactly b PE marks, the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1 + x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education).InputThe first line contains an integer n (2 ≀ n ≀ 105), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a, b (1 ≀ a, b ≀ n - 1, a + b = n). The third line contains a sequence of integers t1, t2, ..., tn (1 ≀ ti ≀ 5), they are Polycarp's marks.OutputPrint the sequence of integers f1, f2, ..., fn, where fi (1 ≀ fi ≀ 2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1, f2, ..., fn is the smallest lexicographically.The sequence p1, p2, ..., pn is lexicographically less than q1, q2, ..., qn if there exists such j (1 ≀ j ≀ n) that pi = qi for all 1 ≀ i < j, Π°nd pj < qj.ExamplesInput53 24 4 5 4 4Output1 1 2 1 2 Input42 23 5 4 5Output1 1 2 2 Input61 54 4 4 5 4 4Output2 2 2 1 2 2 NoteIn the first sample the average score in the first subject is equal to 4, and in the second one β€” to 4.5. The total average score is 8.5.
Input53 24 4 5 4 4
Output1 1 2 1 2
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1700']
B. Sequence Formattingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2Β ,3,...,Β Β Β 10" will be corrected to "1,Β 2,Β 3,Β ...,Β 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be: a positive integer of an arbitrary length (leading zeroes are not allowed), a "comma" symbol (","), a "space" symbol (" "), "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following: each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it), each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term), if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left, there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.InputThe input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.OutputPrint the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.ExamplesInput1,2 ,3,..., 10Output1, 2, 3, ..., 10Input1,,,4...5......6Output1, , , 4 ...5 ... ...6Input...,1,2,3,...Output..., 1, 2, 3, ...
Input1,2 ,3,..., 10
Output1, 2, 3, ..., 10
2 seconds
256 megabytes
['implementation', 'strings', '*1700']
A. Plug-intime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result. InputThe input data consists of a single line to be processed. The length of the line is from 1 to 2Β·105 characters inclusive. The string contains only lowercase Latin letters. OutputPrint the given string after it is processed. It is guaranteed that the result will contain at least one character.ExamplesInputhhoowaaaareyyoouuOutputwreInputreallazyOutputrezyInputabacabaabacabaaOutputa
Inputhhoowaaaareyyoouu
Outputwre
1 second
256 megabytes
['implementation', '*1400']
B. Depressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDo you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle... Everybody was upset. The beautiful Belle was upset, so was the Beast, so was Lumiere the candlestick. But the worst thing was that Cogsworth was upset. Cogsworth is not a human, but is the mantel clock, which was often used as an alarm clock.Due to Cogsworth's frustration all the inhabitants of the castle were in trouble: now they could not determine when it was time to drink morning tea, and when it was time for an evening stroll. Fortunately, deep in the basement are lying digital clock showing the time in the format HH:MM. Now the residents of the castle face a difficult task. They should turn Cogsworth's hour and minute mustache hands in such a way, that Cogsworth began to show the correct time. Moreover they need to find turn angles in degrees for each mustache hands. The initial time showed by Cogsworth is 12:00.You can only rotate the hands forward, that is, as is shown in the picture: As since there are many ways too select such angles because of full rotations, choose the smallest angles in the right (non-negative) direction.Note that Cogsworth's hour and minute mustache hands move evenly and continuously. Hands are moving independently, so when turning one hand the other hand remains standing still.InputThe only line of input contains current time according to the digital clock, formatted as HH:MM (00 ≀ HH ≀ 23, 00 ≀ MM ≀ 59). The mantel clock initially shows 12:00.Pretests contain times of the beginning of some morning TV programs of the Channel One Russia.OutputPrint two numbers x and y β€” the angles of turning the hour and minute hands, respectively (0 ≀ x, y < 360). The absolute or relative error in the answer should not exceed 10 - 9.ExamplesInput12:00Output0 0Input04:30Output135 180Input08:17Output248.5 102NoteA note to the second example: the hour hand will be positioned exactly in the middle, between 4 and 5.
Input12:00
Output0 0
1 second
256 megabytes
['geometry', 'math', '*1200']
A. Panoramix's Predictiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 isΒ not the next prime number for 2.One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers, where y is the next prime number after x, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.Yesterday the Gauls beat n Roman soldiers and it turned out that the number n was prime! Today their victims were a troop of m Romans (m > n). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?InputThe first and only input line contains two positive integers β€” n and m (2 ≀ n < m ≀ 50). It is guaranteed that n is prime.Pretests contain all the cases with restrictions 2 ≀ n < m ≀ 4.OutputPrint YES, if m is the next prime number after n, or NO otherwise.ExamplesInput3 5OutputYESInput7 11OutputYESInput7 9OutputNO
Input3 5
OutputYES
2 seconds
256 megabytes
['brute force', '*800']
E. Security Systemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.Ciel is at point (1, 1) of the castle now, and wants to move to point (n, n), which is the position of her room. By one step, Ciel can move from point (x, y) to either (x + 1, y) (rightward) or (x, y + 1) (upward).In her castle, c2 sensors are set at points (a + i, b + j) (for every integer i and j such that: 0 ≀ i < c, 0 ≀ j < c).Each sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is t. Every time Ciel moves to point (x, y), the count value of a sensor at point (u, v) decreases by (|u - x| + |v - y|). When the count value of some sensor becomes strictly less than 0, the sensor will catch Ciel as a suspicious individual!Determine whether Ciel can move from (1, 1) to (n, n) without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.InputIn the first line there are five integers n, t, a, b, c (2 ≀ n ≀ 2Β·105,  0 ≀ t ≀ 1014,  1 ≀ a ≀ n - c + 1,  1 ≀ b ≀ n - c + 1,  1 ≀ c ≀ n).Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin stream (also you may use the %I64d specificator).OutputIf Ciel's objective is possible, output in first line 2n - 2 characters that represent her feasible steps, where i-th character is R if i-th step is moving rightward, or U if moving upward. If there are several solution, output lexicographically first one. Character R is lexicographically earlier than the character U.If her objective is impossible, output Impossible.ExamplesInput5 25 2 4 1OutputRRUURURUInput3 6 1 2 2OutputURURInput3 5 1 2 2OutputImpossibleInput20 492 11 4 8OutputRRRRRRRRRRRRRRRRUUUUURUUUUURRUUUUUUUUUNoteThe answers for the first sample and the second sample are shown on the picture: Here, a red point represents a point that contains a sensor.
Input5 25 2 4 1
OutputRRUURURU
1 second
256 megabytes
['math', '*2900']
D. Passwordtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFinally Fox Ciel arrived in front of her castle!She have to type a password to enter her castle. An input device attached to her castle is a bit unusual.The input device is a 1 × n rectangle divided into n square panels. They are numbered 1 to n from left to right. Each panel has a state either ON or OFF. Initially all panels are in the OFF state. She can enter her castle if and only if x1-th, x2-th, ..., xk-th panels are in the ON state and other panels are in the OFF state.She is given an array a1, ..., al. In each move, she can perform the following operation: choose an index i (1 ≀ i ≀ l), choose consecutive ai panels, and flip the states of those panels (i.e. ON → OFF, OFF → ON).Unfortunately she forgets how to type the password with only above operations. Determine the minimal number of operations required to enter her castle.InputThe first line contains three integers n, k and l (1 ≀ n ≀ 10000, 1 ≀ k ≀ 10, 1 ≀ l ≀ 100), separated by single spaces.The second line contains k integers x1, ..., xk (1 ≀ x1 < x2 < ... < xk ≀ n), separated by single spaces.The third line contains l integers a1, ..., al (1 ≀ ai ≀ n), separated by single spaces. It is possible that some elements of the array ai are equal value.OutputPrint the minimal number of moves required to type the password. If it's impossible, print -1.ExamplesInput10 8 21 2 3 5 6 7 8 93 5Output2Input3 2 11 23Output-1NoteOne possible way to type the password in the first example is following: In the first move, choose 1st, 2nd, 3rd panels and flip those panels. In the second move, choose 5th, 6th, 7th, 8th, 9th panels and flip those panels.
Input10 8 21 2 3 5 6 7 8 93 5
Output2
1 second
256 megabytes
['bitmasks', 'dp', 'shortest paths', '*2800']
C. Beavertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s.Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response.InputIn the first line there is a string s. The length of s will be between 1 and 105, inclusive.In the second line there is a single integer n (1 ≀ n ≀ 10). Next n lines, there is a string bi (1 ≀ i ≀ n). Each length of bi will be between 1 and 10, inclusive.Each character of the given strings will be either a English alphabet (both lowercase and uppercase) or a underscore ('_') or a digit. Assume that these strings are case-sensitive.OutputOutput in the first line two space-separated integers len and pos: the length of the longest contiguous substring of s that does not contain any bi, and the first position of the substring (0-indexed). The position pos must be between 0 and |s| - len inclusive, where |s| is the length of string s.If there are several solutions, output any.ExamplesInputGo_straight_along_this_street5strlongtreebigintegerellipseOutput12 4InputIhaveNoIdea9IhaveNoIdOutput0 0Inputunagioisii2ioiunagiOutput5 5NoteIn the first sample, the solution is traight_alon.In the second sample, the solution is an empty string, so the output can be Β«0 0Β», Β«0 1Β», Β«0 2Β», and so on.In the third sample, the solution is either nagio or oisii.
InputGo_straight_along_this_street5strlongtreebigintegerellipse
Output12 4
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'hashing', 'strings', 'two pointers', '*1800']
B. Colorful Fieldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel saw a large field while she was on a bus. The field was a n × m rectangle divided into 1 × 1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes. After seeing the field carefully, Ciel found that the crop plants of each cell were planted in following procedure: Assume that the rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right, and a cell in row i and column j is represented as (i, j). First, each field is either cultivated or waste. Crop plants will be planted in the cultivated cells in the order of (1, 1) → ... → (1, m) → (2, 1) → ... → (2, m) → ... → (n, 1) → ... → (n, m). Waste cells will be ignored. Crop plants (either carrots or kiwis or grapes) will be planted in each cell one after another cyclically. Carrots will be planted in the first cell, then kiwis in the second one, grapes in the third one, carrots in the forth one, kiwis in the fifth one, and so on. The following figure will show you the example of this procedure. Here, a white square represents a cultivated cell, and a black square represents a waste cell. Now she is wondering how to determine the crop plants in some certain cells. InputIn the first line there are four positive integers n, m, k, t (1 ≀ n ≀ 4Β·104, 1 ≀ m ≀ 4Β·104, 1 ≀ k ≀ 103, 1 ≀ t ≀ 103), each of which represents the height of the field, the width of the field, the number of waste cells and the number of queries that ask the kind of crop plants in a certain cell.Following each k lines contains two integers a, b (1 ≀ a ≀ n, 1 ≀ b ≀ m), which denotes a cell (a, b) is waste. It is guaranteed that the same cell will not appear twice in this section.Following each t lines contains two integers i, j (1 ≀ i ≀ n, 1 ≀ j ≀ m), which is a query that asks you the kind of crop plants of a cell (i, j).OutputFor each query, if the cell is waste, print Waste. Otherwise, print the name of crop plants in the cell: either Carrots or Kiwis or Grapes.ExamplesInput4 5 5 64 31 33 32 53 21 31 42 32 41 11 1OutputWasteGrapesCarrotsKiwisCarrotsCarrotsNoteThe sample corresponds to the figure in the statement.
Input4 5 5 64 31 33 32 53 21 31 42 32 41 11 1
OutputWasteGrapesCarrotsKiwisCarrotsCarrots
2 seconds
256 megabytes
['implementation', 'sortings', '*1400']
A. Bus Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. Initially, there is a pile that contains x 100-yen coins and y 10-yen coins. They take turns alternatively. Ciel takes the first turn. In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins. If Ciel or Hanako can't take exactly 220 yen from the pile, she loses. Determine the winner of the game.InputThe first line contains two integers x (0 ≀ x ≀ 106) and y (0 ≀ y ≀ 106), separated by a single space.OutputIf Ciel wins, print "Ciel". Otherwise, print "Hanako".ExamplesInput2 2OutputCielInput3 22OutputHanakoNoteIn the first turn (Ciel's turn), she will choose 2 100-yen coins and 2 10-yen coins. In the second turn (Hanako's turn), she will choose 1 100-yen coin and 12 10-yen coins. In the third turn (Ciel's turn), she can't pay exactly 220 yen, so Ciel will lose.
Input2 2
OutputCiel
2 seconds
256 megabytes
['greedy', '*1200']
E. Evacuationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThey've screwed something up yet again... In one nuclear reactor of a research station an uncontrolled reaction is in progress and explosion which will destroy the whole station will happen soon.The station is represented by a square n × n divided into 1 × 1 blocks. Each block is either a reactor or a laboratory. There can be several reactors and exactly one of them will explode soon. The reactors can be considered impassable blocks, but one can move through laboratories. Between any two laboratories, which are in adjacent blocks, there is a corridor. Blocks are considered adjacent if they have a common edge.In each laboratory there is some number of scientists and some number of rescue capsules. Once the scientist climbs into a capsule, he is considered to be saved. Each capsule has room for not more than one scientist.The reactor, which is about to explode, is damaged and a toxic coolant trickles from it into the neighboring blocks. The block, which contains the reactor, is considered infected. Every minute the coolant spreads over the laboratories through corridors. If at some moment one of the blocks is infected, then the next minute all the neighboring laboratories also become infected. Once a lab is infected, all the scientists there that are not in rescue capsules die. The coolant does not spread through reactor blocks.There are exactly t minutes to the explosion. Any scientist in a minute can move down the corridor to the next lab, if it is not infected. On any corridor an unlimited number of scientists can simultaneously move in both directions. It is believed that the scientists inside a lab moves without consuming time. Moreover, any scientist could get into the rescue capsule instantly. It is also believed that any scientist at any given moment always has the time to perform their actions (move from the given laboratory into the next one, or climb into the rescue capsule) before the laboratory will be infected.Find the maximum number of scientists who will be able to escape.InputThe first line contains two integers n and t (2 ≀ n ≀ 10, 1 ≀ t ≀ 60). Each of the next n lines contains n characters. These lines describe the scientists' locations. Then exactly one empty line follows. Each of the next n more lines contains n characters. These lines describe the rescue capsules' locations.In the description of the scientists' and the rescue capsules' locations the character "Y" stands for a properly functioning reactor, "Z" stands for the malfunctioning reactor. The reactors' positions in both descriptions coincide. There is exactly one malfunctioning reactor on the station. The digits "0" - "9" stand for the laboratories. In the description of the scientists' locations those numbers stand for the number of scientists in the corresponding laboratories. In the rescue capsules' descriptions they stand for the number of such capsules in each laboratory.OutputPrint a single number β€” the maximum number of scientists who will manage to save themselves.ExamplesInput3 31YZ1YY1000YZ0YY003Output2Input4 4Y1101Y1Z1Y0Y0100Y0010Y0Z0Y0Y0005Output3NoteIn the second sample the events could take place as follows:
Input3 31YZ1YY1000YZ0YY003
Output2
1 second
256 megabytes
['flows', 'graphs', 'shortest paths', '*2300']
D. Archer's Shottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them.The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playing field. The field can be considered infinite. Let's take a look at the battle unit called an "Archer". Each archer has a parameter "shot range". It's a positive integer that determines the radius of the circle in which the archer can hit a target. The center of the circle coincides with the center of the cell in which the archer stays. A cell is considered to be under the archer’s fire if and only if all points of this cell, including border points are located inside the circle or on its border.The picture below shows the borders for shot ranges equal to 3, 4 and 5. The archer is depicted as A. Find the number of cells that are under fire for some archer.InputThe first and only line of input contains a single positive integer k β€” the archer's shot range (1 ≀ k ≀ 106).OutputPrint the single number, the number of cells that are under fire.Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cout stream (also you may use the %I64d specificator).ExamplesInput3Output7Input4Output13Input5Output19
Input3
Output7
2 seconds
256 megabytes
['binary search', 'geometry', 'math', 'two pointers', '*2300']
C. Beaver Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo beavers, Timur and Marsel, play the following game.There are n logs, each of exactly m meters in length. The beavers move in turns. For each move a beaver chooses a log and gnaws it into some number (more than one) of equal parts, the length of each one is expressed by an integer and is no less than k meters. Each resulting part is also a log which can be gnawed in future by any beaver. The beaver that can't make a move loses. Thus, the other beaver wins.Timur makes the first move. The players play in the optimal way. Determine the winner.InputThe first line contains three integers n, m, k (1 ≀ n, m, k ≀ 109).OutputPrint "Timur", if Timur wins, or "Marsel", if Marsel wins. You should print everything without the quotes. ExamplesInput1 15 4OutputTimurInput4 9 5OutputMarselNoteIn the first sample the beavers only have one log, of 15 meters in length. Timur moves first. The only move he can do is to split the log into 3 parts each 5 meters in length. Then Marsel moves but he can't split any of the resulting logs, as k = 4. Thus, the winner is Timur.In the second example the beavers have 4 logs 9 meters in length. Timur can't split any of them, so that the resulting parts possessed the length of not less than 5 meters, that's why he loses instantly.
Input1 15 4
OutputTimur
1 second
256 megabytes
['dp', 'games', 'number theory', '*2000']
B. Easter Eggstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Easter Rabbit laid n eggs in a circle and is about to paint them. Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied: Each of the seven colors should be used to paint at least one egg. Any four eggs lying sequentially should be painted different colors. Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.InputThe only line contains an integer n β€” the amount of eggs (7 ≀ n ≀ 100).OutputPrint one line consisting of n characters. The i-th character should describe the color of the i-th egg in the order they lie in the circle. The colors should be represented as follows: "R" stands for red, "O" stands for orange, "Y" stands for yellow, "G" stands for green, "B" stands for blue, "I" stands for indigo, "V" stands for violet.If there are several answers, print any of them.ExamplesInput8OutputROYGRBIVInput13OutputROYGBIVGBIVYGNoteThe way the eggs will be painted in the first sample is shown on the picture:
Input8
OutputROYGRBIV
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1200']
A. Haikutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaiku is a genre of Japanese traditional poetry.A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). A haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. Each word has a special meaning, a special role. The main principle of haiku is to say much using a few words.To simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. Only the following letters are regarded as vowel letters: "a", "e", "i", "o" and "u".Three phases from a certain poem are given. Determine whether it is haiku or not.InputThe input data consists of three lines. The length of each line is between 1 and 100, inclusive. The i-th line contains the i-th phrase of the poem. Each phrase consists of one or more words, which are separated by one or more spaces. A word is a non-empty sequence of lowercase Latin letters. Leading and/or trailing spaces in phrases are allowed. Every phrase has at least one non-space character. See the example for clarification.OutputPrint "YES" (without the quotes) if the poem is a haiku. Otherwise, print "NO" (also without the quotes).ExamplesInputon codeforces beta round is running a rustling of keys OutputYESInputhow many gallonsof edo s rain did you drink cuckooOutputNO
Inputon codeforces beta round is running a rustling of keys
OutputYES
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. Martian Foodtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHave you ever tasted Martian food? Well, you should.Their signature dish is served on a completely black plate with the radius of R, flat as a pancake.First, they put a perfectly circular portion of the Golden Honduras on the plate. It has the radius of r and is located as close to the edge of the plate as possible staying entirely within the plate. I. e. Golden Honduras touches the edge of the plate from the inside. It is believed that the proximity of the portion of the Golden Honduras to the edge of a plate demonstrates the neatness and exactness of the Martians.Then a perfectly round portion of Pink Guadeloupe is put on the plate. The Guadeloupe should not overlap with Honduras, should not go beyond the border of the plate, but should have the maximum radius. I. e. Pink Guadeloupe should touch the edge of the plate from the inside, and touch Golden Honduras from the outside. For it is the size of the Rose Guadeloupe that shows the generosity and the hospitality of the Martians.Further, the first portion (of the same perfectly round shape) of Green Bull Terrier is put on the plate. It should come in contact with Honduras and Guadeloupe, should not go beyond the border of the plate and should have maximum radius.Each of the following portions of the Green Bull Terrier must necessarily touch the Golden Honduras, the previous portion of the Green Bull Terrier and touch the edge of a plate, but should not go beyond the border.To determine whether a stranger is worthy to touch the food, the Martians ask him to find the radius of the k-th portion of the Green Bull Terrier knowing the radii of a plate and a portion of the Golden Honduras. And are you worthy?InputThe first line contains integer t (1 ≀ t ≀ 104) β€” amount of testcases.Each of the following t lines contain three positive integers: the radii of the plate and a portion of the Golden Honduras R and r (1 ≀ r < R ≀ 104) and the number k (1 ≀ k ≀ 104).In the pretests 1 ≀ k ≀ 2.OutputPrint t lines β€” the radius of the k-th portion of the Green Bull Terrier for each test. The absolute or relative error of the answer should not exceed 10 - 6.ExamplesInput24 3 14 2 2Output0.92307692310.6666666667NoteDish from the first sample looks like this:Dish from the second sample looks like this:
Input24 3 14 2 2
Output0.92307692310.6666666667
1 second
256 megabytes
['geometry', '*2800']
D. Domino Carpettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output...Mike the TV greets you again! Tired of the monotonous furniture? Sick of gray routine? Dreaming about dizzying changes in your humble abode? We have something to offer you! This domino carpet for only $99.99 will change your life! You can lay it on the floor, hang it on the wall or even on the ceiling! Among other things ... Having watched the commercial, virus Hexadecimal also wanted to get a Domino Carpet and wanted badly to be photographed in front of it. But of course, a virus will never consent to buying a licensed Carpet! So she ordered a truck of dominoes and decided to make such a Carpet herself. The original Domino Carpet is a field of squares n × m in size. Each square is half of a domino, and can be rotated either vertically or horizontally, independently from its neighbors. Vertically rotated domino halves look like this: And horizontally rotated halves look like this: Notice, that some halves looks the same in both rotations, but other halves differ.Dominoes bought by Hexadecimal are represented by uncuttable chips 1 × 2 in size, which can be laid either vertically or horizontally. If the chip is laid vertically, then both of it's halves should be laid vertically orientated; if the chip is laid horizontally, then both of it's halves should be laid horizontally.The samples of valid and invalid dominoes laid vertically and horizontally are: Virus Hexadecimal assembles her own Domino Carpet so that the following conditions are satisfied: each carpet square is covered by a domino chip, i.e. there are no empty squares; all domino chips lie entirely within the carpet and don't overlap with each other; if there is a horizontal domino chip with its left half in column j then there are no horizontal domino chips with their left halves in columns j - 1 or j + 1. Before starting to assemble her own Domino Carpet, the virus wants to know the number of ways to achieve the intended purpose modulo 109 + 7.You can assume that the virus has an infinitely large number of dominoes of each type.InputThe first line contains two integers n and m, separated by a space β€” the size of the Domino Carpet (1 ≀ n, m ≀ 250). Next 4n + 1 lines contain 4m + 1 symbols. Each square of the Domino Carpet, which is a domino half, is described by a 3 × 3 square. Symbol 'O' in this square indicates the presence of a point, symbol '.' β€” its absence. Each 3 × 3 square is delineated from adjacent squares by symbols '#' as shown in the examples. It is guaranteed that every box describes the correct half of a domino. In all pretests the Domino Carpets have the size of 2 × 2 and 4 × 4.OutputPrint a single number, the number of ways to assemble the Domino Carpet modulo 109 + 7, using only standard dominoes of size 1 × 2.ExamplesInput3 4##################O..#...#O.O#...##.O.#.O.#.O.#...##..O#...#O.O#...###################O.O#OOO#O.O#...##.O.#...#...#.O.##O.O#OOO#O.O#...###################O.O#...#O.O#...##...#...#...#.O.##O.O#...#O.O#...##################Output3Input2 2##########O.O#O.O##.O.#...##O.O#O.O###########...#O.O##...#...##...#O.O##########Output2Input2 2##########..O#O..##...#...##O..#..O###########O..#..O##...#...##..O#O..##########Output0NoteA note to the first example: all correct ways to make Domino Carpet are represented below: And this way is incorrect:
Input3 4##################O..#...#O.O#...##.O.#.O.#.O.#...##..O#...#O.O#...###################O.O#OOO#O.O#...##.O.#...#...#.O.##O.O#OOO#O.O#...###################O.O#...#O.O#...##...#...#...#.O.##O.O#...#O.O#...##################
Output3
2 seconds
256 megabytes
['dp', 'implementation', '*2300']
C. Beavermuncher-0xFFtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output"Eat a beaver, save a tree!" β€” That will be the motto of ecologists' urgent meeting in Beaverley Hills.And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.The prototype is ready, you now need to urgently carry out its experiments in practice. You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers. "Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place. Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.InputThe first line contains integer n β€” the number of vertices in the tree (1 ≀ n ≀ 105). The second line contains n integers ki (1 ≀ ki ≀ 105) β€” amounts of beavers on corresponding vertices. Following n - 1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to n. The last line contains integer s β€” the number of the starting vertex (1 ≀ s ≀ n).OutputPrint the maximum number of beavers munched by the "Beavermuncher-0xFF".Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).ExamplesInput51 3 1 3 22 53 44 51 54Output6Input32 1 13 21 23Output2
Input51 3 1 3 22 53 44 51 54
Output6
3 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'greedy', 'trees', '*2100']
B. Falling Anvilstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all.Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who throws anvils from the sky? From what height? We are sure that such questions have never troubled you!It turns out that throwing an anvil properly is not an easy task at all. Let's describe one of the most popular anvil throwing models.Let the height p of the potential victim vary in the range [0;a] and the direction of the wind q vary in the range [ - b;b]. p and q could be any real (floating) numbers. Then we can assume that the anvil will fit the toon's head perfectly only if the following equation has at least one real root: Determine the probability with which an aim can be successfully hit by an anvil.You can assume that the p and q coefficients are chosen equiprobably and independently in their ranges.InputThe first line contains integer t (1 ≀ t ≀ 10000) β€” amount of testcases.Each of the following t lines contain two space-separated integers a and b (0 ≀ a, b ≀ 106).Pretests contain all the tests with 0 < a < 10, 0 ≀ b < 10.OutputPrint t lines β€” the probability of a successful anvil hit for each testcase. The absolute or relative error of the answer should not exceed 10 - 6.ExamplesInput24 21 2Output0.62500000000.5312500000
Input24 21 2
Output0.62500000000.5312500000
2 seconds
256 megabytes
['math', 'probabilities', '*1800']
A. Heroestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe year of 2012 is coming...According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us mere mortals from the effect of this terrible evil.The seven great heroes are: amazon Anka, barbarian Chapay, sorceress Cleo, druid Troll, necromancer Dracul, paladin Snowy and a professional hit girl Hexadecimal. Heroes already know how much experience will be given for each of the three megabosses: a for Mephisto, b for Diablo and c for Baal.Here's the problem: heroes are as much as seven and megabosses are only three! Then our heroes decided to split into three teams, where each team will go to destroy their own megaboss. Each team member will receive a of experience, rounded down, where x will be the amount of experience for the killed megaboss and y β€” the number of people in the team.Heroes do not want to hurt each other's feelings, so they want to split into teams so that the difference between the hero who received the maximum number of experience and the hero who received the minimum number of experience were minimal. Since there can be several divisions into teams, then you need to find the one in which the total amount of liking in teams were maximum.It is known that some heroes like others. But if hero p likes hero q, this does not mean that the hero q likes hero p. No hero likes himself.The total amount of liking in teams is the amount of ordered pairs (p, q), such that heroes p and q are in the same group, and hero p likes hero q (but it is not important if hero q likes hero p). In case of heroes p and q likes each other and they are in the same group, this pair should be counted twice, as (p, q) and (q, p).A team can consist even of a single hero, but it is important that every megaboss was destroyed. All heroes must be involved in the campaign against evil. None of the heroes can be in more than one team.It is guaranteed that every hero is able to destroy any megaboss alone.InputThe first line contains a single non-negative integer n (0 ≀ n ≀ 42) β€” amount of liking between the heroes. Next n lines describe liking in the form "p likes q", meaning that the hero p likes the hero q (p  ≠  q). Every liking is described in the input exactly once, no hero likes himself.In the last line are given three integers a, b and c (1 ≀ a, b, c ≀ 2Β·109), separated by spaces: the experience for Mephisto, the experience for Diablo and experience for Baal.In all the pretests, except for examples from the statement, the following condition is satisfied: a = b = c.OutputPrint two integers β€” the minimal difference in the experience between two heroes who will receive the maximum and minimum number of experience points, and the maximal total amount of liking in teams (the number of friendships between heroes that end up in one team).When calculating the second answer, the team division should satisfy the difference-minimizing contraint. I.e. primary you should minimize the difference in the experience and secondary you should maximize the total amount of liking.ExamplesInput3Troll likes DraculDracul likes AnkaSnowy likes Hexadecimal210 200 180Output30 3Input2Anka likes ChapayChapay likes Anka10000 50 50Output1950 2NoteA note to first example: it the first team should be Dracul, Troll and Anka, in the second one Hexadecimal and Snowy, and in the third Cleo ΠΈ Chapay.
Input3Troll likes DraculDracul likes AnkaSnowy likes Hexadecimal210 200 180
Output30 3
2 seconds
256 megabytes
['brute force', 'implementation', '*1400']
F. Touristtime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTourist walks along the X axis. He can choose either of two directions and any speed not exceeding V. He can also stand without moving anywhere. He knows from newspapers that at time t1 in the point with coordinate x1 an interesting event will occur, at time t2 in the point with coordinate x2 β€” another one, and so on up to (xn, tn). Interesting events are short so we can assume they are immediate. Event i counts visited if at time ti tourist was at point with coordinate xi.Write program tourist that will find maximum number of events tourist if: at the beginning (when time is equal to 0) tourist appears at point 0, tourist can choose initial point for himself. Yes, you should answer on two similar but different questions.InputThe first line of input contains single integer number N (1 ≀ N ≀ 100000) β€” number of interesting events. The following N lines contain two integers xi and ti β€” coordinate and time of the i-th event. The last line of the input contains integer V β€” maximum speed of the tourist. All xi will be within range  - 2Β·108 ≀ xi ≀ 2Β·108, all ti will be between 1 and 2Β·106 inclusive. V will be positive and will not exceed 1000. The input may contain events that happen at the same time or in the same place but not in the same place at the same time.OutputThe only line of the output should contain two space-sepatated integers β€” maximum number of events tourist can visit in he starts moving from point 0 at time 0, and maximum number of events tourist can visit if he chooses the initial point for himself.ExamplesInput3-1 142 740 82Output1 2
Input3-1 142 740 82
Output1 2
0.5 second
256 megabytes
['binary search', 'data structures', 'dp', '*2300']
E. Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.InputThe first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.OutputThe only line of output should contain the required sum of squares of distances between all pairs of points.ExamplesInput41 1-1 -11 -1-1 1Output32
Input41 1-1 -11 -1-1 1
Output32
1 second
256 megabytes
['implementation', 'math', '*1700']
D. Plus and xortime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBitwise exclusive OR (or bitwise addition modulo two) is a binary operation which is equivalent to applying logical exclusive OR to every pair of bits located on the same positions in binary notation of operands. In other words, a binary digit of the result is equal to 1 if and only if bits on the respective positions in the operands are different.For example, if X = 10910 = 11011012, Y = 4110 = 1010012, then: X xor Y  =  6810  =  10001002. Write a program, which takes two non-negative integers A and B as an input and finds two non-negative integers X and Y, which satisfy the following conditions: A = X + Y B  =  X xor Y, where xor is bitwise exclusive or. X is the smallest number among all numbers for which the first two conditions are true. InputThe first line contains integer number A and the second line contains integer number B (0 ≀ A, B ≀ 264 - 1).OutputThe only output line should contain two integer non-negative numbers X and Y. Print the only number -1 if there is no answer.ExamplesInput14276Output33 109
Input14276
Output33 109
0.5 second
256 megabytes
['dp', 'greedy', 'math', '*1700']
C. Mutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScientists of planet Olympia are conducting an experiment in mutation of primitive organisms. Genome of organism from this planet can be represented as a string of the first K capital English letters. For each pair of types of genes they assigned ai, j β€” a risk of disease occurence in the organism provided that genes of these types are adjacent in the genome, where i β€” the 1-based index of the first gene and j β€” the index of the second gene. The gene 'A' has index 1, 'B' has index 2 and so on. For example, a3, 2 stands for the risk of 'CB' fragment. Risk of disease occurence in the organism is equal to the sum of risks for each pair of adjacent genes in the genome.Scientists have already obtained a base organism. Some new organisms can be obtained by mutation of this organism. Mutation involves removal of all genes of some particular types. Such removal increases the total risk of disease occurence additionally. For each type of genes scientists determined ti β€” the increasement of the total risk of disease occurence provided by removal of all genes having type with index i. For example, t4 stands for the value of additional total risk increasement in case of removing all the 'D' genes.Scientists want to find a number of different organisms that can be obtained from the given one which have the total risk of disease occurence not greater than T. They can use only the process of mutation described above. Two organisms are considered different if strings representing their genomes are different. Genome should contain at least one gene.InputThe first line of the input contains three integer numbers N (1 ≀ N ≀ 200 000) β€” length of the genome of base organism, K (1 ≀ K ≀ 22) β€” the maximal index of gene type in the genome and T (1 ≀ T ≀ 2Β·109) β€” maximal allowable risk of disease occurence. The second line contains the genome of the given organism. It is a string of the first K capital English letters having length N.The third line contains K numbers t1, t2, ..., tK, where ti is additional risk value of disease occurence provided by removing of all genes of the i-th type.The following K lines contain the elements of the given matrix ai, j. The i-th line contains K numbers. The j-th number of the i-th line stands for a risk of disease occurence for the pair of genes, first of which corresponds to the i-th letter and second of which corresponds to the j-th letter. The given matrix is not necessarily symmetrical.All the numbers in the input are integer, non-negative and all of them except T are not greater than 109. It is guaranteed that the maximal possible risk of organism that can be obtained from the given organism is strictly smaller than 231.OutputOutput the number of organisms that can be obtained from the base one and which have the total risk of disease occurence not greater than T.ExamplesInput5 3 13BACAC4 1 21 2 32 3 43 4 10Output5NoteExplanation: one can obtain the following organisms (risks are stated in brackets): BACAC (11), ACAC (10), BAA (5), B (6), AA (4).
Input5 3 13BACAC4 1 21 2 32 3 43 4 10
Output5
1 second
256 megabytes
['bitmasks', 'dp', 'math', '*2700']
B. Micetime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputModern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal.If there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located N mice and M pieces of cheese on a cartesian plane where all mice are located on the line y = Y0 and all pieces of cheese β€” on another line y = Y1. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice.Write a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.InputThe first line of the input contains four integer numbers N (1 ≀ N ≀ 105), M (0 ≀ M ≀ 105), Y0 (0 ≀ Y0 ≀ 107), Y1 (0 ≀ Y1 ≀ 107, Y0 ≠ Y1). The second line contains a strictly increasing sequence of N numbers β€” x coordinates of mice. Third line contains a strictly increasing sequence of M numbers β€” x coordinates of cheese. All coordinates are integers and do not exceed 107 by absolute value.OutputThe only line of output should contain one number β€” the minimal number of mice which will remain without cheese.ExamplesInput3 2 0 20 1 32 5Output1NoteAll the three mice will choose the first piece of cheese. Second and third mice will eat this piece. The first one will remain hungry, because it was running towards the same piece, but it was late. The second piece of cheese will remain uneaten.
Input3 2 0 20 1 32 5
Output1
0.5 second
256 megabytes
['greedy', 'two pointers', '*2100']
A. Gifttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe kingdom of Olympia consists of N cities and M bidirectional roads. Each road connects exactly two cities and two cities can be connected with more than one road. Also it possible that some roads connect city with itself making a loop.All roads are constantly plundered with bandits. After a while bandits became bored of wasting time in road robberies, so they suggested the king of Olympia to pay off. According to the offer, bandits want to get a gift consisted of gold and silver coins. Offer also contains a list of restrictions: for each road it is known gi β€” the smallest amount of gold and si β€” the smallest amount of silver coins that should be in the gift to stop robberies on the road. That is, if the gift contains a gold and b silver coins, then bandits will stop robberies on all the roads that gi ≀ a and si ≀ b.Unfortunately kingdom treasury doesn't contain neither gold nor silver coins, but there are Olympian tugriks in it. The cost of one gold coin in tugriks is G, and the cost of one silver coin in tugriks is S. King really wants to send bandits such gift that for any two cities there will exist a safe path between them. Your task is to find the minimal cost in Olympian tugriks of the required gift.InputThe first line of the input contains two integers N and M (2 ≀ N ≀ 200, 1 ≀ M ≀ 50 000) β€” the number of cities and the number of roads, respectively. The second line contains two integers G and S (1 ≀ G, S ≀ 109) β€” the prices of gold and silver coins in tugriks. The following M lines contain information about the offer. Each of the records in list is given as four integers xi, yi, gi, si, where xi and yi are the numbers of cities that the road connects and gi, si are minimal gold and silver coins requirements for the i-th road (1 ≀ xi, yi ≀ N, 1 ≀ gi, si ≀ 109). Cities are numbered from 1 to N. It is possible that there are more than one road between a pair of cities. It is possible that a road connects the city with itself.OutputThe output should contain the minimal cost of the gift in Olympian tugriks. If there is no gift that satisfies the given requirements output .ExamplesInput3 32 11 2 10 151 2 4 201 3 5 1Output30
Input3 32 11 2 10 151 2 4 201 3 5 1
Output30
2 seconds
256 megabytes
['dsu', 'graphs', 'sortings', 'trees', '*2200']
E. Ship's Shortest Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have got a new job, and it's very interesting, you are a ship captain. Your first task is to move your ship from one point to another point, and for sure you want to move it at the minimum cost.And it's well known that the shortest distance between any 2 points is the length of the line segment between these 2 points. But unfortunately there is an island in the sea, so sometimes you won't be able to move your ship in the line segment between the 2 points.You can only move to safe points. A point is called safe if it's on the line segment between the start and end points, or if it's on the island's edge.But you are too lucky, you have got some clever and strong workers and they can help you in your trip, they can help you move the ship in the sea and they will take 1 Egyptian pound for each moving unit in the sea, and they can carry the ship (yes, they are very strong) and walk on the island and they will take 2 Egyptian pounds for each moving unit in the island. The money which you will give to them will be divided between all workers, so the number of workers does not matter here.You can move your ship on the island edge, and it will be considered moving in the sea.Now you have a sea map, and you have to decide what is the minimum cost for your trip.Your starting point is (xStart, yStart), and the end point is (xEnd, yEnd), both points will be different.The island will be a convex polygon and there will be no more than 2 polygon points on the same line, also the starting and the end points won't be inside or on the boundary of the island. The points for the polygon will be given in the anti-clockwise order.InputThe first line contains 4 integers, xStart, yStart, xEnd and yEnd ( - 100 ≀ xStart, yStart, xEnd, yEnd ≀ 100). The second line contains an integer n, which is the number of points in the polygon (3 ≀ n ≀ 30), followed by a line containing n pairs of integers x and y, which are the coordinates of the points ( - 100 ≀ x, y ≀ 100), the polygon points will be distinct.OutputPrint one line which contains the minimum possible cost. The absolute or relative error in the answer should not exceed 10 - 6.ExamplesInput1 7 6 744 2 4 12 3 12 3 2Output6.000000000Input-1 0 2 040 0 1 0 1 1 0 1Output3.000000000
Input1 7 6 744 2 4 12 3 12 3 2
Output6.000000000
2 seconds
256 megabytes
['geometry', 'shortest paths', '*2400']
D. Big Maximum Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAhmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.This problem is similar to a standard problem but it has a different format and constraints.In the standard problem you are given an array of integers, and you have to find one or more consecutive elements in this array where their sum is the maximum possible sum.But in this problem you are given n small arrays, and you will create one big array from the concatenation of one or more instances of the small arrays (each small array could occur more than once). The big array will be given as an array of indexes (1-based) of the small arrays, and the concatenation should be done in the same order as in this array. Then you should apply the standard problem mentioned above on the resulting big array.For example let's suppose that the small arrays are {1, 6, -2}, {3, 3} and {-5, 1}. And the indexes in the big array are {2, 3, 1, 3}. So the actual values in the big array after formatting it as concatenation of the small arrays will be {3, 3, -5, 1, 1, 6, -2, -5, 1}. In this example the maximum sum is 9.Can you help Mostafa solve this problem?InputThe first line contains two integers n and m, n is the number of the small arrays (1 ≀ n ≀ 50), and m is the number of indexes in the big array (1 ≀ m ≀ 250000). Then follow n lines, the i-th line starts with one integer l which is the size of the i-th array (1 ≀ l ≀ 5000), followed by l integers each one will be greater than or equal -1000 and less than or equal 1000. The last line contains m integers which are the indexes in the big array, and you should concatenate the small arrays in the same order, and each index will be greater than or equal to 1 and less than or equal to n.The small arrays are numbered from 1 to n in the same order as given in the input. Some of the given small arrays may not be used in big array.Note, that the array is very big. So if you try to build it straightforwardly, you will probably get time or/and memory limit exceeded.OutputPrint one line containing the maximum sum in the big array after formatting it as described above. You must choose at least one element for the sum, i. e. it cannot be empty.Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).ExamplesInput3 43 1 6 -22 3 32 -5 12 3 1 3Output9Input6 14 0 8 -3 -108 3 -2 -5 10 8 -9 -5 -41 01 -33 -8 5 62 9 61Output8
Input3 43 1 6 -22 3 32 -5 12 3 1 3
Output9
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'implementation', 'math', 'trees', '*2000']
C. Modified GCDtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWell, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.A common divisor for two positive numbers is a number which both numbers are divisible by.But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≀ d ≀ high. It is possible that there is no common divisor in the given range.You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.InputThe first line contains two integers a and b, the two integers as described above (1 ≀ a, b ≀ 109). The second line contains one integer n, the number of queries (1 ≀ n ≀ 104). Then n lines follow, each line contains one query consisting of two integers, low and high (1 ≀ low ≀ high ≀ 109).OutputPrint n lines. The i-th of them should contain the result of the i-th query in the input. If there is no common divisor in the given range for any query, you should print -1 as a result for this query.ExamplesInput9 2731 510 119 11Output3-19
Input9 2731 510 119 11
Output3-19
2 seconds
256 megabytes
['binary search', 'number theory', '*1600']
B. Facetook Priority Walltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFacetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).This priority factor will be affected by three types of actions: 1. "X posted on Y's wall" (15 points), 2. "X commented on Y's post" (10 points), 3. "X likes Y's post" (5 points). X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.InputThe first line contains your name. The second line contains an integer n, which is the number of actions (1 ≀ n ≀ 100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.OutputPrint m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order.Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor.The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1 ≀ i ≀ min(|a|, |b|)), that ai < bi, and for any j (1 ≀ j < i) aj = bj, where |a| and |b| stand for the lengths of strings a and b correspondently.ExamplesInputahmed3ahmed posted on fatma's wallfatma commented on ahmed's postmona likes ahmed's postOutputfatmamonaInputaba1likes likes posted's postOutputlikesposted
Inputahmed3ahmed posted on fatma's wallfatma commented on ahmed's postmona likes ahmed's post
Outputfatmamona
2 seconds
256 megabytes
['expression parsing', 'implementation', 'strings', '*1500']
A. Life Without Zerostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCan you imagine our life if we removed all zeros from it? For sure we will have many problems.In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a and b. Now let's remove all zeros from this equation. Will the equation remain correct after removing all zeros?For example if the equation is 101 + 102 = 203, if we removed all zeros it will be 11 + 12 = 23 which is still a correct equation.But if the equation is 105 + 106 = 211, if we removed all zeros it will be 15 + 16 = 211 which is not a correct equation.InputThe input will consist of two lines, the first line will contain the integer a, and the second line will contain the integer b which are in the equation as described above (1 ≀ a, b ≀ 109). There won't be any leading zeros in both. The value of c should be calculated as c = a + b.OutputThe output will be just one line, you should print "YES" if the equation will remain correct after removing all zeros, and print "NO" otherwise.ExamplesInput101102OutputYESInput105106OutputNO
Input101102
OutputYES
2 seconds
256 megabytes
['implementation', '*1000']
E. Shift It!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a square box 6 × 6 in size. It contains 36 chips 1 × 1 in size. Those chips contain 36 different characters β€” "0"-"9" and "A"-"Z". There is exactly one chip with each character.You are allowed to make the following operations: you may choose one of 6 rows or one of 6 columns and cyclically shift the chips there to one position to the left or to the right (for the row) or upwards or downwards (for the column). Those operations are allowed to perform several times. To solve the puzzle is to shift the chips using the above described operations so that they were written in the increasing order (exactly equal to the right picture). An example of solving the puzzle is shown on a picture below. Write a program that finds the sequence of operations that solves the puzzle. That sequence should not necessarily be shortest, but you should not exceed the limit of 10000 operations. It is guaranteed that the solution always exists.InputThe input data are represented by 6 lines containing 6 characters each. They are the puzzle's initial position. Those lines contain each character from the string "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" exactly once.OutputOn the first line print number n, which is the number of operations. On the next n lines print the sequence of operations one per line. An operation is described by a word consisting of two characters. The first character shows the direction where the row or the column will be shifted. The possible directions are "L", "R" (to the left, to the right correspondingly, we shift a row), "U", "D" (upwards, downwards correspondingly, we shift a column). The second character is the number of the row (or the column), it is an integer from "1" to "6". The rows are numbered from the top to the bottom, the columns are numbered from the left to the right.The number of operations should not exceed 104. If there are several solutions, print any of them.ExamplesInput01W345729AB6CD8FGHIJELMNOPKRSTUVQXYZOutput2R2U3
Input01W345729AB6CD8FGHIJELMNOPKRSTUVQXYZ
Output2R2U3
2 seconds
256 megabytes
['constructive algorithms', '*2800']
D. Hangertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one very large and very respectable company there is a cloakroom with a coat hanger. It is represented by n hooks, positioned in a row. The hooks are numbered with positive integers from 1 to n from the left to the right.The company workers have a very complicated work schedule. At the beginning of a work day all the employees are not there and the coat hanger in the cloakroom is empty. At some moments of time the employees arrive and some of them leave.When some employee arrives, he hangs his cloak on one of the available hooks. To be of as little discomfort to his colleagues as possible, the hook where the coat will hang, is chosen like this. First the employee chooses the longest segment among available hooks following in a row. If there are several of such segments, then he chooses the one closest to the right. After that the coat is hung on the hook located in the middle of this segment. If the segment has an even number of hooks, then among two central hooks we choose the one closest to the right.When an employee leaves, he takes his coat. As all the company workers deeply respect each other, no one takes somebody else's coat.From time to time the director of this respectable company gets bored and he sends his secretary to see how many coats hang on the coat hanger from the i-th to the j-th hook inclusive. And this whim is always to be fulfilled, otherwise the director gets angry and has a mental breakdown.Not to spend too much time traversing from the director's office to the cloakroom and back again, the secretary asked you to write a program, emulating the company cloakroom's work.InputThe first line contains two integers n, q (1 ≀ n ≀ 109, 1 ≀ q ≀ 105), which are the number of hooks on the hanger and the number of requests correspondingly. Then follow q lines with requests, sorted according to time. The request of the type "0 i j" (1 ≀ i ≀ j ≀ n) β€” is the director's request. The input data has at least one director's request. In all other cases the request contains a positive integer not exceeding 109 β€” an employee identificator. Each odd appearance of the identificator of an employee in the request list is his arrival. Each even one is his leaving. All employees have distinct identificators. When any employee arrives, there is always at least one free hook.OutputFor each director's request in the input data print a single number on a single line β€” the number of coats hanging on the hooks from the i-th one to the j-th one inclusive.ExamplesInput9 11120 5 81130 3 890 6 960 1 9Output2325
Input9 11120 5 81130 3 890 6 960 1 9
Output2325
4 seconds
256 megabytes
['data structures', '*2400']
C. Chessboard Billiardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.More formally, first one of four diagonal directions is chosen and the billiard ball moves in that direction. When it reaches the square located on the board's edge, the billiard ball reflects from it; it changes the direction of its movement by 90 degrees and continues moving. Specifically, having reached a corner square, the billiard ball is reflected twice and starts to move the opposite way. While it moves, the billiard ball can make an infinite number of reflections. At any square of its trajectory the billiard ball can stop and on that the move is considered completed. It is considered that one billiard ball a beats another billiard ball b if a can reach a point where b is located.You are suggested to find the maximal number of billiard balls, that pairwise do not beat each other and that can be positioned on a chessboard n × m in size.InputThe first line contains two integers n and m (2 ≀ n, m ≀ 106).OutputPrint a single number, the maximum possible number of billiard balls that do not pairwise beat each other.Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is preferred to use cin (also you may use the %I64d specificator).ExamplesInput3 4Output2Input3 3Output3
Input3 4
Output2
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'number theory', '*2100']
B. Traintime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA stowaway and a controller play the following game. The train is represented by n wagons which are numbered with positive integers from 1 to n from the head to the tail. The stowaway and the controller are initially in some two different wagons. Every minute the train can be in one of two conditions β€” moving or idle. Every minute the players move.The controller's move is as follows. The controller has the movement direction β€” to the train's head or to its tail. During a move the controller moves to the neighbouring wagon correspondingly to its movement direction. If at the end of his move the controller enters the 1-st or the n-th wagon, that he changes the direction of his movement into the other one. In other words, the controller cyclically goes from the train's head to its tail and back again during all the time of a game, shifting during each move by one wagon. Note, that the controller always have exactly one possible move.The stowaway's move depends from the state of the train. If the train is moving, then the stowaway can shift to one of neighbouring wagons or he can stay where he is without moving. If the train is at a station and is idle, then the stowaway leaves the train (i.e. he is now not present in any train wagon) and then, if it is not the terminal train station, he enters the train again into any of n wagons (not necessarily into the one he's just left and not necessarily into the neighbouring one). If the train is idle for several minutes then each such minute the stowaway leaves the train and enters it back.Let's determine the order of the players' moves. If at the given minute the train is moving, then first the stowaway moves and then the controller does. If at this minute the train is idle, then first the stowaway leaves the train, then the controller moves and then the stowaway enters the train.If at some point in time the stowaway and the controller happen to be in one wagon, then the controller wins: he makes the stowaway pay fine. If after a while the stowaway reaches the terminal train station, then the stowaway wins: he simply leaves the station during his move and never returns there again.At any moment of time the players know each other's positions. The players play in the optimal way. Specifically, if the controller wins, then the stowaway plays so as to lose as late as possible. As all the possible moves for the controller are determined uniquely, then he is considered to play optimally always. Determine the winner.InputThe first line contains three integers n, m and k. They represent the number of wagons in the train, the stowaway's and the controller's initial positions correspondingly (2 ≀ n ≀ 50, 1 ≀ m, k ≀ n, m ≠ k).The second line contains the direction in which a controller moves. "to head" means that the controller moves to the train's head and "to tail" means that the controller moves to its tail. It is guaranteed that in the direction in which the controller is moving, there is at least one wagon. Wagon 1 is the head, and wagon n is the tail.The third line has the length from 1 to 200 and consists of symbols "0" and "1". The i-th symbol contains information about the train's state at the i-th minute of time. "0" means that in this very minute the train moves and "1" means that the train in this very minute stands idle. The last symbol of the third line is always "1" β€” that's the terminal train station.OutputIf the stowaway wins, print "Stowaway" without quotes. Otherwise, print "Controller" again without quotes, then, separated by a space, print the number of a minute, at which the stowaway will be caught.ExamplesInput5 3 2to head0001001OutputStowawayInput3 2 1to tail0001OutputController 2
Input5 3 2to head0001001
OutputStowaway
2 seconds
256 megabytes
['dp', 'games', 'greedy', '*1500']
A. Room Leadertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us remind you part of the rules of Codeforces. The given rules slightly simplified, use the problem statement as a formal document.In the beginning of the round the contestants are divided into rooms. Each room contains exactly n participants. During the contest the participants are suggested to solve five problems, A, B, C, D and E. For each of these problem, depending on when the given problem was solved and whether it was solved at all, the participants receive some points. Besides, a contestant can perform hacks on other contestants. For each successful hack a contestant earns 100 points, for each unsuccessful hack a contestant loses 50 points. The number of points for every contestant is represented by the sum of points he has received from all his problems, including hacks.You are suggested to determine the leader for some room; the leader is a participant who has maximum points.InputThe first line contains an integer n, which is the number of contestants in the room (1 ≀ n ≀ 50). The next n lines contain the participants of a given room. The i-th line has the format of "handlei plusi minusi ai bi ci di ei" β€” it is the handle of a contestant, the number of successful hacks, the number of unsuccessful hacks and the number of points he has received from problems A, B, C, D, E correspondingly. The handle of each participant consists of Latin letters, digits and underscores and has the length from 1 to 20 characters. There are the following limitations imposed upon the numbers: 0 ≀ plusi, minusi ≀ 50; 150 ≀ ai ≀ 500 or ai = 0, if problem A is not solved; 300 ≀ bi ≀ 1000 or bi = 0, if problem B is not solved; 450 ≀ ci ≀ 1500 or ci = 0, if problem C is not solved; 600 ≀ di ≀ 2000 or di = 0, if problem D is not solved; 750 ≀ ei ≀ 2500 or ei = 0, if problem E is not solved. All the numbers are integer. All the participants have different handles. It is guaranteed that there is exactly one leader in the room (i.e. there are no two participants with the maximal number of points).OutputPrint on the single line the handle of the room leader.ExamplesInput5Petr 3 1 490 920 1000 1200 0tourist 2 0 490 950 1100 1400 0Egor 7 0 480 900 950 0 1000c00lH4x0R 0 10 150 0 0 0 0some_participant 2 1 450 720 900 0 0OutputtouristNoteThe number of points that each participant from the example earns, are as follows: Petr β€” 3860 tourist β€” 4140 Egor β€” 4030 c00lH4x0R β€”  - 350 some_participant β€” 2220 Thus, the leader of the room is tourist.
Input5Petr 3 1 490 920 1000 1200 0tourist 2 0 490 950 1100 1400 0Egor 7 0 480 900 950 0 1000c00lH4x0R 0 10 150 0 0 0 0some_participant 2 1 450 720 900 0 0
Outputtourist
2 seconds
256 megabytes
['implementation', '*1000']
F. Plane of Tankstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the Plane of Tanks. The tanks in this game keep trying to finish each other off. But your "Pedalny" is not like that... He just needs to drive in a straight line from point A to point B on the plane. Unfortunately, on the same plane are n enemy tanks. We shall regard all the tanks as points. At the initial moment of time Pedalny is at the point A. Enemy tanks would be happy to destroy it immediately, but initially their turrets are tuned in other directions. Specifically, for each tank we know the initial rotation of the turret ai (the angle in radians relative to the OX axis in the counterclockwise direction) and the maximum speed of rotation of the turret wi (radians per second). If at any point of time a tank turret will be aimed precisely at the tank Pedalny, then the enemy fires and it never misses. Pedalny can endure no more than k shots. Gun reloading takes very much time, so we can assume that every enemy will produce no more than one shot. Your task is to determine what minimum speed of v Pedalny must have to get to the point B. It is believed that Pedalny is able to instantly develop the speed of v, and the first k shots at him do not reduce the speed and do not change the coordinates of the tank.InputThe first line contains 4 numbers – the coordinates of points A and B (in meters), the points do not coincide. On the second line number n is given (1 ≀ n ≀ 104). It is the number of enemy tanks. Each of the following n lines contain the coordinates of a corresponding tank xi, yi and its parameters ai and wi (0 ≀ ai ≀ 2Ο€, 0 ≀ wi ≀ 100). Numbers ai and wi contain at most 5 digits after the decimal point. All coordinates are integers and their absolute values do not exceed 105. Enemy tanks can rotate a turret in the clockwise as well as in the counterclockwise direction at the angular speed of not more than wi. It is guaranteed that each of the enemy tanks will need at least 0.1 seconds to aim at any point of the segment AB and each of the enemy tanks is posistioned no closer than 0.1 meters to line AB. On the last line is given the number k (0 ≀ k ≀ n).OutputPrint a single number with absolute or relative error no more than 10 - 4 β€” the minimum required speed of Pedalny in meters per second.ExamplesInput0 0 10 015 -5 4.71238 10Output4.2441Input0 0 10 015 -5 4.71238 11Output0.0000
Input0 0 10 015 -5 4.71238 10
Output4.2441
4 seconds
256 megabytes
['brute force', 'geometry', '*2900']
E. Morrowindowstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays The Elder Trolls III: Morrowindows. He has a huge list of items in the inventory, however, there is no limits on the size of things. Vasya does not know the total amount of items but he is sure that are not more than x and not less than 2 items in his inventory. A new patch for the game appeared to view inventory in n different modes. Displaying in mode i is a partition of all inventory items on pages, each of which (except for maybe the last one) shows exactly ai items. In addition, each mode shows how many pages bi is in a complete list. Great! Perhaps this information will be enough for Vasya to find the required number. Moreover, it is very interesting, what is the fewest number of modes in which Vasya can see inventory to determine the number of items in it?Vasya cannot use the information that was received while looking on inventory in some mode for selection of next actions. I. e. Vasya chooses some set of modes first, and then sees all the results and determines the size.Knowing the number of ai, x and assuming that Vasya is very smart, check whether he can uniquely determine the number of items in his inventory, and how many modes he will need to do that if he knows numbers ai, x and he is able to know number bi after viewing items in mode i.InputThe first line contains two integers n and x (0 ≀ n ≀ 105, 2 ≀ x ≀ 109). The second line contains integers ai (1 ≀ ai ≀ 109). Some numbers among all ai may be equal.OutputOutput the fewest amount of modes required to uniquely determine amount of items in the inventory. If there is no solution output  - 1.ExamplesInput2 42 3Output2Input1 42Output-1NoteIn the second example Vasya is not able to determine items count uniquely because 3 items, as well as 4 items, can be displayed on two pages.
Input2 42 3
Output2
2 seconds
256 megabytes
['math', 'number theory', '*2400']
D. FreeDivtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays FreeDiv. In this game he manages a huge state, which has n cities and m two-way roads between them. Unfortunately, not from every city you can reach any other one moving along these roads. Therefore Vasya decided to divide the state into provinces so that in every province, one could reach from every city all the cities of the province, but there are no roads between provinces. Unlike other turn-based strategies, in FreeDiv a player has the opportunity to build tunnels between cities. The tunnels are two-way roads along which one can move armies undetected by the enemy. However, no more than one tunnel can be connected to each city. As for Vasya, he wants to build a network of tunnels so that any pair of cities in his state were reachable by some path consisting of roads and a tunnels. But at that no more than k tunnels are connected to each province (otherwise, the province will be difficult to keep in case other provinces are captured by enemy armies).Vasya discovered that maybe he will not be able to build such a network for the current condition of the state. Maybe he'll have first to build several roads between cities in different provinces to merge the provinces. Your task is to determine the minimum number of roads Vasya needs to build so that it was possible to build the required network of tunnels in the resulting state.InputThe first line contains three integers n, m and k (1 ≀ n, k ≀ 106, 0 ≀ m ≀ 106). Each of the next m lines contains two integers. They are the numbers of cities connected by a corresponding road. No road connects city to itself and there is at most one road between each pair of cities.OutputPrint a single number, the minimum number of additional roads.ExamplesInput3 3 21 22 33 1Output0Input4 2 21 23 4Output0Input4 0 2Output1NoteIn the first example only one province exists, so it is not necessary to build any tunnels or roads.In the second example two provinces exist. It is possible to merge the provinces by building a tunnel between cities 1 and 3.In the third example at least one additional road is necessary. For example it is possible to build additional road between cities 1 and 2 and build two tunnels between cities 1 and 3, 2 and 4 after that.
Input3 3 21 22 33 1
Output0
5 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', '*2200']
C. LionAge IItime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character β€” non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character.InputThe first line contains character's name s and an integer number k (0 ≀ k ≀ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≀ n ≀ 676) β€” amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs Β«x y cΒ», which means that sequence xy gives bonus c (x, y β€” lowercase Latin letters,  - 1000 ≀ c ≀ 1000). It is guaranteed that no pair x y mentioned twice in the input data.OutputOutput the only number β€” maximum possible euphony ΠΎf the new character's name.ExamplesInputwinner 44s e 7o s 8l o 13o o 8Output36Inputabcdef 15a b -10b c 5c d 5d e 5e f 5Output20NoteIn the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36.
Inputwinner 44s e 7o s 8l o 13o o 8
Output36
2 seconds
256 megabytes
['dp', '*1800']
B. Need For Braketime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays the Need For Brake. He plays because he was presented with a new computer wheel for birthday! Now he is sure that he will win the first place in the championship in his favourite racing computer game! n racers take part in the championship, which consists of a number of races. After each race racers are arranged from place first to n-th (no two racers share the same place) and first m places are awarded. Racer gains bi points for i-th awarded place, which are added to total points, obtained by him for previous races. It is known that current summary score of racer i is ai points. In the final standings of championship all the racers will be sorted in descending order of points. Racers with an equal amount of points are sorted by increasing of the name in lexicographical order.Unfortunately, the championship has come to an end, and there is only one race left. Vasya decided to find out what the highest and lowest place he can take up as a result of the championship.InputThe first line contains number n (1 ≀ n ≀ 105) β€” number of racers. Each of the next n lines contains si and ai β€” nick of the racer (nonempty string, which consist of no more than 20 lowercase Latin letters) and the racer's points (0 ≀ ai ≀ 106). Racers are given in the arbitrary order.The next line contains the number m (0 ≀ m ≀ n). Then m nonnegative integer numbers bi follow. i-th number is equal to amount of points for the i-th awarded place (0 ≀ bi ≀ 106).The last line contains Vasya's racer nick.OutputOutput two numbers β€” the highest and the lowest place Vasya can take up as a result of the championship.ExamplesInput3teama 10teamb 20teamc 40210 20teamaOutput2 3Input2teama 10teamb 10210 10teambOutput2 2
Input3teama 10teamb 20teamc 40210 20teama
Output2 3
4 seconds
256 megabytes
['binary search', 'greedy', 'sortings', '*2000']
A. The Elder Trolls IV: Oblivontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays The Elder Trolls IV: Oblivon. Oh, those creators of computer games! What they do not come up with! Absolutely unique monsters have been added to the The Elder Trolls IV: Oblivon. One of these monsters is Unkillable Slug. Why it is "Unkillable"? Firstly, because it can be killed with cutting weapon only, so lovers of two-handed amber hammers should find suitable knife themselves. Secondly, it is necessary to make so many cutting strokes to Unkillable Slug. Extremely many. Too many! Vasya has already promoted his character to 80-th level and in order to gain level 81 he was asked to kill Unkillable Slug. The monster has a very interesting shape. It looks like a rectangular parallelepiped with size x × y × z, consisting of undestructable cells 1 × 1 × 1. At one stroke Vasya can cut the Slug along an imaginary grid, i.e. cut with a plane parallel to one of the parallelepiped side. Monster dies when amount of parts it is divided reaches some critical value.All parts of monster do not fall after each cut, they remains exactly on its places. I. e. Vasya can cut several parts with one cut.Vasya wants to know what the maximum number of pieces he can cut the Unkillable Slug into striking him at most k times.Vasya's character uses absolutely thin sword with infinite length.InputThe first line of input contains four integer numbers x, y, z, k (1 ≀ x, y, z ≀ 106, 0 ≀ k ≀ 109).OutputOutput the only number β€” the answer for the problem.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput2 2 2 3Output8Input2 2 2 1Output2NoteIn the first sample Vasya make 3 pairwise perpendicular cuts. He cuts monster on two parts with the first cut, then he divides each part on two with the second cut, and finally he divides each of the 4 parts on two.
Input2 2 2 3
Output8
2 seconds
256 megabytes
['greedy', 'math', '*1600']
I. Goofy Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe non-negative integer a is a divisor of the non-negative integer b if and only if there exists a positive integer c such that a × c = b. Some numbers are really interesting. Commander Surena defines some interesting properties for non-negative integers: An integer is happy if it is divisible by at least one of its digits and not by all of them. An integer is happier if it is divisible by all of its digits. An integer is upset if it's divisible by none of its digits. Surena asks you to find out if a given number is happy, happier or upset.InputInput contains a single non-negative integer n (1 ≀ n ≀ 108).OutputWrite on a single line the type of the integer: happy, happier or upset. Print the type in lowercase letters.ExamplesInput99OutputhappierInput29994OutputhappyInput23OutputupsetNoteIn the second test 29994 is only divisible by 2.In the third test 23 is a prime number.
Input99
Outputhappier
2 seconds
256 megabytes
['*special problem', 'implementation', '*1500']
H. Reverse It!time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe 14th of March was the international day of mathematics, because of number π = 3.1415926...In the occasion of this day Goofy Nephews Unity Organization (GNU) wants to publish the fastest program in math at 1:59:26 AM. Now the time is 1:11:11 AM and the project team haven't checked their program yet. Because of shortage of time they want to check their program with some queries. So they hired Hormizd (one of the greatest programmers in world) to write a tester for GNU's new program. Because Hormizd has much more important things to do, he wants you to write a small part of tester and it is reversing the numbers. Help him before 1:59:26.We can reverse numbers easily. For example by reversing 1234 we get 4321.Note, that if the integer is negative then its reverse would be also negative. For example reverse of  - 123 is  - 321.Also, you have to delete all the leading zeroes before and after the reverse.Given an integer you have to help Hormizd reverse it.InputThe first line contains a single integer n. It is less than 101000 by it's absolute value. This integer may have leading zeros. If it had leading zeros you should first omit them and print the reverse of remaining digits. It's guaranteed that input contains less than 10001 characters.OutputOutput a single integer, the reverse of the given number. You have to omit leading zeros in the output.ExamplesInput23Output32Input-032Output-23Input01234560Output654321
Input23
Output32
4 seconds
256 megabytes
['*special problem', 'implementation', '*1600']
G. Fibonacci armytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKing Cambyses loves Fibonacci numbers. He has several armies. Today he wants to make a new army for himself and he wants the number of men in this army to be the n-th Fibonacci number.Given n you should find n-th Fibonacci number. The set of Fibonacci numbers start with f0 = f1 = 1 and for each i β‰₯ 2, fi = fi - 1 + fi - 2.InputInput contains a single integer n (1 ≀ n ≀ 20).OutputWrite a single integer. The n-th Fibonacci number.ExamplesInput2Output2Input1Output1
Input2
Output2
2 seconds
256 megabytes
['*special problem', 'dp', '*1000']
F. Oiltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the nationalization of the oil industry, Dr. Mosaddegh wants to dig some oil wells to extract all the oil in Persian Gulf. But Persian Gulf is huge and has an infinite amount of oil. So Dr. Mosaddegh works only on a rectangular plane of size n × m of the Persian Gulf. Each of the cells in this rectangle either contains an infinite amount of oil or nothing.Two cells are considered adjacent if and only if they have a common edge, a path is a sequence c1, c2, ..., cx of cells so that all of them contain oil and for each i, ci is adjacent to ci - 1 and ci + 1 (if they exist). Two cells are considered connected to each other if and only if there exists a path between them. If we dig a well in a certain cell, we can extract oil from all the cells that are connected to it by oil paths. It is not allowed to dig wells on empty cells.Dr. Mosaddegh also knows that in Persian Gulf, the empty cells form rows and columns. I. e. if some cell is empty, then it's column is completely empty or it's row is completely empty, or both.Help Dr. Mosaddegh find out how many wells he has to dig to access all the oil in that region.InputIn the first line there are two positive integers n and m (1 ≀ n, m ≀ 100).In the second line there is an integer t (0 ≀ t ≀ n), the number of empty rows. t distinct positive integers follow, these are the numbers of empty rows and are in range [1, n].In the second line there is an integer s (0 ≀ s ≀ m) that shows the number of columns not having any oil. s distinct positive integers follow, these are the numbers of empty columns and are in range of [1, m].Note that rows are numbered from 1 to n (from top to bottom) and columns are numbered from 1 to m (from left to right).OutputA single integer, the minimum number of wells that Dr. Mossadegh has to dig.This is actually finding how many regions are made by removing the given rows and columns.ExamplesInput2 31 21 2Output2Input4 42 2 33 2 3 1Output2Input2 31 10Output1
Input2 31 21 2
Output2
2 seconds
256 megabytes
['*special problem', 'greedy', 'math', '*1900']
E. Ali goes shoppingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAli Koochooloo is going to buy new clothes since we're reaching Noruz, the ancient Persian festival and the beginning of new Persian year.When Ali entered a shop, he saw that the shopkeeper was a programmer and since there is no money in programming he had changed his career. The shopkeeper told Ali that he can buy anything for free if he could answer a simple question in 10 seconds. But to see the question Ali has to pay 3 tomans.Ali agreed instantly and the shopkeeper handed him a piece of paper containing the task. The task was indeed very simple. It said: Let string A be ababababababab. Which non-empty substring of A is repeated the most times in it?Ali answered fast. He said the answer is a. But the shopkeeper said that Ali is wrong and asked him to read the rest of statement:If several substrings have the maximal repeat time, then the substring with maximal length would be the answer, in case of a tie the alphabetically latest substring will be chosen.So the answer is ab.Now Ali wants us to solve this problem for different strings. We don't have a great advantage over Ali, we just have a computer and a weird language.InputThe single line consisting of a string A. It is non-empty, made of lower-case Latin letters and contains at most 30 characters.OutputThe single line contains the answer.ExamplesInputababOutputabInputabcdOutputabcd
Inputabab
Outputab
5 seconds
256 megabytes
['*special problem', 'brute force', 'strings', '*1800']
D. Perse-scripttime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo good friends were trying to make a new programming language called Perse-script.The most important part of this language is strings. A string in Perse-script is put between characters "So for example "Hello" is a string. But Hello is a variable name or a keyword, which are not considered in this problem.Perse-script is function-based. So there are no operators in this language. For example for summing two numbers you have to write sum(a,b) and not a+b.There are several functions for working on strings. These include: concat(x,y) is a function which gets two strings x and y and puts y at the end of x and returns the result. For example concat("Hello","World") returns "HelloWorld". reverse(x) gets a single string x and reverses it. For example reverse("Hello") returns "olleH". substr(x,a,b) gets a string x and two integers a and b (1 ≀ a ≀ b ≀ n, where n is the length of x). And returns the substring of x between indexes a and b, inclusive. For example substr("Hello",2,4) returns "ell". substr(x,a,b,c) is another version of substr which works just like the last one but c is the step of adding. c is positive. For example substr("HelloWorld",1,10,2) returns "Hlool". This substr means that you put the ath character , and then every cth character until you reach b.You're going to manipulate the string part of Perse-script. Given a string expression, you should print its result. It is guaranteed that the expression contains only strings shown by characters " and the above functions.Commands in Perse-script are case-insensitive. So to call substr function you can write SUBsTr(). But you can't print as the result "hElLo" instead of printing "Hello".See the samples for more information.InputA single line containing the correct expression. It is guaranteed that the total length of this expression does not exceed 103 and that all the integers used in it are less than or equal to 100 by absolute value. The given string is non-empty.All strings in the input which are placed between "s consist of uppercase and lowercase Latin letters only.OutputPrint in single line the resulting string. It is guaranteed that an answer exists and that the length of the answer does not exceed 104. It is guaranteed that the answer is non-empty.ExamplesInput"HelloWorld"Output"HelloWorld"InputREVerse(substr("helloworld",1,5))Output"olleh"InputconCAT(rEveRSE("olleh"),"world")Output"helloworld"InputreversE(concAT(substr("hello",1,2),sUbstr("world",1,5,1)))Output"dlroweh"InputsuBstr("Noruz",1,4,2)Output"Nr"
Input"HelloWorld"
Output"HelloWorld"
7 seconds
256 megabytes
['*special problem', 'expression parsing', '*2300']
C. Extraordinarily Nice Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe positive integer a is a divisor of the positive integer b if and only if there exists a positive integer c such that a × c = b. King Astyages thinks a positive integer x is extraordinarily nice if the number of its even divisors is equal to the number of its odd divisors.For example 3 has two positive divisors 3 and 1, both of which are odd, so 3 is not extraordinarily nice. On the other hand 2 is only divisible by 2 and 1, so it has one odd and one even divisor. Therefore 2 is extraordinarily nice.Given a positive integer x determine whether it's extraordinarily nice.InputThe input contains only a single integer x (1 ≀ x ≀ 103).OutputWrite a single yes or no. Write yes if the number is extraordinarily nice and no otherwise.You don't need to care about capital or small letters. The output is case-insensitive.ExamplesInput2OutputyesInput3Outputno
Input2
Outputyes
2 seconds
256 megabytes
['*special problem', 'math', '*1200']
B. INI-filetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe INI file format is a de facto standard for configuration files. INI files are simple text files with a basic structure. They are commonly associated with Microsoft Windows, but are also used on other platforms.Each line in INI-file stands for key-value mapping or defines new section. A key-value line has a format "key=value",where key β€” is the name of some property, and value β€” it's value. It is possible that it will be spaces from the both sides of key and/or value, the spaces should be ignored.A section line has a format "[section]". It means that all key-value lines after it define properties of the specified section. Of cause, the following section line changes the current section. A section line may have spaces around any of brackets.Also you should ignore comment lines β€” the first non-space character of comment line is ";".You task is to write the program which will format given INI-file in a special way: first, print key-value lines which do not belong to any section; print all the sections in the lexicographical (alphabetical) order of their names; inside each of two previous items, order key-value lines lexicographically by "key"; if there are more than one key-value lines with the same key inside a single section (or outside any sections), leave only one line (which appears later in the input data); remove all redundant spaces and lines. InputThe first line contains single integer n (1 ≀ n ≀ 510) β€” the number of lines in given INI-file.The rest of the input contains a valid INI-file in n lines. Values of section, key and value contain only Latin letters, digits, "." and/or "-".Each line has length not exceeding 255 characters and not less than 1 character. The total length of all the lines does’t exceed 10000.OutputPrint formatted INI-file.ExamplesInput11a= 1b=aa = 2 ; comment[z]1=2[y]2=3[z]2=1[w]Outputa=2b=a[w][y]2=3[z]1=22=1
Input11a= 1b=aa = 2 ; comment[z]1=2[y]2=3[z]2=1[w]
Outputa=2b=a[w][y]2=3[z]1=22=1
5 seconds
256 megabytes
['*special problem', 'implementation', '*2200']
A. Goshtasp, Vishtasp and Eiditime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGoshtasp was known to be a good programmer in his school. One day Vishtasp, Goshtasp's friend, asked him to solve this task:Given a positive integer n, you should determine whether n is rich.The positive integer x is rich, if there exists some set of distinct numbers a1, a2, ..., am such that . In addition: every ai should be either a prime number, or equal to 1.Vishtasp said that he would share his Eidi 50 / 50 with Goshtasp, if he could solve the task. Eidi is money given to children for Noruz by their parents and/or relatives.Goshtasp needs to solve this problem to get money, you need to solve it to get score!InputInput contains a single positive integer n (1 ≀ n ≀ 10000).OutputIf the number is not rich print 0. Otherwise print the numbers a1, ..., am. If several solutions exist print the lexicographically latest solution. Answers are compared as sequences of numbers, not as strings.For comparing two sequences a1, ..., am and b1, ..., bn we first find the first index i such that ai ≠ bi, if ai < bi then a is lexicographically earlier and if bi < ai then b is lexicographically earlier. If m ≠ n we add zeroes at the end of the smaller sequence (only for the moment of comparison) and then perform the comparison.You do not need to minimize the number of elements in sequence (i.e. m). You just need to print the lexicographically latest solution.See samples to find out how to print the sequence.ExamplesInput11Output11=11Input545Output541+3+1=545
Input11
Output11=11
5 seconds
256 megabytes
['*special problem', 'greedy', 'math', '*1800']
E. Nuclear Fusiontime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is the following puzzle popular among nuclear physicists.A reactor contains a set of n atoms of some chemical elements. We shall understand the phrase "atomic number" as the number of this atom's element in the periodic table of the chemical elements.You are allowed to take any two different atoms and fuse a new one from them. That results in a new atom, whose number is equal to the sum of the numbers of original atoms. The fusion operation can be performed several times.The aim is getting a new pregiven set of k atoms.The puzzle's difficulty is that it is only allowed to fuse two atoms into one, it is not allowed to split an atom into several atoms. You are suggested to try to solve the puzzle.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 17). The second line contains space-separated symbols of elements of n atoms, which are available from the start. The third line contains space-separated symbols of elements of k atoms which need to be the result of the fusion. The symbols of the elements coincide with the symbols from the periodic table of the chemical elements. The atomic numbers do not exceed 100 (elements possessing larger numbers are highly unstable). Some atoms can have identical numbers (that is, there can be several atoms of the same element). The sum of numbers of initial atoms is equal to the sum of numbers of the atoms that need to be synthesized.OutputIf it is impossible to synthesize the required atoms, print "NO" without the quotes. Otherwise, print on the first line Β«YESΒ», and on the next k lines print the way of synthesizing each of k atoms as equations. Each equation has the following form: "x1+x2+...+xt->yi", where xj is the symbol of the element of some atom from the original set, and yi is the symbol of the element of some atom from the resulting set. Each atom from the input data should occur in the output data exactly one time. The order of summands in the equations, as well as the output order does not matter. If there are several solutions, print any of them. For a better understanding of the output format, see the samples.ExamplesInput10 3Mn Co Li Mg C P F Zn Sc KSn Pt YOutputYESMn+C+K->SnCo+Zn+Sc->PtLi+Mg+P+F->YInput2 1H HHeOutputYESH+H->HeInput2 2Bk FmCf EsOutputNONoteThe reactions from the first example possess the following form (the atomic number is written below and to the left of the element):To find a periodic table of the chemical elements, you may use your favorite search engine.The pretest set contains each of the first 100 elements of the periodic table at least once. You can use that information to check for misprints.
Input10 3Mn Co Li Mg C P F Zn Sc KSn Pt Y
OutputYESMn+C+K->SnCo+Zn+Sc->PtLi+Mg+P+F->Y
1.5 seconds
256 megabytes
['bitmasks', 'dp', '*2200']
D. Solitairetime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.Vasya lays out nm cards as a rectangle n × m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which are not layed out) so that there were no jokers left. Vasya can pick the cards to replace the jokers arbitrarily. Remember, that each card presents in pack exactly once (i. e. in a single copy). Vasya tries to perform the replacements so that the solitaire was solved.Vasya thinks that the solitaire is solved if after the jokers are replaced, there exist two non-overlapping squares 3 × 3, inside each of which all the cards either have the same suit, or pairwise different ranks.Determine by the initial position whether the solitaire can be solved or not. If it can be solved, show the way in which it is possible.InputThe first line contains integers n and m (3 ≀ n, m ≀ 17, n × m ≀ 52). Next n lines contain m words each. Each word consists of two letters. The jokers are defined as "J1" and "J2" correspondingly. For the rest of the cards, the first letter stands for the rank and the second one β€” for the suit. The possible ranks are: "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K" and "A". The possible suits are: "C", "D", "H" and "S". All the cards are different.OutputIf the Solitaire can be solved, print on the first line "Solution exists." without the quotes. On the second line print in what way the jokers can be replaced. Three variants are possible: "There are no jokers.", if there are no jokers in the input data. "Replace Jx with y.", if there is one joker. x is its number, and y is the card it should be replaced with. "Replace J1 with x and J2 with y.", if both jokers are present in the input data. x and y here represent distinct cards with which one should replace the first and the second jokers correspondingly.On the third line print the coordinates of the upper left corner of the first square 3 × 3 in the format "Put the first square to (r, c).", where r and c are the row and the column correspondingly. In the same manner print on the fourth line the coordinates of the second square 3 × 3 in the format "Put the second square to (r, c).".If there are several solutions to that problem, print any of them.If there are no solutions, print of the single line "No solution." without the quotes.See the samples to understand the output format better.ExamplesInput4 62S 3S 4S 7S 8S AS5H 6H 7H 5S TC AC8H 9H TH 7C 8C 9C2D 2C 3C 4C 5C 6COutputNo solution.Input4 62S 3S 4S 7S 8S AS5H 6H 7H J1 TC AC8H 9H TH 7C 8C 9C2D 2C 3C 4C 5C 6COutputSolution exists.Replace J1 with 2H.Put the first square to (1, 1).Put the second square to (2, 4).Input4 62S 3S 4S 7S 8S AS5H 6H 7H QC TC AC8H 9H TH 7C 8C 9C2D 2C 3C 4C 5C 6COutputSolution exists.There are no jokers.Put the first square to (1, 1).Put the second square to (2, 4).NoteThe pretests cover all the possible output formats.
Input4 62S 3S 4S 7S 8S AS5H 6H 7H 5S TC AC8H 9H TH 7C 8C 9C2D 2C 3C 4C 5C 6C
OutputNo solution.
1.5 seconds
256 megabytes
['brute force', 'implementation', '*2200']
C. Round Table Knightstime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood. King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.InputThe first line contains number n, which is the number of knights at the round table (3 ≀ n ≀ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.OutputPrint "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".ExamplesInput31 1 1OutputYESInput61 0 1 1 1 0OutputYESInput61 0 0 1 0 1OutputNO
Input31 1 1
OutputYES
0.5 second
256 megabytes
['dp', 'math', 'number theory', '*1600']
B. Progress Bartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1 ≀ i ≀ n) is displayed, squares 1, 2, ... , i - 1 has the saturation k, squares i + 1, i + 2, ... , n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.InputWe are given 3 space-separated integers n, k, t (1 ≀ n, k ≀ 100, 0 ≀ t ≀ 100).OutputPrint n numbers. The i-th of them should be equal to ai.ExamplesInput10 10 54Output10 10 10 10 10 4 0 0 0 0 Input11 13 37Output13 13 13 13 0 0 0 0 0 0 0
Input10 10 54
Output10 10 10 10 10 4 0 0 0 0
1 second
256 megabytes
['implementation', 'math', '*1300']
A. Way Too Long Wordstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, "localization" will be spelt as "l10n", and "internationalizationΒ» will be spelt as "i18n".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.InputThe first line contains an integer n (1 ≀ n ≀ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.OutputPrint n lines. The i-th line should contain the result of replacing of the i-th word from the input data.ExamplesInput4wordlocalizationinternationalizationpneumonoultramicroscopicsilicovolcanoconiosisOutputwordl10ni18np43s
Input4wordlocalizationinternationalizationpneumonoultramicroscopicsilicovolcanoconiosis
Outputwordl10ni18np43s
1 second
256 megabytes
['strings', '*800']
E. Information Reformtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThought it is already the XXI century, the Mass Media isn't very popular in Walrusland. The cities get news from messengers who can only travel along roads. The network of roads in Walrusland is built so that it is possible to get to any city from any other one in exactly one way, and the roads' lengths are equal.The North Pole governor decided to carry out an information reform. Several cities were decided to be chosen and made regional centers. Maintaining a region center takes k fishlars (which is a local currency) per year. It is assumed that a regional center always has information on the latest news.For every city which is not a regional center, it was decided to appoint a regional center which will be responsible for keeping this city informed. In that case the maintenance costs will be equal to dlen fishlars per year, where len is the distance from a city to the corresponding regional center, measured in the number of roads along which one needs to go.Your task is to minimize the costs to carry out the reform.InputThe first line contains two given numbers n and k (1 ≀ n ≀ 180, 1 ≀ k ≀ 105).The second line contains n - 1 integers di, numbered starting with 1 (di ≀ di + 1, 0 ≀ di ≀ 105).Next n - 1 lines contain the pairs of cities connected by a road.OutputOn the first line print the minimum number of fishlars needed for a year's maintenance. On the second line print n numbers, where the i-th number will represent the number of the regional center, appointed to the i-th city. If the i-th city is a regional center itself, then you should print number i.If there are several solutions to that problem, print any of them.ExamplesInput8 102 5 9 11 15 19 201 41 31 74 62 82 33 5Output383 3 3 4 3 4 3 3
Input8 102 5 9 11 15 19 201 41 31 74 62 82 33 5
Output383 3 3 4 3 4 3 3
2 seconds
256 megabytes
['dp', 'implementation', 'trees', '*2700']
D. Professor's tasktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce a walrus professor Plato asked his programming students to perform the following practical task. The students had to implement such a data structure that would support a convex hull on some set of points S. The input to the program had q queries of two types: 1. Add a point with coordinates (x, y) into the set S. Note that in this case the convex hull of S could have changed, and could have remained the same. 2. Say whether a point with coordinates (x, y) belongs to an area limited by the convex hull, including the border. All the students coped with the task. What about you?InputThe first line contains an integer q (4 ≀ q ≀ 105). Then follow q lines in the following way: "t x y", where t is the query type (1 or 2), and (x, y) are the coordinates of the point ( - 106 ≀ x, y ≀ 106, x and y are integers). There is at least one query of type 2.It is guaranteed that the three queries of the first type follow first and the points given in the queries form a non-degenerative triangle. Also all the points added in S are distinct.OutputFor each query of the second type print one string containing "YES", if the point lies inside the convex hull or on its border. Otherwise, print "NO".ExamplesInput81 0 01 2 01 2 22 1 01 0 22 1 12 2 12 20 -1OutputYESYESYESNO
Input81 0 01 2 01 2 22 1 01 0 22 1 12 2 12 20 -1
OutputYESYESYESNO
1 second
256 megabytes
['data structures', 'geometry', '*2700']
C. Lucky Ticketstime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Walrusland public transport tickets are characterized by two integers: by the number of the series and by the number of the ticket in the series. Let the series number be represented by a and the ticket number β€” by b, then a ticket is described by the ordered pair of numbers (a, b). The walruses believe that a ticket is lucky if a * b = rev(a) * rev(b). The function rev(x) reverses a number written in the decimal system, at that the leading zeroes disappear. For example, rev(12343) = 34321, rev(1200) = 21.The Public Transport Management Committee wants to release x series, each containing y tickets, so that at least w lucky tickets were released and the total number of released tickets (x * y) were minimum. The series are numbered from 1 to x inclusive. The tickets in each series are numbered from 1 to y inclusive. The Transport Committee cannot release more than maxx series and more than maxy tickets in one series.InputThe first line contains three integers maxx, maxy, w (1 ≀ maxx, maxy ≀ 105, 1 ≀ w ≀ 107).OutputPrint on a single line two space-separated numbers, the x and the y. If there are several possible variants, print any of them. If such x and y do not exist, print a single number  - 1.ExamplesInput2 2 1Output1 1Input132 10 35Output7 5Input5 18 1000Output-1Input48 132 235Output22 111
Input2 2 1
Output1 1
1.5 seconds
256 megabytes
['binary search', 'data structures', 'sortings', 'two pointers', '*2200']
B. Text Messagingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?InputThe first line contains an integer n, which is the size of one message (2 ≀ n ≀ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.OutputOn the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.ExamplesInput25Hello. I am a little walrus.Output2Input2How are you?OutputImpossibleInput19Hello! Do you like fish? Why?Output3NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".
Input25Hello. I am a little walrus.
Output2
1 second
256 megabytes
['expression parsing', 'greedy', 'strings', '*1600']
A. Cookiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square k × k in size, divided into blocks 1 × 1 in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie k in size. Fangy also has a box with a square base 2n × 2n, divided into blocks 1 × 1 in size. In a box the cookies should not overlap, and they should not be turned over or rotated. See cookies of sizes 2 and 4 respectively on the figure: To stack the cookies the little walrus uses the following algorithm. He takes out of the repository the largest cookie which can fit in some place in the box and puts it there. Everything could be perfect but alas, in the repository the little walrus has infinitely many cookies of size 2 and larger, and there are no cookies of size 1, therefore, empty cells will remain in the box. Fangy wants to know how many empty cells will be left in the end.InputThe first line contains a single integer n (0 ≀ n ≀ 1000).OutputPrint the single number, equal to the number of empty cells in the box. The answer should be printed modulo 106 + 3.ExamplesInput3Output9NoteIf the box possesses the base of 23 × 23 (as in the example), then the cookies will be put there in the following manner:
Input3
Output9
1 second
256 megabytes
['math', '*1300']
E. Subsegmentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgrammer Sasha has recently begun to study data structures. His coach Stas told him to solve the problem of finding a minimum on the segment of the array in , which Sasha coped with. For Sasha not to think that he had learned all, Stas gave him a new task. For each segment of the fixed length Sasha must find the maximum element of those that occur on the given segment exactly once. Help Sasha solve this problem. InputThe first line contains two positive integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ n) β€” the number of array elements and the length of the segment. Then follow n lines: the i-th one contains a single number ai ( - 109 ≀ ai ≀ 109). OutputPrint n–k + 1 numbers, one per line: on the i-th line print of the maximum number of those numbers from the subarray ai ai + 1 … ai + k - 1 that occur in this subarray exactly 1 time. If there are no such numbers in this subarray, print "Nothing".ExamplesInput5 312233Output132Input6 4333442Output4Nothing3
Input5 312233
Output132
1 second
256 megabytes
['data structures', 'implementation', '*1800']
D. Dottime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules: On the checkered paper a coordinate system is drawn. A dot is initially put in the position (x, y). A move is shifting a dot to one of the pre-selected vectors. Also each player can once per game symmetrically reflect a dot relatively to the line y = x. Anton and Dasha take turns. Anton goes first. The player after whose move the distance from the dot to the coordinates' origin exceeds d, loses. Help them to determine the winner.InputThe first line of the input file contains 4 integers x, y, n, d ( - 200 ≀ x, y ≀ 200, 1 ≀ d ≀ 200, 1 ≀ n ≀ 20) β€” the initial coordinates of the dot, the distance d and the number of vectors. It is guaranteed that the initial dot is at the distance less than d from the origin of the coordinates. The following n lines each contain two non-negative numbers xi and yi (0 ≀ xi, yi ≀ 200) β€” the coordinates of the i-th vector. It is guaranteed that all the vectors are nonzero and different.OutputYou should print "Anton", if the winner is Anton in case of both players play the game optimally, and "Dasha" otherwise.ExamplesInput0 0 2 31 11 2OutputAntonInput0 0 2 41 11 2OutputDashaNoteIn the first test, Anton goes to the vector (1;2), and Dasha loses. In the second test Dasha with her first move shifts the dot so that its coordinates are (2;3), and Anton loses, as he has the only possible move β€” to reflect relatively to the line y = x. Dasha will respond to it with the same move and return the dot in position (2;3).
Input0 0 2 31 11 2
OutputAnton
3 seconds
256 megabytes
['dp', 'games', '*1900']
C. Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts.After the composing composite artifact, all the components disappear.Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts. InputThe first line has 4 natural numbers: k (1 ≀ k ≀ 100) β€” the number of Kostya's allies, n (1 ≀ n ≀ 50) β€” the number of basic artifacts, m (0 ≀ m ≀ 50) β€” the number of composite artifacts, q (1 ≀ q ≀ 500) β€” the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format:<Art. Name>: <Art. β„–1> <Art. β„–1 Number>, <Art. β„–2> <Art. β„–2 Number>, ... <Art. β„–X> <Art. β„–Π₯ Number>All the numbers are natural numbers not exceeding 100 (1 ≀ X ≀ n).The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts. Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≀ ai ≀ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there.It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it.OutputThe output file should consist of k blocks. The first line should contain number bi β€” the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive.ExamplesInput2 3 2 5desolatorrefresherperseverancevanguard: desolator 1, refresher 1maelstorm: perseverance 21 desolator2 perseverance1 refresher2 desolator2 perseveranceOutput1vanguard 12desolator 1maelstorm 1
Input2 3 2 5desolatorrefresherperseverancevanguard: desolator 1, refresher 1maelstorm: perseverance 21 desolator2 perseverance1 refresher2 desolator2 perseverance
Output1vanguard 12desolator 1maelstorm 1
2 seconds
256 megabytes
['implementation', '*2000']
B. Betstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: li β€” the number of the starting section, ri β€” the number of the finishing section (li ≀ ri), ti β€” the time a biathlete needs to complete an section of the path, ci β€” the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)Β·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives kΒ·ci roubles.In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.We should also add that Nikita can bet on each section and on any contestant running in this section.Help the friends find the maximum possible profit.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≀ li ≀ ri ≀ n, 1 ≀ ti, ci ≀ 1000).OutputPrint a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman.ExamplesInput4 41 4 20 51 3 21 103 3 4 303 4 4 20Output60Input8 41 5 24 102 4 6 154 6 30 506 7 4 20Output105NoteIn the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.
Input4 41 4 20 51 3 21 103 3 4 303 4 4 20
Output60
2 seconds
256 megabytes
['greedy', 'implementation', '*1200']
A. Young Physicisttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" β€” thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.InputThe first line contains a positive integer n (1 ≀ n ≀ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≀ xi, yi, zi ≀ 100).OutputPrint the word "YES" if the body is in equilibrium, or the word "NO" if it is not.ExamplesInput34 1 7-2 4 -11 -5 -3OutputNOInput33 -1 7-5 2 -42 -1 -3OutputYES
Input34 1 7-2 4 -11 -5 -3
OutputNO
2 seconds
256 megabytes
['implementation', 'math', '*1000']
E. Contacttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya is preparing for the first contact with aliens. He knows that alien spaceships have shapes of non-degenerate triangles and there will be exactly 4 ships. Landing platform for a ship can be made of 3 special columns located at some points of a Cartesian plane such that these 3 points form a triangle equal to the ship with respect to rotations, translations (parallel shifts along some vector) and reflections (symmetries along the edges). The ships can overlap after the landing.Each column can be used to land more than one ship, for example, if there are two equal ships, we don't need to build 6 columns to land both ships, 3 will be enough. Petya wants to know what minimum number of columns will be enough to land all ships. InputEach of 4 lines will contain 6 integers x1 y1 x2 y2 x3 y3 (0 ≀ x1, y1, x2, y2, x3, y3 ≀ 20), representing 3 points that describe the shape of each of 4 ships. It is guaranteed that 3 points in each line will represent a non-degenerate triangle.OutputFirst line should contain minimum number of columns enough to land all spaceships.ExamplesInput0 0 1 0 1 20 0 0 2 2 20 0 3 0 1 20 0 3 0 2 2Output4Input0 0 0 1 1 10 0 0 2 2 20 0 0 5 5 50 0 0 17 17 17Output9NoteIn the first test case columns can be put in these points: (0, 0), (1, 0), (3, 0), (1, 2). Note that the second ship can land using last 3 columns.In the second test case following points can be chosen: (0, 0), (0, 1), (1, 0), (0, 2), (2, 0), (0, 5), (5, 0), (0, 17), (17, 0). It is impossible to use less than 9 columns.
Input0 0 1 0 1 20 0 0 2 2 20 0 3 0 1 20 0 3 0 2 2
Output4
3 seconds
256 megabytes
['geometry', '*2900']
D. Half-decay treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Petya has become keen on physics. Anna V., his teacher noticed Petya's interest and gave him a fascinating physical puzzle β€” a half-decay tree. A half-decay tree is a complete binary tree with the height h. The height of a tree is the length of the path (in edges) from the root to a leaf in the tree. While studying the tree Petya can add electrons to vertices or induce random decay with synchrophasotron. Random decay is a process during which the edges of some path from the root to the random leaf of the tree are deleted. All the leaves are equiprobable. As the half-decay tree is the school property, Petya will return back the deleted edges into the tree after each decay.After being desintegrated, the tree decomposes into connected components. Charge of each component is the total quantity of electrons placed in vertices of the component. Potential of desintegerated tree is the maximum from the charges of its connected components. Each time before inducing random decay Petya is curious about the mathematical expectation of potential of the tree after being desintegrated. InputFirst line will contain two integers h and q (1 ≀ h ≀ 30, 1 ≀ q ≀ 105). Next q lines will contain a query of one of two types: add v ePetya adds e electrons to vertex number v (1 ≀ v ≀ 2h + 1 - 1, 0 ≀ e ≀ 104). v and e are integers.The vertices of the tree are numbered in the following way: the root is numbered with 1, the children of the vertex with number x are numbered with 2x and 2x + 1. decayPetya induces tree decay. OutputFor each query decay solution you should output the mathematical expectation of potential of the tree after being desintegrated. The absolute or relative error in the answer should not exceed 10 - 4.ExamplesInput1 4add 1 3add 2 10add 3 11decayOutput13.50000000
Input1 4add 1 3add 2 10add 3 11decay
Output13.50000000
3 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'math', 'probabilities', '*2500']
C. Synchrophasotrontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor some experiments little Petya needs a synchrophasotron. He has already got the device, all that's left is to set the fuel supply. Fuel comes through a system of nodes numbered from 1 to n and connected by pipes. Pipes go from every node with smaller number to every node with greater number. Fuel can only flow through pipes in direction from node with smaller number to node with greater number. Any amount of fuel can enter through the first node and the last node is connected directly to the synchrophasotron. It is known that every pipe has three attributes: the minimum amount of fuel that should go through it, the maximum amount of fuel that can possibly go through it and the cost of pipe activation. If cij units of fuel (cij > 0) flow from node i to node j, it will cost aij + cij2 tugriks (aij is the cost of pipe activation), and if fuel doesn't flow through the pipe, it doesn't cost anything. Only integer number of units of fuel can flow through each pipe.Constraints on the minimal and the maximal fuel capacity of a pipe take place always, not only if it is active. You may assume that the pipe is active if and only if the flow through it is strictly greater than zero.Petya doesn't want the pipe system to be overloaded, so he wants to find the minimal amount of fuel, that, having entered the first node, can reach the synchrophasotron. Besides that he wants to impress the sponsors, so the sum of money needed to be paid for fuel to go through each pipe, must be as big as possible.InputFirst line contains integer n (2 ≀ n ≀ 6), which represents the number of nodes. Each of the next n(n - 1) / 2 lines contains five integers s, f, l, h, a that describe pipes β€” the first node of the pipe, the second node of the pipe, the minimum and the maximum amount of fuel that can flow through the pipe and the the activation cost, respectively. (1 ≀ s < f ≀ n, 0 ≀ l ≀ h ≀ 5, 0 ≀ a ≀ 6). It is guaranteed that for each pair of nodes with distinct numbers there will be exactly one pipe between them described in the input.OutputOutput in the first line two space-separated numbers: the minimum possible amount of fuel that can flow into the synchrophasotron, and the maximum possible sum that needs to be paid in order for that amount of fuel to reach synchrophasotron. If there is no amount of fuel that can reach synchrophasotron, output "-1 -1".The amount of fuel which will flow into synchrophasotron is not neccessary positive. It could be equal to zero if the minimum constraint of every pipe is equal to zero.ExamplesInput21 2 1 2 3Output1 4Input31 2 1 2 31 3 0 0 02 3 3 4 5Output-1 -1Input41 2 0 2 12 3 0 2 11 3 0 2 61 4 0 0 12 4 0 0 03 4 2 3 0Output2 15Input31 2 0 2 11 3 1 2 12 3 1 2 1Output2 6NoteIn the first test, we can either pass 1 or 2 units of fuel from node 1 to node 2. The minimum possible amount is 1, it costs a12 + 12 = 4.In the second test, you can pass at most 2 units from node 1 to node 2, and at you have to pass at least 3 units from node 2 to node 3. It is impossible.In the third test, the minimum possible amount is 2. You can pass each unit of fuel through two different paths: either 1->2->3->4 or 1->3->4. If you use the first path twice, it will cost a12 + 22 + a23 + 22 + a34 + 22=14. If you use the second path twice, it will cost a13 + 22 + a34 + 22=14. However, if you use each path (allowing one unit of fuel go through pipes 1->2, 2->3, 1->3, and two units go through 3->4) it will cost a12 + 12 + a23 + 12 + a13 + 12 + a34 + 22=15 and it is the maximum possible cost.Also note that since no fuel flows from node 1 to node 4, activation cost for that pipe is not added to the answer.
Input21 2 1 2 3
Output1 4
3 seconds
256 megabytes
['brute force', '*2200']
B. Energy exchangetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.InputFirst line of the input contains two integers n and k (1 ≀ n ≀ 10000, 0 ≀ k ≀ 99) β€” number of accumulators and the percent of energy that is lost during transfers.Next line contains n integers a1, a2, ... , an β€” amounts of energy in the first, second, .., n-th accumulator respectively (0 ≀ ai ≀ 1000, 1 ≀ i ≀ n).OutputOutput maximum possible amount of energy that can remain in each of accumulators after the transfers of energy.The absolute or relative error in the answer should not exceed 10 - 6.ExamplesInput3 504 2 1Output2.000000000Input2 901 11Output1.909090909
Input3 504 2 1
Output2.000000000
2 seconds
256 megabytes
['binary search', '*1600']
A. Irrational problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya was given this problem for homework:You are given function (here represents the operation of taking the remainder). His task is to count the number of integers x in range [a;b] with property f(x) = x.It is a pity that Petya forgot the order in which the remainders should be taken and wrote down only 4 numbers. Each of 24 possible orders of taking the remainder has equal probability of being chosen. For example, if Petya has numbers 1, 2, 3, 4 then he can take remainders in that order or first take remainder modulo 4, then modulo 2, 3, 1. There also are 22 other permutations of these numbers that represent orders in which remainder can be taken. In this problem 4 numbers wrote down by Petya will be pairwise distinct.Now it is impossible for Petya to complete the task given by teacher but just for fun he decided to find the number of integers with property that probability that f(x) = x is not less than 31.4159265352718281828459045%. In other words, Petya will pick up the number x if there exist at least 7 permutations of numbers p1, p2, p3, p4, for which f(x) = x.InputFirst line of the input will contain 6 integers, separated by spaces: p1, p2, p3, p4, a, b (1 ≀ p1, p2, p3, p4 ≀ 1000, 0 ≀ a ≀ b ≀ 31415). It is guaranteed that numbers p1, p2, p3, p4 will be pairwise distinct.OutputOutput the number of integers in the given range that have the given property.ExamplesInput2 7 1 8 2 8Output0Input20 30 40 50 0 100Output20Input31 41 59 26 17 43Output9
Input2 7 1 8 2 8
Output0
2 seconds
256 megabytes
['implementation', 'number theory', '*1100']
E. Save the City!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not. Figure 1 Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.InputThe first line of the test case will consist of the number of vertices n (3 ≀ n ≀ 1000).Next n lines will contain the coordinates of the vertices in the clockwise order of the polygon. On the i-th line are integers xi and yi (0 ≀ xi, yi ≀ 106) separated by a space.The endpoints of the fence AB are the first two points, (x1, y1) and (x2, y2).OutputOutput consists of a single line containing the number of points where the watchtower can be set up.ExamplesInput54 88 89 44 00 4Output5Input54 85 85 47 42 2Output0NoteFigure 2 shows the first test case. All the points in the figure are watchable from any point on fence AB. Since, AB has 5 integer coordinates, so answer is 5.For case two, fence CD and DE are not completely visible, thus answer is 0.
Input54 88 89 44 00 4
Output5
1 second
256 megabytes
['geometry', '*2500']
D. Optical Experimenttime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor Phunsuk Wangdu has performed some experiments on rays. The setup for n rays is as follows.There is a rectangular box having exactly n holes on the opposite faces. All rays enter from the holes of the first side and exit from the holes of the other side of the box. Exactly one ray can enter or exit from each hole. The holes are in a straight line. Professor Wangdu is showing his experiment to his students. He shows that there are cases, when all the rays are intersected by every other ray. A curious student asked the professor: "Sir, there are some groups of rays such that all rays in that group intersect every other ray in that group. Can we determine the number of rays in the largest of such groups?".Professor Wangdu now is in trouble and knowing your intellect he asks you to help him.InputThe first line contains n (1 ≀ n ≀ 106), the number of rays. The second line contains n distinct integers. The i-th integer xi (1 ≀ xi ≀ n) shows that the xi-th ray enters from the i-th hole. Similarly, third line contains n distinct integers. The i-th integer yi (1 ≀ yi ≀ n) shows that the yi-th ray exits from the i-th hole. All rays are numbered from 1 to n. OutputOutput contains the only integer which is the number of rays in the largest group of rays all of which intersect each other.ExamplesInput51 4 5 2 33 4 2 1 5Output3Input33 1 22 3 1Output2NoteFor the first test case, the figure is shown above. The output of the first test case is 3, since the rays number 1, 4 and 3 are the ones which are intersected by each other one i.e. 1 is intersected by 4 and 3, 3 is intersected by 4 and 1, and 4 is intersected by 1 and 3. Hence every ray in this group is intersected by each other one. There does not exist any group containing more than 3 rays satisfying the above-mentioned constraint.
Input51 4 5 2 33 4 2 1 5
Output3
5 seconds
256 megabytes
['binary search', 'data structures', 'dp', '*1900']
C. Sequence of Ballstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of balls A by your teacher, each labeled with a lowercase Latin letter 'a'-'z'. You don't like the given sequence. You want to change it into a new sequence, B that suits you better. So, you allow yourself four operations: You can insert any ball with any label into the sequence at any position. You can delete (remove) any ball from any position. You can replace any ball with any other ball. You can exchange (swap) two adjacent balls. Your teacher now places time constraints on each operation, meaning that an operation can only be performed in certain time. So, the first operation takes time ti, the second one takes td, the third one takes tr and the fourth one takes te. Also, it is given that 2Β·te β‰₯ ti + td.Find the minimal time to convert the sequence A to the sequence B.InputThe first line contains four space-separated integers ti, td, tr, te (0 < ti, td, tr, te ≀ 100). The following two lines contain sequences A and B on separate lines. The length of each line is between 1 and 4000 characters inclusive.OutputPrint a single integer representing minimum time to convert A into B.ExamplesInput1 1 1 1youshouldnotthoushaltnotOutput5Input2 4 10 3abbaOutput3Input1 10 20 30azaOutput1NoteIn the second sample, you could delete the ball labeled 'a' from the first position and then insert another 'a' at the new second position with total time 6. However exchanging the balls give total time 3.
Input1 1 1 1youshouldnotthoushaltnot
Output5
1 second
256 megabytes
['dp', '*2600']
B. Restoration of the Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet A = {a1, a2, ..., an} be any permutation of the first n natural numbers {1, 2, ..., n}. You are given a positive integer k and another sequence B = {b1, b2, ..., bn}, where bi is the number of elements aj in A to the left of the element at = i such that aj β‰₯ (i + k).For example, if n = 5, a possible A is {5, 1, 4, 2, 3}. For k = 2, B is given by {1, 2, 1, 0, 0}. But if k = 3, then B = {1, 1, 0, 0, 0}.For two sequences X = {x1, x2, ..., xn} and Y = {y1, y2, ..., yn}, let i-th elements be the first elements such that xi ≠ yi. If xi < yi, then X is lexicographically smaller than Y, while if xi > yi, then X is lexicographically greater than Y.Given n, k and B, you need to determine the lexicographically smallest A.InputThe first line contains two space separated integers n and k (1 ≀ n ≀ 1000, 1 ≀ k ≀ n). On the second line are n integers specifying the values of B = {b1, b2, ..., bn}.OutputPrint on a single line n integers of A = {a1, a2, ..., an} such that A is lexicographically minimal. It is guaranteed that the solution exists.ExamplesInput5 21 2 1 0 0Output4 1 5 2 3 Input4 21 0 0 0Output2 3 1 4
Input5 21 2 1 0 0
Output4 1 5 2 3
1 second
256 megabytes
['greedy', '*1800']
A. Partial Teachertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks they get the same number of toffees. The same procedure is followed for each pair of adjacent students starting from the first one to the last one.It is given that each student receives at least one toffee. You have to find the number of toffees given to each student by the teacher such that the total number of toffees is minimum.InputThe first line of input contains the number of students n (2 ≀ n ≀ 1000). The second line gives (n - 1) characters consisting of "L", "R" and "=". For each pair of adjacent students "L" means that the left student has higher marks, "R" means that the right student has higher marks and "=" means that both have equal marks. OutputOutput consists of n integers separated by a space representing the number of toffees each student receives in the queue starting from the first one to the last one.ExamplesInput5LRLROutput2 1 2 1 2Input5=RRROutput1 1 2 3 4
Input5LRLR
Output2 1 2 1 2
1 second
256 megabytes
['dp', 'graphs', 'greedy', 'implementation', '*1800']
E. Petya and Posttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then he must drive in the given car exactly one round along the circular road and return to the starting post office (the uncle can drive along the circle in any direction, counterclockwise or clockwise). Besides, since the car belongs to the city post, it should also be fuelled with gasoline only at the Post Office stations. The total number of stations equals to n. One can fuel the car at the i-th station with no more than ai liters of gasoline. Besides, one can fuel the car no more than once at each station. Also, the distance between the 1-st and the 2-nd station is b1 kilometers, the distance between the 2-nd and the 3-rd one is b2 kilometers, ..., between the (n - 1)-th and the n-th ones the distance is bn - 1 kilometers and between the n-th and the 1-st one the distance is bn kilometers. Petya's uncle's high-tech car uses only one liter of gasoline per kilometer. It is known that the stations are located so that the sum of all ai is equal to the sum of all bi. The i-th gas station and i-th post office are very close, so the distance between them is 0 kilometers.Thus, it becomes clear that if we start from some post offices, then it is not always possible to drive one round along a circular road. The uncle faces the following problem: to what stations can he go in the morning to be able to ride exactly one circle along the circular road and visit all the post offices that are on it?Petya, who used to attend programming classes, has volunteered to help his uncle, but his knowledge turned out to be not enough, so he asks you to help him write the program that will solve the posed problem.InputThe first line contains integer n (1 ≀ n ≀ 105). The second line contains n integers ai β€” amount of gasoline on the i-th station. The third line contains n integers b1, b2, ..., bn. They are the distances between the 1-st and the 2-nd gas stations, between the 2-nd and the 3-rd ones, ..., between the n-th and the 1-st ones, respectively. The sum of all bi equals to the sum of all ai and is no more than 109. Each of the numbers ai, bi is no less than 1 and no more than 109.OutputPrint on the first line the number k β€” the number of possible post offices, from which the car can drive one circle along a circular road. Print on the second line k numbers in the ascending order β€” the numbers of offices, from which the car can start.ExamplesInput41 7 2 38 1 1 3Output22 4Input81 2 1 2 1 2 1 22 1 2 1 2 1 2 1Output81 2 3 4 5 6 7 8
Input41 7 2 38 1 1 3
Output22 4
2 seconds
256 megabytes
['data structures', 'dp', '*2000']
D. Petya and His Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya has a birthday soon. Due this wonderful event, Petya's friends decided to give him sweets. The total number of Petya's friends equals to n.Let us remind you the definition of the greatest common divisor: GCD(a1, ..., ak) = d, where d represents such a maximal positive number that each ai (1 ≀ i ≀ k) is evenly divisible by d. At that, we assume that all ai's are greater than zero.Knowing that Petya is keen on programming, his friends has agreed beforehand that the 1-st friend gives a1 sweets, the 2-nd one gives a2 sweets, ..., the n-th one gives an sweets. At the same time, for any i and j (1 ≀ i, j ≀ n) they want the GCD(ai, aj) not to be equal to 1. However, they also want the following condition to be satisfied: GCD(a1, a2, ..., an) = 1. One more: all the ai should be distinct.Help the friends to choose the suitable numbers a1, ..., an.InputThe first line contains an integer n (2 ≀ n ≀ 50).OutputIf there is no answer, print "-1" without quotes. Otherwise print a set of n distinct positive numbers a1, a2, ..., an. Each line must contain one number. Each number must consist of not more than 100 digits, and must not contain any leading zeros. If there are several solutions to that problem, print any of them.Do not forget, please, that all of the following conditions must be true: For every i and j (1 ≀ i, j ≀ n): GCD(ai, aj) ≠ 1 GCD(a1, a2, ..., an) = 1 For every i and j (1 ≀ i, j ≀ n, i ≠ j): ai ≠ aj Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).ExamplesInput3Output995511115Input4Output3853607928360
Input3
Output995511115
2 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1700']
C. Petya and File Systemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, on a programming lesson little Petya showed how quickly he can create files and folders on the computer. But he got soon fed up with this activity, and he decided to do a much more useful thing. He decided to calculate what folder contains most subfolders (including nested folders, nested folders of nested folders, and so on) and what folder contains most files (including the files in the subfolders).More formally, the subfolders of the folder are all its directly nested folders and the subfolders of these nested folders. The given folder is not considered the subfolder of itself. A file is regarded as lying in a folder, if and only if it either lies directly in this folder, or lies in some subfolder of the folder.For a better understanding of how to count subfolders and files for calculating the answer, see notes and answers to the samples.You are given a few files that Petya has managed to create. The path to each file looks as follows:diskName:\folder1\folder2\...\ foldern\fileName diskName is single capital letter from the set {C,D,E,F,G}. folder1, ..., foldern are folder names. Each folder name is nonempty sequence of lowercase Latin letters and digits from 0 to 9. (n β‰₯ 1) fileName is a file name in the form of name.extension, where the name and the extension are nonempty sequences of lowercase Latin letters and digits from 0 to 9. It is also known that there is no file whose path looks like diskName:\fileName. That is, each file is stored in some folder, but there are no files directly in the root. Also let us assume that the disk root is not a folder.Help Petya to find the largest number of subfolders, which can be in some folder, and the largest number of files that can be in some folder, counting all its subfolders.InputEach line of input data contains the description of one file path. The length of each line does not exceed 100, and overall there are no more than 100 lines. It is guaranteed, that all the paths are correct and meet the above rules. It is also guaranteed, that there are no two completely equal lines. That is, each file is described exactly once.There is at least one line in the input data.OutputPrint two space-separated numbers. The first one is the maximal number of possible subfolders in a folder (including nested folders, nested folders of nested folders, and so on). The second one is the maximal number of files in a folder (including nested files in subfolders). Note that the disks are not regarded as folders.ExamplesInputC:\folder1\file1.txtOutput0 1InputC:\folder1\folder2\folder3\file1.txtC:\folder1\folder2\folder4\file1.txtD:\folder1\file1.txtOutput3 2InputC:\file\file\file\file\file.txtC:\file\file\file\file2\file.txtOutput4 2NoteIn the first sample we have one folder on the "C" disk. It has no subfolders, which is why the first number in the answer is 0. But this folder contains one file, so the second number of the answer is 1.In the second sample we have several different folders. Consider the "folder1" folder on the "C" disk. This folder directly contains one folder, "folder2". The "folder2" folder contains two more folders β€” "folder3" and "folder4". Thus, the "folder1" folder on the "C" drive has exactly 3 subfolders. Also this folder contains two files, even though they do not lie directly in the folder, but they are located in subfolders of "folder1".In the third example we see that the names of some folders and some subfolders are identical. Consider the "file" folder, which lies directly on the "C" disk. That folder contains another "file" folder, which in turn contains another "file" folder, which contains two more folders, "file" and "file2". Thus, the "file" folder, which lies directly on the "C" disk, contains 4 subfolders.
InputC:\folder1\file1.txt
Output0 1
3 seconds
256 megabytes
['data structures', 'implementation', '*1800']
B. Petya and Countrysidetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture: As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him. InputThe first line contains a positive integer n (1 ≀ n ≀ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.OutputPrint a single number, the maximal number of watered sections if we create artificial rain above exactly one section.ExamplesInput12Output1Input51 2 1 2 1Output3Input81 2 1 1 1 3 3 4Output6
Input12
Output1
2 seconds
256 megabytes
['brute force', 'implementation', '*1100']
A. Petya and Javatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Petya has recently started attending a programming club. Naturally he is facing the problem of choosing a programming language. After long considerations he realized that Java is the best choice. The main argument in favor of choosing Java was that it has a very large integer data type, called BigInteger.But having attended several classes of the club, Petya realized that not all tasks require using the BigInteger type. It turned out that in some tasks it is much easier to use small data types. That's why a question arises: "Which integer type to use if one wants to store a positive integer n?"Petya knows only 5 integer types:1) byte occupies 1 byte and allows you to store numbers from  - 128 to 1272) short occupies 2 bytes and allows you to store numbers from  - 32768 to 327673) int occupies 4 bytes and allows you to store numbers from  - 2147483648 to 21474836474) long occupies 8 bytes and allows you to store numbers from  - 9223372036854775808 to 92233720368547758075) BigInteger can store any integer number, but at that it is not a primitive type, and operations with it are much slower.For all the types given above the boundary values are included in the value range.From this list, Petya wants to choose the smallest type that can store a positive integer n. Since BigInteger works much slower, Peter regards it last. Help him.InputThe first line contains a positive number n. It consists of no more than 100 digits and doesn't contain any leading zeros. The number n can't be represented as an empty string.Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preffered to use cout (also you may use %I64d).OutputPrint the first type from the list "byte, short, int, long, BigInteger", that can store the natural number n, in accordance with the data given above.ExamplesInput127OutputbyteInput130OutputshortInput123456789101112131415161718192021222324OutputBigInteger
Input127
Outputbyte
2 seconds
256 megabytes
['implementation', 'strings', '*1300']
E. Harry Potter and Moving Staircasestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHarry Potter lost his Invisibility Cloak, running from the school caretaker Filch. Finding an invisible object is not an easy task. Fortunately, Harry has friends who are willing to help. Hermione Granger had read "The Invisibility Cloaks, and Everything about Them", as well as six volumes of "The Encyclopedia of Quick Search of Shortest Paths in Graphs, Network Flows, the Maximal Increasing Subsequences and Other Magical Objects". She has already developed a search algorithm for the invisibility cloak in complex dynamic systems (Hogwarts is one of them).Hogwarts consists of n floors, numbered by integers from 1 to n. Some pairs of floors are connected by staircases. The staircases may change its position, moving exactly one end. Formally the situation is like this: if a staircase connects the floors a and b, then in one move it may modify its position so as to connect the floors a and c or b and c, where c is any floor different from a and b. Under no circumstances the staircase can connect a floor with itself. At the same time there can be multiple stairs between a pair of floors.Initially, Harry is on the floor with the number 1. He does not remember on what floor he has lost the cloak and wants to look for it on each of the floors. Therefore, his goal is to visit each of n floors at least once. Harry can visit the floors in any order and finish the searching at any floor.Nowadays the staircases move quite rarely. However, Ron and Hermione are willing to put a spell on any of them to help Harry find the cloak. To cause less suspicion, the three friends plan to move the staircases one by one, and no more than once for each staircase. In between shifting the staircases Harry will be able to move about the floors, reachable at the moment from the staircases, and look for his Invisibility Cloak. It is assumed that during all this time the staircases will not move spontaneously.Help the three friends to compose a searching plan. If there are several variants to solve the problem, any valid option (not necessarily the optimal one) will be accepted.InputThe first line contains integers n and m (1 ≀ n ≀ 100000, 0 ≀ m ≀ 200000), which are the number of floors and staircases in Hogwarts, respectively. The following m lines contain pairs of floors connected by staircases at the initial moment of time.OutputIn the first line print "YES" (without the quotes) if Harry is able to search all the floors, and "NO" otherwise. If the answer is positive, then print on the second line the number of staircases that Ron and Hermione will have to shift. Further output should look like this:Harry's moves a staircase's move Harry's movesa staircase's move...a staircase's moveHarry's movesEach "Harry's move" should be represented as a list of floors in the order in which they have been visited. The total amount of elements of these lists must not exceed 106. When you print each list, first print the number of elements in it, and then in the same line print the actual space-separated elements. The first number in the first list should be the number 1 (the floor, from which Harry begins to search). Any list except the first one might contain the zero number of elements. Note that Harry can visit some floors again, but must visit all n floors at least once. Two consecutively visited floors must be directly connected by a staircase (at the time Harry goes from one of them to the other one). No two floors that are visited consequtively can be equal.In the description of a "staircase's move" indicate the number of staircase (the staircases are numbered from 1 to m in the order in which they are given in the input data) and its new location (two numbers of the connected floors in any order).Any staircase can be moved at most once. If there are several solutions, output any.ExamplesInput6 41 21 32 34 5OutputYES23 1 2 32 3 53 5 4 54 5 63 6 5 3Input4 11 2OutputNOInput5 51 21 33 43 54 5OutputYES06 1 2 1 3 4 5
Input6 41 21 32 34 5
OutputYES23 1 2 32 3 53 5 4 54 5 63 6 5 3
2 seconds
256 megabytes
['dfs and similar', 'implementation', '*2900']
D. Harry Potter and the Sorting Hattime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones β€” to Ravenclaw, the persistent and honest ones β€” to Hufflepuff and the clever and cunning ones β€” to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far. Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.InputThe first input line contains an integer n (1 ≀ n ≀ 10000). It is the number of students who are in the list before Hermione. The next line contains n symbols. If all the relatives of a student used to study in the same house, then the i-th character in the string coincides with the first letter of the name of this house. Otherwise, the i-th symbol is equal to "?".OutputPrint all the possible houses where Hermione can be sent. The names of the houses should be printed in the alphabetical order, one per line.ExamplesInput11G????SS???HOutputGryffindorRavenclawInput2H?OutputGryffindorRavenclawSlytherinNoteConsider the second example. There are only two students before Hermione. The first student is sent to Hufflepuff. The second disciple is given the choice between the houses where the least number of students has been sent, i.e. Gryffindor, Slytherin and Ravenclaw. If he chooses Gryffindor, Hermione is forced to choose between Ravenclaw and Slytherin, if he chooses Ravenclaw, Hermione will choose between Gryffindor and Slytherin, if he chooses Slytherin, Hermione will choose between Gryffindor and Ravenclaw. In the end, the following situation is possible (it depends on the choice of the second student and Hermione). Hermione will end up 1) in Gryffindor, 2) in Ravenclaw, 3) in Slytherin. Note that, despite the fact that in neither case Hermione will be given a choice between all the three options, they are all possible and they should all be printed in the answer. Hermione will not, under any circumstances, end up in Hufflepuff.
Input11G????SS???H
OutputGryffindorRavenclaw
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'hashing', '*2200']
C. Harry Potter and the Golden Snitchtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBrothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.InputThe first line contains a single integer n (1 ≀ n ≀ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≀ vp.OutputIf Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO".ExamplesInput40 0 00 10 010 10 010 0 00 0 01 15 5 25OutputYES25.500000000010.0000000000 4.5000000000 0.0000000000Input40 0 00 10 010 10 010 0 00 0 01 15 5 50OutputNOInput11 2 34 5 620 101 2 3OutputYES0.00000000001.0000000000 2.0000000000 3.0000000000
Input40 0 00 10 010 10 010 0 00 0 01 15 5 25
OutputYES25.500000000010.0000000000 4.5000000000 0.0000000000
2 seconds
256 megabytes
['binary search', 'geometry', '*2100']
B. Harry Potter and the History of Magictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has a soporific effect even on the quill. That's why the quill often makes mistakes, especially in dates.So, at the end of the semester Professor Binns decided to collect the students' parchments with notes and check them. Ron Weasley is in a panic: Harry's notes may contain errors, but at least he has some notes, whereas Ron does not have any. Ronald also has been sleeping during the lectures and his quill had been eaten by his rat Scabbers. Hermione Granger refused to give Ron her notes, because, in her opinion, everyone should learn on their own. Therefore, Ron has no choice but to copy Harry's notes.Due to the quill's errors Harry's dates are absolutely confused: the years of goblin rebellions and other important events for the wizarding world do not follow in order, and sometimes even dates from the future occur. Now Ron wants to change some of the digits while he copies the notes so that the dates were in the chronological (i.e. non-decreasing) order and so that the notes did not have any dates strictly later than 2011, or strictly before than 1000. To make the resulting sequence as close as possible to the one dictated by Professor Binns, Ron will change no more than one digit in each date into other digit. Help him do it.InputThe first input line contains an integer n (1 ≀ n ≀ 1000). It represents the number of dates in Harry's notes. Next n lines contain the actual dates y1, y2, ..., yn, each line contains a date. Each date is a four-digit integer (1000 ≀ yi ≀ 9999).OutputPrint n numbers z1, z2, ..., zn (1000 ≀ zi ≀ 2011). They are Ron's resulting dates. Print each number on a single line. Numbers zi must form the non-decreasing sequence. Each number zi should differ from the corresponding date yi in no more than one digit. It is not allowed to change the first digit of a number into 0. If there are several possible solutions, print any of them. If there's no solution, print "No solution" (without the quotes).ExamplesInput3187519361721Output183518361921Input49999200030003011Output1999200020002011Input3199950552000OutputNo solution
Input3187519361721
Output183518361921
1 second
256 megabytes
['brute force', 'greedy', 'implementation', '*1700']
A. Harry Potter and Three Spellstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago (probably even in the first book), Nicholas Flamel, a great alchemist and the creator of the Philosopher's Stone, taught Harry Potter three useful spells. The first one allows you to convert a grams of sand into b grams of lead, the second one allows you to convert c grams of lead into d grams of gold and third one allows you to convert e grams of gold into f grams of sand. When Harry told his friends about these spells, Ron Weasley was amazed. After all, if they succeed in turning sand into lead, lead into gold, and then turning part of the gold into sand again and so on, then it will be possible to start with a small amount of sand and get huge amounts of gold! Even an infinite amount of gold! Hermione Granger, by contrast, was skeptical about that idea. She argues that according to the law of conservation of matter getting an infinite amount of matter, even using magic, is impossible. On the contrary, the amount of matter may even decrease during transformation, being converted to magical energy. Though Hermione's theory seems convincing, Ron won't believe her. As far as Ron is concerned, Hermione made up her law of conservation of matter to stop Harry and Ron wasting their time with this nonsense, and to make them go and do homework instead. That's why Ron has already collected a certain amount of sand for the experiments. A quarrel between the friends seems unavoidable...Help Harry to determine which one of his friends is right, and avoid the quarrel after all. To do this you have to figure out whether it is possible to get the amount of gold greater than any preassigned number from some finite amount of sand.InputThe first line contains 6 integers a, b, c, d, e, f (0 ≀ a, b, c, d, e, f ≀ 1000).OutputPrint "Ron", if it is possible to get an infinitely large amount of gold having a certain finite amount of sand (and not having any gold and lead at all), i.e., Ron is right. Otherwise, print "Hermione".ExamplesInput100 200 250 150 200 250OutputRonInput100 50 50 200 200 100OutputHermioneInput100 10 200 20 300 30OutputHermioneInput0 0 0 0 0 0OutputHermioneInput1 1 0 1 1 1OutputRonInput1 0 1 2 1 2OutputHermioneInput100 1 100 1 0 1OutputRonNoteConsider the first sample. Let's start with the 500 grams of sand. Apply the first spell 5 times and turn the sand into 1000 grams of lead. Then apply the second spell 4 times to get 600 grams of gold. Let’s take 400 grams from the resulting amount of gold turn them back into sand. We get 500 grams of sand and 200 grams of gold. If we apply the same operations to 500 grams of sand again, we can get extra 200 grams of gold every time. Thus, you can get 200, 400, 600 etc. grams of gold, i.e., starting with a finite amount of sand (500 grams), you can get the amount of gold which is greater than any preassigned number.In the forth sample it is impossible to get sand, or lead, or gold, applying the spells.In the fifth sample an infinitely large amount of gold can be obtained by using only the second spell, which allows you to receive 1 gram of gold out of nothing. Note that if such a second spell is available, then the first and the third one do not affect the answer at all.The seventh sample is more interesting. We can also start with a zero amount of sand there. With the aid of the third spell you can get sand out of nothing. We get 10000 grams of sand in this manner. Let's get 100 grams of lead using the first spell 100 times. Then make 1 gram of gold from them. We managed to receive 1 gram of gold, starting with a zero amount of sand! Clearly, in this manner you can get an infinitely large amount of gold.
Input100 200 250 150 200 250
OutputRon
2 seconds
256 megabytes
['implementation', 'math', '*1800']