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. Hamsters and Tigerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday there is going to be an unusual performance at the circus β€” hamsters and tigers will perform together! All of them stand in circle along the arena edge and now the trainer faces a difficult task: he wants to swap the animals' positions so that all the hamsters stood together and all the tigers also stood together. The trainer swaps the animals in pairs not to create a mess. He orders two animals to step out of the circle and swap places. As hamsters feel highly uncomfortable when tigers are nearby as well as tigers get nervous when there's so much potential prey around (consisting not only of hamsters but also of yummier spectators), the trainer wants to spend as little time as possible moving the animals, i.e. he wants to achieve it with the minimal number of swaps. Your task is to help him.InputThe first line contains number n (2 ≀ n ≀ 1000) which indicates the total number of animals in the arena. The second line contains the description of the animals' positions. The line consists of n symbols "H" and "T". The "H"s correspond to hamsters and the "T"s correspond to tigers. It is guaranteed that at least one hamster and one tiger are present on the arena. The animals are given in the order in which they are located circle-wise, in addition, the last animal stands near the first one.OutputPrint the single number which is the minimal number of swaps that let the trainer to achieve his goal.ExamplesInput3HTHOutput0Input9HTHTHTHHTOutput2NoteIn the first example we shouldn't move anybody because the animals of each species already stand apart from the other species. In the second example you may swap, for example, the tiger in position 2 with the hamster in position 5 and then β€” the tiger in position 9 with the hamster in position 7.
Input3HTH
Output0
2 seconds
256 megabytes
['two pointers', '*1600']
B. T-shirts from Sponsortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day a well-known sponsor of a well-known contest decided to give every participant of the contest a T-shirt as a present. A natural problem occurred: on the one hand, it is not clear how many T-shirts of what sizes should be ordered, and on the other hand, one doesn't want to order too many T-shirts (and we do not exactly paper the walls with the oversupply). After considerable brain racking and some pre-estimating, the sponsor representatives ordered a certain number of T-shirts of sizes S, M, L, XL and XXL. The T-shirts turned out to bring good luck, that's why on the contest day there built up a line of K participants willing to get one. Every contestant is characterized by his/her desired T-shirt size (so it happens that for all the participants it is also one of the sizes S, M, L, XL and XXL). The participants come up to get a T-shirt one by one and try to choose the most suitable one, choosing it like this. If there is still a T-shirt of the optimal size left, that he/she takes it without further ado. Otherwise the contestant would prefer to choose a T-shirt with the size as close to the optimal one as possible (the distance between neighboring sizes is considered equal to one). If the variant of choice is not unique, the contestant will take a T-shirt of a bigger size (in case he/she grows more). For example, for a person whose optimal size is L the preference list looks like this: L, XL, M, XXL, S. Using the data on how many T-shirts of every size had been ordered by the organizers, on the size of contestants in the line determine who got a T-shirt of what size.InputThe first line contains five non-negative integers NS, NM, NL, NXL, NXXL not exceeding 1000 which represent the number of T-shirts of the corresponding sizes. The second line contains an integer K (1 ≀ K ≀ 1000) which represents the number of participants. The next K lines contain the optimal T-shirt sizes for the contestants. The sizes are given in the order in which the participants stand in the line. It is guaranteed that NS + NM + NL + NXL + NXXL β‰₯ K.OutputFor each contestant, print a line containing the size of the T-shirt he/she got.ExamplesInput1 0 2 0 13XLXXLMOutputXXLLL
Input1 0 2 0 13XLXXLM
OutputXXLLL
2 seconds
256 megabytes
['implementation', '*1100']
A. Ball Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count. The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is holding the ball. First the first child throws the ball to the next one clockwise, i.e. to the child number 2. Then the child number 2 throws the ball to the next but one child, i.e. to the child number 4, then the fourth child throws the ball to the child that stands two children away from him, i.e. to the child number 7, then the ball is thrown to the child who stands 3 children away from the child number 7, then the ball is thrown to the child who stands 4 children away from the last one, and so on. It should be mentioned that when a ball is thrown it may pass the beginning of the circle. For example, if n = 5, then after the third throw the child number 2 has the ball again. Overall, n - 1 throws are made, and the game ends.The problem is that not all the children get the ball during the game. If a child doesn't get the ball, he gets very upset and cries until Natalia Pavlovna gives him a candy. That's why Natalia Pavlovna asks you to help her to identify the numbers of the children who will get the ball after each throw.InputThe first line contains integer n (2 ≀ n ≀ 100) which indicates the number of kids in the circle.OutputIn the single line print n - 1 numbers which are the numbers of children who will get the ball after each throw. Separate the numbers by spaces.ExamplesInput10Output2 4 7 1 6 2 9 7 6Input3Output2 1
Input10
Output2 4 7 1 6 2 9 7 6
2 seconds
256 megabytes
['brute force', 'implementation', '*800']
J. Planting Treestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into n × m squares and decided to plant a forest there. Vasya will plant nm trees of all different heights from 1 to nm. For his forest to look more natural he wants any two trees growing in the side neighbouring squares to have the absolute value of difference in heights to be strictly more than 1. Help Vasya: make the plan of the forest planting for which this condition is fulfilled.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100) β€” the number of rows and columns on Vasya's fieldOutputIf there's no solution, print -1. Otherwise, print n lines containing m numbers each β€” the trees' planting plan. In every square of the plan the height of a tree that should be planted on this square should be written. If there are several solutions to that problem, print any of them.ExamplesInput2 3Output3 6 25 1 4Input2 1Output-1
Input2 3
Output3 6 25 1 4
2 seconds
256 megabytes
['constructive algorithms', '*1800']
I. TCMCF+++time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has gotten interested in programming contests in TCMCF+++ rules. On the contest n problems were suggested and every problem had a cost β€” a certain integral number of points (perhaps, negative or even equal to zero). According to TCMCF+++ rules, only accepted problems can earn points and the overall number of points of a contestant was equal to the product of the costs of all the problems he/she had completed. If a person didn't solve anything, then he/she didn't even appear in final standings and wasn't considered as participant. Vasya understood that to get the maximal number of points it is not always useful to solve all the problems. Unfortunately, he understood it only after the contest was finished. Now he asks you to help him: find out what problems he had to solve to earn the maximal number of points.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of the suggested problems. The next line contains n space-separated integers ci ( - 100 ≀ ci ≀ 100) β€” the cost of the i-th task. The tasks' costs may coinсide.OutputPrint space-separated the costs of the problems that needed to be solved to get the maximal possible number of points. Do not forget, please, that it was necessary to solve at least one problem. If there are several solutions to that problem, print any of them.ExamplesInput51 2 -3 3 3Output3 1 2 3 Input13100 100 100 100 100 100 100 100 100 100 100 100 100Output100 100 100 100 100 100 100 100 100 100 100 100 100 Input4-2 -2 -2 -2Output-2 -2 -2 -2
Input51 2 -3 3 3
Output3 1 2 3
2 seconds
256 megabytes
['greedy', '*1400']
H. Road Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions. The city administration noticed that in the cities of all the developed countries between any two roads one can drive along at least two paths so that the paths don't share any roads (but they may share the same junction). The administration decided to add the minimal number of roads so that this rules was fulfilled in the Berland capital as well. In the city road network should exist no more than one road between every pair of junctions before or after the reform.InputThe first input line contains a pair of integers n, m (2 ≀ n ≀ 900, 1 ≀ m ≀ 100000), where n is the number of junctions and m is the number of roads. Each of the following m lines contains a description of a road that is given by the numbers of the connected junctions ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi). The junctions are numbered from 1 to n. It is possible to reach any junction of the city from any other one moving along roads.OutputOn the first line print t β€” the number of added roads. Then on t lines print the descriptions of the added roads in the format of the input data. You can use any order of printing the roads themselves as well as the junctions linked by every road. If there are several solutions to that problem, print any of them.If the capital doesn't need the reform, print the single number 0.If there's no solution, print the single number -1.ExamplesInput4 31 22 33 4Output11 4Input4 41 22 32 43 4Output11 3
Input4 31 22 33 4
Output11 4
3 seconds
256 megabytes
['graphs', '*2100']
G. Prime Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland prime numbers are fashionable β€” the respectable citizens dwell only on the floors with numbers that are prime numbers. The numismatists value particularly high the coins with prime nominal values. All the prime days are announced holidays!Yet even this is not enough to make the Berland people happy. On the main street of the capital stand n houses, numbered from 1 to n. The government decided to paint every house a color so that the sum of the numbers of the houses painted every color is a prime number.However it turned out that not all the citizens approve of this decision β€” many of them protest because they don't want many colored houses on the capital's main street. That's why it is decided to use the minimal possible number of colors. The houses don't have to be painted consecutively, but every one of n houses should be painted some color. The one-colored houses should not stand consecutively, any way of painting is acceptable.There are no more than 5 hours left before the start of painting, help the government find the way when the sum of house numbers for every color is a prime number and the number of used colors is minimal. InputThe single input line contains an integer n (2 ≀ n ≀ 6000) β€” the number of houses on the main streets of the capital.OutputPrint the sequence of n numbers, where the i-th number stands for the number of color for house number i. Number the colors consecutively starting from 1. Any painting order is allowed. If there are several solutions to that problem, print any of them. If there's no such way of painting print the single number -1.ExamplesInput8Output1 2 2 1 1 1 1 2
Input8
Output1 2 2 1 1 1 1 2
1 second
256 megabytes
['number theory', '*2200']
F. Goats and Wolvestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Vasya needed to transport m goats and m wolves from riverbank to the other as quickly as possible. The boat can hold n animals and Vasya, in addition, he is permitted to put less than n animals in the boat. If in one place (on one of the banks or in the boat) the wolves happen to strictly outnumber the goats, then the wolves eat the goats and Vasya gets upset. When Vasya swims on the boat from one shore to the other, he must take at least one animal to accompany him, otherwise he will get bored and he will, yet again, feel upset. When the boat reaches the bank, first all the animals get off simultaneously, and then the animals chosen by Vasya simultaneously get on the boat. That means that at the moment when the animals that have just arrived have already got off and the animals that are going to leave haven't yet got on, somebody might eat someone. Vasya needs to transport all the animals from one river bank to the other so that nobody eats anyone and Vasya doesn't get upset. What is the minimal number of times he will have to cross the river?InputThe first line contains two space-separated numbers m and n (1 ≀ m, n ≀ 105) β€” the number of animals and the boat's capacity.OutputIf it is impossible to transport all the animals so that no one got upset, and all the goats survived, print -1. Otherwise print the single number β€” how many times Vasya will have to cross the river.ExamplesInput3 2Output11Input33 3Output-1NoteThe first sample match to well-known problem for children.
Input3 2
Output11
2 seconds
256 megabytes
['greedy', '*2500']
E. Directortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a born Berland film director, he is currently working on a new blockbuster, "The Unexpected". Vasya knows from his own experience how important it is to choose the main characters' names and surnames wisely. He made up a list of n names and n surnames that he wants to use. Vasya haven't decided yet how to call characters, so he is free to match any name to any surname. Now he has to make the list of all the main characters in the following format: "Name1 Surname1, Name2 Surname2, ..., Namen Surnamen", i.e. all the name-surname pairs should be separated by exactly one comma and exactly one space, and the name should be separated from the surname by exactly one space. First of all Vasya wants to maximize the number of the pairs, in which the name and the surname start from one letter. If there are several such variants, Vasya wants to get the lexicographically minimal one. Help him.An answer will be verified a line in the format as is shown above, including the needed commas and spaces. It's the lexicographical minimality of such a line that needs to be ensured. The output line shouldn't end with a space or with a comma.InputThe first input line contains number n (1 ≀ n ≀ 100) β€” the number of names and surnames. Then follow n lines β€” the list of names. Then follow n lines β€” the list of surnames. No two from those 2n strings match. Every name and surname is a non-empty string consisting of no more than 10 Latin letters. It is guaranteed that the first letter is uppercase and the rest are lowercase.OutputThe output data consist of a single line β€” the needed list. Note that one should follow closely the output data format!ExamplesInput4AnnAnnaSabrinaJohnPetrovIvanovaStoltzAbacabaOutputAnn Abacaba, Anna Ivanova, John Petrov, Sabrina StoltzInput4AaAbAcBaAdAeBbBcOutputAa Ad, Ab Ae, Ac Bb, Ba Bc
Input4AnnAnnaSabrinaJohnPetrovIvanovaStoltzAbacaba
OutputAnn Abacaba, Anna Ivanova, John Petrov, Sabrina Stoltz
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
D. Event Datestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such n dates of famous events that will fulfill both conditions. It is guaranteed that it is possible.InputThe first line contains one integer n (1 ≀ n ≀ 100) β€” the number of known events. Then follow n lines containing two integers li and ri each (1 ≀ li ≀ ri ≀ 107) β€” the earliest acceptable date and the latest acceptable date of the i-th event.OutputPrint n numbers β€” the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists.ExamplesInput31 22 33 4Output1 2 3 Input21 31 3Output1 2
Input31 22 33 4
Output1 2 3
2 seconds
256 megabytes
['greedy', 'meet-in-the-middle', 'sortings', '*1900']
C. Dancing Lessonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people taking dancing lessons. Every person is characterized by his/her dancing skill ai. At the beginning of the lesson they line up from left to right. While there is at least one couple of a boy and a girl in the line, the following process is repeated: the boy and girl who stand next to each other, having the minimal difference in dancing skills start to dance. If there are several such couples, the one first from the left starts to dance. After a couple leaves to dance, the line closes again, i.e. as a result the line is always continuous. The difference in dancing skills is understood as the absolute value of difference of ai variable. Your task is to find out what pairs and in what order will start dancing.InputThe first line contains an integer n (1 ≀ n ≀ 2Β·105) β€” the number of people. The next line contains n symbols B or G without spaces. B stands for a boy, G stands for a girl. The third line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the dancing skill. People are specified from left to right in the order in which they lined up.OutputPrint the resulting number of couples k. Then print k lines containing two numerals each β€” the numbers of people forming the couple. The people are numbered with integers from 1 to n from left to right. When a couple leaves to dance you shouldn't renumber the people. The numbers in one couple should be sorted in the increasing order. Print the couples in the order in which they leave to dance.ExamplesInput4BGBG4 2 4 3Output23 41 2Input4BBGG4 6 1 5Output22 31 4Input4BGBB1 1 2 3Output11 2
Input4BGBG4 2 4 3
Output23 41 2
2 seconds
256 megabytes
['data structures', '*1900']
B. Schooltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students studying in the 6th grade, in group "B" of a berland secondary school. Every one of them has exactly one friend whom he calls when he has some news. Let us denote the friend of the person number i by g(i). Note that the friendships are not mutual, i.e. g(g(i)) is not necessarily equal to i.On day i the person numbered as ai learns the news with the rating of bi (bi β‰₯ 1). He phones the friend immediately and tells it. While he is doing it, the news becomes old and its rating falls a little and becomes equal to bi - 1. The friend does the same thing β€” he also calls his friend and also tells the news. The friend of the friend gets the news already rated as bi - 2. It all continues until the rating of the news reaches zero as nobody wants to tell the news with zero rating. More formally, everybody acts like this: if a person x learns the news with a non-zero rating y, he calls his friend g(i) and his friend learns the news with the rating of y - 1 and, if it is possible, continues the process.Let us note that during a day one and the same person may call his friend and tell him one and the same news with different ratings. Thus, the news with the rating of bi will lead to as much as bi calls.Your task is to count the values of resi β€” how many students learned their first news on day i.The values of bi are known initially, whereas ai is determined from the following formula: where mod stands for the operation of taking the excess from the cleavage, res0 is considered equal to zero and vi β€” some given integers.InputThe first line contains two space-separated integers n and m (2 ≀ n, m ≀ 105) β€” the number of students and the number of days. The second line contains n space-separated integers g(i) (1 ≀ g(i) ≀ n, g(i) ≠ i) β€” the number of a friend of the i-th student. The third line contains m space-separated integers vi (1 ≀ vi ≀ 107). The fourth line contains m space-separated integers bi (1 ≀ bi ≀ 107).OutputPrint m lines containing one number each. The i-th line should contain resi β€” for what number of students the first news they've learned over the m days in question, was the news number i. The number of the news is the number of the day on which it can be learned. The days are numbered starting from one in the order in which they are given in the input file. Don't output res0.ExamplesInput3 42 3 11 2 3 41 2 3 4Output1110Input8 67 6 4 2 3 5 5 710 4 3 8 9 11 1 1 2 2 2Output111211
Input3 42 3 11 2 3 41 2 3 4
Output1110
2 seconds
256 megabytes
['dp', 'dsu', '*2200']
A. Codecraft IIItime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand that.All the twelve months in Vasya's calendar are named using their usual English names: January, February, March, April, May, June, July, August, September, October, November, December.InputThe first input line contains the name of the current month. It is guaranteed that it is a proper English name of one of twelve months. The first letter is uppercase, the rest are lowercase. The second line contains integer k (0 ≀ k ≀ 100) β€” the number of months left till the appearance of Codecraft III.OutputPrint starting from an uppercase letter the name of the month in which the continuation of Codeforces II will appear. The printed name must be contained in the list January, February, March, April, May, June, July, August, September, October, November, December.ExamplesInputNovember3OutputFebruaryInputMay24OutputMay
InputNovember3
OutputFebruary
2 seconds
256 megabytes
['implementation', '*900']
J. Triminoestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are many interesting tasks on domino tilings. For example, an interesting fact is known. Let us take a standard chessboard (8 × 8) and cut exactly two squares out of it. It turns out that the resulting board can always be tiled using dominoes 1 × 2, if the two cut out squares are of the same color, otherwise it is impossible. Petya grew bored with dominoes, that's why he took a chessboard (not necessarily 8 × 8), cut some squares out of it and tries to tile it using triminoes. Triminoes are reactangles 1 × 3 (or 3 × 1, because triminoes can be rotated freely), also the two extreme squares of a trimino are necessarily white and the square in the middle is black. The triminoes are allowed to put on the chessboard so that their squares matched the colors of the uncut squares of the chessboard, and also the colors must match: the black squares must be matched with the black ones only and the white ones β€” with the white squares. The triminoes must not protrude above the chessboard or overlap each other. All the uncut squares of the board must be covered with triminoes. Help Petya find out if it is possible to tile his board using triminos in the described way and print one of the variants of tiling.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 1000) β€” the board size. Next n lines contain m symbols each and represent the board description. If some position contains ".", then the square in this position has been cut out. Symbol "w" stands for a white square, "b" stands for a black square. It is guaranteed that through adding the cut squares can result in a correct chessboard (i.e. with alternating black and white squares), thought, perhaps, of a non-standard size.OutputIf at least one correct tiling exists, in the first line print "YES" (without quotes), and then β€” the tiling description. The description must contain n lines, m symbols in each. The cut out squares, as well as in the input data, are marked by ".". To denote triminoes symbols "a", "b", "c", "d" can be used, and all the three squares of each trimino must be denoted by the same symbol. If two triminoes share a side, than they must be denoted by different symbols. Two triminoes not sharing a common side can be denoted by one and the same symbol (c.f. sample).If there are multiple correct ways of tiling, it is allowed to print any. If it is impossible to tile the board using triminoes or the correct tiling, for which four symbols "a", "b", "c", "d" would be enough, doesn't exist, print "NO" (without quotes) in the first line.ExamplesInput6 10.w.wbw.wbwwbwbw.w.w.bw.wbwbwbww.wbw.wbwb...wbw.w.w..wbw.wbw.OutputYES.a.aaa.cccbaccc.c.a.ba.dddcbabb.aaa.cbab...bbb.b.b..ccc.ddd.Input2 2wbbwOutputNOInput1 3wbwOutputYESbbbInput1 3...OutputYES...
Input6 10.w.wbw.wbwwbwbw.w.w.bw.wbwbwbww.wbw.wbwb...wbw.w.w..wbw.wbw.
OutputYES.a.aaa.cccbaccc.c.a.ba.dddcbabb.aaa.cbab...bbb.b.b..ccc.ddd.
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
I. Toystime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still can't calm Masha down and mom is going to come home soon and punish Sasha for having made Masha crying. That's why he decides to restore the piles' arrangement. However, he doesn't remember at all the way the toys used to lie. Of course, Masha remembers it, but she can't talk yet and can only help Sasha by shouting happily when he arranges the toys in the way they used to lie. That means that Sasha will have to arrange the toys in every possible way until Masha recognizes the needed arrangement. The relative position of the piles and toys in every pile is irrelevant, that's why the two ways of arranging the toys are considered different if can be found two such toys that when arranged in the first way lie in one and the same pile and do not if arranged in the second way. Sasha is looking for the fastest way of trying all the ways because mom will come soon. With every action Sasha can take a toy from any pile and move it to any other pile (as a result a new pile may appear or the old one may disappear). Sasha wants to find the sequence of actions as a result of which all the pile arrangement variants will be tried exactly one time each. Help Sasha. As we remember, initially all the toys are located in one pile. InputThe first line contains an integer n (1 ≀ n ≀ 10) β€” the number of toys.OutputIn the first line print the number of different variants of arrangement of toys into piles. Then print all the ways of arranging toys into piles in the order in which Sasha should try them (i.e. every next way must result from the previous one through the operation described in the statement). Every way should be printed in the following format. In every pile the toys should be arranged in ascending order of the numbers. Then the piles should be sorted in ascending order of the numbers of the first toys there. Output every way on a single line. Cf. the example to specify the output data format. If the solution is not unique, output any of them.ExamplesInput3Output5{1,2,3}{1,2},{3}{1},{2,3}{1},{2},{3}{1,3},{2}
Input3
Output5{1,2,3}{1,2},{3}{1},{2,3}{1},{2},{3}{1,3},{2}
5 seconds
256 megabytes
['brute force', 'combinatorics', '*2300']
H. Phone Numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlas, finding one's true love is not easy. Masha has been unsuccessful in that yet. Her friend Dasha told Masha about a way to determine the phone number of one's Prince Charming through arithmancy. The phone number is divined like that. First one needs to write down one's own phone numbers. For example, let's suppose that Masha's phone number is 12345. After that one should write her favorite digit from 0 to 9 under the first digit of her number. That will be the first digit of the needed number. For example, Masha's favorite digit is 9. The second digit is determined as a half sum of the second digit of Masha's number and the already written down first digit from her beloved one's number. In this case the arithmetic average equals to (2 + 9) / 2 = 5.5. Masha can round the number up or down, depending on her wishes. For example, she chooses the digit 5. Having written down the resulting digit under the second digit of her number, Masha moves to finding the third digit in the same way, i.e. finding the half sum the the third digit of her number and the second digit of the new number. The result is (5 + 3) / 2 = 4. In this case the answer is unique. Thus, every i-th digit is determined as an arithmetic average of the i-th digit of Masha's number and the i - 1-th digit of her true love's number. If needed, the digit can be rounded up or down. For example, Masha can get: 12345 95444 Unfortunately, when Masha tried dialing the number, she got disappointed: as it turned out, the number was unavailable or outside the coverage area. But Masha won't give up. Perhaps, she rounded to a wrong digit or chose the first digit badly. That's why she keeps finding more and more new numbers and calling them. Count the number of numbers Masha calls. Masha calls all the possible numbers that can be found by the described means of arithmancy, except for, perhaps, her own one.InputThe first line contains nonempty sequence consisting of digits from 0 to 9 β€” Masha's phone number. The sequence length does not exceed 50.OutputOutput the single number β€” the number of phone numbers Masha will dial.ExamplesInput12345Output48Input09Output15
Input12345
Output48
2 seconds
256 megabytes
['dp', '*1700']
G. Shooting Gallerytime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland amusement park shooting gallery is rightly acknowledged as one of the best in the world. Every day the country's best shooters master their skills there and the many visitors compete in clay pigeon shooting to win decent prizes. And the head of the park has recently decided to make an online version of the shooting gallery. During the elaboration process it turned out that the program that imitates the process of shooting effectively, is needed. To formulate the requirements to the program, the shooting gallery was formally described. A 3D Cartesian system of coordinates was introduced, where the X axis ran across the gallery floor along the line, along which the shooters are located, the Y axis ran vertically along the gallery wall and the positive direction of the Z axis matched the shooting direction. Let's call the XOY plane a shooting plane and let's assume that all the bullets are out of the muzzles at the points of this area and fly parallel to the Z axis. Every clay pigeon can be represented as a rectangle whose sides are parallel to X and Y axes, and it has a positive z-coordinate. The distance between a clay pigeon and the shooting plane is always different for every target. The bullet hits the target if it goes through the inner area or border of the rectangle corresponding to it. When the bullet hits the target, the target falls down vertically into the crawl-space of the shooting gallery and cannot be shot at any more. The targets are tough enough, that's why a bullet can not pierce a target all the way through and if a bullet hits a target it can't fly on. In input the simulator program is given the arrangement of all the targets and also of all the shots in the order of their appearance. The program should determine which target was hit by which shot. If you haven't guessed it yet, you are the one who is to write such a program.InputThe first line contains an integer n (1 ≀ n ≀ 105) β€” the number of targets. Each of the subsequent n lines contains the description of a target. The target is described by five integers xl, xr, yl, yr, z, that determine it's location in space (0 ≀ xl < xr ≀ 107, 0 ≀ yl < yr ≀ 107, 0 < z ≀ 107). The next line contains an integer m (1 ≀ m ≀ 105), determining the number of shots. Then in m lines shots are described. Every shot is determined by the coordinates of a bullet on the shooting plane (x, y) (0 ≀ x, y ≀ 107, the coordinates of bullets are integers). The shots are given in the order of their firing. The intervals between shots are large enough, and a target falls very quickly, that's why assume that a falling target can not be an obstruction for all the shots following the one that hit it.OutputFor every shot in the single line print the number of the target which the shot has hit, or 0, if the bullet did not hit any target. The targets are numbered starting from 1 in the order in which they were given in the input data.ExamplesInput21 4 1 4 12 5 2 6 240 03 34 53 5Output0120
Input21 4 1 4 12 5 2 6 240 03 34 53 5
Output0120
5 seconds
256 megabytes
['data structures', 'implementation', '*2500']
F. BerPainttime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnfisa the monkey got disappointed in word processors as they aren't good enough at reflecting all the range of her emotions, that's why she decided to switch to graphics editors. Having opened the BerPaint, she saw a white rectangle W × H in size which can be painted on. First Anfisa learnt to navigate the drawing tool which is used to paint segments and quickly painted on that rectangle a certain number of black-colored segments. The resulting picture didn't seem bright enough to Anfisa, that's why she turned her attention to the "fill" tool which is used to find a point on the rectangle to paint and choose a color, after which all the area which is the same color as the point it contains, is completely painted the chosen color. Having applied the fill several times, Anfisa expressed her emotions completely and stopped painting. Your task is by the information on the painted segments and applied fills to find out for every color the total area of the areas painted this color after all the fills.InputThe first input line has two integers W and H (3 ≀ W, H ≀ 104) β€” the sizes of the initially white rectangular painting area. The second line contains integer n β€” the number of black segments (0 ≀ n ≀ 100). On the next n lines are described the segments themselves, each of which is given by coordinates of their endpoints x1, y1, x2, y2 (0 < x1, x2 < W, 0 < y1, y2 < H). All segments have non-zero length. The next line contains preset number of fills m (0 ≀ m ≀ 100). Each of the following m lines defines the fill operation in the form of "x y color", where (x, y) are the coordinates of the chosen point (0 < x < W, 0 < y < H), and color β€” a line of lowercase Latin letters from 1 to 15 symbols in length, determining the color. All coordinates given in the input are integers. Initially the rectangle is "white" in color, whereas the segments are drawn "black" in color.OutputFor every color present in the final picture print on the single line the name of the color and the total area of areas painted that color with an accuracy of 10 - 6. Print the colors in any order. ExamplesInput4 561 1 1 31 3 3 33 3 3 13 1 1 11 3 3 11 1 3 322 1 red2 2 blueOutputblue 0.00000000white 20.00000000Input5 551 1 2 22 2 4 24 2 4 44 4 2 42 4 2 223 3 black3 3 greenOutputgreen 4.00000000white 21.00000000Input7 491 2 2 32 3 3 23 2 2 12 1 1 23 2 4 24 2 5 35 3 6 26 2 5 15 1 4 222 2 black2 2 redOutputred 2.00000000white 26.00000000NoteInitially the black segments painted by Anfisa can also be painted a color if any of the chosen points lays on the segment. The segments have areas equal to 0. That is why if in the final picture only parts of segments is painted some color, then the area, painted the color is equal to 0.
Input4 561 1 1 31 3 3 33 3 3 13 1 1 11 3 3 11 1 3 322 1 red2 2 blue
Outputblue 0.00000000white 20.00000000
5 seconds
256 megabytes
['geometry', 'graphs', '*2700']
E. Anfisa the Monkeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human speech more. Help Anfisa.InputThe first line contains three integers k, a and b (1 ≀ k ≀ 200, 1 ≀ a ≀ b ≀ 200). The second line contains a sequence of lowercase Latin letters β€” the text typed by Anfisa. It is guaranteed that the given line is not empty and its length does not exceed 200 symbols.OutputPrint k lines, each of which contains no less than a and no more than b symbols β€” Anfisa's text divided into lines. It is not allowed to perform any changes in the text, such as: deleting or adding symbols, changing their order, etc. If the solution is not unique, print any of them. If there is no solution, print "No solution" (without quotes). ExamplesInput3 2 5abrakadabraOutputabrakadabraInput4 1 2abrakadabraOutputNo solution
Input3 2 5abrakadabra
Outputabrakadabra
2 seconds
256 megabytes
['dp', '*1400']
D. Hyperdrivetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a far away galaxy there are n inhabited planets, numbered with numbers from 1 to n. They are located at large distances from each other, that's why the communication between them was very difficult until on the planet number 1 a hyperdrive was invented. As soon as this significant event took place, n - 1 spaceships were built on the planet number 1, and those ships were sent to other planets to inform about the revolutionary invention. Paradoxical thought it may be, but the hyperspace is represented as simple three-dimensional Euclidean space. The inhabited planets may be considered fixed points in it, and no two points coincide and no three points lie on the same straight line. The movement of a ship with a hyperdrive between two planets is performed along a straight line at the constant speed, the same for all the ships. That's why the distance in the hyperspace are measured in hyperyears (a ship with a hyperdrive covers a distance of s hyperyears in s years).When the ship reaches an inhabited planet, the inhabitants of the planet dissemble it, make n - 2 identical to it ships with a hyperdrive and send them to other n - 2 planets (except for the one from which the ship arrived). The time to make a new ship compared to the time in which they move from one planet to another is so small that it can be disregarded. New ships are absolutely identical to the ones sent initially: they move at the same constant speed along a straight line trajectory and, having reached a planet, perform the very same mission, i.e. are dissembled to build new n - 2 ships and send them to all the planets except for the one from which the ship arrived. Thus, the process of spreading the important news around the galaxy continues.However the hyperdrive creators hurried to spread the news about their invention so much that they didn't study completely what goes on when two ships collide in the hyperspace. If two moving ships find themselves at one point, they provoke an explosion of colossal power, leading to the destruction of the galaxy!Your task is to find the time the galaxy will continue to exist from the moment of the ships' launch from the first planet.InputThe first line contains a number n (3 ≀ n ≀ 5000) β€” the number of inhabited planets in the galaxy. The next n lines contain integer coordinates of the planets in format "xi yi zi" ( - 104 ≀ xi, yi, zi ≀ 104). OutputPrint the single number β€” the solution to the task with an absolute or relative error not exceeding 10 - 6.ExamplesInput40 0 00 0 10 1 01 0 0Output1.7071067812
Input40 0 00 0 10 1 01 0 0
Output1.7071067812
2 seconds
256 megabytes
['math', '*1800']
C. Holidaystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSchool holidays come in Berland. The holidays are going to continue for n days. The students of school β„–N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are in charge of the daily watering of flowers in shifts according to the schedule. However when Marina Sergeyevna was making the schedule, she was so tired from work and so lost in dreams of the oncoming vacation that she perhaps made several mistakes. In fact, it is possible that according to the schedule, on some days during the holidays the flowers will not be watered or will be watered multiple times. Help Marina Sergeyevna to find a mistake.InputThe first input line contains two numbers n and m (1 ≀ n, m ≀ 100) β€” the number of days in Berland holidays and the number of people in charge of the watering respectively. The next m lines contain the description of the duty schedule. Each line contains two integers ai and bi (1 ≀ ai ≀ bi ≀ n), meaning that the i-th person in charge should water the flowers from the ai-th to the bi-th day inclusively, once a day. The duty shifts are described sequentially, i.e. bi ≀ ai + 1 for all i from 1 to n - 1 inclusively. OutputPrint "OK" (without quotes), if the schedule does not contain mistakes. Otherwise you have to find the minimal number of a day when the flowers will not be watered or will be watered multiple times, and output two integers β€” the day number and the number of times the flowers will be watered that day.ExamplesInput10 51 23 34 67 78 10OutputOKInput10 51 22 34 57 89 10Output2 2Input10 51 23 35 77 77 10Output4 0NoteKeep in mind that in the second sample the mistake occurs not only on the second day, but also on the sixth day, when nobody waters the flowers. However, you have to print the second day, i.e. the day with the minimal number.
Input10 51 23 34 67 78 10
OutputOK
2 seconds
256 megabytes
['implementation', '*1300']
B. Colatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo celebrate the opening of the Winter Computer School the organizers decided to buy in n liters of cola. However, an unexpected difficulty occurred in the shop: it turned out that cola is sold in bottles 0.5, 1 and 2 liters in volume. At that, there are exactly a bottles 0.5 in volume, b one-liter bottles and c of two-liter ones. The organizers have enough money to buy any amount of cola. What did cause the heated arguments was how many bottles of every kind to buy, as this question is pivotal for the distribution of cola among the participants (and organizers as well).Thus, while the organizers are having the argument, discussing different variants of buying cola, the Winter School can't start. Your task is to count the number of all the possible ways to buy exactly n liters of cola and persuade the organizers that this number is too large, and if they keep on arguing, then the Winter Computer School will have to be organized in summer.All the bottles of cola are considered indistinguishable, i.e. two variants of buying are different from each other only if they differ in the number of bottles of at least one kind.InputThe first line contains four integers β€” n, a, b, c (1 ≀ n ≀ 10000, 0 ≀ a, b, c ≀ 5000).OutputPrint the unique number β€” the solution to the problem. If it is impossible to buy exactly n liters of cola, print 0. ExamplesInput10 5 5 5Output9Input3 0 0 2Output0
Input10 5 5 5
Output9
2 seconds
256 megabytes
['implementation', '*1500']
A. Indian Summertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIndian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy β€” she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.OutputOutput the single number β€” the number of Alyona's leaves.ExamplesInput5birch yellowmaple redbirch yellowmaple yellowmaple greenOutput4Input3oak yellowoak yellowoak yellowOutput1
Input5birch yellowmaple redbirch yellowmaple yellowmaple green
Output4
2 seconds
256 megabytes
['implementation', '*900']
E. Racetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday s kilometer long auto race takes place in Berland. The track is represented by a straight line as long as s kilometers. There are n cars taking part in the race, all of them start simultaneously at the very beginning of the track. For every car is known its behavior β€” the system of segments on each of which the speed of the car is constant. The j-th segment of the i-th car is pair (vi, j, ti, j), where vi, j is the car's speed on the whole segment in kilometers per hour and ti, j is for how many hours the car had been driving at that speed. The segments are given in the order in which they are "being driven on" by the cars.Your task is to find out how many times during the race some car managed to have a lead over another car. A lead is considered a situation when one car appears in front of another car. It is known, that all the leads happen instantly, i. e. there are no such time segment of positive length, during which some two cars drive "together". At one moment of time on one and the same point several leads may appear. In this case all of them should be taken individually. Meetings of cars at the start and finish are not considered to be counted as leads.InputThe first line contains two integers n and s (2 ≀ n ≀ 100, 1 ≀ s ≀ 106) β€” the number of cars and the length of the track in kilometers. Then follow n lines β€” the description of the system of segments for each car. Every description starts with integer k (1 ≀ k ≀ 100) β€” the number of segments in the system. Then k space-separated pairs of integers are written. Each pair is the speed and time of the segment. These integers are positive and don't exceed 1000. It is guaranteed, that the sum of lengths of all segments (in kilometers) for each car equals to s; and all the leads happen instantly.OutputPrint the single number β€” the number of times some car managed to take the lead over another car during the race.ExamplesInput2 332 5 1 2 141 3 11Output1Input2 332 1 3 10 31 11 3Output0Input5 332 1 3 3 101 11 32 5 3 3 62 3 1 10 32 6 3 3 5Output2
Input2 332 5 1 2 141 3 11
Output1
2 seconds
256 megabytes
['brute force', 'implementation', 'two pointers', '*2300']
D. Journeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited every square (except the capital) exactly one time. The king must visit the capital exactly two times, at the very beginning and at the very end of his journey. The king can only move to the side-neighboring squares. However, the royal advise said that the King possibly will not be able to do it. But there is a way out β€” one can build the system of one way teleporters between some squares so that the king could fulfill his plan. No more than one teleporter can be installed on one square, every teleporter can be used any number of times, however every time it is used, it transports to the same given for any single teleporter square. When the king reaches a square with an installed teleporter he chooses himself whether he is or is not going to use the teleport. What minimum number of teleporters should be installed for the king to complete the journey? You should also compose the journey path route for the king.InputThe first line contains two space-separated integers n and m (1 ≀ n, m ≀ 100, 2 ≀  n Β· m) β€” the field size. The upper left square has coordinates (1, 1), and the lower right square has coordinates of (n, m).OutputOn the first line output integer k β€” the minimum number of teleporters. Then output k lines each containing 4 integers x1 y1 x2 y2 (1 ≀ x1, x2 ≀ n, 1 ≀ y1, y2 ≀ m) β€” the coordinates of the square where the teleporter is installed (x1, y1), and the coordinates of the square where the teleporter leads (x2, y2).Then print nm + 1 lines containing 2 numbers each β€” the coordinates of the squares in the order in which they are visited by the king. The travel path must start and end at (1, 1). The king can move to side-neighboring squares and to the squares where a teleporter leads. Besides, he also should visit the capital exactly two times and he should visit other squares exactly one time.ExamplesInput2 2Output01 11 22 22 11 1Input3 3Output13 3 1 11 11 21 32 32 22 13 13 23 31 1
Input2 2
Output01 11 22 22 11 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'implementation', '*2000']
C. Lucky Ticketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya thinks that lucky tickets are the tickets whose numbers are divisible by 3. He gathered quite a large collection of such tickets but one day his younger brother Leonid was having a sulk and decided to destroy the collection. First he tore every ticket exactly in two, but he didn’t think it was enough and Leonid also threw part of the pieces away. Having seen this, Vasya got terrified but still tried to restore the collection. He chose several piece pairs and glued each pair together so that each pair formed a lucky ticket. The rest of the pieces Vasya threw away reluctantly. Thus, after the gluing of the 2t pieces he ended up with t tickets, each of which was lucky.When Leonid tore the tickets in two pieces, one piece contained the first several letters of his number and the second piece contained the rest.Vasya can glue every pair of pieces in any way he likes, but it is important that he gets a lucky ticket in the end. For example, pieces 123 and 99 can be glued in two ways: 12399 and 99123.What maximum number of tickets could Vasya get after that?InputThe first line contains integer n (1 ≀ n ≀ 104) β€” the number of pieces. The second line contains n space-separated numbers ai (1 ≀ ai ≀ 108) β€” the numbers on the pieces. Vasya can only glue the pieces in pairs. Even if the number of a piece is already lucky, Vasya should glue the piece with some other one for it to count as lucky. Vasya does not have to use all the pieces. The numbers on the pieces an on the resulting tickets may coincide.OutputPrint the single number β€” the maximum number of lucky tickets that will be able to be restored. Don't forget that every lucky ticket is made of exactly two pieces glued together.ExamplesInput3123 123 99Output1Input61 1 1 23 10 3Output1
Input3123 123 99
Output1
2 seconds
256 megabytes
['greedy', '*1300']
B. Lettertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading β€” he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.InputThe first line contains a newspaper heading s1. The second line contains the letter text s2. s1 ΠΈ s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.OutputIf Vasya can write the given anonymous letter, print YES, otherwise print NOExamplesInputInstead of dogging Your footsteps it disappears but you dont notice anythingwhere is your dogOutputNOInputInstead of dogging Your footsteps it disappears but you dont notice anythingYour dog is upstearsOutputYESInputInstead of dogging your footsteps it disappears but you dont notice anythingYour dog is upstearsOutputNOInputabcdefg hijkk j i h g f e d c b aOutputYES
InputInstead of dogging Your footsteps it disappears but you dont notice anythingwhere is your dog
OutputNO
2 seconds
256 megabytes
['implementation', 'strings', '*1100']
A. Footballtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of lines in the description. Then follow n lines β€” for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.OutputPrint the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.ExamplesInput1ABCOutputABCInput5AABAABAAAOutputA
Input1ABC
OutputABC
2 seconds
256 megabytes
['strings', '*1000']
E. Baldman and the militarytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBaldman is a warp master. He possesses a unique ability β€” creating wormholes! Given two positions in space, Baldman can make a wormhole which makes it possible to move between them in both directions. Unfortunately, such operation isn't free for Baldman: each created wormhole makes him lose plenty of hair from his head.Because of such extraordinary abilities, Baldman has caught the military's attention. He has been charged with a special task. But first things first.The military base consists of several underground objects, some of which are connected with bidirectional tunnels. There necessarily exists a path through the tunnel system between each pair of objects. Additionally, exactly two objects are connected with surface. For the purposes of security, a patrol inspects the tunnel system every day: he enters one of the objects which are connected with surface, walks the base passing each tunnel at least once and leaves through one of the objects connected with surface. He can enter and leave either through the same object, or through different objects. The military management noticed that the patrol visits some of the tunnels multiple times and decided to optimize the process. Now they are faced with a problem: a system of wormholes needs to be made to allow of a patrolling which passes each tunnel exactly once. At the same time a patrol is allowed to pass each wormhole any number of times.This is where Baldman comes to operation: he is the one to plan and build the system of the wormholes. Unfortunately for him, because of strict confidentiality the military can't tell him the arrangement of tunnels. Instead, they insist that his system of portals solves the problem for any arrangement of tunnels which satisfies the given condition. Nevertheless, Baldman has some information: he knows which pairs of objects he can potentially connect and how much it would cost him (in hair). Moreover, tomorrow he will be told which objects (exactly two) are connected with surface. Of course, our hero decided not to waste any time and calculate the minimal cost of getting the job done for some pairs of objects (which he finds likely to be the ones connected with surface). Help Baldman!InputFirst line of the input contains a single natural number n (2 ≀ n ≀ 100000) β€” the number of objects on the military base. The second line β€” one number m (1 ≀ m ≀ 200000) β€” the number of the wormholes Baldman can make. The following m lines describe the wormholes: each line contains three integer numbers a, b, c (1 ≀ a, b ≀ n, 1 ≀ c ≀ 100000) β€” the numbers of objects which can be connected and the number of hair Baldman has to spend to make this wormhole.The next line contains one natural number q (1 ≀ q ≀ 100000) β€” the number of queries. Finally, the last q lines contain a description of one query each β€” a pair of numbers of different objects ai, bi (1 ≀ ai, bi ≀ n, ai ≠ bi). There could be more than one wormhole between a pair of objects.OutputYour program should output q lines, one for each query. The i-th line should contain a single integer number β€” the answer for i-th query: the minimum cost (in hair) of a system of wormholes allowing the optimal patrol for any system of tunnels (satisfying the given conditions) if ai and bi are the two objects connected with surface, or "-1" if such system of wormholes cannot be made.ExamplesInput211 2 311 2Output0Input311 2 321 21 3Output-13
Input211 2 311 2
Output0
4 seconds
256 megabytes
['dfs and similar', 'graphs', 'trees', '*2700']
D. Strange towntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVolodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour β€” a cycle which visits every attraction exactly once β€” the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.InputInput contains just one natural number (3 ≀ N ≀ 20) β€” the number of town attractions.OutputOutput should contain N rows containing N positive integer numbers each β€” the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.ExamplesInput3Output0 3 4 3 0 5 4 5 0
Input3
Output0 3 4 3 0 5 4 5 0
2 seconds
256 megabytes
['constructive algorithms', 'math', '*2300']
C. Safe crackingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRight now you are to solve a very, very simple problem β€” to crack the safe. Four positive integers stand one by one on a circle protecting the safe. You know that to unlock this striking safe you have to make all four numbers equal to one. Operations are as follows: you may choose two adjacent numbers and increase both by one; you may choose two adjacent even numbers and divide both by two. Nothing else. Crack the safe!InputThe single line of the input contains four space-separated integer positive numbers not greater than 109 each β€” four numbers on the circle in consecutive order.OutputThe output should contain "-1" (quotes for clarity) if the safe is secure, that is it's impossible to crack it. Otherwise, output should contain the sequence of operations (one operations per line) leading to unlocking the safe. You don't have to minimize the number of operations, but it should not exceed 1000. To make things clear, assume numbers stand on positions 1 through 4. Each operation is encoded by two symbols. If the following operation is dividing then first symbol is '/'; otherwise it's '+' (addition). The second symbol is the position of the first number in pair in consecutive order. (see samples for clarification).If there are several solutions, output any of them.ExamplesInput1 1 1 1OutputInput1 2 4 2Output/2/3Input3 3 1 1Output+1/1/1Input2 1 2 4Output/3/4
Input1 1 1 1
Output
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*2200']
B. Game of chess unfinishedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Volodya was at the museum and saw a regular chessboard as a museum piece. And there were only four chess pieces on it: two white rooks, a white king and a black king. "Aha, blacks certainly didn't win!", β€” Volodya said and was right for sure. And your task is to say whether whites had won or not.Pieces on the chessboard are guaranteed to represent a correct position (every piece occupies one cell, no two pieces occupy the same cell and kings cannot take each other). Thus, your task is only to decide whether whites mate blacks. We would remind you that it means that the black king can be taken by one of the opponent's pieces at the moment and also it cannot move to an unbeaten position. A rook moves vertically or horizontally by any number of free cells (assuming there are no other pieces on its path), a king β€” to the adjacent cells (either by corner or by side). Certainly, pieces cannot leave the board. The black king might be able to take opponent's rooks at his turn (see sample 3).InputThe input contains 4 space-separated piece positions: positions of the two rooks, the white king and the black king. Each position on 8 × 8 chessboard is denoted by two symbols β€” ('a' - 'h') and ('1' - '8') β€” which stand for horizontal and vertical coordinates of the cell occupied by the piece. It is guaranteed, that no two pieces occupy the same cell, and kings cannot take each other.OutputOutput should contain one word: "CHECKMATE" if whites mate blacks, and "OTHER" otherwise.ExamplesInputa6 b4 c8 a8OutputCHECKMATEInputa6 c4 b6 b8OutputOTHERInputa2 b1 a3 a1OutputOTHER
Inputa6 b4 c8 a8
OutputCHECKMATE
2 seconds
256 megabytes
['implementation', '*1700']
A. Guilty β€” to the kitchen!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a very unfortunate day for Volodya today. He got bad mark in algebra and was therefore forced to do some work in the kitchen, namely to cook borscht (traditional Russian soup). This should also improve his algebra skills.According to the borscht recipe it consists of n ingredients that have to be mixed in proportion litres (thus, there should be a1 ·x, ..., an ·x litres of corresponding ingredients mixed for some non-negative x). In the kitchen Volodya found out that he has b1, ..., bn litres of these ingredients at his disposal correspondingly. In order to correct his algebra mistakes he ought to cook as much soup as possible in a V litres volume pan (which means the amount of soup cooked can be between 0 and V litres). What is the volume of borscht Volodya will cook ultimately?InputThe first line of the input contains two space-separated integers n and V (1 ≀ n ≀ 20, 1 ≀ V ≀ 10000). The next line contains n space-separated integers ai (1 ≀ ai ≀ 100). Finally, the last line contains n space-separated integers bi (0 ≀ bi ≀ 100).OutputYour program should output just one real number β€” the volume of soup that Volodya will cook. Your answer must have a relative or absolute error less than 10 - 4.ExamplesInput1 100140Output40.0Input2 1001 125 30Output50.0Input2 1001 160 60Output100.0
Input1 100140
Output40.0
2 seconds
256 megabytes
['greedy', 'implementation', '*1400']
E. 3-cyclestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring a recent research Berland scientists found out that there were n cities in Ancient Berland, joined by two-way paths. Any two cities are joined by no more than one path. No path joins a city with itself. According to a well-known tradition, the road network was built so that it would be impossible to choose three cities from each of which one can get to any other one directly. That is, there was no cycle exactly as long as 3. Unfortunately, the road map has not been preserved till nowadays. Now the scientists are interested how much developed a country Ancient Berland was. Help them - find, what maximal number of roads could be in the country. You also have to restore any of the possible road maps.InputThe first line contains an integer n (1 ≀ n ≀ 100) β€” the number of cities in Berland.OutputOn the first line must be printed number m β€” the maximal number of roads in Berland. Then print m lines containing two numbers each β€” the numbers of cities that the given road joins. The cities are numbered with integers from 1 to n. If there are several variants of solving the problem, print any of them.ExamplesInput3Output21 22 3Input4Output41 22 33 44 1
Input3
Output21 22 3
2 seconds
256 megabytes
['constructive algorithms', 'graphs', 'greedy', '*1900']
D. Pawntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.InputThe first line contains three integers n, m, k (2 ≀ n, m ≀ 100, 0 ≀ k ≀ 10) β€” the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces β€” the chessboard's description. Each square is described by one number β€” the number of peas in it. The first line corresponds to the uppermost row and the last line β€” to the lowest row.OutputIf it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1. Otherwise, the first line must contain a single number β€” the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number β€” the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols β€” the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.ExamplesInput3 3 1123456789Output162RLInput3 3 0123456789Output173LRInput2 2 109875Output-1
Input3 3 1123456789
Output162RL
2 seconds
256 megabytes
['dp', '*1900']
C. Email addresstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address ([emailΒ protected]). It is known that a proper email address contains only such symbols as . @ and lower-case Latin letters, doesn't start with and doesn't end with a dot. Also, a proper email address doesn't start with and doesn't end with an at sign. Moreover, an email address contains exactly one such symbol as @, yet may contain any number (possible, zero) of dots. You have to carry out a series of replacements so that the length of the result was as short as possible and it was a proper email address. If the lengths are equal, you should print the lexicographically minimal result. Overall, two variants of replacement are possible: dot can be replaced by a dot, at can be replaced by an at. InputThe first line contains the email address description. It is guaranteed that that is a proper email address with all the dots replaced by dot an the at signs replaced by at. The line is not empty and its length does not exceed 100 symbols.OutputPrint the shortest email address, from which the given line could be made by the described above replacements. If there are several solutions to that problem, print the lexicographically minimal one (the lexicographical comparison of the lines are implemented with an operator < in modern programming languages).In the ASCII table the symbols go in this order: . @ ab...zExamplesInputvasyaatgmaildotcomOutput[emailΒ protected]InputdotdotdotatdotdotatOutput[emailΒ protected]InputaattOutputa@t
Inputvasyaatgmaildotcom
Output[emailΒ protected]
2 seconds
256 megabytes
['expression parsing', 'implementation', '*1300']
B. Martian Dollartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Martian laws, one can buy only an integer number of dollars. Which maximal sum of money in bourles can Vasya get by the end of day n?InputThe first line contains two integers n and b (1 ≀ n, b ≀ 2000) β€” the number of days and the initial number of money in bourles. The next line contains n integers ai (1 ≀ ai ≀ 2000) β€” the prices of Martian dollars.OutputPrint the single number β€” which maximal sum of money in bourles can Vasya get by the end of day n.ExamplesInput2 43 7Output8Input4 104 3 2 1Output10Input4 104 2 3 1Output15
Input2 43 7
Output8
2 seconds
256 megabytes
['brute force', '*1400']
A. Translationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the Β«translationΒ». Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.InputThe first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.OutputIf the word t is a word s, written reversely, print YES, otherwise print NO.ExamplesInputcodeedocOutputYESInputabbabaOutputNOInputcodecodeOutputNO
Inputcodeedoc
OutputYES
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. Number Tabletime limit per test2 secondsmemory limit per test216 megabytesinputstandard inputoutputstandard outputAs it has been found out recently, all the Berland's current economical state can be described using a simple table n × m in size. n β€” the number of days in each Berland month, m β€” the number of months. Thus, a table cell corresponds to a day and a month of the Berland's year. Each cell will contain either 1, or -1, which means the state's gains in a particular month, on a particular day. 1 corresponds to profits, -1 corresponds to losses. It turned out important for successful development to analyze the data on the state of the economy of the previous year, however when the treasurers referred to the archives to retrieve the data, it turned out that the table had been substantially damaged. In some table cells the number values had faded and were impossible to be deciphered. It is known that the number of cells in which the data had been preserved is strictly less than max(n, m). However, there is additional information β€” the product of the numbers in each line and column equaled -1. Your task is to find out how many different tables may conform to the preserved data. As the answer to the task can be quite large, you have to find it modulo p.InputThe first line contains integers n and m (1 ≀ n, m ≀ 1000). The second line contains the integer k (0 ≀ k < max(n, m)) β€” the number of cells in which the data had been preserved. The next k lines contain the data on the state of the table in the preserved cells. Each line is of the form "a b c", where a (1 ≀ a ≀ n) β€” the number of the table row, b (1 ≀ b ≀ m) β€” the number of the column, c β€” the value containing in the cell (1 or -1). They are numbered starting from 1. It is guaranteed that no two lines with same a and b values exist. The last line contains an integer p (2 ≀ p ≀ 109 + 7).OutputPrint the number of different tables that could conform to the preserved data modulo p.ExamplesInput2 20100Output2Input2 211 1 -1100Output1
Input2 20100
Output2
2 seconds
216 megabytes
['combinatorics', '*2500']
D. Interesting Sequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). After one Berland year after the start of the chronology the population had already equaled 13 people (the second year). However, tracing the population number during the following years was an ultimately difficult task, still it was found out that if di β€” the number of people in Berland in the year of i, then either di = 12di - 2, or di = 13di - 1 - 12di - 2. Of course no one knows how many people are living in Berland at the moment, but now we can tell if there could possibly be a year in which the country population equaled A. That's what we ask you to determine. Also, if possible, you have to find out in which years it could be (from the beginning of Berland chronology). Let's suppose that it could be in the years of a1, a2, ..., ak. Then you have to define how many residents could be in the country during those years apart from the A variant. Look at the examples for further explanation.InputThe first line contains integer A (1 ≀ A < 10300). It is guaranteed that the number doesn't contain leading zeros.OutputOn the first output line print YES, if there could be a year in which the total population of the country equaled A, otherwise print NO. If the answer is YES, then you also have to print number k β€” the number of years in which the population could equal A. On the next line you have to output precisely k space-separated numbers β€” a1, a2, ..., ak. Those numbers have to be output in the increasing order.On the next line you should output number p β€” how many variants of the number of people could be in the years of a1, a2, ..., ak, apart from the A variant. On each of the next p lines you have to print one number β€” the sought number of residents. Those number also have to go in the increasing order. If any number (or both of them) k or p exceeds 1000, then you have to print 1000 instead of it and only the first 1000 possible answers in the increasing order.The numbers should have no leading zeros.ExamplesInput2OutputYES110Input3OutputNOInput13OutputYES120Input1729OutputYES141156
Input2
OutputYES110
3 seconds
256 megabytes
['math', '*2600']
C. Berland Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLast year the world's largest square was built in Berland. It is known that the square can be represented as an infinite plane with an introduced Cartesian system of coordinates. On that square two sets of concentric circles were painted. Let's call the set of concentric circles with radii 1, 2, ..., K and the center in the point (z, 0) a (K, z)-set. Thus, on the square were painted a (N, x)-set and a (M, y)-set. You have to find out how many parts those sets divided the square into.InputThe first line contains integers N, x, M, y. (1 ≀ N, M ≀ 100000,  - 100000 ≀ x, y ≀ 100000, x ≠ y).OutputPrint the sought number of parts.ExamplesInput1 0 1 1Output4Input1 0 1 2Output3Input3 3 4 7Output17NotePicture for the third sample:
Input1 0 1 1
Output4
2 seconds
256 megabytes
['implementation', 'math', '*2300']
B. Repaintingstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues ad infinitum. You have to figure out how many squares we repainted exactly x times.The upper left square of the board has to be assumed to be always black. Two squares are called corner-adjacent, if they have exactly one common point.InputThe first line contains integers n and m (1 ≀ n, m ≀ 5000). The second line contains integer x (1 ≀ x ≀ 109).OutputPrint how many squares will be painted exactly x times.ExamplesInput3 31Output4Input3 32Output1Input1 11Output1
Input3 31
Output4
2 seconds
256 megabytes
['math', '*1600']
A. Find Colortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot so long ago as a result of combat operations the main Berland place of interest β€” the magic clock β€” was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin corresponds to the clock center. The clock was painted two colors as is shown in the picture: The picture shows only the central part of the clock. This coloring naturally extends to infinity.The balls can be taken to be points on the plane. Your task is to find the color of the area, damaged by the given ball.All the points located on the border of one of the areas have to be considered painted black.InputThe first and single line contains two integers x and y β€” the coordinates of the hole made in the clock by the ball. Each of the numbers x and y has an absolute value that does not exceed 1000.OutputFind the required color.All the points between which and the origin of coordinates the distance is integral-value are painted black.ExamplesInput-2 1OutputwhiteInput2 1OutputblackInput4 3Outputblack
Input-2 1
Outputwhite
2 seconds
256 megabytes
['constructive algorithms', 'geometry', 'implementation', 'math', '*1300']
K. Testingtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field n × m in size, divided into unit squares 1 × 1 in size. The polygon contains k objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit squares. The objects don't intersect and don't touch each other.The principle according to which the weapon works is highly secret. You only know that one can use it to strike any rectangular area whose area is not equal to zero with sides, parallel to the sides of the polygon. The area must completely cover some of the unit squares into which the polygon is divided and it must not touch the other squares. Of course the area mustn't cross the polygon border. Your task is as follows: you should hit no less than one and no more than three rectangular objects. Each object must either lay completely inside the area (in that case it is considered to be hit), or lay completely outside the area.Find the number of ways of hitting.InputThe first line has three integers n, m ΠΈ k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 90) β€” the sizes of the polygon and the number of objects on it respectively. Next n lines contain m symbols each and describe the polygon. The symbol "*" stands for a square occupied an object, whereas the symbol "." stands for an empty space. The symbols "*" form exactly k rectangular connected areas that meet the requirements of the task.OutputOutput a single number β€” the number of different ways to hit a target.ExamplesInput3 3 3*.*...*..Output21Input4 5 4.*.**...****......**Output38Input2 2 1.*..Output4
Input3 3 3*.*...*..
Output21
2 seconds
64 megabytes
['*2600']
J. Spelling Checktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has noticed that when he types using a keyboard, he often presses extra buttons and adds extra letters to the words. Of course, the spell-checking system underlines the words for him and he has to click every word and choose the right variant. Petya got fed up with correcting his mistakes himself, that’s why he decided to invent the function that will correct the words itself. Petya started from analyzing the case that happens to him most of the time, when all one needs is to delete one letter for the word to match a word from the dictionary. Thus, Petya faces one mini-task: he has a printed word and a word from the dictionary, and he should delete one letter from the first word to get the second one. And now the very non-trivial question that Petya faces is: which letter should he delete?InputThe input data contains two strings, consisting of lower-case Latin letters. The length of each string is from 1 to 106 symbols inclusive, the first string contains exactly 1 symbol more than the second one.OutputIn the first line output the number of positions of the symbols in the first string, after the deleting of which the first string becomes identical to the second one. In the second line output space-separated positions of these symbols in increasing order. The positions are numbered starting from 1. If it is impossible to make the first string identical to the second string by deleting one symbol, output one number 0.ExamplesInputabdrakadabraabrakadabraOutput13InputaaaOutput21 2InputcompetitioncodeforcesOutput0
Inputabdrakadabraabrakadabra
Output13
2 seconds
256 megabytes
['hashing', 'implementation', 'strings', '*1500']
I. Tramtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn a Berland city S*** there is a tram engine house and only one tram. Three people work in the house β€” the tram driver, the conductor and the head of the engine house. The tram used to leave the engine house every morning and drove along his loop route. The tram needed exactly c minutes to complete the route. The head of the engine house controlled the tram’s movement, going outside every c minutes when the tram drove by the engine house, and the head left the driver without a bonus if he was even one second late.It used to be so. Afterwards the Berland Federal Budget gave money to make more tramlines in S***, and, as it sometimes happens, the means were used as it was planned. The tramlines were rebuilt and as a result they turned into a huge network. The previous loop route may have been destroyed. S*** has n crossroads and now m tramlines that links the pairs of crossroads. The traffic in Berland is one way so the tram can move along each tramline only in one direction. There may be several tramlines between two crossroads, which go same way or opposite ways. Every tramline links two different crossroads and for each crossroad there is at least one outgoing tramline.So, the tramlines were built but for some reason nobody gave a thought to increasing the number of trams in S***! The tram continued to ride alone but now the driver had an excellent opportunity to get rid of the unending control of the engine house head. For now due to the tramline network he could choose the route freely! Now at every crossroad the driver can arbitrarily choose the way he can go. The tram may even go to the parts of S*** from where it cannot return due to one way traffic. The driver is not afraid of the challenge: at night, when the city is asleep, he can return to the engine house safely, driving along the tramlines in the opposite direction.The city people were rejoicing for some of the had been waiting for the tram to appear on their streets for several years. However, the driver’s behavior enraged the engine house head. Now he tries to carry out an insidious plan of installing cameras to look after the rebellious tram.The plan goes as follows. The head of the engine house wants to install cameras at some crossroads, to choose a period of time t and every t minutes turn away from the favourite TV show to check where the tram is. Also the head of the engine house wants at all moments of time, divisible by t, and only at such moments the tram to appear on a crossroad under a camera. There must be a camera on the crossroad by the engine house to prevent possible terrorist attacks on the engine house head. Among all the possible plans the engine house head chooses the plan with the largest possible value of t (as he hates being distracted from his favourite TV show but he has to). If such a plan is not unique, pick the plan that requires the minimal possible number of cameras. Find such a plan.InputThe first line contains integers n and m (2 ≀ n, m ≀ 105) β€” the number of crossroads and tramlines in S*** respectively. The next m lines contain the descriptions of the tramlines in "u v" format, where u is the initial tramline crossroad and v is its final crossroad. The crossroads are numbered with integers from 1 to n, and the engine house is at the crossroad number 1.OutputIn the first line output the value of t. In the next line output the value of k β€” the required number of the cameras. In the next line output space-separated numbers of the crossroads, where the cameras should be installed. Output the numbers in increasing order.ExamplesInput4 51 22 33 44 11 4Output221 3
Input4 51 22 33 44 11 4
Output221 3
2 seconds
64 megabytes
['*2500']
H. Multiplication Tabletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPetya studies positional notations. He has already learned to add and subtract numbers in the systems of notations with different radices and has moved on to a more complicated action β€” multiplication. To multiply large numbers one has to learn the multiplication table. Unfortunately, in the second grade students learn only the multiplication table of decimals (and some students even learn it in the first grade). Help Petya make a multiplication table for numbers in the system of notations with the radix k.InputThe first line contains a single integer k (2 ≀ k ≀ 10) β€” the radix of the system.OutputOutput the multiplication table for the system of notations with the radix k. The table must contain k - 1 rows and k - 1 columns. The element on the crossing of the i-th row and the j-th column is equal to the product of i and j in the system of notations with the radix k. Each line may have any number of spaces between the numbers (the extra spaces in the samples are put for clarity).ExamplesInput10Output1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81Input3Output1 22 11
Input10
Output1 2 3 4 5 6 7 8 92 4 6 8 10 12 14 16 183 6 9 12 15 18 21 24 274 8 12 16 20 24 28 32 365 10 15 20 25 30 35 40 456 12 18 24 30 36 42 48 547 14 21 28 35 42 49 56 638 16 24 32 40 48 56 64 729 18 27 36 45 54 63 72 81
2 seconds
64 megabytes
['implementation', '*1300']
G. Inverse Functiontime limit per test5 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPetya wrote a programme on C++ that calculated a very interesting function f(n). Petya ran the program with a certain value of n and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the input file so that Petya can't figure out for which value of n the program was run. Help Petya, carry out the inverse function!Mostly, the program consists of a function in C++ with the following simplified syntax: function ::= int f(int n) {operatorSequence} operatorSequence ::= operatorΒ |Β operatorΒ operatorSequence operator ::= return arithmExpr; | if (logicalExpr) return arithmExpr; logicalExpr ::= arithmExpr > arithmExpr | arithmExpr < arithmExpr | arithmExpr == arithmExpr arithmExpr ::= sum sum ::= product | sum + product | sum - product product ::= multiplier | product * multiplier | product / multiplier multiplier ::= n | number | f(arithmExpr) number ::= 0|1|2|... |32767 The whitespaces in a operatorSequence are optional.Thus, we have a function, in which body there are two kinds of operators. There is the operator "return arithmExpr;" that returns the value of the expression as the value of the function, and there is the conditional operator "if (logicalExpr) return arithmExpr;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language β€” cycles, assignment operators, nested conditional operators etc, and other variables except the n parameter are used in the function. All the constants are integers in the interval [0..32767].The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations ">" (more), "<" (less) and "==" (equals) also have standard meanings.Now you've got to pay close attention! The program is compiled with the help of 15-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo 32768 (if the result of subtraction is negative, then 32768 is added to it until the number belongs to the interval [0..32767]). Division "/" is a usual integer division where the remainder is omitted.Examples of arithmetical operations: Guaranteed that for all values of n from 0 to 32767 the given function is performed correctly. That means that:1. Division by 0 never occures.2. When performing a function for the value n = N recursive calls of the function f may occur only for the parameter value of 0, 1, ..., N - 1. Consequently, the program never has an infinite recursion.3. As the result of the sequence of the operators, the function always returns a value.We have to mention that due to all the limitations the value returned by the function f is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of n parameter. That's why the f function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of n from the interval [0..32767] and a value of f(n) from the same interval.Given the value of f(n), and you should find n. If the suitable n value is not unique, you should find the maximal one (from the interval [0..32767]).InputThe first line has an integer f(n) from the interval [0..32767]. The next lines have the description of the function f. In the description can be found extra spaces and line breaks (see the examples) which, of course, can’t break key words int, if, return and numbers. The size of input data can’t exceed 100 bytes.OutputOutput a single number β€” the answer to the problem. If there’s no answer, output "-1" (without quotes).ExamplesInput17int f(int n){if (n < 100) return 17;if (n > 99) return 27;}Output99Input13int f(int n){if (n == 0) return 0;return f(n - 1) + 1;}Output13Input144int f(int n){if (n == 0) return 0;if (n == 1) return n;return f(n - 1) + f(n - 2);}Output24588
Input17int f(int n){if (n < 100) return 17;if (n > 99) return 27;}
Output99
5 seconds
64 megabytes
['implementation', '*2400']
F. Pacifist frogstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputThumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much.One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n and the number of a hill is equal to the distance in meters between it and the island. The distance between the n-th hill and the shore is also 1 meter.Thumbelina is too small to make such jumps. Fortunately, a family of frogs living in the swamp suggests to help her. Each frog agrees to give Thumbelina a ride but Thumbelina should choose only one frog. Each frog has a certain jump length. If Thumbelina agrees to accept help from a frog whose jump length is d, the frog will jump from the island on the hill d, then β€” on the hill 2d, then 3d and so on until they get to the shore (i.e. find itself beyond the hill n).However, there is one more problem: mosquitoes also live in the swamp. At the moment they have a siesta, and they are having a nap on some hills. If the frog jumps on a hill with a mosquito the frog will smash it. The frogs Thumbelina has met are pacifists, so they will find the death of each mosquito very much sad. Help Thumbelina choose a frog that will bring her to the shore and smash as small number of mosquitoes as possible.InputThe first line contains three integers n, m and k (1 ≀ n ≀ 109, 1 ≀ m, k ≀ 100) β€” the number of hills, frogs and mosquitoes respectively. The second line contains m integers di (1 ≀ di ≀ 109) β€” the lengths of the frogs’ jumps. The third line contains k integers β€” the numbers of the hills on which each mosquito is sleeping. No more than one mosquito can sleep on each hill. The numbers in the lines are separated by single spaces.OutputIn the first line output the number of frogs that smash the minimal number of mosquitoes, in the second line β€” their numbers in increasing order separated by spaces. The frogs are numbered from 1 to m in the order of the jump length given in the input data.ExamplesInput5 3 52 3 41 2 3 4 5Output22 3Input1000000000 2 32 5999999995 999999998 999999996Output12
Input5 3 52 3 41 2 3 4 5
Output22 3
2 seconds
64 megabytes
['implementation', '*1300']
E. What Has Dirichlet Got to Do with That?time limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou all know the Dirichlet principle, the point of which is that if n boxes have no less than n + 1 items, that leads to the existence of a box in which there are at least two items.Having heard of that principle, but having not mastered the technique of logical thinking, 8 year olds Stas and Masha invented a game. There are a different boxes and b different items, and each turn a player can either add a new box or a new item. The player, after whose turn the number of ways of putting b items into a boxes becomes no less then a certain given number n, loses. All the boxes and items are considered to be different. Boxes may remain empty.Who loses if both players play optimally and Stas's turn is first?InputThe only input line has three integers a, b, n (1 ≀ a ≀ 10000, 1 ≀ b ≀ 30, 2 ≀ n ≀ 109) β€” the initial number of the boxes, the number of the items and the number which constrains the number of ways, respectively. Guaranteed that the initial number of ways is strictly less than n.OutputOutput "Stas" if Masha wins. Output "Masha" if Stas wins. In case of a draw, output "Missing".ExamplesInput2 2 10OutputMashaInput5 5 16808OutputMashaInput3 1 4OutputStasInput1 4 10OutputMissingNoteIn the second example the initial number of ways is equal to 3125. If Stas increases the number of boxes, he will lose, as Masha may increase the number of boxes once more during her turn. After that any Stas's move will lead to defeat. But if Stas increases the number of items, then any Masha's move will be losing.
Input2 2 10
OutputMasha
2 seconds
64 megabytes
['dp', 'games', '*2000']
D. Cubical Planettime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0, 0, 0) and (1, 1, 1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.InputThe first line contains three space-separated integers (0 or 1) β€” the coordinates of the first fly, the second line analogously contains the coordinates of the second fly.OutputOutput "YES" (without quotes) if the flies see each other. Otherwise, output "NO".ExamplesInput0 0 00 1 0OutputYESInput1 1 00 1 0OutputYESInput0 0 01 1 1OutputNO
Input0 0 00 1 0
OutputYES
2 seconds
64 megabytes
['math', '*1100']
C. Moon Craterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are lots of theories concerning the origin of moon craters. Most scientists stick to the meteorite theory, which says that the craters were formed as a result of celestial bodies colliding with the Moon. The other version is that the craters were parts of volcanoes.An extraterrestrial intelligence research specialist professor Okulov (the namesake of the Okulov, the author of famous textbooks on programming) put forward an alternate hypothesis. Guess what kind of a hypothesis it was –– sure, the one including extraterrestrial mind involvement. Now the professor is looking for proofs of his hypothesis.Professor has data from the moon robot that moves linearly in one direction along the Moon surface. The moon craters are circular in form with integer-valued radii. The moon robot records only the craters whose centers lay on his path and sends to the Earth the information on the distance from the centers of the craters to the initial point of its path and on the radii of the craters.According to the theory of professor Okulov two craters made by an extraterrestrial intelligence for the aims yet unknown either are fully enclosed one in the other or do not intersect at all. Internal or external tangency is acceptable. However the experimental data from the moon robot do not confirm this theory! Nevertheless, professor Okulov is hopeful. He perfectly understands that to create any logical theory one has to ignore some data that are wrong due to faulty measuring (or skillful disguise by the extraterrestrial intelligence that will be sooner or later found by professor Okulov!) That’s why Okulov wants to choose among the available crater descriptions the largest set that would satisfy his theory.InputThe first line has an integer n (1 ≀ n ≀ 2000) β€” the number of discovered craters. The next n lines contain crater descriptions in the "ci ri" format, where ci is the coordinate of the center of the crater on the moon robot’s path, ri is the radius of the crater. All the numbers ci and ri are positive integers not exceeding 109. No two craters coincide.OutputIn the first line output the number of craters in the required largest set. In the next line output space-separated numbers of craters that this set consists of. The craters are numbered from 1 to n in the order in which they were given in the input data. The numbers may be output in any order. If the result is not unique, output any.ExamplesInput41 12 24 15 1Output31 2 4
Input41 12 24 15 1
Output31 2 4
1 second
256 megabytes
['dp', 'sortings', '*2100']
B. Company Income Growthtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputPetya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 β€” to a2 billion, ..., and in the current (2000 + n)-th year β€” an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year β€” 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 β€” 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.InputThe first line contains an integer n (1 ≀ n ≀ 100). The next line contains n integers ai ( - 100 ≀ ai ≀ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces.OutputOutput k β€” the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.ExamplesInput10-2 1 1 3 2 3 4 -10 -2 5Output52002 2005 2006 2007 2010Input3-1 -2 -3Output0
Input10-2 1 1 3 2 3 4 -10 -2 5
Output52002 2005 2006 2007 2010
2 seconds
64 megabytes
['greedy', '*1300']
A. C*++ Calculationstime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputC*++ language is quite similar to C++. The similarity manifests itself in the fact that the programs written in C*++ sometimes behave unpredictably and lead to absolutely unexpected effects. For example, let's imagine an arithmetic expression in C*++ that looks like this (expression is the main term): expression ::= summand | expression + summand | expression - summand summand ::= increment | coefficient*increment increment ::= a++ | ++a coefficient ::= 0|1|2|...|1000 For example, "5*a++-3*++a+a++" is a valid expression in C*++.Thus, we have a sum consisting of several summands divided by signs "+" or "-". Every summand is an expression "a++" or "++a" multiplied by some integer coefficient. If the coefficient is omitted, it is suggested being equal to 1.The calculation of such sum in C*++ goes the following way. First all the summands are calculated one after another, then they are summed by the usual arithmetic rules. If the summand contains "a++", then during the calculation first the value of the "a" variable is multiplied by the coefficient, then value of "a" is increased by 1. If the summand contains "++a", then the actions on it are performed in the reverse order: first "a" is increased by 1, then β€” multiplied by the coefficient.The summands may be calculated in any order, that's why sometimes the result of the calculation is completely unpredictable! Your task is to find its largest possible value.InputThe first input line contains an integer a ( - 1000 ≀ a ≀ 1000) β€” the initial value of the variable "a". The next line contains an expression in C*++ language of the described type. The number of the summands in the expression does not exceed 1000. It is guaranteed that the line describing the expression contains no spaces and tabulation. OutputOutput a single number β€” the maximal possible value of the expression.ExamplesInput15*a++-3*++a+a++Output11Input3a+++++aOutput8NoteConsider the second example. Initially a = 3. Suppose that at first the first summand is calculated, and then the second one is. The first summand gets equal to 3, and the value of a is increased by 1. At the calculation of the second summand a is increased once more (gets equal to 5). The value of the second summand is 5, and together they give 8. If we calculate the second summand first and the first summand later, then the both summands equals to 4, and the result is 8, too.
Input15*a++-3*++a+a++
Output11
2 seconds
64 megabytes
['expression parsing', 'greedy', '*2000']
H. The Great Marathontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the Berland Dependence Day it was decided to organize a great marathon. Berland consists of n cities, some of which are linked by two-way roads. Each road has a certain length. The cities are numbered from 1 to n. It is known that one can get from any city to any other one by the roads.n runners take part in the competition, one from each city. But Berland runners are talkative by nature and that's why the juries took measures to avoid large crowds of marathon participants. The jury decided that every runner should start the marathon from their hometown. Before the start every sportsman will get a piece of paper containing the name of the city where the sportsman's finishing line is. The finish is chosen randomly for every sportsman but it can't coincide with the sportsman's starting point. Several sportsmen are allowed to finish in one and the same city. All the sportsmen start simultaneously and everyone runs the shortest route from the starting point to the finishing one. All the sportsmen run at one speed which equals to 1.After the competition a follow-up table of the results will be composed where the sportsmen will be sorted according to the nondecrease of time they spent to cover the distance. The first g sportsmen in the table will get golden medals, the next s sportsmen will get silver medals and the rest will get bronze medals. Besides, if two or more sportsmen spend the same amount of time to cover the distance, they are sorted according to the number of the city where a sportsman started to run in the ascending order. That means no two sportsmen share one and the same place.According to the rules of the competition the number of gold medals g must satisfy the inequation g1 ≀ g ≀ g2, where g1 and g2 are values formed historically. In a similar way, the number of silver medals s must satisfy the inequation s1 ≀ s ≀ s2, where s1 and s2 are also values formed historically.At present, before the start of the competition, the destination points of every sportsman are unknown. However, the press demands details and that's why you are given the task of counting the number of the ways to distribute the medals. Two ways to distribute the medals are considered different if at least one sportsman could have received during those distributions different kinds of medals.InputThe first input line contains given integers n and m (3 ≀ n ≀ 50, n - 1 ≀ m ≀ 1000), where n is the number of Berland towns and m is the number of roads.Next in m lines road descriptions are given as groups of three integers v, u, c, which are the numbers of linked towns and its length (1 ≀ v, u ≀ n, v ≠ u, 1 ≀ c ≀ 1000). Every pair of cities have no more than one road between them.The last line contains integers g1, g2, s1, s2 (1 ≀ g1 ≀ g2, 1 ≀ s1 ≀ s2, g2 + s2 < n). The input data numbers, located on one line, are space-separated.OutputPrint the single number β€” the number of ways to distribute the medals. It is guaranteed that the number fits in the standard 64-bit signed data type.ExamplesInput3 21 2 12 3 11 1 1 1Output3Input4 51 2 22 3 13 4 24 1 21 3 31 2 1 1Output19Input3 31 2 22 3 13 1 21 1 1 1Output4
Input3 21 2 12 3 11 1 1 1
Output3
4 seconds
256 megabytes
['dp', '*2400']
G. Queuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a cold winter evening our hero Vasya stood in a railway queue to buy a ticket for Codeforces championship final. As it usually happens, the cashier said he was going to be away for 5 minutes and left for an hour. Then Vasya, not to get bored, started to analyze such a mechanism as a queue. The findings astonished Vasya.Every man is characterized by two numbers: ai, which is the importance of his current task (the greater the number is, the more important the task is) and number ci, which is a picture of his conscience. Numbers ai form the permutation of numbers from 1 to n.Let the queue consist of n - 1 people at the moment. Let's look at the way the person who came number n behaves. First, he stands at the end of the queue and the does the following: if importance of the task ai of the man in front of him is less than an, they swap their places (it looks like this: the man number n asks the one before him: "Erm... Excuse me please but it's very important for me... could you please let me move up the queue?"), then he again poses the question to the man in front of him and so on. But in case when ai is greater than an, moving up the queue stops. However, the man number n can perform the operation no more than cn times.In our task let us suppose that by the moment when the man number n joins the queue, the process of swaps between n - 1 will have stopped. If the swap is possible it necessarily takes place.Your task is to help Vasya model the described process and find the order in which the people will stand in queue when all the swaps stops.InputThe first input line contains an integer n which is the number of people who has joined the queue (1 ≀ n ≀ 105). In the next n lines descriptions of the people are given in order of their coming β€” space-separated integers ai and ci (1 ≀ ai ≀ n, 0 ≀ ci ≀ n). Every description is located on s single line. All the ai's are different.OutputOutput the permutation of numbers from 1 to n, which signifies the queue formed according to the above described rules, starting from the beginning to the end. In this succession the i-th number stands for the number of a person who will stand in line on the place number i after the swaps ends. People are numbered starting with 1 in the order in which they were given in the input. Separate numbers by a space.ExamplesInput21 02 1Output2 1 Input31 32 33 3Output3 2 1 Input52 31 44 33 15 2Output3 1 5 4 2
Input21 02 1
Output2 1
2 seconds
256 megabytes
['data structures', '*2300']
F. Smart Boytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Petya and Vasya invented a new game and called it "Smart Boy". They located a certain set of words β€” the dictionary β€” for the game. It is admissible for the dictionary to contain similar words. The rules of the game are as follows: first the first player chooses any letter (a word as long as 1) from any word from the dictionary and writes it down on a piece of paper. The second player adds some other letter to this one's initial or final position, thus making a word as long as 2, then it's the first player's turn again, he adds a letter in the beginning or in the end thus making a word as long as 3 and so on. But the player mustn't break one condition: the newly created word must be a substring of a word from a dictionary. The player who can't add a letter to the current word without breaking the condition loses.Also if by the end of a turn a certain string s is written on paper, then the player, whose turn it just has been, gets a number of points according to the formula:where is a sequence number of symbol c in Latin alphabet, numbered starting from 1. For example, , and . is the number of words from the dictionary where the line s occurs as a substring at least once. Your task is to learn who will win the game and what the final score will be. Every player plays optimally and most of all tries to win, then β€” to maximize the number of his points, then β€” to minimize the number of the points of the opponent.InputThe first input line contains an integer n which is the number of words in the located dictionary (1 ≀ n ≀ 30). The n lines contain the words from the dictionary β€” one word is written on one line. Those lines are nonempty, consisting of Latin lower-case characters no longer than 30 characters. Equal words can be in the list of words.OutputOn the first output line print a line "First" or "Second" which means who will win the game. On the second line output the number of points of the first player and the number of points of the second player after the game ends. Separate the numbers by a single space.ExamplesInput2abaabacOutputSecond29 35Input3artemnikmaxOutputFirst2403 1882
Input2abaabac
OutputSecond29 35
4 seconds
256 megabytes
['dp', 'games', 'strings', '*2100']
E. Let's Go Rolling!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble number i is equal to ci, number ci may be negative. After you choose and stick the pins you need, the marbles will start to roll left according to the rule: if a marble has a pin stuck in it, then the marble doesn't move, otherwise the marble rolls all the way up to the next marble which has a pin stuck in it and stops moving there. If there is no pinned marble on the left to the given unpinned one, it is concluded that the marble rolls to the left to infinity and you will pay an infinitely large fine for it. If no marble rolled infinitely to the left, then the fine will consist of two summands: the sum of the costs of stuck pins; the sum of the lengths of the paths of each of the marbles, that is the sum of absolute values of differences between their initial and final positions. Your task is to choose and pin some marbles in the way that will make the fine for you to pay as little as possible.InputThe first input line contains an integer n (1 ≀ n ≀ 3000) which is the number of marbles. The next n lines contain the descriptions of the marbles in pairs of integers xi, ci ( - 109 ≀ xi, ci ≀ 109). The numbers are space-separated. Each description is given on a separate line. No two marbles have identical initial positions.OutputOutput the single number β€” the least fine you will have to pay.ExamplesInput32 33 41 2Output5Input41 73 15 106 1Output11
Input32 33 41 2
Output5
2 seconds
256 megabytes
['dp', 'sortings', '*1800']
D. Vasya the Architecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Vasya played bricks. All the bricks in the set had regular cubical shape. Vasya vas a talented architect, however the tower he built kept falling apart.Let us consider the building process. Vasya takes a brick and puts it on top of the already built tower so that the sides of the brick are parallel to the sides of the bricks he has already used. Let's introduce a Cartesian coordinate system on the horizontal plane, where Vasya puts the first brick. Then the projection of brick number i on the plane is a square with sides parallel to the axes of coordinates with opposite corners in points (xi, 1, yi, 1) and (xi, 2, yi, 2). The bricks are cast from homogeneous plastic and the weight of a brick a × a × a is a3 grams.It is guaranteed that Vasya puts any brick except the first one on the previous one, that is the area of intersection of the upper side of the previous brick and the lower side of the next brick is always positive.We (Vasya included) live in a normal world where the laws of physical statics work. And that is why, perhaps, if we put yet another brick, the tower will collapse under its own weight. Vasya puts the cubes consecutively one on top of the other until at least one cube loses the balance and falls down. If it happens, Vasya gets upset and stops the construction. Print the number of bricks in the maximal stable tower, that is the maximal number m satisfying the condition that all the towers consisting of bricks 1, 2, ..., k for every integer k from 1 to m remain stable.InputThe first input file contains an integer n (1 ≀ n ≀ 100) which is the number of bricks. Each of the next n lines contains four numbers xi, 1, yi, 1, xi, 2, yi, 2 (xi, 1 ≠ xi, 2, |xi, 1 - xi, 2| = |yi, 1 - yi, 2|) which are the coordinates of the opposite angles of the base of the brick number i. The coordinates are integers and their absolute value does not exceed 50. The cubes are given in the order Vasya puts them. It is guaranteed that the area of intersection of the upper side of the brick number i - 1 and the lower side of the brick number i is strictly strictly greater than zero for all i β‰₯ 2.OutputPrint the number of bricks in the maximal stable tower.ExamplesInput20 0 3 31 0 4 3Output2Input20 0 3 32 0 5 3Output1Input30 0 3 31 0 4 32 0 5 3Output3
Input20 0 3 31 0 4 3
Output2
2 seconds
256 megabytes
['implementation', '*1900']
C. Blindstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they may not have the same length (it is even possible for them to have different lengths)Every stripe can be cut into two or more parts. The cuttings are made perpendicularly to the side along which the length is measured. Thus the cuttings do not change the width of a stripe but each of the resulting pieces has a lesser length (the sum of which is equal to the length of the initial stripe)After all the cuttings the blinds are constructed through consecutive joining of several parts, similar in length, along sides, along which length is measured. Also, apart from the resulting pieces an initial stripe can be used as a blind if it hasn't been cut. It is forbidden to construct blinds in any other way.Thus, if the blinds consist of k pieces each d in length, then they are of form of a rectangle of k × d bourlemeters. Your task is to find for what window possessing the largest possible area the blinds can be made from the given stripes if on technical grounds it is forbidden to use pieces shorter than l bourlemeter. The window is of form of a rectangle with side lengths as positive integers.InputThe first output line contains two space-separated integers n and l (1 ≀ n, l ≀ 100). They are the number of stripes in the warehouse and the minimal acceptable length of a blind stripe in bourlemeters. The second line contains space-separated n integers ai. They are the lengths of initial stripes in bourlemeters (1 ≀ ai ≀ 100).OutputPrint the single number β€” the maximal area of the window in square bourlemeters that can be completely covered. If no window with a positive area that can be covered completely without breaking any of the given rules exist, then print the single number 0.ExamplesInput4 21 2 3 4Output8Input5 35 5 7 3 1Output15Input2 31 2Output0NoteIn the first sample test the required window is 2 × 4 in size and the blinds for it consist of 4 parts, each 2 bourlemeters long. One of the parts is the initial stripe with the length of 2, the other one is a part of a cut stripe with the length of 3 and the two remaining stripes are parts of a stripe with the length of 4 cut in halves.
Input4 21 2 3 4
Output8
2 seconds
256 megabytes
['brute force', '*1400']
B. Chesstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo chess pieces, a rook and a knight, stand on a standard chessboard 8 × 8 in size. The positions in which they are situated are known. It is guaranteed that none of them beats the other one.Your task is to find the number of ways to place another knight on the board so that none of the three pieces on the board beat another one. A new piece can only be placed on an empty square.InputThe first input line contains the description of the rook's position on the board. This description is a line which is 2 in length. Its first symbol is a lower-case Latin letter from a to h, and its second symbol is a number from 1 to 8. The second line contains the description of the knight's position in a similar way. It is guaranteed that their positions do not coincide.OutputPrint a single number which is the required number of ways.ExamplesInputa1b2Output44Inputa8d4Output38
Inputa1b2
Output44
2 seconds
256 megabytes
['brute force', 'implementation', 'math', '*1200']
A. Armytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.InputThe first input line contains an integer n (2 ≀ n ≀ 100). The second line contains n - 1 integers di (1 ≀ di ≀ 100). The third input line contains two integers a and b (1 ≀ a < b ≀ n). The numbers on the lines are space-separated.OutputPrint the single number which is the number of years that Vasya needs to rise from rank a to rank b.ExamplesInput35 61 2Output5Input35 61 3Output11
Input35 61 2
Output5
2 seconds
256 megabytes
['implementation', '*800']
E. Trial for Chieftime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHaving unraveled the Berland Dictionary, the scientists managed to read the notes of the chroniclers of that time. For example, they learned how the chief of the ancient Berland tribe was chosen.As soon as enough pretenders was picked, the following test took place among them: the chief of the tribe took a slab divided by horizontal and vertical stripes into identical squares (the slab consisted of N lines and M columns) and painted every square black or white. Then every pretender was given a slab of the same size but painted entirely white. Within a day a pretender could paint any side-linked set of the squares of the slab some color. The set is called linked if for any two squares belonging to the set there is a path belonging the set on which any two neighboring squares share a side. The aim of each pretender is to paint his slab in the exactly the same way as the chief’s slab is painted. The one who paints a slab like that first becomes the new chief.Scientists found the slab painted by the ancient Berland tribe chief. Help them to determine the minimal amount of days needed to find a new chief if he had to paint his slab in the given way.InputThe first line contains two integers N and M (1 ≀ N, M ≀ 50) β€” the number of lines and columns on the slab. The next N lines contain M symbols each β€” the final coloration of the slab. W stands for the square that should be painted white and B β€” for the square that should be painted black.OutputIn the single line output the minimal number of repaintings of side-linked areas needed to get the required coloration of the slab.ExamplesInput3 3WBWBWBWBWOutput2Input2 3BBBBWBOutput1
Input3 3WBWBWBWBW
Output2
2 seconds
256 megabytes
['graphs', 'greedy', 'shortest paths', '*2600']
D. Lesson Timetabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Petya has free from computer games time, he attends university classes. Every day the lessons on Petya’s faculty consist of two double classes. The floor where the lessons take place is a long corridor with M classrooms numbered from 1 to M, situated along it.All the students of Petya’s year are divided into N groups. Petya has noticed recently that these groups’ timetable has the following peculiarity: the number of the classroom where the first lesson of a group takes place does not exceed the number of the classroom where the second lesson of this group takes place. Once Petya decided to count the number of ways in which one can make a lesson timetable for all these groups. The timetable is a set of 2N numbers: for each group the number of the rooms where the first and the second lessons take place. Unfortunately, he quickly lost the track of his calculations and decided to count only the timetables that satisfy the following conditions:1) On the first lesson in classroom i exactly Xi groups must be present.2) In classroom i no more than Yi groups may be placed.Help Petya count the number of timetables satisfying all those conditionsю As there can be a lot of such timetables, output modulo 109 + 7.InputThe first line contains one integer M (1 ≀ M ≀ 100) β€” the number of classrooms.The second line contains M space-separated integers β€” Xi (0 ≀ Xi ≀ 100) the amount of groups present in classroom i during the first lesson.The third line contains M space-separated integers β€” Yi (0 ≀ Yi ≀ 100) the maximal amount of groups that can be present in classroom i at the same time.It is guaranteed that all the Xi ≀ Yi, and that the sum of all the Xi is positive and does not exceed 1000.OutputIn the single line output the answer to the problem modulo 109 + 7.ExamplesInput31 1 11 2 3Output36Input31 1 11 1 1Output6NoteIn the second sample test the first and the second lessons of each group must take place in the same classroom, that’s why the timetables will only be different in the rearrangement of the classrooms’ numbers for each group, e.g. 3! = 6.
Input31 1 11 2 3
Output36
1 second
256 megabytes
['combinatorics', 'dp', 'math', '*2300']
C. Old Berland Languagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland scientists know that the Old Berland language had exactly n words. Those words had lengths of l1, l2, ..., ln letters. Every word consisted of two letters, 0 and 1. Ancient Berland people spoke quickly and didn’t make pauses between the words, but at the same time they could always understand each other perfectly. It was possible because no word was a prefix of another one. The prefix of a string is considered to be one of its substrings that starts from the initial symbol.Help the scientists determine whether all the words of the Old Berland language can be reconstructed and if they can, output the words themselves.InputThe first line contains one integer N (1 ≀ N ≀ 1000) β€” the number of words in Old Berland language. The second line contains N space-separated integers β€” the lengths of these words. All the lengths are natural numbers not exceeding 1000.OutputIf there’s no such set of words, in the single line output NO. Otherwise, in the first line output YES, and in the next N lines output the words themselves in the order their lengths were given in the input file. If the answer is not unique, output any.ExamplesInput31 2 3OutputYES010110Input31 1 1OutputNO
Input31 2 3
OutputYES010110
2 seconds
256 megabytes
['data structures', 'greedy', 'trees', '*1900']
B. Computer Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max β€” the initial amount of health and reg β€” regeneration rate per second.2) Every scroll also has two parameters: powi β€” spell power measured in percents β€” the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≀ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.InputThe first line contains three integers N, max and reg (1 ≀ N, max, reg ≀ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each β€” the parameters of the i-th scroll (0 ≀ powi ≀ 100, 1 ≀ dmgi ≀ 2000). OutputIn case Petya can’t complete this level, output in the single line NO.Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds.Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.ExamplesInput2 10 3100 399 1OutputNOInput2 100 10100 1190 9OutputYES19 20 110 2
Input2 10 3100 399 1
OutputNO
1 second
256 megabytes
['greedy', 'implementation', '*1800']
A. Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.InputThe first line contains an integer N (1 ≀ N ≀ 1000) β€” the number of bars at Vasya’s disposal. The second line contains N space-separated integers li β€” the lengths of the bars. All the lengths are natural numbers not exceeding 1000.OutputIn one line output two numbers β€” the height of the largest tower and their total number. Remember that Vasya should use all the bars.ExamplesInput31 2 3Output1 3Input46 5 6 7Output2 3
Input31 2 3
Output1 3
2 seconds
256 megabytes
['sortings', '*1000']
E. Two Pathstime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtOnce archaeologists found m mysterious papers, each of which had a pair of integers written on them. Ancient people were known to like writing down the indexes of the roads they walked along, as Β«a bΒ» or Β«b aΒ», where a, b are the indexes of two different cities joint by the road . It is also known that the mysterious papers are pages of two travel journals (those days a new journal was written for every new journey).During one journey the traveler could walk along one and the same road several times in one or several directions but in that case he wrote a new entry for each time in his journal. Besides, the archaeologists think that the direction the traveler took on a road had no effect upon the entry: the entry that looks like Β«a bΒ» could refer to the road from a to b as well as to the road from b to a.The archaeologists want to put the pages in the right order and reconstruct the two travel paths but unfortunately, they are bad at programming. That’s where you come in. Go help them!InputThe first input line contains integer m (1 ≀ m ≀ 10000). Each of the following m lines describes one paper. Each description consists of two integers a, b (1 ≀ a, b ≀ 10000, a ≠ b).OutputIn the first line output the number L1. That is the length of the first path, i.e. the amount of papers in its description. In the following line output L1 space-separated numbers β€” the indexes of the papers that describe the first path. In the third and fourth lines output similarly the length of the second path L2 and the path itself. Both paths must contain at least one road, i.e. condition L1 > 0 and L2 > 0 must be met. The papers are numbered from 1 to m according to the order of their appearance in the input file. The numbers should be output in the order in which the traveler passed the corresponding roads. If the answer is not unique, output any.If it’s impossible to find such two paths, output Β«-1Β».Don’t forget that each paper should be used exactly once, i.e L1 + L2 = m.ExamplesInput24 54 3Output12 11Input11 2Output-1
Input24 54 3
Output12 11
2 seconds
64 megabytes
['constructive algorithms', 'dsu', 'graphs', 'implementation', '*2600']
D. New Game with a Chess Piecetime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtPetya and Vasya are inventing a new game that requires a rectangular board and one chess piece. At the beginning of the game the piece stands in the upper-left corner of the board. Two players move the piece in turns. Each turn the chess piece can be moved either one square to the right or one square down or jump k squares diagonally down and to the right. The player who can’t move the piece loses. The guys haven’t yet thought what to call the game or the best size of the board for it. Your task is to write a program that can determine the outcome of the game depending on the board size.InputThe first input line contains two integers t and k (1 ≀ t ≀ 20, 1 ≀ k ≀ 109). Each of the following t lines contains two numbers n, m β€” the board’s length and width (1 ≀ n, m ≀ 109).OutputOutput t lines that can determine the outcomes of the game on every board. Write Β«+Β» if the first player is a winner, and Β«-Β» otherwise.ExamplesInput10 21 11 22 12 21 32 33 13 23 34 3Output-++--+-+++
Input10 21 11 22 12 21 32 33 13 23 34 3
Output-++--+-+++
2 seconds
64 megabytes
['games', '*2300']
C. Bowlstime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtOnce Petya was in such a good mood that he decided to help his mum with the washing-up. There were n dirty bowls in the sink. From the geometrical point of view each bowl looks like a blunted cone. We can disregard the width of the walls and bottom. Petya puts the clean bowls one on another naturally, i. e. so that their vertical axes coincide (see the picture). You will be given the order in which Petya washes the bowls. Determine the height of the construction, i.e. the distance from the bottom of the lowest bowl to the top of the highest one. InputThe first input line contains integer n (1 ≀ n ≀ 3000). Each of the following n lines contains 3 integers h, r and R (1 ≀ h ≀ 10000, 1 ≀ r < R ≀ 10000). They are the height of a bowl, the radius of its bottom and the radius of its top. The plates are given in the order Petya puts them on the table.OutputOutput the height of the plate pile accurate to at least 10 - 6.ExamplesInput240 10 5060 20 30Output70.00000000Input350 30 8035 25 7040 10 90Output55.00000000
Input240 10 5060 20 30
Output70.00000000
2 seconds
64 megabytes
['geometry', 'implementation', '*2200']
B. Fractaltime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtEver since Kalevitch, a famous Berland abstractionist, heard of fractals, he made them the main topic of his canvases. Every morning the artist takes a piece of graph paper and starts with making a model of his future canvas. He takes a square as big as n × n squares and paints some of them black. Then he takes a clean square piece of paper and paints the fractal using the following algorithm: Step 1. The paper is divided into n2 identical squares and some of them are painted black according to the model.Step 2. Every square that remains white is divided into n2 smaller squares and some of them are painted black according to the model.Every following step repeats step 2. Unfortunately, this tiresome work demands too much time from the painting genius. Kalevitch has been dreaming of making the process automatic to move to making 3D or even 4D fractals.InputThe first line contains integers n and k (2 ≀ n ≀ 3, 1 ≀ k ≀ 5), where k is the amount of steps of the algorithm. Each of the following n lines contains n symbols that determine the model. Symbol Β«.Β» stands for a white square, whereas Β«*Β» stands for a black one. It is guaranteed that the model has at least one white square. OutputOutput a matrix nk × nk which is what a picture should look like after k steps of the algorithm.ExamplesInput2 3.*..Output.*******..******.*.*****....****.***.***..**..**.*.*.*.*........Input3 2.*.***.*.Output.*.***.*.*********.*.***.*.***************************.*.***.*.*********.*.***.*.
Input2 3.*..
Output.*******..******.*.*****....****.***.***..**..**.*.*.*.*........
2 seconds
64 megabytes
['implementation', '*1600']
A. Extra-terrestrial Intelligencetime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtRecently Vasya got interested in finding extra-terrestrial intelligence. He made a simple extra-terrestrial signals’ receiver and was keeping a record of the signals for n days in a row. Each of those n days Vasya wrote a 1 in his notebook if he had received a signal that day and a 0 if he hadn’t. Vasya thinks that he has found extra-terrestrial intelligence if there is a system in the way the signals has been received, i.e. if all the intervals between successive signals are equal. Otherwise, Vasya thinks that the signals were sent by some stupid aliens no one cares about. Help Vasya to deduce from the information given by the receiver if he has found extra-terrestrial intelligence or not.InputThe first line contains integer n (3 ≀ n ≀ 100) β€” amount of days during which Vasya checked if there were any signals. The second line contains n characters 1 or 0 β€” the record Vasya kept each of those n days. It’s guaranteed that the given record sequence contains at least three 1s.OutputIf Vasya has found extra-terrestrial intelligence, output YES, otherwise output NO.ExamplesInput800111000OutputYESInput71001011OutputNOInput71010100OutputYES
Input800111000
OutputYES
2 seconds
64 megabytes
['implementation', '*1300']
E. Paradetime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtNo Great Victory anniversary in Berland has ever passed without the war parade. This year is not an exception. That’s why the preparations are on in full strength. Tanks are building a line, artillery mounts are ready to fire, soldiers are marching on the main square... And the air forces general Mr. Generalov is in trouble again. This year a lot of sky-scrapers have been built which makes it difficult for the airplanes to fly above the city. It was decided that the planes should fly strictly from south to north. Moreover, there must be no sky scraper on a plane’s route, otherwise the anniversary will become a tragedy. The Ministry of Building gave the data on n sky scrapers (the rest of the buildings are rather small and will not be a problem to the planes). When looking at the city from south to north as a geometrical plane, the i-th building is a rectangle of height hi. Its westernmost point has the x-coordinate of li and the easternmost β€” of ri. The terrain of the area is plain so that all the buildings stand on one level. Your task as the Ministry of Defence’s head programmer is to find an enveloping polyline using the data on the sky-scrapers. The polyline’s properties are as follows: If you look at the city from south to north as a plane, then any part of any building will be inside or on the boarder of the area that the polyline encloses together with the land surface. The polyline starts and ends on the land level, i.e. at the height equal to 0. The segments of the polyline are parallel to the coordinate axes, i.e. they can only be vertical or horizontal. The polyline’s vertices should have integer coordinates. If you look at the city from south to north the polyline (together with the land surface) must enclose the minimum possible area. The polyline must have the smallest length among all the polylines, enclosing the minimum possible area with the land. The consecutive segments of the polyline must be perpendicular. Picture to the second sample test (the enveloping polyline is marked on the right). InputThe first input line contains integer n (1 ≀ n ≀ 100000). Then follow n lines, each containing three integers hi, li, ri (1 ≀ hi ≀ 109,  - 109 ≀ li < ri ≀ 109).OutputIn the first line output integer m β€” amount of vertices of the enveloping polyline. The next m lines should contain 2 integers each β€” the position and the height of the polyline’s vertex. Output the coordinates of each vertex in the order of traversing the polyline from west to east. Remember that the first and the last vertices of the polyline should have the height of 0.ExamplesInput23 0 24 1 3Output60 00 31 31 43 43 0Input53 -3 02 -1 14 2 42 3 73 6 8Output14-3 0-3 30 30 21 21 02 02 44 44 26 26 38 38 0
Input23 0 24 1 3
Output60 00 31 31 43 43 0
2 seconds
64 megabytes
['data structures', 'sortings', '*2100']
D. Animalstime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtOnce upon a time DravDe, an outstanding person famous for his professional achievements (as you must remember, he works in a warehouse storing Ogudar-Olok, a magical but non-alcoholic drink) came home after a hard day. That day he had to drink 9875 boxes of the drink and, having come home, he went to bed at once.DravDe dreamt about managing a successful farm. He dreamt that every day one animal came to him and asked him to let it settle there. However, DravDe, being unimaginably kind, could send the animal away and it went, rejected. There were exactly n days in DravDe’s dream and the animal that came on the i-th day, ate exactly ci tons of food daily starting from day i. But if one day the animal could not get the food it needed, it got really sad. At the very beginning of the dream there were exactly X tons of food on the farm.DravDe woke up terrified...When he retold the dream to you, he couldn’t remember how many animals were on the farm by the end of the n-th day any more, but he did remember that nobody got sad (as it was a happy farm) and that there was the maximum possible amount of the animals. That’s the number he wants you to find out. It should be noticed that the animals arrived in the morning and DravDe only started to feed them in the afternoon, so that if an animal willing to join them is rejected, it can’t eat any farm food. But if the animal does join the farm, it eats daily from that day to the n-th.InputThe first input line contains integers n and X (1 ≀ n ≀ 100, 1 ≀ X ≀ 104) β€” amount of days in DravDe’s dream and the total amount of food (in tons) that was there initially. The second line contains integers ci (1 ≀ ci ≀ 300). Numbers in the second line are divided by a space.OutputOutput the only number β€” the maximum possible amount of animals on the farm by the end of the n-th day given that the food was enough for everybody.ExamplesInput3 41 1 1Output2Input3 61 1 1Output3NoteNote to the first example: DravDe leaves the second and the third animal on the farm. The second animal will eat one ton of food on the second day and one ton on the third day. The third animal will eat one ton of food on the third day.
Input3 41 1 1
Output2
2 seconds
64 megabytes
['dp', 'greedy', '*1700']
C. Fire Againtime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtAfter a terrifying forest fire in Berland a forest rebirth program was carried out. Due to it N rows with M trees each were planted and the rows were so neat that one could map it on a system of coordinates so that the j-th tree in the i-th row would have the coordinates of (i, j). However a terrible thing happened and the young forest caught fire. Now we must find the coordinates of the tree that will catch fire last to plan evacuation.The burning began in K points simultaneously, which means that initially K trees started to burn. Every minute the fire gets from the burning trees to the ones that aren’t burning and that the distance from them to the nearest burning tree equals to 1.Find the tree that will be the last to start burning. If there are several such trees, output any.InputThe first input line contains two integers N, M (1 ≀ N, M ≀ 2000) β€” the size of the forest. The trees were planted in all points of the (x, y) (1 ≀ x ≀ N, 1 ≀ y ≀ M) type, x and y are integers.The second line contains an integer K (1 ≀ K ≀ 10) β€” amount of trees, burning in the beginning. The third line contains K pairs of integers: x1, y1, x2, y2, ..., xk, yk (1 ≀ xi ≀ N, 1 ≀ yi ≀ M) β€” coordinates of the points from which the fire started. It is guaranteed that no two points coincide.OutputOutput a line with two space-separated integers x and y β€” coordinates of the tree that will be the last one to start burning. If there are several such trees, output any.ExamplesInput3 312 2Output1 1Input3 311 1Output3 3Input3 321 1 3 3Output2 2
Input3 312 2
Output1 1
2 seconds
64 megabytes
['brute force', 'dfs and similar', 'shortest paths', '*1500']
B. Warehousetime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtOnce upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse.The warehouse has one set of shelving. It has n shelves, each of which is divided into m sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught.After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you.The process of counting contains two types of query messages: Β«+1 x y idΒ» (where x, y are integers, 1 ≀ x ≀ n, 1 ≀ y ≀ m, and id is a string of lower case Latin letters β€” from 1 to 10 characters long). That query means that the warehouse got a box identified as id, which should be put in the section y on the shelf x. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query. Β«-1 idΒ» (where id is a string of lower case Latin letters β€” from 1 to 10 characters long). That query means that a box identified as id is removed from the warehouse. You have to answer this query (see output format). InputThe first input line contains integers n, m and k (1 ≀ n, m ≀ 30, 1 ≀ k ≀ 2000) β€” the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following k lines the queries are given in the order of appearance in the format described above.OutputFor each query of the Β«-1 idΒ» type output two numbers in a separate line β€” index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output Β«-1 -1Β» without quotes.ExamplesInput2 2 9+1 1 1 cola+1 1 1 fanta+1 1 1 sevenup+1 1 1 whitekey-1 cola-1 fanta-1 sevenup-1 whitekey-1 colaOutput1 11 22 12 2-1 -1Input2 2 8+1 1 1 cola-1 cola+1 1 1 fanta-1 fanta+1 1 1 sevenup-1 sevenup+1 1 1 whitekey-1 whitekeyOutput1 11 11 11 1
Input2 2 9+1 1 1 cola+1 1 1 fanta+1 1 1 sevenup+1 1 1 whitekey-1 cola-1 fanta-1 sevenup-1 whitekey-1 cola
Output1 11 22 12 2-1 -1
2 seconds
64 megabytes
['implementation', '*1700']
A. Shell Gametime limit per test2 secondsmemory limit per test64 megabytesinputinput.txtoutputoutput.txtToday the Β«ZΒ» city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. The performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so that on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct they get a prize. Maybe you can try to find the ball too?InputThe first input line contains an integer from 1 to 3 β€” index of the cup which covers the ball before the shuffles. The following three lines describe the shuffles. Each description of a shuffle contains two distinct integers from 1 to 3 β€” indexes of the cups which the performer shuffled this time. The cups are numbered from left to right and are renumbered after each shuffle from left to right again. In other words, the cup on the left always has index 1, the one in the middle β€” index 2 and the one on the right β€” index 3.OutputIn the first line output an integer from 1 to 3 β€” index of the cup which will have the ball after all the shuffles. ExamplesInput11 22 12 1Output2Input12 13 11 3Output2
Input11 22 12 1
Output2
2 seconds
64 megabytes
['implementation', '*1000']
E. Collisionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored.The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds will be: .Your task is to find out, where each ball will be t seconds after.InputThe first line contains two integers n and t (1 ≀ n ≀ 10, 0 ≀ t ≀ 100) β€” amount of balls and duration of the process. Then follow n lines, each containing three integers: xi, vi, mi (1 ≀ |vi|, mi ≀ 100, |xi| ≀ 100) β€” coordinate, speed and weight of the ball with index i at time moment 0.It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;t]).OutputOutput n numbers β€” coordinates of the balls t seconds after. Output the numbers accurate to at least 4 digits after the decimal point.ExamplesInput2 93 4 50 7 8Output68.53846153844.538461538Input3 101 2 34 -5 67 -8 9Output-93.666666667-74.666666667-15.666666667
Input2 93 4 50 7 8
Output68.53846153844.538461538
2 seconds
256 megabytes
['brute force', 'implementation', 'math', '*2000']
D. Road Maptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities in Berland. Each city has its index β€” an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi β€” index of the last city on the way from the capital to i.Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above.InputThe first line contains three space-separated integers n, r1, r2 (2 ≀ n ≀ 5Β·104, 1 ≀ r1 ≠ r2 ≀ n) β€” amount of cities in Berland, index of the old capital and index of the new one, correspondingly.The following line contains n - 1 space-separated integers β€” the old representation of the road map. For each city, apart from r1, there is given integer pi β€” index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes.OutputOutput n - 1 numbers β€” new representation of the road map in the same format.ExamplesInput3 2 32 2Output2 3 Input6 2 46 1 2 4 2Output6 4 1 4 2
Input3 2 32 2
Output2 3
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*1600']
C. Page Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputΒ«BersoftΒ» company is working on a new version of its most popular text editor β€” Bord 2010. Bord, like many other text editors, should be able to print out multipage documents. A user keys a sequence of the document page numbers that he wants to print out (separates them with a comma, without spaces).Your task is to write a part of the program, responsible for Β«standardizationΒ» of this sequence. Your program gets the sequence, keyed by the user, as input. The program should output this sequence in format l1-r1,l2-r2,...,lk-rk, where ri + 1 < li + 1 for all i from 1 to k - 1, and li ≀ ri. The new sequence should contain all the page numbers, keyed by the user, and nothing else. If some page number appears in the input sequence several times, its appearances, starting from the second one, should be ignored. If for some element i from the new sequence li = ri, this element should be output as li, and not as Β«li - liΒ».For example, sequence 1,2,3,1,1,2,6,6,2 should be output as 1-3,6.InputThe only line contains the sequence, keyed by the user. The sequence contains at least one and at most 100 positive integer numbers. It's guaranteed, that this sequence consists of positive integer numbers, not exceeding 1000, separated with a comma, doesn't contain any other characters, apart from digits and commas, can't end with a comma, and the numbers don't contain leading zeroes. Also it doesn't start with a comma or contain more than one comma in a row.OutputOutput the sequence in the required format.ExamplesInput1,2,3,1,1,2,6,6,2Output1-3,6Input3,2,1Output1-3Input30,20,10Output10,20,30
Input1,2,3,1,1,2,6,6,2
Output1-3,6
2 seconds
256 megabytes
['expression parsing', 'implementation', 'sortings', 'strings', '*1300']
B. Saletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β€” their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.InputThe first line contains two space-separated integers n and m (1 ≀ m ≀ n ≀ 100) β€” amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≀ ai ≀ 1000) β€” prices of the TV sets. OutputOutput the only number β€” the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.ExamplesInput5 3-6 0 35 -2 4Output8Input4 27 0 0 -7Output7
Input5 3-6 0 35 -2 4
Output8
2 seconds
256 megabytes
['greedy', 'sortings', '*900']
A. Reconnaissance 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.InputThe first line contains integer n (2 ≀ n ≀ 100) β€” amount of soldiers. Then follow the heights of the soldiers in their order in the circle β€” n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 1000). The soldier heights are given in clockwise or counterclockwise direction.OutputOutput two integers β€” indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.ExamplesInput510 12 13 15 10Output5 1Input410 20 30 40Output1 2
Input510 12 13 15 10
Output5 1
2 seconds
256 megabytes
['implementation', '*800']
E. Helpertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's unbelievable, but an exam period has started at the OhWord University. It's even more unbelievable, that Valera got all the tests before the exam period for excellent work during the term. As now he's free, he wants to earn money by solving problems for his groupmates. He's made a list of subjects that he can help with. Having spoken with n of his groupmates, Valera found out the following information about them: what subject each of them passes, time of the exam and sum of money that each person is ready to pay for Valera's help.Having this data, Valera's decided to draw up a timetable, according to which he will solve problems for his groupmates. For sure, Valera can't solve problems round the clock, that's why he's found for himself an optimum order of day and plans to stick to it during the whole exam period. Valera assigned time segments for sleep, breakfast, lunch and dinner. The rest of the time he can work.Obviously, Valera can help a student with some subject, only if this subject is on the list. It happened, that all the students, to whom Valera spoke, have different, but one-type problems, that's why Valera can solve any problem of subject listi in ti minutes.Moreover, if Valera starts working at some problem, he can break off only for sleep or meals, but he can't start a new problem, not having finished the current one. Having solved the problem, Valera can send it instantly to the corresponding student via the Internet.If this student's exam hasn't started yet, he can make a crib, use it to pass the exam successfully, and pay Valera the promised sum. Since Valera has little time, he asks you to write a program that finds the order of solving problems, which can bring Valera maximum profit.InputThe first line contains integers m, n, k (1 ≀ m, n ≀ 100, 1 ≀ k ≀ 30) β€” amount of subjects on the list, amount of Valera's potential employers and the duration of the exam period in days.The following m lines contain the names of subjects listi (listi is a non-empty string of at most 32 characters, consisting of lower case Latin letters). It's guaranteed that no two subjects are the same.The (m + 2)-th line contains m integers ti (1 ≀ ti ≀ 1000) β€” time in minutes that Valera spends to solve problems of the i-th subject. Then follow four lines, containing time segments for sleep, breakfast, lunch and dinner correspondingly.Each line is in format H1:M1-H2:M2, where 00 ≀  H1, H2  ≀ 23, 00 ≀  M1, M2  ≀ 59. Time H1:M1 stands for the first minute of some Valera's action, and time H2:M2 stands for the last minute of this action. No two time segments cross. It's guaranteed that Valera goes to bed before midnight, gets up earlier than he has breakfast, finishes his breakfast before lunch, finishes his lunch before dinner, and finishes his dinner before midnight. All these actions last less than a day, but not less than one minute. Time of the beginning and time of the ending of each action are within one and the same day. But it's possible that Valera has no time for solving problems.Then follow n lines, each containing the description of students. For each student the following is known: his exam subject si (si is a non-empty string of at most 32 characters, consisting of lower case Latin letters), index of the exam day di (1 ≀ di ≀ k), the exam time timei, and sum of money ci (0 ≀ ci ≀ 106, ci β€” integer) that he's ready to pay for Valera's help. Exam time timei is in the format HH:MM, where 00 ≀  HH  ≀ 23, 00 ≀  MM  ≀ 59. Valera will get money, if he finishes to solve the problem strictly before the corresponding student's exam begins.OutputIn the first line output the maximum profit that Valera can get. The second line should contain number p β€” amount of problems that Valera is to solve. In the following p lines output the order of solving problems in chronological order in the following format: index of a student, to whom Valera is to help; index of the time, when Valera should start the problem; time, when Valera should start the problem (the first minute of his work); index of the day, when Valera should finish the problem; time, when Valera should finish the problem (the last minute of his work). To understand the output format better, study the sample tests.ExamplesInput3 3 4calculusalgebrahistory58 23 1500:00-08:1508:20-08:3509:30-10:2519:00-19:45calculus 1 09:36 100english 4 21:15 5000history 1 19:50 50Output15021 1 08:16 1 09:293 1 10:26 1 10:40Input2 2 1matancodeforces1 200:00-08:0009:00-09:0012:00-12:0018:00-18:00codeforces 1 08:04 2matan 1 08:02 1Output322 1 08:01 1 08:011 1 08:02 1 08:03Input2 2 1matancodeforces2 200:00-08:0009:00-09:0012:00-12:0018:00-18:00codeforces 1 08:04 2matan 1 08:03 1Output211 1 08:01 1 08:02
Input3 3 4calculusalgebrahistory58 23 1500:00-08:1508:20-08:3509:30-10:2519:00-19:45calculus 1 09:36 100english 4 21:15 5000history 1 19:50 50
Output15021 1 08:16 1 09:293 1 10:26 1 10:40
2 seconds
256 megabytes
['*2600']
D. Knightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland is facing dark times again. The army of evil lord Van de Mart is going to conquer the whole kingdom. To the council of war called by the Berland's king Valery the Severe came n knights. After long discussions it became clear that the kingdom has exactly n control points (if the enemy conquers at least one of these points, the war is lost) and each knight will occupy one of these points. Berland is divided into m + 1 regions with m fences, and the only way to get from one region to another is to climb over the fence. Each fence is a circle on a plane, no two fences have common points, and no control point is on the fence. You are given k pairs of numbers ai, bi. For each pair you have to find out: how many fences a knight from control point with index ai has to climb over to reach control point bi (in case when Van de Mart attacks control point bi first). As each knight rides a horse (it is very difficult to throw a horse over a fence), you are to find out for each pair the minimum amount of fences to climb over.InputThe first input line contains three integers n, m, k (1 ≀ n, m ≀ 1000, 0 ≀ k ≀ 100000). Then follow n lines, each containing two integers Kxi, Kyi ( - 109 ≀ Kxi, Kyi ≀ 109) β€” coordinates of control point with index i. Control points can coincide.Each of the following m lines describes fence with index i with three integers ri, Cxi, Cyi (1 ≀ ri ≀ 109,  - 109 ≀ Cxi, Cyi ≀ 109) β€” radius and center of the circle where the corresponding fence is situated.Then follow k pairs of integers ai, bi (1 ≀ ai, bi ≀ n), each in a separate line β€” requests that you have to answer. ai and bi can coincide.OutputOutput exactly k lines, each containing one integer β€” the answer to the corresponding request.ExamplesInput2 1 10 03 32 0 01 2Output1Input2 3 10 04 41 0 02 0 03 0 01 2Output3
Input2 1 10 03 32 0 01 2
Output1
2 seconds
256 megabytes
['geometry', 'graphs', 'shortest paths', 'sortings', '*2000']
C. Wonderful Randomized Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLearn, learn and learn again β€” Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite that Valera is one of the best students, he failed to manage with the new homework. That's why he asks for your help. He has the following task. A sequence of n numbers is given. A prefix of a sequence is the part of the sequence (possibly empty), taken from the start of the sequence. A suffix of a sequence is the part of the sequence (possibly empty), taken from the end of the sequence. It is allowed to sequentially make two operations with the sequence. The first operation is to take some prefix of the sequence and multiply all numbers in this prefix by  - 1. The second operation is to take some suffix and multiply all numbers in it by  - 1. The chosen prefix and suffix may intersect. What is the maximum total sum of the sequence that can be obtained by applying the described operations?InputThe first line contains integer n (1 ≀ n ≀ 105) β€” amount of elements in the sequence. The second line contains n integers ai ( - 104 ≀ ai ≀ 104) β€” the sequence itself.OutputThe first and the only line of the output should contain the answer to the problem.ExamplesInput3-1 -2 -3Output6Input5-4 2 0 5 0Output11Input5-1 10 -5 10 -2Output18
Input3-1 -2 -3
Output6
2 seconds
256 megabytes
['greedy', '*1800']
B. String Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBoy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings. InputThe first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≀ n ≀ 500)Β β€” amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≀ Wi ≀ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.OutputIf the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.ExamplesInputuayduxxd3a x 8x y 13d c 3Output21uxydInputab3a b 2a b 3b a 5Output2bInputabcab6a b 4a b 7b a 8c b 11c a 3a c 0Output-1
Inputuayduxxd3a x 8x y 13d c 3
Output21uxyd
2 seconds
256 megabytes
['shortest paths', '*1800']
A. What is for dinner?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.InputThe first line contains three integers n, m, k (1 ≀ m ≀ n ≀ 1000, 0 ≀ k ≀ 106) β€” total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1 ≀ r ≀ m) β€” index of the row, where belongs the corresponding tooth, and c (0 ≀ c ≀ 106) β€” its residual viability.It's guaranteed that each tooth row has positive amount of teeth.OutputIn the first line output the maximum amount of crucians that Valerie can consume for dinner.ExamplesInput4 3 182 31 23 62 3Output11Input2 2 131 132 12Output13
Input4 3 182 31 23 62 3
Output11
2 seconds
256 megabytes
['greedy', 'implementation', '*1200']
E. Hide-and-Seektime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVictor and Peter are playing hide-and-seek. Peter has hidden, and Victor is to find him. In the room where they are playing, there is only one non-transparent wall and one double-sided mirror. Victor and Peter are points with coordinates (xv, yv) and (xp, yp) respectively. The wall is a segment joining points with coordinates (xw, 1, yw, 1) and (xw, 2, yw, 2), the mirror β€” a segment joining points (xm, 1, ym, 1) and (xm, 2, ym, 2).If an obstacle has a common point with a line of vision, it's considered, that the boys can't see each other with this line of vision. If the mirror has a common point with the line of vision, it's considered, that the boys can see each other in the mirror, i.e. reflection takes place. The reflection process is governed by laws of physics β€” the angle of incidence is equal to the angle of reflection. The incident ray is in the same half-plane as the reflected ray, relative to the mirror. I.e. to see each other Victor and Peter should be to the same side of the line, containing the mirror (see example 1). If the line of vision is parallel to the mirror, reflection doesn't take place, and the mirror isn't regarded as an obstacle (see example 4).Victor got interested if he can see Peter, while standing at the same spot. Help him solve this problem.InputThe first line contains two numbers xv and yv β€” coordinates of Victor.The second line contains two numbers xp and yp β€” coordinates of Peter.The third line contains 4 numbers xw, 1, yw, 1, xw, 2, yw, 2 β€” coordinates of the wall.The forth line contains 4 numbers xm, 1, ym, 1, xm, 2, ym, 2 β€” coordinates of the mirror.All the coordinates are integer numbers, and don't exceed 104 in absolute value. It's guaranteed, that the segments don't have common points, Victor and Peter are not on any of the segments, coordinates of Victor and Peter aren't the same, the segments don't degenerate into points.OutputOutput YES, if Victor can see Peter without leaving the initial spot. Otherwise output NO.ExamplesInput-1 31 30 2 0 40 0 0 1OutputNOInput0 01 10 1 1 0-100 -100 -101 -101OutputNOInput0 01 10 1 1 0-1 1 1 3OutputYESInput0 010 0100 100 101 1011 0 3 0OutputYES
Input-1 31 30 2 0 40 0 0 1
OutputNO
2 seconds
256 megabytes
['geometry', 'implementation', '*2400']
D. Constellationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is true: the 2nd is on the same vertical line as the 1st, but x squares up the 3rd is on the same vertical line as the 1st, but x squares down the 4th is on the same horizontal line as the 1st, but x squares left the 5th is on the same horizontal line as the 1st, but x squares right Such constellations can be very numerous, that's why they are numbered with integers from 1 on the following principle: when two constellations are compared, the one with a smaller radius gets a smaller index; if their radii are equal β€” the one, whose central star if higher than the central star of the other one; if their central stars are at the same level β€” the one, whose central star is to the left of the central star of the other one.Your task is to find the constellation with index k by the given Berland's star map.InputThe first line contains three integers n, m and k (1 ≀ n, m ≀ 300, 1 ≀ k ≀ 3Β·107) β€” height and width of the map and index of the required constellation respectively. The upper-left corner has coordinates (1, 1), and the lower-right β€” (n, m). Then there follow n lines, m characters each β€” description of the map. j-th character in i-th line is Β«*Β», if there is a star in the corresponding square, and Β«.Β» if this square is empty.OutputIf the number of the constellations is less than k, output -1. Otherwise output 5 lines, two integers each β€” coordinates of the required constellation. Output the stars in the following order: central, upper, lower, left, right.ExamplesInput5 6 1....*....***....*...*....***..Output2 51 53 52 42 6Input5 6 2....*....***....*...*....***..Output-1Input7 7 2...*.............*...*.***.*...*.............*...Output4 41 47 44 14 7
Input5 6 1....*....***....*...*....***..
Output2 51 53 52 42 6
2 seconds
256 megabytes
['implementation', '*1600']
C. Fleatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is known that fleas in Berland can jump only vertically and horizontally, and the length of the jump is always equal to s centimeters. A flea has found herself at the center of some cell of the checked board of the size n × m centimeters (each cell is 1 × 1 centimeters). She can jump as she wishes for an arbitrary number of times, she can even visit a cell more than once. The only restriction is that she cannot jump out of the board.The flea can count the amount of cells that she can reach from the starting position (x, y). Let's denote this amount by dx, y. Your task is to find the number of such starting positions (x, y), which have the maximum possible value of dx, y.InputThe first line contains three integers n, m, s (1 ≀ n, m, s ≀ 106) β€” length of the board, width of the board and length of the flea's jump.OutputOutput the only integer β€” the number of the required starting positions of the flea.ExamplesInput2 3 1000000Output6Input3 3 2Output4
Input2 3 1000000
Output6
2 seconds
256 megabytes
['math', '*1700']
B. Borzetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTernary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.InputThe first line contains a number in Borze code. The length of the string is between 1 and 200 characters. It's guaranteed that the given string is a valid Borze code of some ternary number (this number can have leading zeroes).OutputOutput the decoded ternary number. It can have leading zeroes.ExamplesInput.-.--Output012Input--.Output20Input-..-.--Output1012
Input.-.--
Output012
2 seconds
256 megabytes
['expression parsing', 'implementation', '*800']
A. Reconnaissancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAccording to the regulations of Berland's army, a reconnaissance unit should consist of exactly two soldiers. Since these two soldiers shouldn't differ much, their heights can differ by at most d centimeters. Captain Bob has n soldiers in his detachment. Their heights are a1, a2, ..., an centimeters. Some soldiers are of the same height. Bob wants to know, how many ways exist to form a reconnaissance unit of two soldiers from his detachment.Ways (1, 2) and (2, 1) should be regarded as different.InputThe first line contains two integers n and d (1 ≀ n ≀ 1000, 1 ≀ d ≀ 109) β€” amount of soldiers in Bob's detachment and the maximum allowed height difference respectively. The second line contains n space-separated integers β€” heights of all the soldiers in Bob's detachment. These numbers don't exceed 109.OutputOutput one number β€” amount of ways to form a reconnaissance unit of two soldiers, whose height difference doesn't exceed d.ExamplesInput5 1010 20 50 60 65Output6Input5 155 30 29 31 55Output6
Input5 1010 20 50 60 65
Output6
2 seconds
256 megabytes
['brute force', '*800']
E. TV Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a new TV game on BerTV. In this game two players get a number A consisting of 2n digits. Before each turn players determine who will make the next move. Each player should make exactly n moves. On it's turn i-th player takes the leftmost digit of A and appends it to his or her number Si. After that this leftmost digit is erased from A. Initially the numbers of both players (S1 and S2) are Β«emptyΒ». Leading zeroes in numbers A, S1, S2 are allowed. In the end of the game the first player gets S1 dollars, and the second gets S2 dollars.One day Homer and Marge came to play the game. They managed to know the number A beforehand. They want to find such sequence of their moves that both of them makes exactly n moves and which maximizes their total prize. Help them.InputThe first line contains integer n (1 ≀ n ≀ 18). The second line contains integer A consisting of exactly 2n digits. This number can have leading zeroes.OutputOutput the line of 2n characters Β«HΒ» and Β«MΒ» β€” the sequence of moves of Homer and Marge, which gives them maximum possible total prize. Each player must make exactly n moves. If there are several solutions, output any of them.ExamplesInput21234OutputHHMMInput29911OutputHMHM
Input21234
OutputHHMM
2 seconds
256 megabytes
['dp', '*2400']
D. Chocolatetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has a rectangular chocolate bar of the size W × H. He introduced a cartesian coordinate system so that the point (0, 0) corresponds to the lower-left corner of the bar, and the point (W, H) corresponds to the upper-right corner. Bob decided to split the bar into pieces by breaking it. Each break is a segment parallel to one of the coordinate axes, which connects the edges of the bar. More formally, each break goes along the line x = xc or y = yc, where xc and yc are integers. It should divide one part of the bar into two non-empty parts. After Bob breaks some part into two parts, he breaks the resulting parts separately and independently from each other. Also he doesn't move the parts of the bar. Bob made n breaks and wrote them down in his notebook in arbitrary order. At the end he got n + 1 parts. Now he wants to calculate their areas. Bob is lazy, so he asks you to do this task.InputThe first line contains 3 integers W, H and n (1 ≀ W, H, n ≀ 100) β€” width of the bar, height of the bar and amount of breaks. Each of the following n lines contains four integers xi, 1, yi, 1, xi, 2, yi, 2 β€” coordinates of the endpoints of the i-th break (0 ≀ xi, 1 ≀ xi, 2 ≀ W, 0 ≀ yi, 1 ≀ yi, 2 ≀ H, or xi, 1 = xi, 2, or yi, 1 = yi, 2). Breaks are given in arbitrary order.It is guaranteed that the set of breaks is correct, i.e. there is some order of the given breaks that each next break divides exactly one part of the bar into two non-empty parts.OutputOutput n + 1 numbers β€” areas of the resulting parts in the increasing order.ExamplesInput2 2 21 0 1 20 1 1 1Output1 1 2 Input2 2 31 0 1 20 1 1 11 1 2 1Output1 1 1 1 Input2 4 20 1 2 10 3 2 3Output2 2 4
Input2 2 21 0 1 20 1 1 1
Output1 1 2
2 seconds
256 megabytes
['dfs and similar', 'implementation', '*2000']
C. Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.InputThe first line contains integer n (1 ≀ n ≀ 5000) β€” amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 ≀ li < ri ≀ 106) β€” starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1).OutputOutput integer k β€” amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers β€” indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.ExamplesInput33 1020 301 3Output31 2 3 Input43 1020 301 31 39Output14 Input31 52 63 7Output0
Input33 1020 301 3
Output31 2 3
2 seconds
256 megabytes
['implementation', '*1700']
B. Sysadmin Bobtime limit per test0.5 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEmail address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in Β«BersoftΒ» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.InputThe first line contains the list of addresses without separators. The length of this string is between 1 and 200, inclusive. The string consists only from small Latin letters and characters Β«@Β».OutputIf there is no list of the valid (according to the Berland rules) email addresses such that after removing all commas it coincides with the given string, output No solution. In the other case, output the list. The same address can be written in this list more than once. If there are several solutions, output any of them.ExamplesInputa@aa@aOutputa@a,a@aInputa@a@aOutputNo solutionInput@aa@aOutputNo solution
Inputa@aa@a
Outputa@a,a@a
0.5 second
256 megabytes
['greedy', 'implementation', 'strings', '*1500']
A. Worms Evolutiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of lengths of the other two forms. Help him to do this.InputThe first line contains integer n (3 ≀ n ≀ 100) β€” amount of worm's forms. The second line contains n space-separated integers ai (1 ≀ ai ≀ 1000) β€” lengths of worms of each form.OutputOutput 3 distinct integers i j k (1 ≀ i, j, k ≀ n) β€” such indexes of worm's forms that ai = aj + ak. If there is no such triple, output -1. If there are several solutions, output any of them. It possible that aj = ak.ExamplesInput51 2 3 5 7Output3 2 1Input51 8 1 5 1Output-1
Input51 2 3 5 7
Output3 2 1
2 seconds
256 megabytes
['implementation', '*1200']
E. Tricky and Clever Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn his very young years the hero of our story, king Copa, decided that his private data was hidden not enough securely, what is unacceptable for the king. That's why he invented tricky and clever password (later he learned that his password is a palindrome of odd length), and coded all his data using it. Copa is afraid to forget his password, so he decided to write it on a piece of paper. He is aware that it is insecure to keep password in such way, so he decided to cipher it the following way: he cut x characters from the start of his password and from the end of it (x can be 0, and 2x is strictly less than the password length). He obtained 3 parts of the password. Let's call it prefix, middle and suffix correspondingly, both prefix and suffix having equal length and middle always having odd length. From these parts he made a string A + prefix + B + middle + C + suffix, where A, B and C are some (possibly empty) strings invented by Copa, and « + » means concatenation.Many years have passed, and just yesterday the king Copa found the piece of paper where his ciphered password was written. The password, as well as the strings A, B and C, was completely forgotten by Copa, so he asks you to find a password of maximum possible length, which could be invented, ciphered and written by Copa.InputThe input contains single string of small Latin letters with length from 1 to 105 characters.OutputThe first line should contain integer k β€” amount of nonempty parts of the password in your answer (). In each of the following k lines output two integers xi and li β€” start and length of the corresponding part of the password. Output pairs in order of increasing xi. Separate the numbers in pairs by a single space.Starting position xi should be an integer from 1 to the length of the input string. All li must be positive, because you should output only non-empty parts. The middle part must have odd length.If there are several solutions, output any. Note that your goal is to maximize the sum of li, but not to maximize k.ExamplesInputabacabaOutput11 7InputaxbyaOutput31 12 15 1InputxabyczbaOutput32 24 17 2
Inputabacaba
Output11 7
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'hashing', 'strings', '*2800']
D. King's Problem?time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvery true king during his life must conquer the world, hold the Codeforces world finals, win pink panda in the shooting gallery and travel all over his kingdom.King Copa has already done the first three things. Now he just needs to travel all over the kingdom. The kingdom is an infinite plane with Cartesian coordinate system on it. Every city is a point on this plane. There are n cities in the kingdom at points with coordinates (x1, 0), (x2, 0), ..., (xn, 0), and there is one city at point (xn + 1, yn + 1). King starts his journey in the city number k. Your task is to find such route for the king, which visits all cities (in any order) and has minimum possible length. It is allowed to visit a city twice. The king can end his journey in any city. Between any pair of cities there is a direct road with length equal to the distance between the corresponding points. No two cities may be located at the same point.InputThe first line contains two integers n and k (1 ≀ n ≀ 105, 1 ≀ k ≀ n + 1) β€” amount of cities and index of the starting city. The second line contains n + 1 numbers xi. The third line contains yn + 1. All coordinates are integers and do not exceed 106 by absolute value. No two cities coincide.OutputOutput the minimum possible length of the journey. Your answer must have relative or absolute error less than 10 - 6.ExamplesInput3 10 1 2 11Output3.41421356237309490000Input3 11 0 2 11Output3.82842712474619030000Input4 50 5 -1 -5 23Output14.24264068711928400000
Input3 10 1 2 11
Output3.41421356237309490000
3 seconds
256 megabytes
['geometry', 'greedy', '*2600']
C. Shooting Gallerytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize β€” big pink plush panda. The king is not good at shooting, so he invited you to help him.The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates xi, and yi, by the time of it's appearance ti and by the number pi, which gives the probability that Copa hits this target if he aims at it.A target appears and disappears instantly, so Copa can hit the target only if at the moment ti his gun sight aimed at (xi, yi). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” amount of targets in the shooting gallery. Then n lines follow, each describing one target. Each description consists of four numbers xi, yi, ti, pi (where xi, yi, ti β€” integers,  - 1000 ≀ xi, yi ≀ 1000, 0 ≀ ti ≀ 109, real number pi is given with no more than 6 digits after the decimal point, 0 ≀ pi ≀ 1). No two targets may be at the same point.OutputOutput the maximum expected value of the amount of targets that was shot by the king. Your answer will be accepted if it differs from the correct answer by not more than 10 - 6.ExamplesInput10 0 0 0.5Output0.5000000000Input20 0 0 0.65 0 5 0.7Output1.3000000000
Input10 0 0 0.5
Output0.5000000000
2 seconds
256 megabytes
['dp', 'probabilities', '*1800']