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
B. String inside outtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string S of even length s1..s2n . Perform the following manipulations: divide it into two halves s1..sn and sn + 1..s2n reverse each of them sn..s1 and s2n..sn + 1 concatenate the resulting strings into sn..s1s2n..sn + 1Output the result of these manipulations.InputThe only line of the input contains a string of lowercase Latin letters. The length of the string is between 2 and 20, inclusive, and it is even. OutputOutput the string which is the result of the described manipulations.ExamplesInputcodeforcesOutputfedocsecroInputqwertyasdfghOutputytrewqhgfdsa
Inputcodeforces
Outputfedocsecro
2 seconds
256 megabytes
['*special problem', '*1600']
A. Quadratic equationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a quadratic equation with integer coefficients A * X2 + B * X + C = 0. It is guaranteed that A ≠ 0 and that the equation has at least one real root. Output the roots of the equation.InputThe only line of input contains integers A, B and C ( - 1000 ≀ A, B, C ≀ 1000, A ≠ 0), separated by spaces.OutputOutput the roots of the equation in increasing order. If the equation has a single root of multiplicity 2, output it once. The root is considered to be correct if its absolute or relative error does not exceed 10 - 4.ExamplesInput1 -2 1Output1Input1 0 -1Output-1 1Input2 -3 1Output0.5 1
Input1 -2 1
Output1
2 seconds
256 megabytes
['*special problem', '*1500']
B. Group Photo 2 (online mirror version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMany years have passed, and n friends met at a party again. Technologies have leaped forward since the last meeting, cameras with timer appeared and now it is not obligatory for one of the friends to stand with a camera, and, thus, being absent on the photo.Simply speaking, the process of photographing can be described as follows. Each friend occupies a rectangle of pixels on the photo: the i-th of them in a standing state occupies a wi pixels wide and a hi pixels high rectangle. But also, each person can lie down for the photo, and then he will occupy a hi pixels wide and a wi pixels high rectangle.The total photo will have size W × H, where W is the total width of all the people rectangles, and H is the maximum of the heights. The friends want to determine what minimum area the group photo can they obtain if no more than n / 2 of them can lie on the ground (it would be strange if more than n / 2 gentlemen lie on the ground together, isn't it?..)Help them to achieve this goal.InputThe first line contains integer n (1 ≀ n ≀ 1000) β€” the number of friends.The next n lines have two integers wi, hi (1 ≀ wi, hi ≀ 1000) each, representing the size of the rectangle, corresponding to the i-th friend.OutputPrint a single integer equal to the minimum possible area of the photo containing all friends if no more than n / 2 of them can lie on the ground.ExamplesInput310 120 230 3Output180Input33 12 24 3Output21Input15 10Output50
Input310 120 230 3
Output180
2 seconds
256 megabytes
['brute force', 'greedy', 'sortings', '*1900']
D. Fuzzy Searchtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeonid works for a small and promising start-up that works on decoding the human genome. His duties include solving complex problems of finding certain patterns in long strings consisting of letters 'A', 'T', 'G' and 'C'.Let's consider the following scenario. There is a fragment of a human DNA chain, recorded as a string S. To analyze the fragment, you need to find all occurrences of string T in a string S. However, the matter is complicated by the fact that the original chain fragment could contain minor mutations, which, however, complicate the task of finding a fragment. Leonid proposed the following approach to solve this problem.Let's write down integer k β‰₯ 0 β€” the error threshold. We will say that string T occurs in string S on position i (1 ≀ i ≀ |S| - |T| + 1), if after putting string T along with this position, each character of string T corresponds to the some character of the same value in string S at the distance of at most k. More formally, for any j (1 ≀ j ≀ |T|) there must exist such p (1 ≀ p ≀ |S|), that |(i + j - 1) - p| ≀ k and S[p] = T[j].For example, corresponding to the given definition, string "ACAT" occurs in string "AGCAATTCAT" in positions 2, 3 and 6. Note that at k = 0 the given definition transforms to a simple definition of the occurrence of a string in a string.Help Leonid by calculating in how many positions the given string T occurs in the given string S with the given error threshold.InputThe first line contains three integers |S|, |T|, k (1 ≀ |T| ≀ |S| ≀ 200 000, 0 ≀ k ≀ 200 000) β€” the lengths of strings S and T and the error threshold.The second line contains string S.The third line contains string T.Both strings consist only of uppercase letters 'A', 'T', 'G' and 'C'.OutputPrint a single number β€” the number of occurrences of T in S with the error threshold k by the given definition.ExamplesInput10 4 1AGCAATTCATACATOutput3NoteIf you happen to know about the structure of the human genome a little more than the author of the problem, and you are not impressed with Leonid's original approach, do not take everything described above seriously.
Input10 4 1AGCAATTCATACAT
Output3
3 seconds
256 megabytes
['bitmasks', 'brute force', 'fft', '*2500']
E. Data Center Dramatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe project of a data center of a Big Software Company consists of n computers connected by m cables. Simply speaking, each computer can be considered as a box with multiple cables going out of the box. Very Important Information is transmitted along each cable in one of the two directions. As the data center plan is not yet approved, it wasn't determined yet in which direction information will go along each cable. The cables are put so that each computer is connected with each one, perhaps through some other computers.The person in charge of the cleaning the data center will be Claudia Ivanova, the janitor. She loves to tie cables into bundles using cable ties. For some reasons, she groups the cables sticking out of a computer into groups of two, and if it isn't possible, then she gets furious and attacks the computer with the water from the bucket.It should also be noted that due to the specific physical characteristics of the Very Important Information, it is strictly forbidden to connect in one bundle two cables where information flows in different directions.The management of the data center wants to determine how to send information along each cable so that Claudia Ivanova is able to group all the cables coming out of each computer into groups of two, observing the condition above. Since it may not be possible with the existing connections plan, you are allowed to add the minimum possible number of cables to the scheme, and then you need to determine the direction of the information flow for each cable (yes, sometimes data centers are designed based on the janitors' convenience...)InputThe first line contains two numbers, n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ 200 000) β€” the number of computers and the number of the already present cables, respectively.Each of the next lines contains two numbers ai, bi (1 ≀ ai, bi ≀ n) β€” the indices of the computers connected by the i-th cable. The data centers often have a very complex structure, so a pair of computers may have more than one pair of cables between them and some cables may connect a computer with itself.OutputIn the first line print a single number p (p β‰₯ m) β€” the minimum number of cables in the final scheme.In each of the next p lines print a pair of numbers ci, di (1 ≀ ci, di ≀ n), describing another cable. Such entry means that information will go along a certain cable in direction from ci to di.Among the cables you printed there should be all the cables presented in the original plan in some of two possible directions. It is guaranteed that there is a solution where p doesn't exceed 500 000.If there are several posible solutions with minimum possible value of p, print any of them.ExamplesInput4 61 22 33 44 11 31 3Output61 23 41 43 21 31 3Input3 41 22 31 13 3Output62 12 31 13 33 11 1NotePicture for the first sample test. The tied pairs of cables are shown going out from the same point. Picture for the second test from the statement. The added cables are drawin in bold. Alternative answer for the second sample test:
Input4 61 22 33 44 11 31 3
Output61 23 41 43 21 31 3
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*2600']
D. Clique Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| β‰₯ wi + wj.Find the size of the maximum clique in such graph.InputThe first line contains the integer n (1 ≀ n ≀ 200 000) β€” the number of points.Each of the next n lines contains two numbers xi, wi (0 ≀ xi ≀ 109, 1 ≀ wi ≀ 109) β€” the coordinate and the weight of a point. All xi are different.OutputPrint a single number β€” the number of vertexes in the maximum clique of the given graph.ExamplesInput42 33 16 10 2Output3NoteIf you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!The picture for the sample test.
Input42 33 16 10 2
Output3
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'implementation', 'sortings', '*1800']
C. Glass Carvingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm  ×  h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.In order not to waste time, he decided to practice the technique of carving. To do this, he makes vertical and horizontal cuts through the entire sheet. This process results in making smaller rectangular fragments of glass. Leonid does not move the newly made glass fragments. In particular, a cut divides each fragment of glass that it goes through into smaller fragments.After each cut Leonid tries to determine what area the largest of the currently available glass fragments has. Since there appear more and more fragments, this question takes him more and more time and distracts him from the fascinating process.Leonid offers to divide the labor β€” he will cut glass, and you will calculate the area of the maximum fragment after each cut. Do you agree?InputThe first line contains three integers w, h, n (2 ≀ w, h ≀ 200 000, 1 ≀ n ≀ 200 000).Next n lines contain the descriptions of the cuts. Each description has the form HΒ y or VΒ x. In the first case Leonid makes the horizontal cut at the distance y millimeters (1 ≀ y ≀ h - 1) from the lower edge of the original sheet of glass. In the second case Leonid makes a vertical cut at distance x (1 ≀ x ≀ w - 1) millimeters from the left edge of the original sheet of glass. It is guaranteed that Leonid won't make two identical cuts.OutputAfter each cut print on a single line the area of the maximum available glass fragment in mm2.ExamplesInput4 3 4H 2V 2V 3V 1Output8442Input7 6 5H 4V 3V 5H 2V 1Output28161264NotePicture for the first sample test: Picture for the second sample test:
Input4 3 4H 2V 2V 3V 1
Output8442
2 seconds
256 megabytes
['binary search', 'data structures', 'implementation', '*1500']
B. Error Correct Systemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFord Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this!InputThe first line contains integer n (1 ≀ n ≀ 200 000) β€” the length of strings S and T.The second line contains string S.The third line contains string T.Each of the lines only contains lowercase Latin letters.OutputIn the first line, print number x β€” the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S.In the second line, either print the indexes i and j (1 ≀ i, j ≀ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters.If there are multiple possible answers, print any of them.ExamplesInput9pergamentpermanentOutput14 6Input6wookiecookieOutput1-1 -1Input4petregorOutput21 2Input6doublebundleOutput24 1NoteIn the second test it is acceptable to print i = 2, j = 3.
Input9pergamentpermanent
Output14 6
2 seconds
256 megabytes
['greedy', '*1500']
A. Playing with Papertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm  ×  b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting the excess part. After making a paper ship from the square piece, Vasya looked on the remaining (a - b) mm  ×  b mm strip of paper. He got the idea to use this strip of paper in the same way to make an origami, and then use the remainder (if it exists) and so on. At the moment when he is left with a square piece of paper, he will make the last ship from it and stop.Can you determine how many ships Vasya will make during the lesson?InputThe first line of the input contains two integers a, b (1 ≀ b < a ≀ 1012) β€” the sizes of the original sheet of paper.OutputPrint a single integer β€” the number of ships that Vasya will make.ExamplesInput2 1Output2Input10 7Output6Input1000000000000 1Output1000000000000NotePictures to the first and second sample test.
Input2 1
Output2
2 seconds
256 megabytes
['implementation', 'math', '*1100']
G. Spiders Evil Plantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSpiders are Om Nom's old enemies. They love eating candies as much as he does and that's why they keep trying to keep the monster away from his favorite candies. They came up with an evil plan to trap Om Nom. Let's consider a rope structure consisting of n nodes and n - 1 ropes connecting the nodes. The structure is connected, thus, the ropes and the nodes form a tree. Each rope of the formed structure is associated with its length. A candy is tied to node x of the structure. Om Nom really wants to eat this candy.The y spiders are trying to stop him from doing it. They decided to entangle the candy and some part of the structure into a web, thus attaching the candy to as large as possible part of the rope structure. Each spider can use his web to cover all ropes on the path between two arbitrary nodes a and b. Thus, y spiders can cover the set of ropes which is a union of y paths in the given tree. These y paths can arbitrarily intersect each other. The spiders want the following conditions to be hold: the node containing the candy is adjacent to at least one rope covered with a web the ropes covered with the web form a connected structure (what's the idea of covering with a web the ropes that are not connected with the candy?) the total length of the ropes covered with web is as large as possible The spiders haven't yet decided to what node of the structure they will tie the candy and how many spiders will cover the structure with web, so they asked you to help them. Help them calculate the optimal plan for multiple values of x and y.InputThe first line contains numbers n and q (1 ≀ n, q ≀ 105) β€” the number of nodes in the structure and the number of questions that the spiders want to ask you.The next n - 1 lines determine the rope structure. The i-th line contains three integers ui, vi, li (1 ≀ ui, vi ≀ n, ui ≠ vi, 1 ≀ li ≀ 1000), showing that there is a rope of length li between nodes ui and vi.Next q lines describe the spiders' questions. As they want you to answer their question online, they encoded their messages in a special manner.Each of the next q lines contains two numbers xi, yi. In the first question of the spiders x = x1, y = y1.To calculate values x and y in the spiders' i-th (2 ≀ i ≀ q) question, you need to use the following formulas:where Ansi - 1 is the total length of the ropes covered by a web in the answer for the (i - 1)-th question.The following inequality holds: 1 ≀ xi, yi ≀ n.OutputFor each question of the spiders print on a separate line a single integer Ansi β€” the total length of the ropes covered with web in the optimal plan.ExamplesInput6 31 2 22 3 23 4 24 6 13 5 103 12 51 1Output141317
Input6 31 2 22 3 23 4 24 6 13 5 103 12 51 1
Output141317
1 second
256 megabytes
['greedy', 'trees', '*3300']
F. Pudding Monsterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will meet the simplified model of game Pudding Monsters.An important process in developing any game is creating levels. A game field in Pudding Monsters is an n × n rectangular grid, n of its cells contain monsters and some other cells contain game objects. The gameplay is about moving the monsters around the field. When two monsters are touching each other, they glue together into a single big one (as they are from pudding, remember?). Statistics showed that the most interesting maps appear if initially each row and each column contains exactly one monster and the rest of map specifics is set up by the correct positioning of the other game objects. A technique that's widely used to make the development process more efficient is reusing the available resources. For example, if there is a large n × n map, you can choose in it a smaller k × k square part, containing exactly k monsters and suggest it as a simplified version of the original map.You wonder how many ways there are to choose in the initial map a k × k (1 ≀ k ≀ n) square fragment, containing exactly k pudding monsters. Calculate this number.InputThe first line contains a single integer n (1 ≀ n ≀ 3 × 105) β€” the size of the initial field.Next n lines contain the coordinates of the cells initially containing monsters. The i-th of the next lines contains two numbers ri, ci (1 ≀ ri, ci ≀ n) β€” the row number and the column number of the cell that initially contains the i-th monster.It is guaranteed that all ri are distinct numbers and all ci are distinct numbers.OutputPrint the number of distinct square fragments of the original field that can form a new map.ExamplesInput51 14 33 22 45 5Output10
Input51 14 33 22 45 5
Output10
2 seconds
256 megabytes
['data structures', 'divide and conquer', '*3000']
E. Transmitting Levelstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOptimizing the amount of data transmitted via a network is an important and interesting part of developing any network application. In one secret game developed deep in the ZeptoLab company, the game universe consists of n levels, located in a circle. You can get from level i to levels i - 1 and i + 1, also you can get from level 1 to level n and vice versa. The map of the i-th level description size is ai bytes.In order to reduce the transmitted traffic, the game gets levels as follows. All the levels on the server are divided into m groups and each time a player finds himself on one of the levels of a certain group for the first time, the server sends all levels of the group to the game client as a single packet. Thus, when a player travels inside the levels of a single group, the application doesn't need any new information. Due to the technical limitations the packet can contain an arbitrary number of levels but their total size mustn't exceed b bytes, where b is some positive integer constant.Usual situation is that players finish levels one by one, that's why a decision was made to split n levels into m groups so that each group was a continuous segment containing multiple neighboring levels (also, the group can have two adjacent levels, n and 1). Specifically, if the descriptions of all levels have the total weight of at most b bytes, then they can all be united into one group to be sent in a single packet.Determine, what minimum number of groups do you need to make in order to organize the levels of the game observing the conditions above?As developing a game is a long process and technology never stagnates, it is yet impossible to predict exactly what value will take constant value b limiting the packet size when the game is out. That's why the developers ask you to find the answer for multiple values of b.InputThe first line contains two integers n, q (2 ≀ n ≀ 106, 1 ≀ q ≀ 50) β€” the number of levels in the game universe and the number of distinct values of b that you need to process.The second line contains n integers ai (1 ≀ ai ≀ 109) β€” the sizes of the levels in bytes.The next q lines contain integers bj (), determining the values of constant b, for which you need to determine the answer.OutputFor each value of kj from the input print on a single line integer mj (1 ≀ mj ≀ n), determining the minimum number of groups to divide game levels into for transmission via network observing the given conditions. ExamplesInput6 32 4 2 1 3 2746Output243NoteIn the test from the statement you can do in the following manner. at b = 7 you can divide into two segments: 2|421|32 (note that one of the segments contains the fifth, sixth and first levels); at b = 4 you can divide into four segments: 2|4|21|3|2; at b = 6 you can divide into three segments: 24|21|32|.
Input6 32 4 2 1 3 2746
Output243
3 seconds
256 megabytes
['dp', 'implementation', '*2400']
D. Om Nom and Necklacetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Om Nom found a thread with n beads of different colors. He decided to cut the first several beads from this thread to make a bead necklace and present it to his girlfriend Om Nelly. Om Nom knows that his girlfriend loves beautiful patterns. That's why he wants the beads on the necklace to form a regular pattern. A sequence of beads S is regular if it can be represented as S = A + B + A + B + A + ... + A + B + A, where A and B are some bead sequences, " + " is the concatenation of sequences, there are exactly 2k + 1 summands in this sum, among which there are k + 1 "A" summands and k "B" summands that follow in alternating order. Om Nelly knows that her friend is an eager mathematician, so she doesn't mind if A or B is an empty sequence.Help Om Nom determine in which ways he can cut off the first several beads from the found thread (at least one; probably, all) so that they form a regular pattern. When Om Nom cuts off the beads, he doesn't change their order.InputThe first line contains two integers n, k (1 ≀ n, k ≀ 1 000 000) β€” the number of beads on the thread that Om Nom found and number k from the definition of the regular sequence above.The second line contains the sequence of n lowercase Latin letters that represent the colors of the beads. Each color corresponds to a single letter.OutputPrint a string consisting of n zeroes and ones. Position i (1 ≀ i ≀ n) must contain either number one if the first i beads on the thread form a regular sequence, or a zero otherwise.ExamplesInput7 2bcabcabOutput0000011Input21 2ababaababaababaababaaOutput000110000111111000011NoteIn the first sample test a regular sequence is both a sequence of the first 6 beads (we can take A = "", B = "bca"), and a sequence of the first 7 beads (we can take A = "b", B = "ca").In the second sample test, for example, a sequence of the first 13 beads is regular, if we take A = "aba", B = "ba".
Input7 2bcabcab
Output0000011
1 second
256 megabytes
['hashing', 'string suffix structures', 'strings', '*2200']
C. Om Nom and Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sweet little monster Om Nom loves candies very much. One day he found himself in a rather tricky situation that required him to think a bit in order to enjoy candies the most. Would you succeed with the same task if you were on his place? One day, when he came to his friend Evan, Om Nom didn't find him at home but he found two bags with candies. The first was full of blue candies and the second bag was full of red candies. Om Nom knows that each red candy weighs Wr grams and each blue candy weighs Wb grams. Eating a single red candy gives Om Nom Hr joy units and eating a single blue candy gives Om Nom Hb joy units.Candies are the most important thing in the world, but on the other hand overeating is not good. Om Nom knows if he eats more than C grams of candies, he will get sick. Om Nom thinks that it isn't proper to leave candy leftovers, so he can only eat a whole candy. Om Nom is a great mathematician and he quickly determined how many candies of what type he should eat in order to get the maximum number of joy units. Can you repeat his achievement? You can assume that each bag contains more candies that Om Nom can eat.InputThe single line contains five integers C, Hr, Hb, Wr, Wb (1 ≀ C, Hr, Hb, Wr, Wb ≀ 109).OutputPrint a single integer β€” the maximum number of joy units that Om Nom can get.ExamplesInput10 3 5 2 3Output16NoteIn the sample test Om Nom can eat two candies of each type and thus get 16 joy units.
Input10 3 5 2 3
Output16
1 second
256 megabytes
['brute force', 'greedy', 'math', '*2000']
B. Om Nom and Dark Parktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOm Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. The park consists of 2n + 1 - 1 squares connected by roads so that the scheme of the park is a full binary tree of depth n. More formally, the entrance to the park is located at the square 1. The exits out of the park are located at squares 2n, 2n + 1, ..., 2n + 1 - 1 and these exits lead straight to the Om Nom friends' houses. From each square i (2 ≀ i < 2n + 1) there is a road to the square . Thus, it is possible to go from the park entrance to each of the exits by walking along exactly n roads. To light the path roads in the evening, the park keeper installed street lights along each road. The road that leads from square i to square has ai lights.Om Nom loves counting lights on the way to his friend. Om Nom is afraid of spiders who live in the park, so he doesn't like to walk along roads that are not enough lit. What he wants is that the way to any of his friends should have in total the same number of lights. That will make him feel safe. He asked you to help him install additional lights. Determine what minimum number of lights it is needed to additionally place on the park roads so that a path from the entrance to any exit of the park contains the same number of street lights. You may add an arbitrary number of street lights to each of the roads.InputThe first line contains integer n (1 ≀ n ≀ 10) β€” the number of roads on the path from the entrance to any exit.The next line contains 2n + 1 - 2 numbers a2, a3, ... a2n + 1 - 1 β€” the initial numbers of street lights on each road of the park. Here ai is the number of street lights on the road between squares i and . All numbers ai are positive integers, not exceeding 100.OutputPrint the minimum number of street lights that we should add to the roads of the park to make Om Nom feel safe.ExamplesInput21 2 3 4 5 6Output5NotePicture for the sample test. Green color denotes the additional street lights.
Input21 2 3 4 5 6
Output5
1 second
256 megabytes
['dfs and similar', 'greedy', 'implementation', '*1400']
A. King of Thievestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will meet the simplified model of game King of Thieves.In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way. An interesting feature of the game is that you can design your own levels that will be available to other players. Let's consider the following simple design of a level.A dungeon consists of n segments located at a same vertical level, each segment is either a platform that character can stand on, or a pit with a trap that makes player lose if he falls into it. All segments have the same length, platforms on the scheme of the level are represented as '*' and pits are represented as '.'. One of things that affects speedrun characteristics of the level is a possibility to perform a series of consecutive jumps of the same length. More formally, when the character is on the platform number i1, he can make a sequence of jumps through the platforms i1 < i2 < ... < ik, if i2 - i1 = i3 - i2 = ... = ik - ik - 1. Of course, all segments i1, i2, ... ik should be exactly the platforms, not pits. Let's call a level to be good if you can perform a sequence of four jumps of the same length or in the other words there must be a sequence i1, i2, ..., i5, consisting of five platforms so that the intervals between consecutive platforms are of the same length. Given the scheme of the level, check if it is good.InputThe first line contains integer n (1 ≀ n ≀ 100) β€” the number of segments on the level.Next line contains the scheme of the level represented as a string of n characters '*' and '.'.OutputIf the level is good, print the word "yes" (without the quotes), otherwise print the word "no" (without the quotes).ExamplesInput16.**.*..*.***.**.OutputyesInput11.*.*...*.*.OutputnoNoteIn the first sample test you may perform a sequence of jumps through platforms 2, 5, 8, 11, 14.
Input16.**.*..*.***.**.
Outputyes
1 second
256 megabytes
['brute force', 'implementation', '*1300']
E. Anya and Cubestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya loves to fold and stick. Today she decided to do just that.Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes.Anya can stick an exclamation mark on the cube and get the factorial of the number written on the cube. For example, if a cube reads 5, then after the sticking it reads 5!, which equals 120.You need to help Anya count how many ways there are to choose some of the cubes and stick on some of the chosen cubes at most k exclamation marks so that the sum of the numbers written on the chosen cubes after the sticking becomes equal to S. Anya can stick at most one exclamation mark on each cube. Can you do it?Two ways are considered the same if they have the same set of chosen cubes and the same set of cubes with exclamation marks.InputThe first line of the input contains three space-separated integers n, k and S (1 ≀ n ≀ 25, 0 ≀ k ≀ n, 1 ≀ S ≀ 1016)Β β€”Β the number of cubes and the number of stickers that Anya has, and the sum that she needs to get. The second line contains n positive integers ai (1 ≀ ai ≀ 109)Β β€”Β the numbers, written on the cubes. The cubes in the input are described in the order from left to right, starting from the first one. Multiple cubes can contain the same numbers.OutputOutput the number of ways to choose some number of cubes and stick exclamation marks on some of them so that the sum of the numbers became equal to the given number S.ExamplesInput2 2 304 3Output1Input2 2 74 3Output1Input3 1 11 1 1Output6NoteIn the first sample the only way is to choose both cubes and stick an exclamation mark on each of them.In the second sample the only way is to choose both cubes but don't stick an exclamation mark on any of them.In the third sample it is possible to choose any of the cubes in three ways, and also we may choose to stick or not to stick the exclamation mark on it. So, the total number of ways is six.
Input2 2 304 3
Output1
2 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'dp', 'math', 'meet-in-the-middle', '*2100']
D. Arthur and Wallstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFinally it is a day when Arthur has enough money for buying an apartment. He found a great option close to the center of the city with a nice price.Plan of the apartment found by Arthur looks like a rectangle n × m consisting of squares of size 1 × 1. Each of those squares contains either a wall (such square is denoted by a symbol "*" on the plan) or a free space (such square is denoted on the plan by a symbol ".").Room in an apartment is a maximal connected area consisting of free squares. Squares are considered adjacent if they share a common side.The old Arthur dream is to live in an apartment where all rooms are rectangles. He asks you to calculate minimum number of walls you need to remove in order to achieve this goal. After removing a wall from a square it becomes a free square. While removing the walls it is possible that some rooms unite into a single one.InputThe first line of the input contains two integers n, m (1 ≀ n, m ≀ 2000) denoting the size of the Arthur apartments.Following n lines each contain m symbols β€” the plan of the apartment.If the cell is denoted by a symbol "*" then it contains a wall.If the cell is denoted by a symbol "." then it this cell is free from walls and also this cell is contained in some of the rooms.OutputOutput n rows each consisting of m symbols that show how the Arthur apartment plan should look like after deleting the minimum number of walls in order to make each room (maximum connected area free from walls) be a rectangle. If there are several possible answers, output any of them.ExamplesInput5 5.*.*.*****.*.*.*****.*.*.Output.*.*.*****.*.*.*****.*.*.Input6 7***.*.*..*.*.**.*.*.**.*.*.*..*...********Output***...*..*...*..*...*..*...*..*...********Input4 5............***..*..Output....................
Input5 5.*.*.*****.*.*.*****.*.*.
Output.*.*.*****.*.*.*****.*.*.
2 seconds
512 megabytes
['constructive algorithms', 'data structures', 'graphs', 'greedy', 'shortest paths', '*2400']
C. Ilya and Stickstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li.Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maximizes their total area. Each stick is used in making at most one rectangle, it is possible that some of sticks remain unused. Bending sticks is not allowed.Sticks with lengths a1, a2, a3 and a4 can make a rectangle if the following properties are observed: a1 ≀ a2 ≀ a3 ≀ a4 a1 = a2 a3 = a4 A rectangle can be made of sticks with lengths of, for example, 3Β 3Β 3Β 3 or 2Β 2Β 4Β 4. A rectangle cannot be made of, for example, sticks 5Β 5Β 5Β 7.Ilya also has an instrument which can reduce the length of the sticks. The sticks are made of a special material, so the length of each stick can be reduced by at most one. For example, a stick with length 5 can either stay at this length or be transformed into a stick of length 4.You have to answer the question β€” what maximum total area of the rectangles can Ilya get with a file if makes rectangles from the available sticks?InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 105)Β β€”Β the number of the available sticks.The second line of the input contains n positive integers li (2 ≀ li ≀ 106)Β β€”Β the lengths of the sticks.OutputThe first line of the output must contain a single non-negative integerΒ β€”Β the maximum total area of the rectangles that Ilya can make from the available sticks.ExamplesInput42 4 4 2Output8Input42 2 3 5Output0Input4100003 100004 100005 100006Output10000800015
Input42 4 4 2
Output8
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1600']
B. Pasha and Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.InputThe first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters.The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string.The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.OutputIn the first line of the output print what Pasha's string s will look like after m days.ExamplesInputabcdef12OutputaedcbfInputvwxyz22 2OutputvwxyzInputabcdef31 2 3Outputfbdcea
Inputabcdef12
Outputaedcbf
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'strings', '*1400']
A. Vitaliy and Pietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on β€” you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.InputThe first line of the input contains a positive integer n (2 ≀ n ≀ 105)Β β€”Β the number of rooms in the house.The second line of the input contains string s of length 2Β·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin lettersΒ β€”Β the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter β€” the type of the key that lies in room number (i + 1) / 2.The even positions in the given string contain uppercase Latin letters β€” the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter β€” the type of the door that leads from room i / 2 to room i / 2 + 1.OutputPrint the only integer β€” the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.ExamplesInput3aAbBOutput0Input4aBaCaBOutput3Input5xYyXzZaZOutput2
Input3aAbB
Output0
2 seconds
256 megabytes
['greedy', 'hashing', 'strings', '*1100']
F. And Yet Another Bracket Sequencetime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a finite sequence of opening and closing brackets. In order not to fall asleep in a lecture, Polycarpus is having fun with his sequence. He is able to perform two operations: adding any bracket in any position (in the beginning, the end, or between any two existing brackets); cyclic shift β€” moving the last bracket from the end of the sequence to the beginning. Polycarpus can apply any number of operations to his sequence and adding a cyclic shift in any order. As a result, he wants to get the correct bracket sequence of the minimum possible length. If there are several such sequences, Polycarpus is interested in the lexicographically smallest one. Help him find such a sequence.Acorrect bracket sequence is a sequence of opening and closing brackets, from which you can get a correct arithmetic expression by adding characters "1" and "+" . Each opening bracket must correspond to a closed one. For example, the sequences "(())()", "()", "(()(()))" are correct and ")(", "(()" and "(()))(" are not.The sequence a1 a2... an is lexicographically smaller than sequence b1 b2... bn, if there is such number i from 1 to n, thatak = bk for 1 ≀ k < i and ai < bi. Consider that "("  <  ")".InputThe first line contains Polycarpus's sequence consisting of characters "(" and ")". The length of a line is from 1 to 1 000 000.OutputPrint a correct bracket sequence of the minimum length that Polycarpus can obtain by his operations. If there are multiple such sequences, print the lexicographically minimum one.ExamplesInput()(())Output(())()Input()(Output(())NoteThe sequence in the first example is already correct, but to get the lexicographically minimum answer, you need to perform four cyclic shift operations. In the second example you need to add a closing parenthesis between the second and third brackets and make a cyclic shift. You can first make the shift, and then add the bracket at the end.
Input()(())
Output(())()
5 seconds
256 megabytes
['data structures', 'greedy', 'hashing', 'string suffix structures', 'strings', '*2700']
E. Rooks and Rectanglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus has a chessboard of size n × m, where k rooks are placed. Polycarpus hasn't yet invented the rules of the game he will play. However, he has already allocated q rectangular areas of special strategic importance on the board, they must be protected well. According to Polycarpus, a rectangular area of ​​the board is well protected if all its vacant squares can be beaten by the rooks that stand on this area. The rooks on the rest of the board do not affect the area's defense. The position of the rooks is fixed and cannot be changed. We remind you that the the rook beats the squares located on the same vertical or horizontal line with it, if there are no other pieces between the square and the rook. Help Polycarpus determine whether all strategically important areas are protected.InputThe first line contains four integers n, m, k and q (1 ≀ n, m ≀ 100 000, 1 ≀ k, q ≀ 200 000) β€” the sizes of the board, the number of rooks and the number of strategically important sites. We will consider that the cells of the board are numbered by integers from 1 to n horizontally and from 1 to m vertically. Next k lines contain pairs of integers "x y", describing the positions of the rooks (1 ≀ x ≀ n, 1 ≀ y ≀ m). It is guaranteed that all the rooks are in distinct squares. Next q lines describe the strategically important areas as groups of four integers "x1 y1 x2 y2" (1 ≀ x1 ≀ x2 ≀ n, 1 ≀ y1 ≀ y2 ≀ m). The corresponding rectangle area consists of cells (x, y), for which x1 ≀ x ≀ x2, y1 ≀ y ≀ y2. Strategically important areas can intersect of coincide.OutputPrint q lines. For each strategically important site print "YES" if it is well defended and "NO" otherwise.ExamplesInput4 3 3 31 13 22 32 3 2 32 1 3 31 2 2 3OutputYESYESNONotePicture to the sample: For the last area the answer is "NO", because cell (1, 2) cannot be hit by a rook.
Input4 3 3 31 13 22 32 3 2 32 1 3 31 2 2 3
OutputYESYESNO
2 seconds
256 megabytes
['data structures', 'sortings', '*2400']
D. Social Networktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.But wait, something is still known, because that day a record was achieved β€” M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that: the number of different users online did not exceed M at any moment, at some second the number of distinct users online reached value M, the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test.InputThe first line contains three integers n, M and T (1 ≀ n, M ≀ 20 000, 1 ≀ T ≀ 86400) β€” the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59). OutputIn the first line print number R β€” the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).ExamplesInput4 2 1017:05:5317:05:5817:06:0122:39:47Output31223Input1 2 8640000:00:00OutputNo solutionNoteConsider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 β€” from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 β€” from 22:39:47 to 22:39:56.In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)
Input4 2 1017:05:5317:05:5817:06:0122:39:47
Output31223
2 seconds
256 megabytes
['greedy', 'two pointers', '*2100']
C. The Art of Dealing with ATMtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.InputThe first line contains two integers n, k (1 ≀ n ≀ 5000, 1 ≀ k ≀ 20).The next line contains n space-separated integers ai (1 ≀ ai ≀ 107) β€” the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order.The next line contains integer q (1 ≀ q ≀ 20) β€” the number of requests for cash withdrawal that you will make.The next q lines contain numbers xi (1 ≀ xi ≀ 2Β·108) β€” the sums of money in burles that you are going to withdraw from the ATM.OutputFor each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print  - 1, if it is impossible to get the corresponding sum.ExamplesInput6 2010 50 100 500 1000 5000842001000009500096000990001010020159950Output6201920-13-1-1Input5 21 2 3 5 8813579111315Output1112222-1
Input6 2010 50 100 500 1000 5000842001000009500096000990001010020159950
Output6201920-13-1-1
2 seconds
256 megabytes
['binary search', 'sortings', '*1900']
B. Π€ΠΎΡ‚ΠΎ Π½Π° ΠΏΠ°ΠΌΡΡ‚ΡŒ - 2 (round version)ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π½Π° тСст2 сСкундыограничСниС ΠΏΠΎ памяти Π½Π° тСст256 мСгабайтвводстандартный вводвыводстандартный Π²Ρ‹Π²ΠΎΠ΄ΠŸΡ€ΠΎΡˆΠ»ΠΎ ΠΌΠ½ΠΎΠ³ΠΎ Π»Π΅Ρ‚, ΠΈ Π½Π° Π²Π΅Ρ‡Π΅Ρ€ΠΈΠ½ΠΊΠ΅ снова Π²ΡΡ‚Ρ€Π΅Ρ‚ΠΈΠ»ΠΈΡΡŒ n Π΄Ρ€ΡƒΠ·Π΅ΠΉ. Π‘ ΠΌΠΎΠΌΠ΅Π½Ρ‚Π° послСднСй встрСчи Ρ‚Π΅Ρ…Π½ΠΈΠΊΠ° ΡˆΠ°Π³Π½ΡƒΠ»Π° Π΄Π°Π»Π΅ΠΊΠΎ Π²ΠΏΠ΅Ρ€Ρ‘Π΄, появились Ρ„ΠΎΡ‚ΠΎΠ°ΠΏΠΏΠ°Ρ€Π°Ρ‚Ρ‹ с автоспуском, ΠΈ Ρ‚Π΅ΠΏΠ΅Ρ€ΡŒ Π½Π΅ трСбуСтся, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΎΠ΄ΠΈΠ½ ΠΈΠ· Π΄Ρ€ΡƒΠ·Π΅ΠΉ стоял с Ρ„ΠΎΡ‚ΠΎΠ°ΠΏΠΏΠ°Ρ€Π°Ρ‚ΠΎΠΌ, ΠΈ, Ρ‚Π΅ΠΌ самым, оказывался Π½Π΅ Π·Π°ΠΏΠ΅Ρ‡Π°Ρ‚Π»Ρ‘Π½Π½Ρ‹ΠΌ Π½Π° снимкС.Π£ΠΏΡ€ΠΎΡ‰Π΅Π½Π½ΠΎ процСсс фотографирования ΠΌΠΎΠΆΠ½ΠΎ ΠΎΠΏΠΈΡΠ°Ρ‚ΡŒ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ. На Ρ„ΠΎΡ‚ΠΎΠ³Ρ€Π°Ρ„ΠΈΠΈ ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ ΠΈΠ· Π΄Ρ€ΡƒΠ·Π΅ΠΉ Π·Π°Π½ΠΈΠΌΠ°Π΅Ρ‚ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ ΠΈΠ· пиксСлСй: Π² стоячСм ΠΏΠΎΠ»ΠΎΠΆΠ΅Π½ΠΈΠΈ i-ΠΉ ΠΈΠ· Π½ΠΈΡ… Π·Π°Π½ΠΈΠΌΠ°Π΅Ρ‚ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ ΡˆΠΈΡ€ΠΈΠ½Ρ‹ wi пиксСлСй ΠΈ высоты hi пиксСлСй. Но Ρ‚Π°ΠΊΠΆΠ΅, ΠΏΡ€ΠΈ Ρ„ΠΎΡ‚ΠΎΠ³Ρ€Π°Ρ„ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠΈ ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ Ρ‡Π΅Π»ΠΎΠ²Π΅ΠΊ ΠΌΠΎΠΆΠ΅Ρ‚ Π»Π΅Ρ‡ΡŒ, ΠΈ Ρ‚ΠΎΠ³Π΄Π° ΠΎΠ½ Π±ΡƒΠ΄Π΅Ρ‚ Π·Π°Π½ΠΈΠΌΠ°Ρ‚ΡŒ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ ΡˆΠΈΡ€ΠΈΠ½Ρ‹ hi пиксСлСй ΠΈ высоты wi пиксСлСй.ΠžΠ±Ρ‰Π°Ρ фотография Π±ΡƒΠ΄Π΅Ρ‚ ΠΈΠΌΠ΅Ρ‚ΡŒ Ρ€Π°Π·ΠΌΠ΅Ρ€Ρ‹ W × H, Π³Π΄Π΅ W β€” суммарная ΡˆΠΈΡ€ΠΈΠ½Π° всСх ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊΠΎΠ²-людСй, Π° H β€” максимальная ΠΈΠ· высот. Π”Ρ€ΡƒΠ·ΡŒΡ хотят ΠΎΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚ΡŒ, ΠΊΠ°ΠΊΡƒΡŽ ΠΌΠΈΠ½ΠΈΠΌΠ°Π»ΡŒΠ½ΡƒΡŽ ΠΏΠ»ΠΎΡ‰Π°Π΄ΡŒ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΈΠΌΠ΅Ρ‚ΡŒ общая фотография. ΠŸΠΎΠΌΠΎΠ³ΠΈΡ‚Π΅ ΠΈΠΌ Π² этом.Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС слСдуСт Ρ†Π΅Π»ΠΎΠ΅ число n (1 ≀ n ≀ 1000) β€” количСство Π΄Ρ€ΡƒΠ·Π΅ΠΉ.Π’ ΠΏΠΎΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΡ… n строках ΡΠ»Π΅Π΄ΡƒΡŽΡ‚ ΠΏΠΎ Π΄Π²Π° Ρ†Π΅Π»Ρ‹Ρ… числа wi, hi (1 ≀ wi, hi ≀ 1000), ΠΎΠ±ΠΎΠ·Π½Π°Ρ‡Π°ΡŽΡ‰ΠΈΠ΅ Ρ€Π°Π·ΠΌΠ΅Ρ€Ρ‹ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊΠ°, ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰Π΅Π³ΠΎ i-ΠΌΡƒ ΠΈΠ· Π΄Ρ€ΡƒΠ·Π΅ΠΉ.Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅Π’Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ СдинствСнноС Ρ†Π΅Π»ΠΎΠ΅ число, Ρ€Π°Π²Π½ΠΎΠ΅ минимальной Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΠΉ ΠΏΠ»ΠΎΡ‰Π°Π΄ΠΈ Ρ„ΠΎΡ‚ΠΎΠ³Ρ€Π°Ρ„ΠΈΠΈ, Π²ΠΌΠ΅Ρ‰Π°ΡŽΡ‰Π΅ΠΉ всСх Π΄Ρ€ΡƒΠ·Π΅ΠΉ.ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅310 120 230 3Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅180Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅33 12 24 3Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅21Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅15 10Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅50
Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅310 120 230 3
Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅180
ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π½Π° тСст2 сСкунды
ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ памяти Π½Π° тСст256 ΠΌΠ΅Π³Π°Π±Π°ΠΉΡ‚
['dp', 'greedy', '*1700']
A. Π’ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ, Π²Ρ‹ Π·Π½Π°Π΅Ρ‚Π΅ этих людСй?ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π½Π° тСст2 сСкундыограничСниС ΠΏΠΎ памяти Π½Π° тСст256 мСгабайтвводстандартный вводвыводстандартный Π²Ρ‹Π²ΠΎΠ΄ΠžΡΠ½ΠΎΠ²ΠΎΠΉ любой ΡΠΎΡ†ΠΈΠ°Π»ΡŒΠ½ΠΎΠΉ сСти являСтся ΠΎΡ‚Π½ΠΎΡˆΠ΅Π½ΠΈΠ΅ Π΄Ρ€ΡƒΠΆΠ±Ρ‹ ΠΌΠ΅ΠΆΠ΄Ρƒ двумя ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»ΡΠΌΠΈ Π² Ρ‚ΠΎΠΌ ΠΈΠ»ΠΈ ΠΈΠ½ΠΎΠΌ смыслС. Π’ ΠΎΠ΄Π½ΠΎΠΉ извСстной ΡΠΎΡ†ΠΈΠ°Π»ΡŒΠ½ΠΎΠΉ сСти Π΄Ρ€ΡƒΠΆΠ±Π° симмСтрична, Ρ‚ΠΎ Π΅ΡΡ‚ΡŒ Ссли a являСтся Π΄Ρ€ΡƒΠ³ΠΎΠΌ b, Ρ‚ΠΎ b Ρ‚Π°ΠΊΠΆΠ΅ являСтся Π΄Ρ€ΡƒΠ³ΠΎΠΌ a. Π’ этой ΠΆΠ΅ сСти Π΅ΡΡ‚ΡŒ функция, которая дСмонстрируСт мноТСство людСй, ΠΈΠΌΠ΅ΡŽΡ‰ΠΈΡ… Π²Ρ‹ΡΠΎΠΊΡƒΡŽ Π²Π΅Ρ€ΠΎΡΡ‚Π½ΠΎΡΡ‚ΡŒ Π±Ρ‹Ρ‚ΡŒ Π·Π½Π°ΠΊΠΎΠΌΡ‹ΠΌΠΈ для ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ. Π­Ρ‚Π° функция Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚ ΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ. ЗафиксируСм ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ x. ΠŸΡƒΡΡ‚ΡŒ Π½Π΅ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π΄Ρ€ΡƒΠ³ΠΎΠΉ Ρ‡Π΅Π»ΠΎΠ²Π΅ΠΊ y, Π½Π΅ ΡΠ²Π»ΡΡŽΡ‰ΠΈΠΉΡΡ Π΄Ρ€ΡƒΠ³ΠΎΠΌ x Π½Π° Ρ‚Π΅ΠΊΡƒΡ‰ΠΈΠΉ ΠΌΠΎΠΌΠ΅Π½Ρ‚, являСтся Π΄Ρ€ΡƒΠ³ΠΎΠΌ Π½Π΅ ΠΌΠ΅Π½Π΅Π΅, Ρ‡Π΅ΠΌ для k% Π΄Ρ€ΡƒΠ·Π΅ΠΉ x. Π’ΠΎΠ³Π΄Π° ΠΎΠ½ являСтся ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹ΠΌ Π΄Ρ€ΡƒΠ³ΠΎΠΌ для x.Π£ ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ Ρ‡Π΅Π»ΠΎΠ²Π΅ΠΊΠ° Π² ΡΠΎΡ†ΠΈΠ°Π»ΡŒΠ½ΠΎΠΉ сСти Π΅ΡΡ‚ΡŒ свой ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹ΠΉ ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ β€” это Ρ†Π΅Π»ΠΎΠ΅ число ΠΎΡ‚ 1 Π΄ΠΎ 109. Π’Π°ΠΌ Π΄Π°Π½ список ΠΏΠ°Ρ€ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ, ΡΠ²Π»ΡΡŽΡ‰ΠΈΡ…ΡΡ Π΄Ρ€ΡƒΠ·ΡŒΡΠΌΠΈ. ΠžΠΏΡ€Π΅Π΄Π΅Π»ΠΈΡ‚Π΅ для ΠΊΠ°ΠΆΠ΄ΠΎΠ³ΠΎ упомянутого ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Ρ мноТСство Π΅Π³ΠΎ ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹Ρ… Π΄Ρ€ΡƒΠ·Π΅ΠΉ.Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅Π’ ΠΏΠ΅Ρ€Π²ΠΎΠΉ строкС ΡΠ»Π΅Π΄ΡƒΡŽΡ‚ Π΄Π²Π° Ρ†Π΅Π»Ρ‹Ρ… числа m ΠΈ k (1 ≀ m ≀ 100, 0 ≀ k ≀ 100) β€” количСство ΠΏΠ°Ρ€ Π΄Ρ€ΡƒΠ·Π΅ΠΉ ΠΈ Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΡ‹ΠΉ ΠΏΡ€ΠΎΡ†Π΅Π½Ρ‚ ΠΎΠ±Ρ‰ΠΈΡ… Π΄Ρ€ΡƒΠ·Π΅ΠΉ для Ρ‚ΠΎΠ³ΠΎ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΡΡ‡ΠΈΡ‚Π°Ρ‚ΡŒΡΡ ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹ΠΌ Π΄Ρ€ΡƒΠ³ΠΎΠΌ.Π’ ΠΏΠΎΡΠ»Π΅Π΄ΡƒΡŽΡ‰ΠΈΡ… m строках записано ΠΏΠΎ Π΄Π²Π° числа ai, bi (1 ≀ ai, bi ≀ 109, ai ≠ bi), ΠΎΠ±ΠΎΠ·Π½Π°Ρ‡Π°ΡŽΡ‰ΠΈΡ… ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€Ρ‹ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ, ΡΠ²Π»ΡΡŽΡ‰ΠΈΡ…ΡΡ Π΄Ρ€ΡƒΠ·ΡŒΡΠΌΠΈ. ГарантируСтся, Ρ‡Ρ‚ΠΎ каТдая ΠΏΠ°Ρ€Π° людСй Ρ„ΠΈΠ³ΡƒΡ€ΠΈΡ€ΡƒΠ΅Ρ‚ Π² спискС Π½Π΅ Π±ΠΎΠ»Π΅Π΅ ΠΎΠ΄Π½ΠΎΠ³ΠΎ Ρ€Π°Π·Π°.Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ данныСДля всСх упомянутых людСй Π² порядкС возрастания id Π²Ρ‹Π²Π΅Π΄ΠΈΡ‚Π΅ ΠΈΠ½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡŽ ΠΎ ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹Ρ… Π΄Ρ€ΡƒΠ·ΡŒΡΡ…. Π˜Π½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡ Π΄ΠΎΠ»ΠΆΠ½Π° ΠΈΠΌΠ΅Ρ‚ΡŒ Π²ΠΈΠ΄ "id:  kΒ id1Β id2Β ...Β idk", Π³Π΄Π΅ id β€” это id самого Ρ‡Π΅Π»ΠΎΠ²Π΅ΠΊΠ°, k β€” количСство Π΅Π³ΠΎ ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹Ρ… Π΄Ρ€ΡƒΠ·Π΅ΠΉ, Π° id1, id2, ..., idk β€” ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€Ρ‹ Π΅Π³ΠΎ ΠΏΡ€Π΅Π΄ΠΏΠΎΠ»Π°Π³Π°Π΅ΠΌΡ‹Ρ… Π΄Ρ€ΡƒΠ·Π΅ΠΉ Π² Π²ΠΎΠ·Ρ€Π°ΡΡ‚Π°ΡŽΡ‰Π΅ΠΌ порядкС. ΠŸΡ€ΠΈΠΌΠ΅Ρ€Ρ‹Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅5 5110 2323 4239 4210 3939 58Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅10: 1 4223: 1 3939: 1 2342: 1 1058: 2 10 42Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅5 1001 21 31 42 32 4Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅1: 02: 03: 1 44: 1 3
Π’Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅5 5110 2323 4239 4210 3939 58
Π’Ρ‹Ρ…ΠΎΠ΄Π½Ρ‹Π΅ Π΄Π°Π½Π½Ρ‹Π΅10: 1 4223: 1 3939: 1 2342: 1 1058: 2 10 42
ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ Π½Π° тСст2 сСкунды
ΠΎΠ³Ρ€Π°Π½ΠΈΡ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ памяти Π½Π° тСст256 ΠΌΠ΅Π³Π°Π±Π°ΠΉΡ‚
['implementation', '*1600']
D. Statistics of Recompressing Videostime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA social network for dogs called DH (DogHouse) has k special servers to recompress uploaded videos of cute cats. After each video is uploaded, it should be recompressed on one (any) of the servers, and only after that it can be saved in the social network.We know that each server takes one second to recompress a one minute fragment. Thus, any server takes m seconds to recompress a m minute video.We know the time when each of the n videos were uploaded to the network (in seconds starting from the moment all servers started working). All videos appear at different moments of time and they are recompressed in the order they appear. If some video appeared at time s, then its recompressing can start at that very moment, immediately. Some videos can await recompressing when all the servers are busy. In this case, as soon as a server is available, it immediately starts recompressing another video. The videos that await recompressing go in a queue. If by the moment the videos started being recompressed some servers are available, then any of them starts recompressing the video.For each video find the moment it stops being recompressed.InputThe first line of the input contains integers n and k (1 ≀ n, k ≀ 5Β·105) β€” the number of videos and servers, respectively.Next n lines contain the descriptions of the videos as pairs of integers si, mi (1 ≀ si, mi ≀ 109), where si is the time in seconds when the i-th video appeared and mi is its duration in minutes. It is guaranteed that all the si's are distinct and the videos are given in the chronological order of upload, that is in the order of increasing si.OutputPrint n numbers e1, e2, ..., en, where ei is the time in seconds after the servers start working, when the i-th video will be recompressed.ExamplesInput3 21 52 53 5Output6711Input6 11 10000000002 10000000003 10000000004 10000000005 10000000006 3Output100000000120000000013000000001400000000150000000015000000004
Input3 21 52 53 5
Output6711
3 seconds
256 megabytes
['*special problem', 'data structures', 'implementation', '*1600']
C. Name Questtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Martian boy is named s β€” he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=Β«abaΒ», then strings Β«baobabΒ», Β«aabbaaΒ», Β«helloabahelloΒ» make him very happy and strings Β«aabΒ», Β«baaaΒ» and Β«helloabhelloΒ» do not.However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.InputThe first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters.The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.OutputPrint the sought number of ways to cut string t in two so that each part made s happy. ExamplesInputababaobababbahOutput2InputmarssunvenusearthmarsjupitersaturnuranusneptuneOutput0
Inputababaobababbah
Output2
2 seconds
256 megabytes
['*special problem', 'greedy', '*1400']
B. Mean Requeststime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem you will have to deal with a real algorithm that is used in the VK social network.As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T = 60Β seconds = 1Β min and T = 86400Β seconds = 1Β day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource at at each moment of time t (1 ≀ t ≀ n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.// setting this constant value correctly can adjust // the time range for which statistics will be calculateddouble c = some constant value; // as the result of the algorithm's performance this variable will contain // the mean number of queries for the last // T seconds by the current moment of timedouble mean = 0.0; for t = 1..n: // at each second, we do the following: // at is the number of queries that came at the last second; mean = (mean + at / T) / c;Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different from the real mean value ax at t - T + 1 ≀ x ≀ t. The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data. You are given n values at, integer T and real number c. Also, you are given m moments pj (1 ≀ j ≀ m), where we are interested in the mean value of the number of queries for the last T seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where approx is the approximate value, obtained by the second algorithm, and real is the exact value obtained by the first algorithm.InputThe first line contains integer n (1 ≀ n ≀ 2Β·105), integer T (1 ≀ T ≀ n) and real number c (1 < c ≀ 100) β€” the time range when the resource should work, the length of the time range during which we need the mean number of requests and the coefficient c of the work of approximate algorithm. Number c is given with exactly six digits after the decimal point.The next line contains n integers at (1 ≀ at ≀ 106) β€” the number of queries to the service at each moment of time.The next line contains integer m (1 ≀ m ≀ n) β€” the number of moments of time when we are interested in the mean number of queries for the last T seconds.The next line contains m integers pj (T ≀ pj ≀ n), representing another moment of time for which we need statistics. Moments pj are strictly increasing.OutputPrint m lines. The j-th line must contain three numbers real, approx and error, where: is the real mean number of queries for the last T seconds; approx is calculated by the given algorithm and equals mean at the moment of time t = pj (that is, after implementing the pj-th iteration of the cycle); is the relative error of the approximate algorithm. The numbers you printed will be compared to the correct numbers with the relative or absolute error 10 - 4. It is recommended to print the numbers with at least five digits after the decimal point.ExamplesInput1 1 2.000000111Output1.000000 0.500000 0.500000Input11 4 1.2500009 11 7 5 15 6 6 6 6 6 684 5 6 7 8 9 10 11Output8.000000 4.449600 0.4438009.500000 6.559680 0.3095078.250000 6.447744 0.2184558.000000 6.358195 0.2052268.250000 6.286556 0.2379936.000000 6.229245 0.0382076.000000 6.183396 0.0305666.000000 6.146717 0.024453Input13 4 1.2500003 3 3 3 3 20 3 3 3 3 3 3 3104 5 6 7 8 9 10 11 12 13Output3.000000 1.771200 0.4096003.000000 2.016960 0.3276807.250000 5.613568 0.2257157.250000 5.090854 0.2978137.250000 4.672684 0.3554927.250000 4.338147 0.4016353.000000 4.070517 0.3568393.000000 3.856414 0.2854713.000000 3.685131 0.2283773.000000 3.548105 0.182702
Input1 1 2.000000111
Output1.000000 0.500000 0.500000
4 seconds
256 megabytes
['*special problem', 'implementation', '*1500']
A. Rotate, Flip and Zoomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice versa) and zooming on the image. He is sure that that there is a large number of transformations that can be expressed through these three.He has recently stopped implementing all three transformations for monochrome images. To test this feature, he asked you to write a code that will consecutively perform three actions with a monochrome image: first it will rotate the image 90 degrees clockwise, then it will flip the image horizontally and finally, it will zoom in twice on the image (that is, it will double all the linear sizes).Implement this feature to help Polycarp test his editor.InputThe first line contains two integers, w and h (1 ≀ w, h ≀ 100) β€” the width and height of an image in pixels. The picture is given in h lines, each line contains w characters β€” each character encodes the color of the corresponding pixel of the image. The line consists only of characters "." and "*", as the image is monochrome.OutputPrint 2w lines, each containing 2h characters β€” the result of consecutive implementing of the three transformations, described above.ExamplesInput3 2.*..*.Output........********........Input9 20**.......****.....******...*******....******.....****.......****.....***************************************....**......****....******..************..******...*****.....***.......*Output********......**********........****************......**********........****************........********......********..********........********......********....********......********....********......********......********....********......********......********..********........********......********..********..........********....****************............********....****************............********....****************............********....****************..............******************..**********..........******************..**********............****************....**********..........****************....**********..............************......**********............************......**********
Input3 2.*..*.
Output........********........
2 seconds
256 megabytes
['*special problem', 'implementation', '*1200']
D. Closest Equalstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given sequence a1, a2, ..., an and m queries lj, rj (1 ≀ lj ≀ rj ≀ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that: both indexes of the elements lie within range [lj, rj], that is, lj ≀ x, y ≀ rj; the values of the elements are equal, that is ax = ay. The text above understands distance as |x - y|.InputThe first line of the input contains a pair of integers n, m (1 ≀ n, m ≀ 5Β·105) β€” the length of the sequence and the number of queries, correspondingly. The second line contains the sequence of integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109). Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the indexes of the query range limits.OutputPrint m integers β€” the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.ExamplesInput5 31 1 2 3 21 52 43 5Output1-12Input6 51 2 1 3 2 34 61 32 52 41 6Output223-12
Input5 31 1 2 3 21 52 43 5
Output1-12
3 seconds
256 megabytes
['*special problem', 'data structures', '*2000']
C. Chicken or Fish?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is flying in the airplane. Finally, it is his favorite time β€” the lunchtime. The BerAvia company stewardess is giving food consecutively to all the passengers from the 1-th one to the last one. Polycarp is sitting on seat m, that means, he will be the m-th person to get food.The flight menu has k dishes in total and when Polycarp boarded the flight, he had time to count the number of portions of each dish on board. Thus, he knows values a1, a2, ..., ak, where ai is the number of portions of the i-th dish.The stewardess has already given food to m - 1 passengers, gave Polycarp a polite smile and asked him what he would prefer. That's when Polycarp realized that they might have run out of some dishes by that moment. For some of the m - 1 passengers ahead of him, he noticed what dishes they were given. Besides, he's heard some strange mumbling from some of the m - 1 passengers ahead of him, similar to phrase 'I'm disappointed'. That happened when a passenger asked for some dish but the stewardess gave him a polite smile and said that they had run out of that dish. In that case the passenger needed to choose some other dish that was available. If Polycarp heard no more sounds from a passenger, that meant that the passenger chose his dish at the first try.Help Polycarp to find out for each dish: whether they could have run out of the dish by the moment Polyarp was served or that dish was definitely available.InputEach test in this problem consists of one or more input sets. First goes a string that contains a single integer t (1 ≀ t ≀ 100 000) β€” the number of input data sets in the test. Then the sets follow, each set is preceded by an empty line.The first line of each set of the input contains integers m, k (2 ≀ m ≀ 100 000, 1 ≀ k ≀ 100 000) β€” the number of Polycarp's seat and the number of dishes, respectively.The second line contains a sequence of k integers a1, a2, ..., ak (1 ≀ ai ≀ 100 000), where ai is the initial number of portions of the i-th dish.Then m - 1 lines follow, each line contains the description of Polycarp's observations about giving food to a passenger sitting in front of him: the j-th line contains a pair of integers tj, rj (0 ≀ tj ≀ k, 0 ≀ rj ≀ 1), where tj is the number of the dish that was given to the j-th passenger (or 0, if Polycarp didn't notice what dish was given to the passenger), and rj β€” a 1 or a 0, depending on whether the j-th passenger was or wasn't disappointed, respectively.We know that sum ai equals at least m, that is,Polycarp will definitely get some dish, even if it is the last thing he wanted. It is guaranteed that the data is consistent.Sum m for all input sets doesn't exceed 100 000. Sum k for all input sets doesn't exceed 100 000.OutputFor each input set print the answer as a single line. Print a string of k letters "Y" or "N". Letter "Y" in position i should be printed if they could have run out of the i-th dish by the time the stewardess started serving Polycarp.ExamplesInput23 42 3 2 11 00 05 51 2 1 3 13 00 02 14 0OutputYNNYYYYNYNoteIn the first input set depending on the choice of the second passenger the situation could develop in different ways: If he chose the first dish, then by the moment the stewardess reaches Polycarp, they will have run out of the first dish; If he chose the fourth dish, then by the moment the stewardess reaches Polycarp, they will have run out of the fourth dish; Otherwise, Polycarp will be able to choose from any of the four dishes. Thus, the answer is "YNNY".In the second input set there is, for example, the following possible scenario. First, the first passenger takes the only third dish, then the second passenger takes the second dish. Then, the third passenger asks for the third dish, but it is not available, so he makes disappointed muttering and ends up with the second dish. Then the fourth passenger takes the fourth dish, and Polycarp ends up with the choice between the first, fourth and fifth dish.Likewise, another possible scenario is when by the time the stewardess comes to Polycarp, they will have run out of either the first or the fifth dish (this can happen if one of these dishes is taken by the second passenger). It is easy to see that there is more than enough of the fourth dish, so Polycarp can always count on it. Thus, the answer is "YYYNY".
Input23 42 3 2 11 00 05 51 2 1 3 13 00 02 14 0
OutputYNNYYYYNY
1 second
256 megabytes
['greedy', '*2100']
B. Photo to Remembertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together. Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of width wi pixels and height hi pixels. On the group photo everybody stands in a line, thus the minimum pixel size of the photo including all the photographed friends, is W × H, where W is the total sum of all widths and H is the maximum height of all the photographed friends.As is usually the case, the friends made n photos β€” the j-th (1 ≀ j ≀ n) photo had everybody except for the j-th friend as he was the photographer.Print the minimum size of each made photo in pixels. InputThe first line contains integer n (2 ≀ n ≀ 200 000) β€” the number of friends. Then n lines follow: the i-th line contains information about the i-th friend. The line contains a pair of integers wi, hi (1 ≀ wi ≀ 10, 1 ≀ hi ≀ 1000) β€” the width and height in pixels of the corresponding rectangle.OutputPrint n space-separated numbers b1, b2, ..., bn, where bi β€” the total number of pixels on the minimum photo containing all friends expect for the i-th one.ExamplesInput31 105 510 1Output75 110 60 Input32 11 22 1Output6 4 6
Input31 105 510 1
Output75 110 60
2 seconds
256 megabytes
['*special problem', 'data structures', 'dp', 'implementation', '*1100']
A. Repoststime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on.These events are given as a sequence of strings "name1 reposted name2", where name1 is the name of the person who reposted the joke, and name2 is the name of the person from whose news feed the joke was reposted. It is guaranteed that for each string "name1 reposted name2" user "name1" didn't have the joke in his feed yet, and "name2" already had it in his feed by the moment of repost. Polycarp was registered as "Polycarp" and initially the joke was only in his feed.Polycarp measures the popularity of the joke as the length of the largest repost chain. Print the popularity of Polycarp's joke.InputThe first line of the input contains integer n (1 ≀ n ≀ 200) β€” the number of reposts. Next follow the reposts in the order they were made. Each of them is written on a single line and looks as "name1 reposted name2". All the names in the input consist of lowercase or uppercase English letters and/or digits and have lengths from 2 to 24 characters, inclusive.We know that the user names are case-insensitive, that is, two names that only differ in the letter case correspond to the same social network user.OutputPrint a single integer β€” the maximum length of a repost chain.ExamplesInput5tourist reposted PolycarpPetr reposted TouristWJMZBMR reposted Petrsdya reposted wjmzbmrvepifanov reposted sdyaOutput6Input6Mike reposted PolycarpMax reposted PolycarpEveryOne reposted Polycarp111 reposted PolycarpVkCup reposted PolycarpCodeforces reposted PolycarpOutput2Input1SoMeStRaNgEgUe reposted PoLyCaRpOutput2
Input5tourist reposted PolycarpPetr reposted TouristWJMZBMR reposted Petrsdya reposted wjmzbmrvepifanov reposted sdya
Output6
1 second
256 megabytes
['*special problem', 'dfs and similar', 'dp', 'graphs', 'trees', '*1200']
E. Cycling Citytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are organizing a cycling race on the streets of the city. The city contains n junctions, some pairs of them are connected by roads; on each road you can move in any direction. No two roads connect the same pair of intersections, and no road connects the intersection with itself.You want the race to be open to both professional athletes and beginner cyclists, and that's why you will organize the race in three nominations: easy, moderate and difficult; each participant will choose the more suitable nomination. For each nomination you must choose the route β€” the chain of junctions, consecutively connected by roads. Routes must meet the following conditions: all three routes should start at the same intersection, and finish at the same intersection (place of start and finish can't be the same); to avoid collisions, no two routes can have common junctions (except for the common start and finish), and can not go along the same road (irrespective of the driving direction on the road for those two routes); no route must pass twice through the same intersection or visit the same road twice (irrespective of the driving direction on the road for the first and second time of visit).Preparing for the competition is about to begin, and you need to determine the routes of the race as quickly as possible. The length of the routes is not important, it is only important that all the given requirements were met.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 2Β·105) β€” the number of intersections and roads, respectively.The following m lines contain two integers β€” the numbers of the intersections connected by a road (the intersections are numbered starting with 1). It is guaranteed that each pair of intersections is connected by no more than one road, and no road connects the intersection to itself.Please note that it is not guaranteed that you can get from any junction to any other one by using the roads.OutputIf it is possible to create the routes, in the first line print "YES". In the next three lines print the descriptions of each of the three routes in the format "l p1 ... pl", where l is the number of intersections in the route, and p1, ..., pl are their numbers in the order they follow. The routes must meet all the requirements specified in the statement.If it is impossible to make the routes in accordance with the requirements, print NO.ExamplesInput4 41 22 33 44 1OutputNOInput5 61 21 31 42 53 54 5OutputYES3 5 4 13 5 3 13 5 2 1
Input4 41 22 33 44 1
OutputNO
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*3100']
D. Shoptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya plays one very well-known and extremely popular MMORPG game. His game character has k skill; currently the i-th of them equals to ai. Also this game has a common rating table in which the participants are ranked according to the product of all the skills of a hero in the descending order.Vasya decided to 'upgrade' his character via the game store. This store offers n possible ways to improve the hero's skills; Each of these ways belongs to one of three types: assign the i-th skill to b; add b to the i-th skill; multiply the i-th skill by b. Unfortunately, a) every improvement can only be used once; b) the money on Vasya's card is enough only to purchase not more than m of the n improvements. Help Vasya to reach the highest ranking in the game. To do this tell Vasya which of improvements he has to purchase and in what order he should use them to make his rating become as high as possible. If there are several ways to achieve it, print any of them.InputThe first line contains three numbers β€” k, n, m (1 ≀ k ≀ 105, 0 ≀ m ≀ n ≀ 105) β€” the number of skills, the number of improvements on sale and the number of them Vasya can afford.The second line contains k space-separated numbers ai (1 ≀ ai ≀ 106), the initial values of skills.Next n lines contain 3 space-separated numbers tj, ij, bj (1 ≀ tj ≀ 3, 1 ≀ ij ≀ k, 1 ≀ bj ≀ 106) β€” the type of the j-th improvement (1 for assigning, 2 for adding, 3 for multiplying), the skill to which it can be applied and the value of b for this improvement.OutputThe first line should contain a number l (0 ≀ l ≀ m) β€” the number of improvements you should use.The second line should contain l distinct space-separated numbers vi (1 ≀ vi ≀ n) β€” the indices of improvements in the order in which they should be applied. The improvements are numbered starting from 1, in the order in which they appear in the input. ExamplesInput2 4 313 201 1 141 2 302 1 63 2 2Output32 3 4
Input2 4 313 201 1 141 2 302 1 63 2 2
Output32 3 4
2 seconds
256 megabytes
['greedy', '*2800']
E. Pluses everywheretime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is sitting on an extremely boring math class. To have fun, he took a piece of paper and wrote out n numbers on a single line. After that, Vasya began to write out different ways to put pluses ("+") in the line between certain digits in the line so that the result was a correct arithmetic expression; formally, no two pluses in such a partition can stand together (between any two adjacent pluses there must be at least one digit), and no plus can stand at the beginning or the end of a line. For example, in the string 100500, ways 100500 (add no pluses), 1+00+500 or 10050+0 are correct, and ways 100++500, +1+0+0+5+0+0 or 100500+ are incorrect.The lesson was long, and Vasya has written all the correct ways to place exactly k pluses in a string of digits. At this point, he got caught having fun by a teacher and he was given the task to calculate the sum of all the resulting arithmetic expressions by the end of the lesson (when calculating the value of an expression the leading zeros should be ignored). As the answer can be large, Vasya is allowed to get only its remainder modulo 109 + 7. Help him!InputThe first line contains two integers, n and k (0 ≀ k < n ≀ 105).The second line contains a string consisting of n digits.OutputPrint the answer to the problem modulo 109 + 7.ExamplesInput3 1108Output27Input3 2108Output9NoteIn the first sample the result equals (1 + 08) + (10 + 8) = 27.In the second sample the result equals 1 + 0 + 8 = 9.
Input3 1108
Output27
3 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'number theory', '*2200']
D. Cubestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9.InputThe first line contains number m (2 ≀ m ≀ 105).The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≀ xi ≀ 109, 0 ≀ yi ≀ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable.No two cubes occupy the same place.OutputIn the only line print the answer to the problem.ExamplesInput32 11 00 1Output19Input50 00 10 20 30 4Output2930
Input32 11 00 1
Output19
3 seconds
256 megabytes
['games', 'greedy', 'implementation', '*2100']
C. DNA Alignmenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t): where is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 105).The second line of the input contains a single string of length n, consisting of characters "ACGT".OutputPrint a single numberΒ β€” the answer modulo 109 + 7.ExamplesInput1COutput1Input2AGOutput4Input3TTTOutput1NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) ΠΈ ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27
Input1C
Output1
2 seconds
256 megabytes
['math', 'strings', '*1500']
B. Two Buttonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?InputThe first and the only line of the input contains two distinct integers n and m (1 ≀ n, m ≀ 104), separated by a space .OutputPrint a single number β€” the minimum number of times one needs to push the button required to get the number m out of number n.ExamplesInput4 6Output2Input10 1Output9NoteIn the first example you need to push the blue button once, and then push the red button once.In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.
Input4 6
Output2
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'implementation', 'math', 'shortest paths', '*1400']
A. Pangramtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.You are given a string consisting of lowercase and uppercase Latin letters. Check whether this string is a pangram. We say that the string contains a letter of the Latin alphabet if this letter occurs in the string in uppercase or lowercase.InputThe first line contains a single integer n (1 ≀ n ≀ 100)Β β€” the number of characters in the string.The second line contains the string. The string consists only of uppercase and lowercase Latin letters.OutputOutput "YES", if the string is a pangram and "NO" otherwise.ExamplesInput12toosmallwordOutputNOInput35TheQuickBrownFoxJumpsOverTheLazyDogOutputYES
Input12toosmallword
OutputNO
2 seconds
256 megabytes
['implementation', 'strings', '*800']
E. A and B and Lecture Roomstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA and B are preparing themselves for programming contests.The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.Every day А and B write contests in some rooms of their university, and after each contest they gather together in the same room and discuss problems. A and B want the distance from the rooms where problems are discussed to the rooms where contests are written to be equal. The distance between two rooms is the number of edges on the shortest path between them.As they write contests in new rooms every day, they asked you to help them find the number of possible rooms to discuss problems for each of the following m days.InputThe first line contains integer n (1 ≀ n ≀ 105) β€” the number of rooms in the University.The next n - 1 lines describe the corridors. The i-th of these lines (1 ≀ i ≀ n - 1) contains two integers ai and bi (1 ≀ ai, bi ≀ n), showing that the i-th corridor connects rooms ai and bi.The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries.Next m lines describe the queries. The j-th of these lines (1 ≀ j ≀ m) contains two integers xj and yj (1 ≀ xj, yj ≀ n) that means that on the j-th day A will write the contest in the room xj, B will write in the room yj.OutputIn the i-th (1 ≀ i ≀ m) line print the number of rooms that are equidistant from the rooms where A and B write contest on the i-th day.ExamplesInput41 21 32 412 3Output1Input41 22 32 421 21 3Output02Notein the first sample there is only one room at the same distance from rooms number 2 and 3 β€” room number 1.
Input41 21 32 412 3
Output1
2 seconds
256 megabytes
['binary search', 'data structures', 'dfs and similar', 'dp', 'trees', '*2100']
D. A and B and Interesting Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it? InputThe first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively.The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer. OutputPrint the answer to the problem. ExamplesInput1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1xabcabOutput2Input1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1aaaOutput2NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Input1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1xabcab
Output2
2 seconds
256 megabytes
['data structures', 'dp', 'two pointers', '*1800']
C. A and B and Team Trainingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA and B are preparing themselves for programming contests.An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.There are n experienced members and m newbies on the training session. Can you calculate what maximum number of teams can be formed?InputThe first line contains two integers n and m (0 ≀ n, m ≀ 5Β·105) β€” the number of experienced participants and newbies that are present at the training session. OutputPrint the maximum number of teams that can be formed.ExamplesInput2 6Output2Input4 5Output3NoteLet's represent the experienced players as XP and newbies as NB.In the first test the teams look as follows: (XP, NB, NB), (XP, NB, NB).In the second test sample the teams look as follows: (XP, NB, NB), (XP, NB, NB), (XP, XP, NB).
Input2 6
Output2
1 second
256 megabytes
['greedy', 'implementation', 'math', 'number theory', '*1300']
B. A and B and Compilation Errorstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared β€” the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?InputThe first line of the input contains integer n (3 ≀ n ≀ 105) β€” the initial number of compilation errors.The second line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the errors the compiler displayed for the first time. The third line contains n - 1 space-separated integers b1, b2, ..., bn - 1 β€” the errors displayed at the second compilation. It is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one. The fourth line contains n - 2 space-separated integers с1, с2, ..., сn - 2 β€” the errors displayed at the third compilation. It is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one. OutputPrint two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively. ExamplesInput51 5 8 123 7123 7 5 15 1 7Output8123Input61 4 3 3 5 73 7 5 4 34 3 7 5Output13NoteIn the first test sample B first corrects the error number 8, then the error number 123.In the second test sample B first corrects the error number 1, then the error number 3. Note that if there are multiple errors with the same number, B can correct only one of them in one step.
Input51 5 8 123 7123 7 5 15 1 7
Output8123
2 seconds
256 megabytes
['data structures', 'implementation', 'sortings', '*1100']
A. A and B and Chesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA and B are preparing themselves for programming contests.To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.For each chess piece we know its weight: the queen's weight is 9, the rook's weight is 5, the bishop's weight is 3, the knight's weight is 3, the pawn's weight is 1, the king's weight isn't considered in evaluating position. The player's weight equals to the sum of weights of all his pieces on the board.As A doesn't like counting, he asked you to help him determine which player has the larger position weight.InputThe input contains eight lines, eight characters each β€” the board's description.The white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.The white pieces are denoted as follows: the queen is represented is 'Q', the rook β€” as 'R', the bishop β€” as'B', the knight β€” as 'N', the pawn β€” as 'P', the king β€” as 'K'.The black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.An empty square of the board is marked as '.' (a dot). It is not guaranteed that the given chess position can be achieved in a real game. Specifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.OutputPrint "White" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, print "Black" if the weight of the black pieces is more than the weight of the white pieces and print "Draw" if the weights of the white and black pieces are equal.ExamplesInput...QK......................................................rk...OutputWhiteInputrnbqkbnrpppppppp................................PPPPPPPPRNBQKBNROutputDrawInputrppppppr...k....................................K...Q...........OutputBlackNoteIn the first test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals 5.In the second test sample the weights of the positions of the black and the white pieces are equal to 39.In the third test sample the weight of the position of the white pieces equals to 9, the weight of the position of the black pieces equals to 16.
Input...QK......................................................rk...
OutputWhite
1 second
256 megabytes
['implementation', '*900']
F. Pasha and Pipetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOn a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city.The city is an n × m rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are denoted by character '.', occupied squares are denoted by character '#'.The pipe must meet the following criteria: the pipe is a polyline of width 1, the pipe goes in empty squares, the pipe starts from the edge of the field, but not from a corner square, the pipe ends at the edge of the field but not in a corner square, the pipe has at most 2 turns (90 degrees), the border squares of the field must share exactly two squares with the pipe, if the pipe looks like a single segment, then the end points of the pipe must lie on distinct edges of the field, for each non-border square of the pipe there are exacly two side-adjacent squares that also belong to the pipe, for each border square of the pipe there is exactly one side-adjacent cell that also belongs to the pipe. Here are some samples of allowed piping routes: ....# ....# .*..# ***** ****. .***. ..#.. ..#*. ..#*. #...# #..*# #..*# ..... ...*. ...*.Here are some samples of forbidden piping routes: .**.# *...# .*.*# ..... ****. .*.*. ..#.. ..#*. .*#*. #...# #..*# #*.*# ..... ...*. .***.In these samples the pipes are represented by characters ' * '.You were asked to write a program that calculates the number of distinct ways to make exactly one pipe in the city. The two ways to make a pipe are considered distinct if they are distinct in at least one square.InputThe first line of the input contains two integers n, m (2 ≀ n, m ≀ 2000)Β β€”Β the height and width of Berland map.Each of the next n lines contains m characters β€” the map of the city. If the square of the map is marked by character '.', then the square is empty and the pipe can through it. If the square of the map is marked by character '#', then the square is full and the pipe can't through it.OutputIn the first line of the output print a single integer β€” the number of distinct ways to create a pipe.ExamplesInput3 3.....#...Output3Input4 2........Output2Input4 5#...##...####.####.#Output4NoteIn the first sample there are 3 ways to make a pipe (the squares of the pipe are marked by characters ' * '): .*. .*. ... .*# **# **# .*. ... .*.
Input3 3.....#...
Output3
4 seconds
512 megabytes
['binary search', 'brute force', 'combinatorics', 'dp', 'implementation', '*2300']
E. Arthur and Questionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1  +  a2Β ...  +  ak,  a2  +  a3  +  ...  +  ak + 1,  ...,  an - k + 1  +  an - k + 2  +  ...  +  an), then those numbers will form strictly increasing sequence.For example, for the following sample: n = 5,  k = 3,  a = (1,  2,  4,  5,  6) the sequence of numbers will look as follows: (1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6)Β =Β (7,  11,  15), that means that sequence a meets the described property. Obviously the sequence of sums will have n - k + 1 elements.Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively.The next line contains n space-separated elements ai (1 ≀ i ≀ n).If ai  =  ?, then the i-th element of Arthur's sequence was replaced by a question mark. Otherwise, ai ( - 109 ≀ ai ≀ 109) is the i-th element of Arthur's sequence.OutputIf Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes).Otherwise, print n integers β€” Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.ExamplesInput3 2? 1 2Output0 1 2 Input5 1-10 -9 ? -7 -6Output-10 -9 -8 -7 -6 Input5 34 6 7 2 9OutputIncorrect sequence
Input3 2? 1 2
Output0 1 2
2 seconds
256 megabytes
['greedy', 'implementation', 'math', 'ternary search', '*2200']
D. Ilya and Escalatortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIlya got tired of sports programming, left university and got a job in the subway. He was given the task to determine the escalator load factor. Let's assume that n people stand in the queue for the escalator. At each second one of the two following possibilities takes place: either the first person in the queue enters the escalator with probability p, or the first person in the queue doesn't move with probability (1 - p), paralyzed by his fear of escalators and making the whole queue wait behind him.Formally speaking, the i-th person in the queue cannot enter the escalator until people with indices from 1 to i - 1 inclusive enter it. In one second only one person can enter the escalator. The escalator is infinite, so if a person enters it, he never leaves it, that is he will be standing on the escalator at any following second. Ilya needs to count the expected value of the number of people standing on the escalator after t seconds. Your task is to help him solve this complicated task.InputThe first line of the input contains three numbers n, p, t (1 ≀ n, t ≀ 2000, 0 ≀ p ≀ 1). Numbers n and t are integers, number p is real, given with exactly two digits after the decimal point.OutputPrint a single real number β€” the expected number of people who will be standing on the escalator after t seconds. The absolute or relative error mustn't exceed 10 - 6.ExamplesInput1 0.50 1Output0.5Input1 0.50 4Output0.9375Input4 0.20 2Output0.4
Input1 0.50 1
Output0.5
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*1700']
C. Anya and Smartphonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture β€” press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.InputThe first line of the input contains three numbers n, m, k (1 ≀ n, m, k ≀ 105)Β β€”Β the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen.The next line contains n integers, permutation a1, a2, ..., anΒ β€”Β the initial order of icons from left to right in the menu (from the first to the last one), aiΒ β€”Β  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai.The third line contains m integers b1, b2, ..., bm(1 ≀ bi ≀ n)Β β€”Β the ids of the launched applications in the planned order. One application may be launched multiple times.OutputPrint a single number β€” the number of gestures that Anya needs to make to launch all the applications in the desired order.ExamplesInput8 3 31 2 3 4 5 6 7 87 8 1Output7Input5 4 23 1 5 2 44 4 4 4Output8NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the iconsΒ β€”Β (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.
Input8 3 31 2 3 4 5 6 7 87 8 1
Output7
1 second
256 megabytes
['constructive algorithms', 'data structures', 'implementation', '*1600']
B. Tanya and Postcardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Tanya decided to present her dad a postcard on his Birthday. She has already created a message β€” string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.InputThe first line contains line s (1 ≀ |s| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text of Tanya's message.The second line contains line t (|s| ≀ |t| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text written in the newspaper.Here |a| means the length of the string a.OutputPrint two integers separated by a space: the first number is the number of times Tanya shouts "YAY!" while making the message, the second number is the number of times Tanya says "WHOOPS" while making the message. ExamplesInputAbCDCbAOutput3 0InputABCabcOutput0 3InputabacabaAbaCaBAOutput3 4
InputAbCDCbA
Output3 0
2 seconds
256 megabytes
['greedy', 'implementation', 'strings', '*1400']
A. Vitaly and Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitaly is a diligent student who never missed a lesson in his five years of studying in the university. He always does his homework on time and passes his exams in time. During the last lesson the teacher has provided two strings s and t to Vitaly. The strings have the same length, they consist of lowercase English letters, string s is lexicographically smaller than string t. Vitaly wondered if there is such string that is lexicographically larger than string s and at the same is lexicographically smaller than string t. This string should also consist of lowercase English letters and have the length equal to the lengths of strings s and t. Let's help Vitaly solve this easy problem!InputThe first line contains string s (1 ≀ |s| ≀ 100), consisting of lowercase English letters. Here, |s| denotes the length of the string.The second line contains string t (|t| = |s|), consisting of lowercase English letters.It is guaranteed that the lengths of strings s and t are the same and string s is lexicographically less than string t.OutputIf the string that meets the given requirements doesn't exist, print a single string "No such string" (without the quotes).If such string exists, print it. If there are multiple valid strings, you may print any of them.ExamplesInputacOutputbInputaaazzzOutputkkkInputabcdefgabcdefhOutputNo such stringNoteString s = s1s2... sn is said to be lexicographically smaller than t = t1t2... tn, if there exists such i, that s1 = t1, s2 = t2, ... si - 1 = ti - 1, si < ti.
Inputac
Outputb
1 second
256 megabytes
['constructive algorithms', 'strings', '*1600']
E. Drazil and His Happy Friendstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if it is happy originally), he stays happy forever.Drazil wants to know on which day all his friends become happy or to determine if they won't become all happy at all.InputThe first line contains two integer n and m (1 ≀ n, m ≀ 109).The second line contains integer b (0 ≀ b ≀ min(n, 105)), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≀ xi < n), denoting the list of indices of happy boys.The third line conatins integer g (0 ≀ g ≀ min(m, 105)), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≀ yj < m), denoting the list of indices of happy girls.It is guaranteed that there is at least one person that is unhappy among his friends.OutputPrint the number of the first day that all friends of Drazil become happy. If this day won't come at all, you print -1.ExamplesInput2 301 0Output4Input2 41 01 2Output-1Input2 31 01 1Output2Input99999 1000002 514 4152 50216 61205Output4970100515NoteBy we define the remainder of integer division of i by k.In first sample case: On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.
Input2 301 0
Output4
4 seconds
256 megabytes
['math', 'number theory', '*3100']
D. Drazil and Morning Exercisetime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil and Varda are the earthworm couple. They want to find a good place to bring up their children. They found a good ground containing nature hole. The hole contains many rooms, some pairs of rooms are connected by small tunnels such that earthworm can move between them.Let's consider rooms and small tunnels as the vertices and edges in a graph. This graph is a tree. In the other words, any pair of vertices has an unique path between them.Each room that is leaf in the graph is connected with a ground by a vertical tunnel. Here, leaf is a vertex that has only one outgoing edge in the graph.Each room is large enough only to fit one earthworm living in it. Earthworm can't live in a tunnel.Drazil and Varda have a plan to educate their children. They want all their children to do morning exercises immediately after getting up!When the morning is coming, all earthworm children get up in the same time, then each of them chooses the farthest path to the ground for gathering with others (these children are lazy, so they all want to do exercises as late as possible).Drazil and Varda want the difference between the time first earthworm child arrives outside and the time the last earthworm child arrives outside to be not larger than l (otherwise children will spread around the ground and it will be hard to keep them exercising together).Also, The rooms that are occupied by their children should form a connected set. In the other words, for any two rooms that are occupied with earthworm children, all rooms that lie on the path between them should be occupied with earthworm children too.How many children Drazil and Varda may have at most in order to satisfy all conditions above? Drazil and Varda want to know the answer for many different choices of l.(Drazil and Varda don't live in the hole with their children)InputThe first line contains one integer n denoting how many rooms there are in the hole (2 ≀ n ≀ 105).Then there are n - 1 lines following. Each of these lines contains three integers x, y, v (1 ≀ x, y ≀ n, 1 ≀ v ≀ 106) denoting there is a small tunnel between room x and room y that takes time v to pass. Suppose that the time for an earthworm to get out to the ground from any leaf room is the same.The next line contains an integer q (1 ≀ q ≀ 50), denoting the number of different value of l you need to process.The last line contains q numbers, each number denoting a value of l (1 ≀ l ≀ 1011).OutputYou should print q lines. Each line should contain one integer denoting the answer for a corresponding value of l.ExamplesInput51 2 32 3 44 5 33 4 251 2 3 4 5Output13335Input125 9 32 1 711 7 26 5 52 5 36 7 21 4 48 5 71 3 811 12 310 8 21013 14 14 13 13 4 6 7 2 1Output101010101033521NoteFor the first sample the hole looks like the following. Rooms 1 and 5 are leaves, so they contain a vertical tunnel connecting them to the ground. The lengths of farthest path from rooms 1 – 5 to the ground are 12, 9, 7, 9, 12 respectively. If l = 1, we may only choose any single room. If l = 2..4, we may choose rooms 2, 3, and 4 as the answer. If l = 5, we may choose all rooms.
Input51 2 32 3 44 5 33 4 251 2 3 4 5
Output13335
3.5 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'trees', 'two pointers', '*2800']
E. Drazil and Parktime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDrazil is a monkey. He lives in a circular park. There are n trees around the park. The distance between the i-th tree and (i + 1)-st trees is di, the distance between the n-th tree and the first tree is dn. The height of the i-th tree is hi.Drazil starts each day with the morning run. The morning run consists of the following steps: Drazil chooses two different trees He starts with climbing up the first tree Then he climbs down the first tree, runs around the park (in one of two possible directions) to the second tree, and climbs on it Then he finally climbs down the second tree. But there are always children playing around some consecutive trees. Drazil can't stand children, so he can't choose the trees close to children. He even can't stay close to those trees.If the two trees Drazil chooses are x-th and y-th, we can estimate the energy the morning run takes to him as 2(hx + hy) + dist(x, y). Since there are children on exactly one of two arcs connecting x and y, the distance dist(x, y) between trees x and y is uniquely defined.Now, you know that on the i-th day children play between ai-th tree and bi-th tree. More formally, if ai ≀ bi, children play around the trees with indices from range [ai, bi], otherwise they play around the trees with indices from .Please help Drazil to determine which two trees he should choose in order to consume the most energy (since he wants to become fit and cool-looking monkey) and report the resulting amount of energy for each day.InputThe first line contains two integer n and m (3 ≀ n ≀ 105, 1 ≀ m ≀ 105), denoting number of trees and number of days, respectively. The second line contains n integers d1, d2, ..., dn (1 ≀ di ≀ 109), the distances between consecutive trees.The third line contains n integers h1, h2, ..., hn (1 ≀ hi ≀ 109), the heights of trees.Each of following m lines contains two integers ai and bi (1 ≀ ai, bi ≀ n) describing each new day. There are always at least two different trees Drazil can choose that are not affected by children.OutputFor each day print the answer in a separate line.ExamplesInput5 32 2 2 2 23 5 2 1 41 32 24 5Output121618Input3 35 1 45 1 43 32 21 1Output172211
Input5 32 2 2 2 23 5 2 1 41 32 24 5
Output121618
2 seconds
512 megabytes
['data structures', '*2300']
D. Drazil and Tilestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.InputThe first line contains two integers n and m (1 ≀ n, m ≀ 2000).The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.OutputIf there is no solution or the solution is not unique, you should print the string "Not unique".Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.ExamplesInput3 3....*....OutputNot uniqueInput4 4..***...*.**....Output<>***^<>*v**<><>Input2 4*..*....Output*<>*<><>Input1 1.OutputNot uniqueInput1 1*Output*NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique".
Input3 3....*....
OutputNot unique
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2000']
C. Drazil and Factorialtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil is playing a math game with Varda.Let's define for positive integer x as a product of factorials of its digits. For example, .First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then they should find maximum positive number x satisfying following two conditions:1. x doesn't contain neither digit 0 nor digit 1.2. = .Help friends find such number.InputThe first line contains an integer n (1 ≀ n ≀ 15) β€” the number of digits in a.The second line contains n digits of a. There is at least one digit in a that is larger than 1. Number a may possibly contain leading zeroes.OutputOutput a maximum possible integer satisfying the conditions above. There should be no zeroes and ones in this number decimal representation.ExamplesInput41234Output33222Input3555Output555NoteIn the first case,
Input41234
Output33222
2 seconds
256 megabytes
['greedy', 'math', 'sortings', '*1400']
B. Drazil and His Happy Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDrazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.InputThe first line contains two integer n and m (1 ≀ n, m ≀ 100).The second line contains integer b (0 ≀ b ≀ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≀ xi < n), denoting the list of indices of happy boys.The third line conatins integer g (0 ≀ g ≀ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≀ yj < m), denoting the list of indices of happy girls.It is guaranteed that there is at least one person that is unhappy among his friends.OutputIf Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".ExamplesInput2 301 0OutputYesInput2 41 01 2OutputNoInput2 31 01 1OutputYesNoteBy we define the remainder of integer division of i by k.In first sample case: On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day. On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day. On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day. On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy. On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.
Input2 301 0
OutputYes
2 seconds
256 megabytes
['brute force', 'dsu', 'meet-in-the-middle', 'number theory', '*1300']
A. Drazil and Datetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSomeday, Drazil wanted to go on date with Varda. Drazil and Varda live on Cartesian plane. Drazil's home is located in point (0, 0) and Varda's home is located in point (a, b). In each step, he can move in a unit distance in horizontal or vertical direction. In other words, from position (x, y) he can go to positions (x + 1, y), (x - 1, y), (x, y + 1) or (x, y - 1). Unfortunately, Drazil doesn't have sense of direction. So he randomly chooses the direction he will go to in each step. He may accidentally return back to his house during his travel. Drazil may even not notice that he has arrived to (a, b) and continue travelling. Luckily, Drazil arrived to the position (a, b) successfully. Drazil said to Varda: "It took me exactly s steps to travel from my house to yours". But Varda is confused about his words, she is not sure that it is possible to get from (0, 0) to (a, b) in exactly s steps. Can you find out if it is possible for Varda?InputYou are given three integers a, b, and s ( - 109 ≀ a, b ≀ 109, 1 ≀ s ≀ 2Β·109) in a single line.OutputIf you think Drazil made a mistake and it is impossible to take exactly s steps and get from his home to Varda's home, print "No" (without quotes).Otherwise, print "Yes".ExamplesInput5 5 11OutputNoInput10 15 25OutputYesInput0 5 1OutputNoInput0 0 2OutputYesNoteIn fourth sample case one possible route is: .
Input5 5 11
OutputNo
1 second
256 megabytes
['math', '*1000']
E. Darth Vader and Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most x from the root. The distance is the sum of the lengths of edges on the path between nodes.But he has got used to this activity and even grew bored of it. 'Why does he do that, then?' β€” you may ask. It's just that he feels superior knowing that only he can solve this problem. Do you want to challenge Darth Vader himself? Count the required number of nodes. As the answer can be rather large, find it modulo 109 + 7.InputThe first line contains two space-separated integers n and x (1 ≀ n ≀ 105, 0 ≀ x ≀ 109) β€” the number of children of each node and the distance from the root within the range of which you need to count the nodes.The next line contains n space-separated integers di (1 ≀ di ≀ 100) β€” the length of the edge that connects each node with its i-th child.OutputPrint a single number β€” the number of vertexes in the tree at distance from the root equal to at most x. ExamplesInput3 31 2 3Output8NotePictures to the sample (the yellow color marks the nodes the distance to which is at most three)
Input3 31 2 3
Output8
2 seconds
256 megabytes
['dp', 'matrices', '*2200']
D. R2D2 and Droid Armytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn army of n droids is lined up in one row. Each droid is described by m integers a1, a2, ..., am, where ai is the number of details of the i-th type in this droid's mechanism. R2-D2 wants to destroy the sequence of consecutive droids of maximum length. He has m weapons, the i-th weapon can affect all the droids in the army by destroying one detail of the i-th type (if the droid doesn't have details of this type, nothing happens to it). A droid is considered to be destroyed when all of its details are destroyed. R2-D2 can make at most k shots. How many shots from the weapon of what type should R2-D2 make to destroy the sequence of consecutive droids of maximum length?InputThe first line contains three integers n, m, k (1 ≀ n ≀ 105, 1 ≀ m ≀ 5, 0 ≀ k ≀ 109) β€” the number of droids, the number of detail types and the number of available shots, respectively.Next n lines follow describing the droids. Each line contains m integers a1, a2, ..., am (0 ≀ ai ≀ 108), where ai is the number of details of the i-th type for the respective robot.OutputPrint m space-separated integers, where the i-th number is the number of shots from the weapon of the i-th type that the robot should make to destroy the subsequence of consecutive droids of the maximum length.If there are multiple optimal solutions, print any of them. It is not necessary to make exactly k shots, the number of shots can be less.ExamplesInput5 2 44 01 22 10 21 3Output2 2Input3 2 41 21 32 2Output1 3NoteIn the first test the second, third and fourth droids will be destroyed. In the second test the first and second droids will be destroyed.
Input5 2 44 01 22 10 21 3
Output2 2
2 seconds
256 megabytes
['binary search', 'data structures', 'two pointers', '*2000']
C. Watto and Mechanismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWatto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.InputThe first line contains two non-negative numbers n and m (0 ≀ n ≀ 3Β·105, 0 ≀ m ≀ 3Β·105) β€” the number of the initial strings and the number of queries, respectively.Next follow n non-empty strings that are uploaded to the memory of the mechanism.Next follow m non-empty strings that are the queries to the mechanism.The total length of lines in the input doesn't exceed 6Β·105. Each line consists only of letters 'a', 'b', 'c'.OutputFor each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).ExamplesInput2 3aaaaaacacacaaabaaccacacccaaacOutputYESNONO
Input2 3aaaaaacacacaaabaaccacacccaaac
OutputYESNONO
3 seconds
256 megabytes
['binary search', 'data structures', 'hashing', 'string suffix structures', 'strings', '*2000']
B. Han Solo and Lazer Guntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location. InputThe first line contains three integers n, x0 ΠΈ y0 (1 ≀ n ≀ 1000,  - 104 ≀ x0, y0 ≀ 104) β€” the number of stormtroopers on the battle field and the coordinates of your gun.Next n lines contain two integers each xi, yi ( - 104 ≀ xi, yi ≀ 104) β€” the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.OutputPrint a single integer β€” the minimum number of shots Han Solo needs to destroy all the stormtroopers. ExamplesInput4 0 01 12 22 0-1 -1Output2Input2 1 21 11 0Output1NoteExplanation to the first and second samples from the statement, respectively:
Input4 0 01 12 22 0-1 -1
Output2
1 second
256 megabytes
['brute force', 'data structures', 'geometry', 'implementation', 'math', '*1400']
A. Chewbaсca and Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.InputThe first line contains a single integer x (1 ≀ x ≀ 1018) β€” the number that Luke Skywalker gave to Chewbacca.OutputPrint the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.ExamplesInput27Output22Input4545Output4444
Input27
Output22
1 second
256 megabytes
['greedy', 'implementation', '*1200']
G3. Inversions problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.InputThe first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n.The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. OutputOutput the answer with absolute or relative error no more than 1e - 9.ExamplesInput3 11 2 3Output0.833333333333333Input3 41 3 2Output1.458333333333334NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .
Input3 11 2 3
Output0.833333333333333
2 seconds
256 megabytes
['dp', '*3100']
G2. Inversions problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.InputThe first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n.The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. OutputOutput the answer with absolute or relative error no more than 1e - 9.ExamplesInput3 11 2 3Output0.833333333333333Input3 41 3 2Output1.458333333333334NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .
Input3 11 2 3
Output0.833333333333333
2 seconds
256 megabytes
['dp', 'probabilities', '*2400']
G1. Inversions problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≀ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.InputThe first line of input contains two integers n and k (1 ≀ n ≀ 100, 1 ≀ k ≀ 109). The next line contains n integers p1, p2, ..., pn β€” the given permutation. All pi are different and in range from 1 to n.The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem G1 (3 points), the constraints 1 ≀ n ≀ 6, 1 ≀ k ≀ 4 will hold. In subproblem G2 (5 points), the constraints 1 ≀ n ≀ 30, 1 ≀ k ≀ 200 will hold. In subproblem G3 (16 points), the constraints 1 ≀ n ≀ 100, 1 ≀ k ≀ 109 will hold. OutputOutput the answer with absolute or relative error no more than 1e - 9.ExamplesInput3 11 2 3Output0.833333333333333Input3 41 3 2Output1.458333333333334NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .
Input3 11 2 3
Output0.833333333333333
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'dp', 'meet-in-the-middle', '*1800']
F2. Scaygerbosstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCthulhu decided to catch Scaygerboss. Scaygerboss found it out and is trying to hide in a pack of his scaygers. Each scayger except Scaygerboss is either a male or a female. Scaygerboss's gender is "other".Scaygers are scattered on a two-dimensional map divided into cells. A scayger looks nerdy and loveable if it is staying in the same cell with exactly one scayger of a gender that is different from its own gender. Cthulhu will not be able to catch Scaygerboss if all the scaygers on the map look nerdy and loveable.The scaygers can move around at different speeds. For each scayger, we are given the time it takes this scayger to move from a cell to an adjacent cell. Cells are adjacent if they share a common side. At any point of time, each cell that does not contain an obstacle can be occupied by an arbitrary number of scaygers. Scaygers cannot move to cells with obstacles.Calculate minimal time in order to make all scaygers look nerdy and loveable if they move optimally toward this goal.InputThe first line contains 4 integers: n, m, males, females (0 ≀ males, females ≀ nΒ·m). n and m are dimensions of the map; males and females are numbers of male scaygers and female scaygers.Next n lines describe the map. Each of these lines contains m characters. Character '.' stands for a free cell; character '#' stands for a cell with an obstacle.The next line contains 3 integers r, c, and t (1 ≀ r ≀ n, 1 ≀ c ≀ m, 1 ≀ t ≀ 109): the current coordinates of Scaygerboss and the time it takes Scaygerboss to move to an adjacent cell. The next males lines contain coordinates and times of male scaygers in the same format as for Scaygerboss. The next females lines contain coordinates and times of female scaygers in the same format as for Scaygerboss. (The coordinates and times adhere to the same limits as for Scaygerboss.) All scaygers reside in cells without obstacles.The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem F1 (14 points), the constraints 1 ≀ n, m ≀ 11 will hold. In subproblem F2 (6 points), the constraints 1 ≀ n, m ≀ 22 will hold. OutputOutput the minimum possible time it takes to make all scaygers look nerdy and loveable or -1 if it is impossible.ExamplesInput4 4 2 3.....###########2 1 12 1 22 1 22 1 22 1 21 1 2Output2Input2 4 2 2.....###2 1 12 1 22 1 22 1 22 1 2Output-1NoteConsider the first sample test. The scaygers are hiding on a 4 by 4 map. Scaygerboss initially resides in the cell (2, 1) and can move between cells in 1 unit of time. There are also 2 male and 3 female scaygers on the map. One of the females initially is in the cell (1, 1), and all the other scaygers are in the cell (2, 1). All the scaygers move between cells in 2 units of time. If Scaygerboss and the female scayger from the cell (1, 1) move to the cell (1, 2), and a male and a female scayger from those residing in the cell (2, 1) move to the cell (1, 1), then all the scaygers will look nerdy and lovable in 2 units of time.
Input4 4 2 3.....###########2 1 12 1 22 1 22 1 22 1 21 1 2
Output2
3 seconds
256 megabytes
['flows', '*2800']
F1. Scaygerbosstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCthulhu decided to catch Scaygerboss. Scaygerboss found it out and is trying to hide in a pack of his scaygers. Each scayger except Scaygerboss is either a male or a female. Scaygerboss's gender is "other".Scaygers are scattered on a two-dimensional map divided into cells. A scayger looks nerdy and loveable if it is staying in the same cell with exactly one scayger of a gender that is different from its own gender. Cthulhu will not be able to catch Scaygerboss if all the scaygers on the map look nerdy and loveable.The scaygers can move around at different speeds. For each scayger, we are given the time it takes this scayger to move from a cell to an adjacent cell. Cells are adjacent if they share a common side. At any point of time, each cell that does not contain an obstacle can be occupied by an arbitrary number of scaygers. Scaygers cannot move to cells with obstacles.Calculate minimal time in order to make all scaygers look nerdy and loveable if they move optimally toward this goal.InputThe first line contains 4 integers: n, m, males, females (0 ≀ males, females ≀ nΒ·m). n and m are dimensions of the map; males and females are numbers of male scaygers and female scaygers.Next n lines describe the map. Each of these lines contains m characters. Character '.' stands for a free cell; character '#' stands for a cell with an obstacle.The next line contains 3 integers r, c, and t (1 ≀ r ≀ n, 1 ≀ c ≀ m, 1 ≀ t ≀ 109): the current coordinates of Scaygerboss and the time it takes Scaygerboss to move to an adjacent cell. The next males lines contain coordinates and times of male scaygers in the same format as for Scaygerboss. The next females lines contain coordinates and times of female scaygers in the same format as for Scaygerboss. (The coordinates and times adhere to the same limits as for Scaygerboss.) All scaygers reside in cells without obstacles.The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem F1 (14 points), the constraints 1 ≀ n, m ≀ 11 will hold. In subproblem F2 (6 points), the constraints 1 ≀ n, m ≀ 22 will hold. OutputOutput the minimum possible time it takes to make all scaygers look nerdy and loveable or -1 if it is impossible.ExamplesInput4 4 2 3.....###########2 1 12 1 22 1 22 1 22 1 21 1 2Output2Input2 4 2 2.....###2 1 12 1 22 1 22 1 22 1 2Output-1NoteConsider the first sample test. The scaygers are hiding on a 4 by 4 map. Scaygerboss initially resides in the cell (2, 1) and can move between cells in 1 unit of time. There are also 2 male and 3 female scaygers on the map. One of the females initially is in the cell (1, 1), and all the other scaygers are in the cell (2, 1). All the scaygers move between cells in 2 units of time. If Scaygerboss and the female scayger from the cell (1, 1) move to the cell (1, 2), and a male and a female scayger from those residing in the cell (2, 1) move to the cell (1, 1), then all the scaygers will look nerdy and lovable in 2 units of time.
Input4 4 2 3.....###########2 1 12 1 22 1 22 1 22 1 21 1 2
Output2
3 seconds
256 megabytes
['flows', '*2700']
E2. Subarray Cutstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of length n and a number k. Let's pick k non-overlapping non-empty subarrays of the initial array. Let si be the sum of the i-th subarray in order from left to right. Compute the maximum value of the following expression: |s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|Here subarray is a contiguous part of an array.InputThe first line of input contains two integers n and k. The second line contains n integers β€” the elements of the array. The absolute values of elements do not exceed 104.The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem E1 (9 points), constraints 2 ≀ n ≀ 400, 2 ≀ k ≀ min(n, 50) will hold. In subproblem E2 (12 points), constraints 2 ≀ n ≀ 30000, 2 ≀ k ≀ min(n, 200) will hold. OutputOutput a single integer β€” the maximum possible value.ExamplesInput5 35 2 4 3 1Output12Input4 27 4 3 7Output8NoteConsider the first sample test. The optimal solution is obtained if the first subarray contains the first element only, the second subarray spans the next three elements and the last subarray contains the last element only. The sums of these subarrays are 5, 9 and 1, correspondingly.Consider the second sample test. In the optimal solution, the first subarray consists of the first two elements and the second subarray consists of the third element only. Note that the last element does not belong to any subarray in this solution.
Input5 35 2 4 3 1
Output12
2 seconds
512 megabytes
['dp', '*2700']
E1. Subarray Cutstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array of length n and a number k. Let's pick k non-overlapping non-empty subarrays of the initial array. Let si be the sum of the i-th subarray in order from left to right. Compute the maximum value of the following expression: |s1 - s2| + |s2 - s3| + ... + |sk - 1 - sk|Here subarray is a contiguous part of an array.InputThe first line of input contains two integers n and k. The second line contains n integers β€” the elements of the array. The absolute values of elements do not exceed 104.The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem E1 (9 points), constraints 2 ≀ n ≀ 400, 2 ≀ k ≀ min(n, 50) will hold. In subproblem E2 (12 points), constraints 2 ≀ n ≀ 30000, 2 ≀ k ≀ min(n, 200) will hold. OutputOutput a single integer β€” the maximum possible value.ExamplesInput5 35 2 4 3 1Output12Input4 27 4 3 7Output8NoteConsider the first sample test. The optimal solution is obtained if the first subarray contains the first element only, the second subarray spans the next three elements and the last subarray contains the last element only. The sums of these subarrays are 5, 9 and 1, correspondingly.Consider the second sample test. In the optimal solution, the first subarray consists of the first two elements and the second subarray consists of the third element only. Note that the last element does not belong to any subarray in this solution.
Input5 35 2 4 3 1
Output12
2 seconds
512 megabytes
['dp', '*2600']
D2. Constrained Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.InputThe first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 ≀ ai, bi ≀ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem D1 (9 points), the constraints 1 ≀ n ≀ 100, 1 ≀ c ≀ 50 will hold. In subproblem D2 (8 points), the constraints 1 ≀ n ≀ 1000000, 1 ≀ c ≀ 100000 will hold. OutputOutput will be on a single line.Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).ExamplesInput3 21 2 LEFT1 3 RIGHTOutput2 1 3Input3 21 2 RIGHT1 3 LEFTOutputIMPOSSIBLENoteConsider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order.For other information regarding in-order and pre-order, see http://en.wikipedia.org/wiki/Tree_traversal.
Input3 21 2 LEFT1 3 RIGHT
Output2 1 3
2 seconds
256 megabytes
['constructive algorithms', 'data structures', '*2600']
D1. Constrained Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.InputThe first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 ≀ ai, bi ≀ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child.The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem D1 (9 points), the constraints 1 ≀ n ≀ 100, 1 ≀ c ≀ 50 will hold. In subproblem D2 (8 points), the constraints 1 ≀ n ≀ 1000000, 1 ≀ c ≀ 100000 will hold. OutputOutput will be on a single line.Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices.If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).ExamplesInput3 21 2 LEFT1 3 RIGHTOutput2 1 3Input3 21 2 RIGHT1 3 LEFTOutputIMPOSSIBLENoteConsider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order.For other information regarding in-order and pre-order, see http://en.wikipedia.org/wiki/Tree_traversal.
Input3 21 2 LEFT1 3 RIGHT
Output2 1 3
2 seconds
256 megabytes
['dfs and similar', '*2400']
C. Second price auctiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receives a request with details about the user, web page and ad slot and they have to respond within those 100 milliseconds with a bid they would pay for putting an advertisement on that ad slot. The company that suggests the highest bid wins the auction and gets to place its advertisement. If there are several companies tied for the highest bid, the winner gets picked at random.However, the company that won the auction does not have to pay the exact amount of its bid. In most of the cases, a second-price auction is used. This means that the amount paid by the company is equal to the maximum of all the other bids placed for this ad slot.Let's consider one such bidding. There are n companies competing for placing an ad. The i-th of these companies will bid an integer number of microdollars equiprobably randomly chosen from the range between Li and Ri, inclusive. In the other words, the value of the i-th company bid can be any integer from the range [Li, Ri] with the same probability. Determine the expected value that the winner will have to pay in a second-price auction.InputThe first line of input contains an integer number n (2 ≀ n ≀ 5). n lines follow, the i-th of them containing two numbers Li and Ri (1 ≀ Li ≀ Ri ≀ 10000) describing the i-th company's bid preferences.This problem doesn't have subproblems. You will get 8 points for the correct submission.OutputOutput the answer with absolute or relative error no more than 1e - 9.ExamplesInput34 78 105 5Output5.7500000000Input32 53 41 6Output3.5000000000NoteConsider the first example. The first company bids a random integer number of microdollars in range [4, 7]; the second company bids between 8 and 10, and the third company bids 5 microdollars. The second company will win regardless of the exact value it bids, however the price it will pay depends on the value of first company's bid. With probability 0.5 the first company will bid at most 5 microdollars, and the second-highest price of the whole auction will be 5. With probability 0.25 it will bid 6 microdollars, and with probability 0.25 it will bid 7 microdollars. Thus, the expected value the second company will have to pay is 0.5Β·5 + 0.25Β·6 + 0.25Β·7 = 5.75.
Input34 78 105 5
Output5.7500000000
2 seconds
256 megabytes
['bitmasks', 'probabilities', '*2000']
B2. Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).InputThe single line of input contains two integers n and m (1 ≀ m ≀ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem B1 (3 points), the constraint 1 ≀ n ≀ 8 will hold. In subproblem B2 (4 points), the constraint 1 ≀ n ≀ 50 will hold. OutputOutput n number forming the required permutation.ExamplesInput2 2Output2 1 Input3 2Output1 3 2 NoteIn the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Input2 2
Output2 1
2 seconds
256 megabytes
['bitmasks', 'divide and conquer', 'math', '*1800']
B1. Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).InputThe single line of input contains two integers n and m (1 ≀ m ≀ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. In subproblem B1 (3 points), the constraint 1 ≀ n ≀ 8 will hold. In subproblem B2 (4 points), the constraint 1 ≀ n ≀ 50 will hold. OutputOutput n number forming the required permutation.ExamplesInput2 2Output2 1 Input3 2Output1 3 2 NoteIn the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Input2 2
Output2 1
2 seconds
256 megabytes
['brute force', '*1400']
A. Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players play a simple game. Each player is provided with a box with balls. First player's box contains exactly n1 balls and second player's box contains exactly n2 balls. In one move first player can take from 1 to k1 balls from his box and throw them away. Similarly, the second player can take from 1 to k2 balls from his box in his move. Players alternate turns and the first player starts the game. The one who can't make a move loses. Your task is to determine who wins if both players play optimally.InputThe first line contains four integers n1, n2, k1, k2. All numbers in the input are from 1 to 50.This problem doesn't have subproblems. You will get 3 points for the correct submission.OutputOutput "First" if the first player wins and "Second" otherwise.ExamplesInput2 2 1 2OutputSecondInput2 1 1 1OutputFirstNoteConsider the first sample test. Each player has a box with 2 balls. The first player draws a single ball from his box in one move and the second player can either take 1 or 2 balls from his box in one move. No matter how the first player acts, the second player can always win if he plays wisely.
Input2 2 1 2
OutputSecond
2 seconds
256 megabytes
['constructive algorithms', 'math', '*800']
E. Fox And Polygontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel just designed a puzzle game called "Polygon"! It is played using triangulations of a regular n-edge polygon. The goal is to transform one triangulation to another by some tricky rules.Triangulation of an n-edge poylgon is a set of n - 3 diagonals satisfying the condition that no two diagonals share a common internal point.For example, the initial state of the game may look like (a) in above figure. And your goal may look like (c). In each step you can choose a diagonal inside the polygon (but not the one of edges of the polygon) and flip this diagonal. Suppose you are going to flip a diagonal a – b. There always exist two triangles sharing a – b as a side, let's denote them as a – b – c and a – b – d. As a result of this operation, the diagonal a – b is replaced by a diagonal c – d. It can be easily proven that after flip operation resulting set of diagonals is still a triangulation of the polygon.So in order to solve above case, you may first flip diagonal 6 – 3, it will be replaced by diagonal 2 – 4. Then you flip diagonal 6 – 4 and get figure (c) as result.Ciel just proved that for any starting and destination triangulations this game has a solution. She wants you to solve it in no more than 20 000 steps for any puzzle satisfying n ≀ 1000.InputThe first line contain an integer n (4 ≀ n ≀ 1000), number of edges of the regular polygon. Then follows two groups of (n - 3) lines describing the original triangulation and goal triangulation.Description of each triangulation consists of (n - 3) lines. Each line contains 2 integers ai and bi (1 ≀ ai, bi ≀ n), describing a diagonal ai – bi.It is guaranteed that both original and goal triangulations are correct (i. e. no two diagonals share a common internal point in both of these triangulations).OutputFirst, output an integer k (0 ≀ k ≀ 20, 000): number of steps.Then output k lines, each containing 2 integers ai and bi: the endpoints of a diagonal you are going to flip at step i. You may output ai and bi in any order.If there are several possible solutions, output any of them.ExamplesInput41 32 4Output11 3Input62 63 64 66 25 24 2Output26 36 4Input87 12 77 36 34 66 16 26 36 46 8Output37 37 27 1NoteSample test 2 is discussed above and shown on the picture.
Input41 32 4
Output11 3
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', '*2900']
D. Fox And Travellingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is going to travel to New Foxland during this summer.New Foxland has n attractions that are linked by m undirected roads. Two attractions are called adjacent if they are linked by a road. Fox Ciel has k days to visit this city and each day she will visit exactly one attraction.There is one important rule in New Foxland: you can't visit an attraction if it has more than one adjacent attraction that you haven't visited yet.At the beginning Fox Ciel haven't visited any attraction. During her travelling she may move aribtrarly between attraction. After visiting attraction a, she may travel to any attraction b satisfying conditions above that hasn't been visited yet, even if it is not reachable from a by using the roads (Ciel uses boat for travelling between attractions, so it is possible). She wants to know how many different travelling plans she can make. Calculate this number modulo 109 + 9 for every k from 0 to n since she hasn't decided for how many days she is visiting New Foxland.InputFirst line contains two integers: n, m (1 ≀ n ≀ 100, ), the number of attractions and number of undirected roads.Then next m lines each contain two integers ai and bi (1 ≀ ai, bi ≀ n and ai ≠ bi), describing a road. There is no more than one road connecting each pair of attractions.OutputOutput n + 1 integer: the number of possible travelling plans modulo 109 + 9 for all k from 0 to n.ExamplesInput3 21 22 3Output1244Input4 41 22 33 44 1Output10000Input12 112 34 74 55 64 66 125 125 88 910 811 9Output163113548313803060504050400000Input13 0Output113156171617160154440123552086486405189184025945920037836791113510373227020746227020746NoteIn the first sample test for k = 3 there are 4 travelling plans: {1, 2, 3}, {1, 3, 2}, {3, 1, 2}, {3, 2, 1}.In the second sample test Ciel can't visit any attraction in the first day, so for k > 0 the answer is 0.In the third sample test Foxlands look like this:
Input3 21 22 3
Output1244
3 seconds
256 megabytes
['dp', 'trees', '*2900']
E. Fox And Dinnertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.They will have dinner around some round tables. You want to distribute foxes such that: Each fox is sitting at some table. Each table has at least 3 foxes sitting around it. The sum of ages of any two adjacent foxes around each table should be a prime number. If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≀ i ≀ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.If it is possible to distribute the foxes in the desired manner, find out a way to do that.InputThe first line contains single integer n (3 ≀ n ≀ 200): the number of foxes in this party. The second line contains n integers ai (2 ≀ ai ≀ 104).OutputIf it is impossible to do this, output "Impossible".Otherwise, in the first line output an integer m (): the number of tables.Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers β€” indices of fox sitting around that table in clockwise order.If there are several possible arrangements, output any of them.ExamplesInput43 4 8 9Output14 1 2 4 3Input52 2 2 2 2OutputImpossibleInput122 3 4 5 6 7 8 9 10 11 12 13Output112 1 2 3 6 5 12 9 8 7 10 11 4Input242 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25Output36 1 2 3 6 5 410 7 8 9 12 15 14 13 16 11 108 17 18 23 22 19 20 21 24NoteIn example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number.
Input43 4 8 9
Output14 1 2 4 3
2 seconds
256 megabytes
['flows', '*2300']
D. Fox And Jumpingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost.InputThe first line contains an integer n (1 ≀ n ≀ 300), number of cards.The second line contains n numbers li (1 ≀ li ≀ 109), the jump lengths of cards.The third line contains n numbers ci (1 ≀ ci ≀ 105), the costs of cards.OutputIf it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.ExamplesInput3100 99 99001 1 1Output2Input510 20 30 40 501 1 1 1 1Output-1Input715015 10010 6006 4290 2730 2310 11 1 1 1 1 1 10Output6Input84264 4921 6321 6984 2316 8432 6120 10264264 4921 6321 6984 2316 8432 6120 1026Output7237NoteIn first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Input3100 99 99001 1 1
Output2
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'math', '*1900']
C. Fox And Namestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.InputThe first line contains an integer n (1 ≀ n ≀ 100): number of names.Each of the following n lines contain one string namei (1 ≀ |namei| ≀ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.OutputIf there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on).Otherwise output a single word "Impossible" (without quotes).ExamplesInput3rivestshamiradlemanOutputbcdefghijklmnopqrsatuvwxyzInput10touristpetrwjmzbmryeputonsvepifanovscottwuoooooooooooooooosubscriberrowdarktankengineerOutputImpossibleInput10petregorendagorionfeferivanilovetanyaromanovakostkadmitriyhmaratsnowbearbredorjaguarturnikcgyforeverOutputaghjlnopefikdmbcqrstuvwxyzInput7carcarecarefulcarefullybecarefuldontforgetsomethingotherwiseyouwillbehackedgoodluckOutputacbdefhijklmnogpqrstuvwxyz
Input3rivestshamiradleman
Outputbcdefghijklmnopqrsatuvwxyz
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'sortings', '*1600']
B. Fox And Two Dotstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition: These k dots are different: if i ≠ j then di is different from dj. k is at least 4. All dots belong to the same color. For all 1 ≀ i ≀ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge. Determine if there exists a cycle on the field.InputThe first line contains two integers n and m (2 ≀ n, m ≀ 50): the number of rows and columns of the board.Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.OutputOutput "Yes" if there exists a cycle, and "No" otherwise.ExamplesInput3 4AAAAABCAAAAAOutputYesInput3 4AAAAABCAAADAOutputNoInput4 4YYYRBYBYBBBYBBBYOutputYesInput7 6AAAAABABBBABABAAABABABBBABAAABABBBABAAAAABOutputYesInput2 13ABCDEFGHIJKLMNOPQRSTUVWXYZOutputNoNoteIn first sample test all 'A' form a cycle.In second sample there is no such cycle.The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
Input3 4AAAAABCAAAAA
OutputYes
2 seconds
256 megabytes
['dfs and similar', '*1500']
A. Fox And Snaketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.InputThe only line contains two integers: n and m (3 ≀ n, m ≀ 50). n is an odd number.OutputOutput n lines. Each line should contain a string consisting of m characters. Do not output spaces.ExamplesInput3 3Output###..####Input3 4Output####...#####Input5 3Output###..#####..###Input9 9Output#########........###########........#########........###########........#########
Input3 3
Output###..####
2 seconds
256 megabytes
['implementation', '*800']
F. Progress Monitoringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgramming teacher Dmitry Olegovich is going to propose the following task for one of his tests for students:You are given a tree T with n vertices, specified by its adjacency matrix a[1... n, 1... n]. What is the output of the following pseudocode?used[1 ... n] = {0, ..., 0};procedure dfs(v): print v; used[v] = 1; for i = 1, 2, ..., n: if (a[v][i] == 1 and used[i] == 0): dfs(i);dfs(1);In order to simplify the test results checking procedure, Dmitry Olegovich decided to create a tree T such that the result is his favorite sequence b. On the other hand, Dmitry Olegovich doesn't want to provide students with same trees as input, otherwise they might cheat. That's why Dmitry Olegovich is trying to find out the number of different trees T such that the result of running the above pseudocode with T as input is exactly the sequence b. Can you help him?Two trees with n vertices are called different if their adjacency matrices a1 and a2 are different, i. e. there exists a pair (i, j), such that 1 ≀ i, j ≀ n and a1[i][j] ≠ a2[i][j].InputThe first line contains the positive integer n (1 ≀ n ≀ 500) β€” the length of sequence b. The second line contains n positive integers b1, b2, ..., bn (1 ≀ bi ≀ n). It is guaranteed that b is a permutation, or in other words, each of the numbers 1, 2, ..., n appears exactly once in the sequence b. Also it is guaranteed that b1 = 1.OutputOutput the number of trees satisfying the conditions above modulo 109 + 7.ExamplesInput31 2 3Output2Input31 3 2Output1
Input31 2 3
Output2
1 second
256 megabytes
['dp', 'trees', '*2300']
E. Pretty Songtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhen Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i ≀ j).Then the simple prettiness of s is defined by the formula:The prettiness of s equals Find the prettiness of the given song title.We assume that the vowels are I, E, A, O, U, Y.InputThe input contains a single string s (1 ≀ |s| ≀ 5Β·105) β€” the title of the song.OutputPrint the prettiness of the song with the absolute or relative error of at most 10 - 6.ExamplesInputIEAIAIOOutput28.0000000InputBYOBOutput5.8333333InputYISVOWELOutput17.0500000NoteIn the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.
InputIEAIAIO
Output28.0000000
1 second
256 megabytes
['math', 'strings', '*2000']
D. Restoring Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya had two arrays consisting of non-negative integers: a of size n and b of size m. Vasya chose a positive integer k and created an n × m matrix v using the following formula:Vasya wrote down matrix v on a piece of paper and put it in the table.A year later Vasya was cleaning his table when he found a piece of paper containing an n × m matrix w. He remembered making a matrix one day by the rules given above but he was not sure if he had found the paper with the matrix v from those days. Your task is to find out if the matrix w that you've found could have been obtained by following these rules and if it could, then for what numbers k, a1, a2, ..., an, b1, b2, ..., bm it is possible.InputThe first line contains integers n and m (1 ≀ n, m ≀ 100), separated by a space β€” the number of rows and columns in the found matrix, respectively. The i-th of the following lines contains numbers wi, 1, wi, 2, ..., wi, m (0 ≀ wi, j ≀ 109), separated by spaces β€” the elements of the i-th row of matrix w.OutputIf the matrix w could not have been obtained in the manner described above, print "NO" (without quotes) in the single line of output.Otherwise, print four lines.In the first line print "YES" (without quotes).In the second line print an integer k (1 ≀ k ≀ 1018). Note that each element of table w should be in range between 0 and k - 1 inclusively.In the third line print n integers a1, a2, ..., an (0 ≀ ai ≀ 1018), separated by spaces.In the fourth line print m integers b1, b2, ..., bm (0 ≀ bi ≀ 1018), separated by spaces.ExamplesInput2 31 2 32 3 4OutputYES10000000070 1 1 2 3 Input2 21 22 0OutputYES30 1 1 2 Input2 21 22 1OutputNONoteBy we denote the remainder of integer division of b by c.It is guaranteed that if there exists some set of numbers k, a1, ..., an, b1, ..., bm, that you could use to make matrix w, then there also exists a set of numbers that meets the limits 1 ≀ k ≀ 1018, 1 ≀ ai ≀ 1018, 1 ≀ bi ≀ 1018 in the output format. In other words, these upper bounds are introduced only for checking convenience purposes.
Input2 31 2 32 3 4
OutputYES10000000070 1 1 2 3
1 second
256 megabytes
['constructive algorithms', 'math', '*2200']
C. Sums of Digitstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.InputThe first line contains a single integer number n (1 ≀ n ≀ 300).Next n lines contain integer numbers b1, ..., bn Β β€” the required sums of digits. All bi belong to the range 1 ≀ bi ≀ 300.OutputPrint n integer numbers, one per lineΒ β€” the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi. If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.ExamplesInput3123Output123Input3321Output311100
Input3123
Output123
2 seconds
256 megabytes
['dp', 'greedy', 'implementation', '*2000']
B. Painting Pebblestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n piles of pebbles on the table, the i-th pile contains ai pebbles. Your task is to paint each pebble using one of the k given colors so that for each color c and any two piles i and j the difference between the number of pebbles of color c in pile i and number of pebbles of color c in pile j is at most one.In other words, let's say that bi, c is the number of pebbles of color c in the i-th pile. Then for any 1 ≀ c ≀ k, 1 ≀ i, j ≀ n the following condition must be satisfied |bi, c - bj, c| ≀ 1. It isn't necessary to use all k colors: if color c hasn't been used in pile i, then bi, c is considered to be zero.InputThe first line of the input contains positive integers n and k (1 ≀ n, k ≀ 100), separated by a space β€” the number of piles and the number of colors respectively.The second line contains n positive integers a1, a2, ..., an (1 ≀ ai ≀ 100) denoting number of pebbles in each of the piles.OutputIf there is no way to paint the pebbles satisfying the given condition, output "NO" (without quotes) .Otherwise in the first line output "YES" (without quotes). Then n lines should follow, the i-th of them should contain ai space-separated integers. j-th (1 ≀ j ≀ ai) of these integers should be equal to the color of the j-th pebble in the i-th pile. If there are several possible answers, you may output any of them.ExamplesInput4 41 2 3 4OutputYES11 41 2 41 2 3 4Input5 23 2 4 1 3OutputNOInput5 43 2 4 3 5OutputYES1 2 31 31 2 3 41 3 41 1 2 3 4
Input4 41 2 3 4
OutputYES11 41 2 41 2 3 4
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1300']
A. Maximum in Tabletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn n × n table a is defined as follows: The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defined by the formula ai, j = ai - 1, j + ai, j - 1. These conditions define all the values in the table.You are given a number n. You need to determine the maximum value in the n × n table defined by the rules above.InputThe only line of input contains a positive integer n (1 ≀ n ≀ 10) β€” the number of rows and columns of the table.OutputPrint a single line containing a positive integer m β€” the maximum value in the table.ExamplesInput1Output1Input5Output70NoteIn the second test the rows of the table look as follows: {1, 1, 1, 1, 1},  {1, 2, 3, 4, 5},  {1, 3, 6, 10, 15},  {1, 4, 10, 20, 35},  {1, 5, 15, 35, 70}.
Input1
Output1
2 seconds
256 megabytes
['brute force', 'implementation', '*800']
E. Arthur and Bracketstime limit per test2 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputNotice that the memory limit is non-standard.Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [li, ri], containing the distance to the corresponding closing bracket.Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [li, ri].Help Arthur restore his favorite correct bracket sequence!InputThe first line contains integer n (1 ≀ n ≀ 600), the number of opening brackets in Arthur's favorite correct bracket sequence. Next n lines contain numbers li and ri (1 ≀ li ≀ ri < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one. The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.OutputIf it is possible to restore the correct bracket sequence by the given data, print any possible choice.If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).ExamplesInput41 11 11 11 1Output()()()()Input35 53 31 1Output((()))Input35 53 32 2OutputIMPOSSIBLEInput32 31 41 4Output(())()
Input41 11 11 11 1
Output()()()()
2 seconds
128 megabytes
['dp', 'greedy', '*2200']
D. Tanya and Passwordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.InputThe first line contains integer n (1 ≀ n ≀ 2Β·105), the number of three-letter substrings Tanya got. Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.OutputIf Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO". If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.ExamplesInput5acaabaabacabbacOutputYESabacabaInput4abcbCbcb1b13OutputNOInput7aaaaaaaaaaaaaaaaaaaaaOutputYESaaaaaaaaa
Input5acaabaabacabbac
OutputYESabacaba
2 seconds
256 megabytes
['dfs and similar', 'graphs', '*2500']
C. Anya and Ghoststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one candle, then this candle burns for exactly t seconds and then goes out and can no longer be used.For each of the m ghosts Anya knows the time at which it comes: the i-th visit will happen wi seconds after midnight, all wi's are distinct. Each visit lasts exactly one second.What is the minimum number of candles Anya should use so that during each visit, at least r candles are burning? Anya can start to light a candle at any time that is integer number of seconds from midnight, possibly, at the time before midnight. That means, she can start to light a candle integer number of seconds before midnight or integer number of seconds after a midnight, or in other words in any integer moment of time.InputThe first line contains three integers m, t, r (1 ≀ m, t, r ≀ 300), representing the number of ghosts to visit Anya, the duration of a candle's burning and the minimum number of candles that should burn during each visit. The next line contains m space-separated numbers wi (1 ≀ i ≀ m, 1 ≀ wi ≀ 300), the i-th of them repesents at what second after the midnight the i-th ghost will come. All wi's are distinct, they follow in the strictly increasing order.OutputIf it is possible to make at least r candles burn during each visit, then print the minimum number of candles that Anya needs to light for that.If that is impossible, print  - 1.ExamplesInput1 8 310Output3Input2 10 15 8Output1Input1 1 310Output-1NoteAnya can start lighting a candle in the same second with ghost visit. But this candle isn't counted as burning at this visit.It takes exactly one second to light up a candle and only after that second this candle is considered burning; it means that if Anya starts lighting candle at moment x, candle is buring from second x + 1 to second x + t inclusively.In the first sample test three candles are enough. For example, Anya can start lighting them at the 3-rd, 5-th and 7-th seconds after the midnight.In the second sample test one candle is enough. For example, Anya can start lighting it one second before the midnight.In the third sample test the answer is  - 1, since during each second at most one candle can burn but Anya needs three candles to light up the room at the moment when the ghost comes.
Input1 8 310
Output3
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1600']
B. Anton and currency you all knowtime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!InputThe first line contains an odd positive integer nΒ β€” the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.OutputIf the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1.Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.ExamplesInput527Output572Input4573Output3574Input1357997531Output-1
Input527
Output572
0.5 seconds
256 megabytes
['greedy', 'math', 'strings', '*1300']
A. Pasha and Pixelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.InputThe first line of the input contains three integers n, m, k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 105)Β β€” the number of rows, the number of columns and the number of moves that Pasha is going to perform. The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≀ i ≀ n, 1 ≀ j ≀ m), representing the row number and column number of the pixel that was painted during a move.OutputIf Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed.If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0.ExamplesInput2 2 41 11 22 12 2Output4Input2 3 62 32 21 32 21 21 1Output5Input5 3 72 31 21 14 13 15 33 2Output0
Input2 2 41 11 22 12 2
Output4
2 seconds
256 megabytes
['brute force', '*1100']
E. Breaking Goodtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBreaking Good is a new video game which a lot of gamers want to have. There is a certain level in the game that is really difficult even for experienced gamers.Walter William, the main character of the game, wants to join a gang called Los Hermanos (The Brothers). The gang controls the whole country which consists of n cities with m bidirectional roads connecting them. There is no road is connecting a city to itself and for any two cities there is at most one road between them. The country is connected, in the other words, it is possible to reach any city from any other city using the given roads. The roads aren't all working. There are some roads which need some more work to be performed to be completely functioning.The gang is going to rob a bank! The bank is located in city 1. As usual, the hardest part is to escape to their headquarters where the police can't get them. The gang's headquarters is in city n. To gain the gang's trust, Walter is in charge of this operation, so he came up with a smart plan.First of all the path which they are going to use on their way back from city 1 to their headquarters n must be as short as possible, since it is important to finish operation as fast as possible.Then, gang has to blow up all other roads in country that don't lay on this path, in order to prevent any police reinforcements. In case of non-working road, they don't have to blow up it as it is already malfunctional. If the chosen path has some roads that doesn't work they'll have to repair those roads before the operation.Walter discovered that there was a lot of paths that satisfied the condition of being shortest possible so he decided to choose among them a path that minimizes the total number of affected roads (both roads that have to be blown up and roads to be repaired).Can you help Walter complete his task and gain the gang's trust?InputThe first line of input contains two integers n, m (2 ≀ n ≀ 105, ), the number of cities and number of roads respectively.In following m lines there are descriptions of roads. Each description consists of three integers x, y, z (1 ≀ x, y ≀ n, ) meaning that there is a road connecting cities number x and y. If z = 1, this road is working, otherwise it is not.OutputIn the first line output one integer k, the minimum possible number of roads affected by gang.In the following k lines output three integers describing roads that should be affected. Each line should contain three integers x, y, z (1 ≀ x, y ≀ n, ), cities connected by a road and the new state of a road. z = 1 indicates that the road between cities x and y should be repaired and z = 0 means that road should be blown up. You may output roads in any order. Each affected road should appear exactly once. You may output cities connected by a single road in any order. If you output a road, it's original state should be different from z.After performing all operations accroding to your plan, there should remain working only roads lying on some certain shortest past between city 1 and n.If there are multiple optimal answers output any.ExamplesInput2 11 2 0Output11 2 1Input4 41 2 11 3 02 3 13 4 1Output31 2 01 3 12 3 0Input8 91 2 08 3 02 3 11 4 18 7 01 5 14 6 15 7 06 8 0Output32 3 01 5 06 8 1NoteIn the first test the only path is 1 - 2In the second test the only shortest path is 1 - 3 - 4In the third test there are multiple shortest paths but the optimal is 1 - 4 - 6 - 8
Input2 11 2 0
Output11 2 1
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'shortest paths', '*2100']
D. The Maths Lecturetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't.First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that: Decimal representation of x (without leading zeroes) consists of exactly n digits; There exists some integer y > 0 such that: ; decimal representation of y is a suffix of decimal representation of x. As the answer to this question may be pretty huge the teacher asked Amr to output only its remainder modulo a number m.Can you help Amr escape this embarrassing situation?InputInput consists of three integers n, k, m (1 ≀ n ≀ 1000, 1 ≀ k ≀ 100, 1 ≀ m ≀ 109).OutputPrint the required number modulo m.ExamplesInput1 2 1000Output4Input2 2 1000Output45Input5 3 1103Output590NoteA suffix of a string S is a non-empty string that can be obtained by removing some number (possibly, zero) of first characters from S.
Input1 2 1000
Output4
1 second
256 megabytes
['dp', 'implementation', '*2200']
C. Guess Your Way Out!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≀ n ≀ 2h, the player doesn't know where the exit is so he has to guess his way out!Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: Character 'L' means "go to the left child of the current node"; Character 'R' means "go to the right child of the current node"; If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; If he reached a leaf node that is not the exit, he returns to the parent of the current node; If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit?InputInput consists of two integers h, n (1 ≀ h ≀ 50, 1 ≀ n ≀ 2h).OutputOutput a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm.ExamplesInput1 2Output2Input2 3Output5Input3 6Output10Input10 1024Output2046NoteA perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit.
Input1 2
Output2
1 second
256 megabytes
['implementation', 'math', 'trees', '*1700']
B. Amr and Pinstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmr loves Geometry. One day he came up with a very interesting problem.Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y').In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.Help Amr to achieve his goal in minimum number of steps.InputInput consists of 5 space-separated integers r, x, y, x' y' (1 ≀ r ≀ 105,  - 105 ≀ x, y, x', y' ≀ 105), circle radius, coordinates of original center of the circle and coordinates of destination center of the circle respectively.OutputOutput a single integer β€” minimum number of steps required to move the center of the circle to the destination point.ExamplesInput2 0 0 0 4Output1Input1 1 1 4 4Output3Input4 5 6 5 6Output0NoteIn the first sample test the optimal way is to put a pin at point (0, 2) and rotate the circle by 180 degrees counter-clockwise (or clockwise, no matter).
Input2 0 0 0 4
Output1
1 second
256 megabytes
['geometry', 'math', '*1400']