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
|
---|---|---|---|---|---|
A. New Bus Routetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities situated along the main road of Berland. Cities are represented by their coordinates β integer numbers a1,βa2,β...,βan. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money β he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.InputThe first line contains one integer number n (2ββ€βnββ€β2Β·105).The second line contains n integer numbers a1,βa2,β...,βan (β-β109ββ€βaiββ€β109). All numbers ai are pairwise distinct.OutputPrint two integer numbers β the minimal distance and the quantity of pairs with this distance.ExamplesInput46 -3 0 4Output2 1Input3-2 0 2Output2 2NoteIn the first example the distance between the first city and the fourth city is |4β-β6|β=β2, and it is the only pair with this distance. | Input46 -3 0 4 | Output2 1 | 1 second | 256 megabytes | ['implementation', 'sortings', '*1100'] |
A. Bear and Big Brothertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.After how many full years will Limak become strictly larger (strictly heavier) than Bob?InputThe only line of the input contains two integers a and b (1ββ€βaββ€βbββ€β10)Β β the weight of Limak and the weight of Bob respectively.OutputPrint one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.ExamplesInput4 7Output2Input4 9Output3Input1 1Output1NoteIn the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4Β·3β=β12 and 7Β·2β=β14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then. | Input4 7 | Output2 | 1 second | 256 megabytes | ['implementation', '*800'] |
B. Masha and geometric depressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1,βb2,βb3,β..., where for each iβ>β1 the respective term satisfies the condition biβ=βbiβ-β1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1,βa2,β...,βam, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi|ββ€βl is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.InputThe first line of input contains four integers b1, q, l, m (-109ββ€βb1,βqββ€β109, 1ββ€βlββ€β109, 1ββ€βmββ€β105)Β β the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively.The second line contains m distinct integers a1,βa2,β...,βam (-109ββ€βaiββ€β109)Β β numbers that will never be written on the board.OutputPrint the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.ExamplesInput3 2 30 46 14 25 48Output3Input123 1 2143435 4123 11 -5453 141245Output0Input123 1 2143435 454343 -13 6 124OutputinfNoteIn the first sample case, Masha will write integers 3,β12,β24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123. | Input3 2 30 46 14 25 48 | Output3 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*1700'] |
A. Anastasia and pebblestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.InputThe first line contains two integers n and k (1ββ€βnββ€β105, 1ββ€βkββ€β109)Β β the number of different pebble types and number of pebbles Anastasia can place in one pocket.The second line contains n integers w1,βw2,β...,βwn (1ββ€βwiββ€β104)Β β number of pebbles of each type. OutputThe only line of output contains one integerΒ β the minimum number of days Anastasia needs to collect all the pebbles.ExamplesInput3 22 3 4Output3Input5 43 1 8 9 7Output5NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second typeΒ β on the second day, and of third typeΒ β on the third day.Optimal sequence of actions in the second sample case: In the first day Anastasia collects 8 pebbles of the third type. In the second day she collects 8 pebbles of the fourth type. In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type. In the fourth day she collects 7 pebbles of the fifth type. In the fifth day she collects 1 pebble of the second type. | Input3 22 3 4 | Output3 | 1 second | 256 megabytes | ['implementation', 'math', '*1100'] |
E. New tasktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the 228-th international Uzhlyandian Wars strategic game tournament teams from each country are called. The teams should consist of 5 participants.The team of Uzhlyandia will consist of soldiers, because there are no gamers.Masha is a new minister of defense and gaming. The prime duty of the minister is to calculate the efficiency of the Uzhlandian army. The army consists of n soldiers standing in a row, enumerated from 1 to n. For each soldier we know his skill in Uzhlyandian Wars: the i-th soldier's skill is ai.It was decided that the team will consist of three players and two assistants. The skills of players should be same, and the assistants' skills should not be greater than the players' skill. Moreover, it is important for Masha that one of the assistants should stand in the row to the left of the players, and the other one should stand in the row to the right of the players. Formally, a team is five soldiers with indexes i, j, k, l, p, such that 1ββ€βiβ<βjβ<βkβ<βlβ<βpββ€βn and aiββ€βajβ=βakβ=βalββ₯βap. The efficiency of the army is the number of different teams Masha can choose. Two teams are considered different if there is such i such that the i-th soldier is a member of one team, but not a member of the other team.Initially, all players are able to be players. For some reasons, sometimes some soldiers become unable to be players. Sometimes some soldiers, that were unable to be players, become able to be players. At any time any soldier is able to be an assistant. Masha wants to control the efficiency of the army, so she asked you to tell her the number of different possible teams modulo 1000000007 (109β+β7) after each change. InputThe first line contains single integer n (1ββ€βnββ€β105)Β β the number of soldiers in Uzhlyandia.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the soldiers' skills.The third line contains single integer m (1ββ€βmββ€β105)Β β the number of changes.The next m lines contain the changes, each change is described with two integers t and x (1ββ€βtββ€β2, 1ββ€βxββ€βn) on a separate line. If tβ=β1, then the x-th soldier is unable to be a player after this change. If tβ=β2, then the x-th soldier is able to be a player after this change. It is guaranteed that before each query of the first type the soldier is able to be a player, and before each query of the second type the soldier is unable to be a player.OutputPrint m integersΒ β the number of distinct teams after each change.Print the answers modulo 1000000007 (109β+β7). ExamplesInput61 1 1 1 1 121 32 3Output16Input83 4 4 2 4 5 4 131 52 51 2Output162NoteIn the first example, after the first change the only team consists of soldiers [1,β2,β4,β5,β6]. After the second change any five soldiers can form a team.In the first example after the first change the only team is soldiers [1,β2,β3,β7,β8]. After the second change the possible teams are: [1,β2,β3,β5,β7], [1,β2,β3,β5,β8], [1,β2,β3,β7,β8], [1,β2,β5,β7,β8], [1,β3,β5,β7,β8], [2,β3,β5,β7,β8]. After the third change the possible teams are: [1,β3,β5,β7,β8], [2,β3,β5,β7,β8]. | Input61 1 1 1 1 121 32 3 | Output16 | 3 seconds | 256 megabytes | ['data structures', '*2900'] |
D. Finding linestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter some programming contest Roma decided to try himself in tourism. His home country Uzhlyandia is a Cartesian plane. He wants to walk along each of the Main Straight Lines in Uzhlyandia. It is known that each of these lines is a straight line parallel to one of the axes (i.e. it is described with the equation xβ=βa or yβ=βa, where a is integer called the coordinate of this line).Roma lost his own map, so he should find out the coordinates of all lines at first. Uncle Anton agreed to help him, using the following rules: Initially Roma doesn't know the number of vertical and horizontal lines and their coordinates; Roma can announce integer coordinates of some point in Uzhlandia, and Anton then will tell him the minimum among the distances from the chosen point to each of the lines. However, since the coordinates of the lines don't exceed 108 by absolute value, Roma can't choose a point with coordinates exceeding 108 by absolute value. Uncle Anton is in a hurry to the UOI (Uzhlandian Olympiad in Informatics), so he can only answer no more than 3Β·105 questions.The problem is that Roma doesn't know how to find out the coordinates of the lines. Write a program that plays Roma's role and finds the coordinates.InputThere is no input initially. Your program should make queries to get information.It is guaranteed that the number of horizontal and vertical lines is at least 1 and less than or equal to 104 for each type.InteractionTo make a query, print a line "0 x y" (-108ββ€βx,βyββ€β108), where x and y are the coordinates of the point. After each query you need to print end-of-line, make "flush" operation, and then read the answer to the queryΒ β the minimum among the distances prom this point to the Main Straight Lines of Uzhlyandia.You can do no more than 3Β·105 queries.When you are ready to print the answer, print three lines: In the first line print "1 n m", where n is the number of vertical lines (parallel to OY), and m is the number of horizontal lines (parallel to OX). In the second line print n integers x1,βx2,β...,βxnΒ β the coordinates of the vertical lines. In the third line in the same format print m integers y1,βy2,β...,βymΒ β the coordinates of the horizontal lines. You can print coordinates in arbitrary order.To make "flush", you can use (just after printing a query/answer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; see the documentation for other languages. You will get Wrong Answer if you make more queries than allowed or make an invalid query. You can get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output.If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Making test for hackingThe first line should contain two integers n and m (1ββ€βn,βmββ€β104).The second line should contain n distinct integers xi (-108ββ€βxiββ€β108)Β β the coordinates of the vertical lines.The third line should contain m distinct integers yi (-108ββ€βyiββ€β108)Β β the coordinates of the horizontal lines.You can write coordinates in arbitrary order.You can see the example case in the notes.ExampleInput1132Output0 1 20 -2 -20 5 60 -2 21 1 220 -3NoteThe example test is 1 220 -3The minimum distances are: from (1,β2) to xβ=β2; from (β-β2,ββ-β2) to yβ=ββ-β3; from (5,β6) to xβ=β2; from (β-β2,β2) to yβ=β0. | Input1132 | Output0 1 20 -2 -20 5 60 -2 21 1 220 -3 | 3 seconds | 256 megabytes | ['constructive algorithms', 'divide and conquer', 'interactive', '*3000'] |
C. The Great Mixingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration . Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration . The drink should also be tasty, so the glass can contain only integer number of liters of each Coke type (some types can be not presented in the glass). Also, they want to minimize the total volume of Coke in the glass.Carbon dioxide concentration is defined as the volume of carbone dioxide in the Coke divided by the total volume of Coke. When you mix two Cokes, the volume of carbon dioxide sums up, and the total volume of Coke sums up as well.Help them, find the minimal natural number of liters needed to create a glass with carbon dioxide concentration . Assume that the friends have unlimited amount of each Coke type.InputThe first line contains two integers n, k (0ββ€βnββ€β1000, 1ββ€βkββ€β106)Β β carbon dioxide concentration the friends want and the number of Coke types.The second line contains k integers a1,βa2,β...,βak (0ββ€βaiββ€β1000)Β β carbon dioxide concentration of each type of Coke. Some Coke types can have same concentration.OutputPrint the minimal natural number of liter needed to prepare a glass with carbon dioxide concentration , or -1 if it is impossible.ExamplesInput400 4100 300 450 500Output2Input50 2100 25Output3NoteIn the first sample case, we can achieve concentration using one liter of Coke of types and : .In the second case, we can achieve concentration using two liters of type and one liter of type: . | Input400 4100 300 450 500 | Output2 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', 'shortest paths', '*2300'] |
B. Weird journeytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherlandΒ β Uzhlyandia.It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over mβ-β2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia.Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help IgorΒ β calculate the number of good paths.InputThe first line contains two integers n, m (1ββ€βn,βmββ€β106)Β β the number of cities and roads in Uzhlyandia, respectively.Each of the next m lines contains two integers u and v (1ββ€βu,βvββ€βn) that mean that there is road between cities u and v.It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself.OutputPrint out the only integerΒ β the number of good paths in Uzhlyandia.ExamplesInput5 41 21 31 41 5Output6Input5 31 22 34 5Output0Input2 21 11 2Output1NoteIn first sample test case the good paths are: 2βββ1βββ3βββ1βββ4βββ1βββ5, 2βββ1βββ3βββ1βββ5βββ1βββ4, 2βββ1βββ4βββ1βββ5βββ1βββ3, 3βββ1βββ2βββ1βββ4βββ1βββ5, 3βββ1βββ2βββ1βββ5βββ1βββ4, 4βββ1βββ2βββ1βββ3βββ1βββ5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: 2βββ1βββ4βββ1βββ3βββ1βββ5, 2βββ1βββ5βββ1βββ3βββ1βββ4, 2βββ1βββ5βββ1βββ4βββ1βββ3, 3βββ1βββ4βββ1βββ2βββ1βββ5, 3βββ1βββ5βββ1βββ2βββ1βββ4, 4βββ1βββ3βββ1βββ2βββ1βββ5, and all the paths in the other direction. Thus, the answer is 6.In the second test case, Igor simply can not walk by all the roads.In the third case, Igor walks once over every road. | Input5 41 21 31 41 5 | Output6 | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', '*2100'] |
A. Functions againtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSomething happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:In the above formula, 1ββ€βlβ<βrββ€βn must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of l and r for the given array a.InputThe first line contains single integer n (2ββ€βnββ€β105)Β β the size of the array a.The second line contains n integers a1,βa2,β...,βan (-109ββ€βaiββ€β109)Β β the array elements.OutputPrint the only integerΒ β the maximum value of f.ExamplesInput51 4 2 3 1Output3Input41 5 4 7Output6NoteIn the first sample case, the optimal value of f is reached on intervals [1,β2] and [2,β5].In the second case maximal value of f is reachable only on the whole array. | Input51 4 2 3 1 | Output3 | 1 second | 256 megabytes | ['dp', 'two pointers', '*1600'] |
B. Not Afraidtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSince the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.InputThe first line of input contains two integers n and m (1ββ€βn,βmββ€β104) β number of universes and number of groups respectively.The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, kβ>β0) followed by k integers vi,β1,βvi,β2,β...,βvi,βk. If vi,βj is negative, it means that Rick from universe number β-βvi,βj has joined this group and otherwise it means that Morty from universe number vi,βj has joined it.Sum of k for all groups does not exceed 104.OutputIn a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.ExamplesInput4 21 -34 -2 3 2 -3OutputYESInput5 25 3 -2 1 -1 53 -5 2 5OutputNOInput7 23 -1 6 77 -5 4 2 4 7 -3 4OutputYESNoteIn the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event. | Input4 21 -34 -2 3 2 -3 | OutputYES | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1300'] |
A. The Monstertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b,βbβ+βa,βbβ+β2a,βbβ+β3a,β... and Morty screams at times d,βdβ+βc,βdβ+β2c,βdβ+β3c,β.... The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.InputThe first line of input contains two integers a and b (1ββ€βa,βbββ€β100). The second line contains two integers c and d (1ββ€βc,βdββ€β100).OutputPrint the first time Rick and Morty will scream at the same time, or β-β1 if they will never scream at the same time.ExamplesInput20 29 19Output82Input2 116 12Output-1NoteIn the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82. In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time. | Input20 29 19 | Output82 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1200'] |
E. ALTtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputALT is a planet in a galaxy called "Encore". Humans rule this planet but for some reason there's no dog in their planet, so the people there are sad and depressed. Rick and Morty are universal philanthropists and they want to make people in ALT happy. ALT has n cities numbered from 1 to n and nβ-β1 bidirectional roads numbered from 1 to nβ-β1. One can go from any city to any other city using these roads.There are two types of people in ALT: Guardians. A guardian lives in a house alongside a road and guards the road. Citizens. A citizen lives in a house inside a city and works in an office in another city. Every person on ALT is either a guardian or a citizen and there's exactly one guardian alongside each road. Rick and Morty talked to all the people in ALT, and here's what they got: There are m citizens living in ALT. Citizen number i lives in city number xi and works in city number yi. Every day each citizen will go through all roads along the shortest path from his home to his work. A citizen will be happy if and only if either he himself has a puppy himself or all of guardians along his path to his work has a puppy (he sees the guardian's puppy in each road and will be happy). A guardian is always happy. You need to tell Rick and Morty the minimum number of puppies they need in order to make all people in ALT happy, and also provide an optimal way to distribute these puppies.InputThe first line of input contains two integers n and m (2ββ€βnββ€β2βΓβ104, 1ββ€βmββ€β104) β number of cities and number of citizens respectively.The next nβ-β1 lines contain the roads, i-th line contains endpoint of i-th edge, v and u (1ββ€βv,βuββ€βn, vββ βu).The next m lines contain the information about citizens. i-th line contains two integers xi and yi (1ββ€βxi,βyiββ€βn, xiββ βyi).OutputIn the first line of input print a single integer k, the total number of puppies they need (1ββ€βkββ€βn).In the second line print an integer q, the number of puppies to give to citizens, followed by q distinct integers a1,βa2,β...,βaq, index of citizens to give puppy to (0ββ€βqββ€βmin(m,βk), 1ββ€βaiββ€βm).In the third line print an integer e, the number of puppies to give to guardians, followed by e distinct integers b1,βb2,β...,βbe, index of road of guardians to give puppy to (0ββ€βeββ€βmin(nβ-β1,βk), 1ββ€βbiββ€βnβ-β1).Sum of q and e should be equal to k.ExamplesInput4 52 43 41 42 42 12 41 22 3Output31 5 2 3 1 Input4 73 41 42 14 24 22 41 42 13 14 2Output31 6 2 2 3 NoteMap of ALT in the first sample testcase (numbers written on a road is its index): Map of ALT in the second sample testcase (numbers written on a road is its index): | Input4 52 43 41 42 42 12 41 22 3 | Output31 5 2 3 1 | 4 seconds | 256 megabytes | ['data structures', 'flows', 'graphs', 'trees', '*3200'] |
D. Rap Godtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRick is in love with Unity. But Mr. Meeseeks also love Unity, so Rick and Mr. Meeseeks are "love rivals". Unity loves rap, so it decided that they have to compete in a rap game (battle) in order to choose the best. Rick is too nerds, so instead he's gonna make his verse with running his original algorithm on lyrics "Rap God" song. His algorithm is a little bit complicated. He's made a tree with n vertices numbered from 1 to n and there's a lowercase english letter written on each edge. He denotes str(a,βb) to be the string made by writing characters on edges on the shortest path from a to b one by one (a string of length equal to distance of a to b). Note that str(a,βb) is reverse of str(b,βa) and str(a,βa) is empty. In order to make the best verse he can, he needs to answer some queries, but he's not a computer scientist and is not able to answer those queries, so he asked you to help him. Each query is characterized by two vertices x and y (xββ βy). Answer to this query is the number of vertices like z such that zββ βx,βzββ βy and str(x,βy) is lexicographically larger than str(x,βz).String xββ=ββx1x2...x|x| is lexicographically larger than string yββ=ββy1y2...y|y|, if either |x|ββ>ββ|y| and x1ββ=ββy1,ββx2ββ=ββy2,ββ...,ββx|y|ββ=ββy|y|, or exists such number r (rββ<ββ|x|,ββrββ<ββ|y|), that x1ββ=ββy1,ββx2ββ=ββy2,ββ...,ββxrββ=ββyr and xrββ+ββ1ββ>ββyrββ+ββ1. Characters are compared like their ASCII codes (or alphabetic order).Help Rick get the girl (or whatever gender Unity has).InputThe first line of input contain two integers n and q (2ββ€βnββ€β20000, 1ββ€βqββ€β20000) β number of vertices in tree and number of queries respectively.The next nβ-β1 lines contain the edges. Each line contains two integers v and u (endpoints of the edge) followed by an English lowercase letter c (1ββ€βv,βuββ€βn,βvββ βu).The next q line contain the queries. Each line contains two integers x and y (1ββ€βx,βyββ€βn,βxββ βy).OutputPrint the answer for each query in one line.ExamplesInput4 34 1 t3 2 p1 2 s3 21 32 1Output011Input8 44 6 p3 7 o7 8 p4 5 d1 3 o4 3 p3 2 e8 63 78 14 3Output6131NoteHere's the tree of first sample testcase: Here's the tree of second sample testcase: In this test: str(8,β1) = poo str(8,β2) = poe str(8,β3) = po str(8,β4) = pop str(8,β5) = popd str(8,β6) = popp str(8,β7) = p So, for the first query, and for the third query is the answer. | Input4 34 1 t3 2 p1 2 s3 21 32 1 | Output011 | 7 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'hashing', 'strings', 'trees', '*3400'] |
C. Till I Collapsetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRick and Morty want to find MR. PBH and they can't do it alone. So they need of Mr. Meeseeks. They Have generated n Mr. Meeseeks, standing in a line numbered from 1 to n. Each of them has his own color. i-th Mr. Meeseeks' color is ai. Rick and Morty are gathering their army and they want to divide Mr. Meeseeks into some squads. They don't want their squads to be too colorful, so each squad should have Mr. Meeseeks of at most k different colors. Also each squad should be a continuous subarray of Mr. Meeseeks in the line. Meaning that for each 1ββ€βiββ€βeββ€βjββ€βn, if Mr. Meeseeks number i and Mr. Meeseeks number j are in the same squad then Mr. Meeseeks number e should be in that same squad. Also, each squad needs its own presidio, and building a presidio needs money, so they want the total number of squads to be minimized.Rick and Morty haven't finalized the exact value of k, so in order to choose it, for each k between 1 and n (inclusive) need to know the minimum number of presidios needed.InputThe first line of input contains a single integer n (1ββ€βnββ€β105) β number of Mr. Meeseeks.The second line contains n integers a1,βa2,β...,βan separated by spaces (1ββ€βaiββ€βn) β colors of Mr. Meeseeks in order they standing in a line.OutputIn the first and only line of input print n integers separated by spaces. i-th integer should be the minimum number of presidios needed if the value of k is i.ExamplesInput51 3 4 3 3Output4 2 1 1 1 Input81 5 7 8 1 7 6 1Output8 4 3 2 1 1 1 1 NoteFor the first sample testcase, some optimal ways of dividing army into squads for each k are: [1],β[3],β[4],β[3,β3] [1],β[3,β4,β3,β3] [1,β3,β4,β3,β3] [1,β3,β4,β3,β3] [1,β3,β4,β3,β3] For the second testcase, some optimal ways of dividing army into squads for each k are: [1],β[5],β[7],β[8],β[1],β[7],β[6],β[1] [1,β5],β[7,β8],β[1,β7],β[6,β1] [1,β5,β7],β[8],β[1,β7,β6,β1] [1,β5,β7,β8],β[1,β7,β6,β1] [1,β5,β7,β8,β1,β7,β6,β1] [1,β5,β7,β8,β1,β7,β6,β1] [1,β5,β7,β8,β1,β7,β6,β1] [1,β5,β7,β8,β1,β7,β6,β1] | Input51 3 4 3 3 | Output4 2 1 1 1 | 2 seconds | 256 megabytes | ['data structures', 'divide and conquer', '*2400'] |
B. Legacytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRick and his co-workers have made a new radioactive formula and a lot of bad guys are after them. So Rick wants to give his legacy to Morty before bad guys catch them. There are n planets in their universe numbered from 1 to n. Rick is in planet number s (the earth) and he doesn't know where Morty is. As we all know, Rick owns a portal gun. With this gun he can open one-way portal from a planet he is in to any other planet (including that planet). But there are limits on this gun because he's still using its free trial. By default he can not open any portal by this gun. There are q plans in the website that sells these guns. Every time you purchase a plan you can only use it once but you can purchase it again if you want to use it more.Plans on the website have three types: With a plan of this type you can open a portal from planet v to planet u. With a plan of this type you can open a portal from planet v to any planet with index in range [l,βr]. With a plan of this type you can open a portal from any planet with index in range [l,βr] to planet v. Rick doesn't known where Morty is, but Unity is going to inform him and he wants to be prepared for when he finds and start his journey immediately. So for each planet (including earth itself) he wants to know the minimum amount of money he needs to get from earth to that planet.InputThe first line of input contains three integers n, q and s (1ββ€βn,βqββ€β105, 1ββ€βsββ€βn) β number of planets, number of plans and index of earth respectively.The next q lines contain the plans. Each line starts with a number t, type of that plan (1ββ€βtββ€β3). If tβ=β1 then it is followed by three integers v, u and w where w is the cost of that plan (1ββ€βv,βuββ€βn, 1ββ€βwββ€β109). Otherwise it is followed by four integers v, l, r and w where w is the cost of that plan (1ββ€βvββ€βn, 1ββ€βlββ€βrββ€βn, 1ββ€βwββ€β109).OutputIn the first and only line of output print n integers separated by spaces. i-th of them should be minimum money to get from earth to i-th planet, or β-β1 if it's impossible to get to that planet.ExamplesInput3 5 12 3 2 3 172 3 2 2 162 2 2 3 33 3 1 1 121 3 3 17Output0 28 12 Input4 3 13 4 1 3 122 2 3 4 101 2 4 16Output0 -1 -1 12 NoteIn the first sample testcase, Rick can purchase 4th plan once and then 2nd plan in order to get to get to planet number 2. | Input3 5 12 3 2 3 172 3 2 2 162 2 2 3 33 3 1 1 121 3 3 17 | Output0 28 12 | 2 seconds | 256 megabytes | ['data structures', 'graphs', 'shortest paths', '*2300'] |
A. Berzerktime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer.In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the others are planets. There's a monster in one of the planet. Rick and Morty don't know on which one yet, only that he's not initially in the black hole, but Unity will inform them before the game starts. But for now, they want to be prepared for every possible scenario. Each one of them has a set of numbers between 1 and nβ-β1 (inclusive). Rick's set is s1 with k1 elements and Morty's is s2 with k2 elements. One of them goes first and the player changes alternatively. In each player's turn, he should choose an arbitrary number like x from his set and the monster will move to his x-th next object from its current position (clockwise). If after his move the monster gets to the black hole he wins.Your task is that for each of monster's initial positions and who plays first determine if the starter wins, loses, or the game will stuck in an infinite loop. In case when player can lose or make game infinity, it more profitable to choose infinity game.InputThe first line of input contains a single integer n (2ββ€βnββ€β7000) β number of objects in game.The second line contains integer k1 followed by k1 distinct integers s1,β1,βs1,β2,β...,βs1,βk1 β Rick's set.The third line contains integer k2 followed by k2 distinct integers s2,β1,βs2,β2,β...,βs2,βk2 β Morty's set1ββ€βkiββ€βnβ-β1 and 1ββ€βsi,β1,βsi,β2,β...,βsi,βkiββ€βnβ-β1 for 1ββ€βiββ€β2.OutputIn the first line print nβ-β1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Rick plays first and monster is initially in object number iβ+β1 he wins, "Lose" if he loses and "Loop" if the game will never end.Similarly, in the second line print nβ-β1 words separated by spaces where i-th word is "Win" (without quotations) if in the scenario that Morty plays first and monster is initially in object number iβ+β1 he wins, "Lose" if he loses and "Loop" if the game will never end.ExamplesInput52 3 23 1 2 3OutputLose Win Win LoopLoop Win Win WinInput84 6 2 3 42 3 6OutputWin Win Win Win Win Win WinLose Win Lose Lose Win Lose Lose | Input52 3 23 1 2 3 | OutputLose Win Win LoopLoop Win Win Win | 4 seconds | 256 megabytes | ['dfs and similar', 'dp', 'games', '*2000'] |
E. Anton and Permutationtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAnton likes permutations, especially he likes to permute their elements. Note that a permutation of n elements is a sequence of numbers {a1,βa2,β...,βan}, in which every number from 1 to n appears exactly once.One day Anton got a new permutation and started to play with it. He does the following operation q times: he takes two elements of the permutation and swaps these elements. After each operation he asks his friend Vanya, how many inversions there are in the new permutation. The number of inversions in a permutation is the number of distinct pairs (i,βj) such that 1ββ€βiβ<βjββ€βn and aiβ>βaj.Vanya is tired of answering Anton's silly questions. So he asked you to write a program that would answer these questions instead of him.Initially Anton's permutation was {1,β2,β...,βn}, that is aiβ=βi for all i such that 1ββ€βiββ€βn.InputThe first line of the input contains two integers n and q (1ββ€βnββ€β200β000,β1ββ€βqββ€β50β000)Β β the length of the permutation and the number of operations that Anton does.Each of the following q lines of the input contains two integers li and ri (1ββ€βli,βriββ€βn)Β β the indices of elements that Anton swaps during the i-th operation. Note that indices of elements that Anton swaps during the i-th operation can coincide. Elements in the permutation are numbered starting with one.OutputOutput q lines. The i-th line of the output is the number of inversions in the Anton's permutation after the i-th operation.ExamplesInput5 44 52 42 52 2Output1433Input2 12 1Output1Input6 71 43 52 33 33 62 15 1Output567710118NoteConsider the first sample.After the first Anton's operation the permutation will be {1,β2,β3,β5,β4}. There is only one inversion in it: (4,β5).After the second Anton's operation the permutation will be {1,β5,β3,β2,β4}. There are four inversions: (2,β3), (2,β4), (2,β5) and (3,β4).After the third Anton's operation the permutation will be {1,β4,β3,β2,β5}. There are three inversions: (2,β3), (2,β4) and (3,β4).After the fourth Anton's operation the permutation doesn't change, so there are still three inversions. | Input5 44 52 42 52 2 | Output1433 | 4 seconds | 512 megabytes | ['brute force', 'data structures', '*2200'] |
D. Anton and School - 2time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met: It is not empty (that is nββ β0). The length of the sequence is even. First charactes of the sequence are equal to "(". Last charactes of the sequence are equal to ")". For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109β+β7.Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!InputThe only line of the input contains a string sΒ β the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200β000.OutputOutput one numberΒ β the answer for the task modulo 109β+β7.ExamplesInput)(()()Output6Input()()()Output7Input)))Output0NoteIn the first sample the following subsequences are possible: If we delete characters at the positions 1 and 5 (numbering starts with one), we will get the subsequence "(())". If we delete characters at the positions 1, 2, 3 and 4, we will get the subsequence "()". If we delete characters at the positions 1, 2, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 2, 5 and 6, we will get the subsequence "()". If we delete characters at the positions 1, 3, 4 and 5, we will get the subsequence "()". If we delete characters at the positions 1, 3, 5 and 6, we will get the subsequence "()". The rest of the subsequnces are not RSBS. So we got 6 distinct subsequences that are RSBS, so the answer is 6. | Input)(()() | Output6 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', 'number theory', '*2300'] |
C. Anton and Fairy Taletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale:"Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that barn for three days and three nights. But they overlooked and there remained a little hole in the barn, from which every day sparrows came through. Here flew a sparrow, took a grain and flew away..."More formally, the following takes place in the fairy tale. At the beginning of the first day the barn with the capacity of n grains was full. Then, every day (starting with the first day) the following happens: m grains are brought to the barn. If m grains doesn't fit to the barn, the barn becomes full and the grains that doesn't fit are brought back (in this problem we can assume that the grains that doesn't fit to the barn are not taken into account). Sparrows come and eat grain. In the i-th day i sparrows come, that is on the first day one sparrow come, on the second day two sparrows come and so on. Every sparrow eats one grain. If the barn is empty, a sparrow eats nothing. Anton is tired of listening how Danik describes every sparrow that eats grain from the barn. Anton doesn't know when the fairy tale ends, so he asked you to determine, by the end of which day the barn will become empty for the first time. Help Anton and write a program that will determine the number of that day!InputThe only line of the input contains two integers n and m (1ββ€βn,βmββ€β1018)Β β the capacity of the barn and the number of grains that are brought every day.OutputOutput one integerΒ β the number of the day when the barn will become empty for the first time. Days are numbered starting with one.ExamplesInput5 2Output4Input8 1Output5NoteIn the first sample the capacity of the barn is five grains and two grains are brought every day. The following happens: At the beginning of the first day grain is brought to the barn. It's full, so nothing happens. At the end of the first day one sparrow comes and eats one grain, so 5β-β1β=β4 grains remain. At the beginning of the second day two grains are brought. The barn becomes full and one grain doesn't fit to it. At the end of the second day two sparrows come. 5β-β2β=β3 grains remain. At the beginning of the third day two grains are brought. The barn becomes full again. At the end of the third day three sparrows come and eat grain. 5β-β3β=β2 grains remain. At the beginning of the fourth day grain is brought again. 2β+β2β=β4 grains remain. At the end of the fourth day four sparrows come and eat grain. 4β-β4β=β0 grains remain. The barn is empty. So the answer is 4, because by the end of the fourth day the barn becomes empty. | Input5 2 | Output4 | 1 second | 256 megabytes | ['binary search', 'math', '*1600'] |
B. Anton and Classestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1,βi,βr1,βi). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2,βi,βr2,βi).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1,βr1) and (l2,βr2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |iβ-βj|, where l1ββ€βiββ€βr1 and l2ββ€βjββ€βr2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!InputThe first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of time periods when Anton can attend chess classes.Each of the following n lines of the input contains two integers l1,βi and r1,βi (1ββ€βl1,βiββ€βr1,βiββ€β109)Β β the i-th variant of a period of time when Anton can attend chess classes.The following line of the input contains a single integer m (1ββ€βmββ€β200β000)Β β the number of time periods when Anton can attend programming classes.Each of the following m lines of the input contains two integers l2,βi and r2,βi (1ββ€βl2,βiββ€βr2,βiββ€β109)Β β the i-th variant of a period of time when Anton can attend programming classes.OutputOutput one integerΒ β the maximal possible distance between time periods.ExamplesInput31 52 62 322 46 8Output3Input31 52 63 722 41 4Output0NoteIn the first sample Anton can attend chess classes in the period (2,β3) and attend programming classes in the period (6,β8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0. | Input31 52 62 322 46 8 | Output3 | 4 seconds | 256 megabytes | ['greedy', 'sortings', '*1100'] |
A. Anton and Polyhedronstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!InputThe first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the number of polyhedrons in Anton's collection.Each of the following n lines of the input contains a string siΒ β the name of the i-th polyhedron in Anton's collection. The string can look like this: "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron. "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube. "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron. "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron. "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron. OutputOutput one numberΒ β the total number of faces in all the polyhedrons in Anton's collection.ExamplesInput4IcosahedronCubeTetrahedronDodecahedronOutput42Input3DodecahedronOctahedronOctahedronOutput28NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20β+β6β+β4β+β12β=β42 faces. | Input4IcosahedronCubeTetrahedronDodecahedron | Output42 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*800'] |
G. BF Calculatortime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputIn this problem you will write a simple generator of Brainfuck (https://en.wikipedia.org/wiki/Brainfuck) calculators.You are given an arithmetic expression consisting of integers from 0 to 255 and addition/subtraction signs between them. Output a Brainfuck program which, when executed, will print the result of evaluating this expression.We use a fairly standard Brainfuck interpreter for checking the programs: 30000 memory cells. memory cells store integers from 0 to 255 with unsigned 8-bit wraparound. console input (, command) is not supported, but it's not needed for this problem.InputThe only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive. The calculations result is guaranteed to be an integer between 0 and 255, inclusive (results of intermediary calculations might be outside of these boundaries).OutputOutput a Brainfuck program which, when executed, will print the result of evaluating this expression. The program must be at most 5000000 characters long (including the non-command characters), and its execution must be complete in at most 50000000 steps.ExamplesInput2+3Output++>+++><[<+>-]<++++++++++++++++++++++++++++++++++++++++++++++++.Input9-7Output+++++++++>+++++++><[<->-]<++++++++++++++++++++++++++++++++++++++++++++++++.NoteYou can download the source code of the Brainfuck interpreter by the link http://assets.codeforces.com/rounds/784/bf.cpp. We use this code to interpret outputs. | Input2+3 | Output++>+++><[<+>-]<++++++++++++++++++++++++++++++++++++++++++++++++. | 2 seconds | 64 megabytes | ['*special problem', '*2000'] |
F. Crunching Numbers Just for Youtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputYou are developing a new feature for the website which sells airline tickets: being able to sort tickets by price! You have already extracted the tickets' prices, so there's just the last step to be done...You are given an array of integers. Sort it in non-descending order.InputThe input consists of a single line of space-separated integers. The first number is n (1ββ€βnββ€β10) β the size of the array. The following n numbers are the elements of the array (1ββ€βaiββ€β100).OutputOutput space-separated elements of the sorted array.ExampleInput3 3 1 2Output1 2 3 NoteRemember, this is a very important feature, and you have to make sure the customers appreciate it! | Input3 3 1 2 | Output1 2 3 | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1900'] |
E. Twisted Circuittime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard output InputThe input consists of four lines, each line containing a single digit 0 or 1.OutputOutput a single digit, 0 or 1.ExampleInput0110Output0 | Input0110 | Output0 | 2 seconds | 64 megabytes | ['*special problem', 'brute force', 'implementation', '*2000'] |
D. Touchy-Feely Palindromestime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputInputThe only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.OutputOutput "Yes" or "No".ExamplesInput373OutputYesInput121OutputNoInput436OutputYes | Input373 | OutputYes | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1900'] |
C. INTERCALCtime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputDO YOU EXPECT ME TO FIND THIS OUT?WHAT BASE AND/XOR LANGUAGE INCLUDES string?DON'T BYTE OF MORE THAN YOU CAN CHEWYOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FARSAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOODTHE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT!I HAVE NO ARRAY AND I MUST SCREAMELEMENTS MAY NOT BE STORED IN WEST HYPERSPACEInputThe first line of input data contains a single integer n (1ββ€βnββ€β10).The second line of input data contains n space-separated integers ai (1ββ€βaiββ€β11).OutputOutput a single integer.ExampleInput42 5 3 1Output4 | Input42 5 3 1 | Output4 | 2 seconds | 64 megabytes | ['*special problem', 'implementation', '*1800'] |
B. Kids' Riddletime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputProgrammers' kids solve this riddle in 5-10 minutes. How fast can you do it?InputThe input contains a single integer n (0ββ€βnββ€β2000000000).OutputOutput a single integer.ExamplesInput11Output2Input14Output0Input61441Output2Input571576Output10Input2128506Output3 | Input11 | Output2 | 2 seconds | 64 megabytes | ['*special problem', '*2000'] |
A. Numbers Joketime limit per test2 secondsmemory limit per test64 megabytesinputstandard inputoutputstandard outputInputThe input contains a single integer a (1ββ€βaββ€β30).OutputOutput a single integer.ExampleInput3Output27 | Input3 | Output27 | 2 seconds | 64 megabytes | ['*special problem', '*1700'] |
H. Intranet of Busestime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new bus route is opened in the city . The route is a closed polygon line in the place, with all segments parallel to one of the axes. m buses will operate on the route. All buses move in a loop along the route in the same direction with equal constant velocities (stopping times are negligible in this problem).Buses start their movement in the first vertex of the route with equal interval. Suppose that T is the total time for a single bus to travel the whole loop of the route. Then, the bus 1 starts moving at time 0, the bus 2 starts at time Tβ/βm, the bus 3 starts at time 2Tβ/βm, and so on; finally, the bus m starts moving at time (mβ-β1)Tβ/βm. Thus, all intervals between pairs of consecutive buses (including the interval between the last and the first bus) are equal.Buses can communicate with each other via wireless transmitters of equal power. If the transmitters have power D, then only buses within distance D of each other can communicate.The buses are also equipped with a distributed system of schedule tracking. For all buses to stick to the schedule, the system has to synchronize the necessary data between all buses from time to time. At the moment of synchronization, the bus 1 communicates with the bus 2, the bus 2Β β with bus 3, and so on; also, the bus m communicates with the bus 1.As a research employee, you are tasked with finding the smallest value of D such that it is possible to find a time moment to perform synchronization once all buses have started moving. InputThe first line contains two integers n and m (2ββ€βn,βmββ€β105)Β β the number of vertices of the polygonal line, and the number of buses respectively.Next n lines describe the vertices of the route in the traversing order. Each of these lines contains two integers xi, yi (β-β1000ββ€βxi,βyiββ€β1000)Β β coordinates of respective vertex.It is guaranteed that each leg of the route (including the leg between the last and the first vertex) is paralles to one of the coordinate axes. Moreover, no two subsequent vertices of the route coincide. The route is allowed to have self-intersections, and travel along the same segment multiple times.OutputPrint one real numberΒ β the answer to the problem. Your answer will be accepted if the relative or the absolute error doesn't exceed 10β-β6.ExamplesInput4 20 00 11 11 0Output1.000000000Input2 20 01 0Output0.000000000NoteSuppose that each bus travel 1 distance unit per second.In the first sample case, in 0.5 seconds buses will be at distance 1, hence we can choose Dβ=β1.In the second sample case, in 0.5 seconds both buses will be at (0.5,β0), hence we can choose Dβ=β0. | Input4 20 00 11 11 0 | Output1.000000000 | 10 seconds | 256 megabytes | ['binary search', 'geometry', 'implementation', 'two pointers', '*3100'] |
G. Andryusha and Nervous Barrierstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndryusha has found a perplexing arcade machine. The machine is a vertically adjusted board divided into square cells. The board has w columns numbered from 1 to w from left to right, and h rows numbered from 1 to h from the bottom to the top.Further, there are barriers in some of board rows. There are n barriers in total, and i-th of them occupied the cells li through ri of the row ui. Andryusha recollects well that no two barriers share the same row. Furthermore, no row is completely occupied with a barrier, that is, at least one cell in each row is free.The player can throw a marble to any column of the machine from above. A marble falls downwards until it encounters a barrier, or falls through the bottom of the board. A marble disappears once it encounters a barrier but is replaced by two more marbles immediately to the left and to the right of the same barrier. In a situation when the barrier is at an edge of the board, both marbles appear next to the barrier at the side opposite to the edge. More than one marble can occupy the same place of the board, without obstructing each other's movement. Ultimately, all marbles are bound to fall from the bottom of the machine. Examples of marble-barrier interaction. Peculiarly, sometimes marbles can go through barriers as if they were free cells. That is so because the barriers are in fact alive, and frightened when a marble was coming at them from a very high altitude. More specifically, if a marble falls towards the barrier i from relative height more than si (that is, it started its fall strictly higher than uiβ+βsi), then the barrier evades the marble. If a marble is thrown from the top of the board, it is considered to appear at height (hβ+β1).Andryusha remembers to have thrown a marble once in each of the columns. Help him find the total number of marbles that came down at the bottom of the machine. Since the answer may be large, print it modulo 109β+β7.InputThe first line contains three integers h, w, and n (1ββ€βhββ€β109, 2ββ€βwββ€β105, 0ββ€βnββ€β105)Β β the number of rows, columns, and barriers in the machine respectively.Next n lines describe barriers. i-th of these lines containts four integers ui, li, ri, and si (1ββ€βuiββ€βh, 1ββ€βliββ€βriββ€βw, 1ββ€βsiββ€β109)Β β row index, leftmost and rightmost column index of i-th barrier, and largest relative fall height such that the barrier does not evade a falling marble. It is guaranteed that each row has at least one free cell, and that all ui are distinct.OutputPrint one integerΒ β the answer to the problem modulo 109β+β7.ExamplesInput10 5 13 2 3 10Output7Input10 5 23 1 3 105 3 5 10Output16Input10 5 23 1 3 75 3 5 10Output14Input10 15 47 3 9 56 4 10 11 1 4 104 11 11 20Output53NoteIn the first sample case, there is a single barrier: if one throws a marble in the second or the third column, two marbles come out, otherwise there is only one. The total answer is 7.In the second sample case, the numbers of resulting marbles are 2, 2, 4, 4, 4 in order of indexing columns with the initial marble.In the third sample case, the numbers of resulting marbles are 1, 1, 4, 4, 4. Note that the first barrier evades the marbles falling from the top of the board, but does not evade the marbles falling from the second barrier.In the fourth sample case, the numbers of resulting marbles are 2, 2, 6, 6, 6, 6, 6, 6, 6, 1, 2, 1, 1, 1, 1. The picture below shows the case when a marble is thrown into the seventh column. The result of throwing a marble into the seventh column. | Input10 5 13 2 3 10 | Output7 | 4 seconds | 256 megabytes | ['data structures', 'dp', '*2700'] |
F. Axel and Marston in Bitlandtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA couple of friends, Axel and Marston are travelling across the country of Bitland. There are n towns in Bitland, with some pairs of towns connected by one-directional roads. Each road in Bitland is either a pedestrian road or a bike road. There can be multiple roads between any pair of towns, and may even be a road from a town to itself. However, no pair of roads shares the starting and the destination towns along with their types simultaneously.The friends are now located in the town 1 and are planning the travel route. Axel enjoys walking, while Marston prefers biking. In order to choose a route diverse and equally interesting for both friends, they have agreed upon the following procedure for choosing the road types during the travel: The route starts with a pedestrian route. Suppose that a beginning of the route is written in a string s of letters P (pedestrain road) and B (biking road). Then, the string is appended to s, where stands for the string s with each character changed to opposite (that is, all pedestrian roads changed to bike roads, and vice versa).In the first few steps the route will look as follows: P, PB, PBBP, PBBPBPPB, PBBPBPPBBPPBPBBP, and so on.After that the friends start travelling from the town 1 via Bitlandian roads, choosing the next road according to the next character of their route type each time. If it is impossible to choose the next road, the friends terminate their travel and fly home instead.Help the friends to find the longest possible route that can be travelled along roads of Bitland according to the road types choosing procedure described above. If there is such a route with more than 1018 roads in it, print -1 instead.InputThe first line contains two integers n and m (1ββ€βnββ€β500, 0ββ€βmββ€β2n2)Β β the number of towns and roads in Bitland respectively.Next m lines describe the roads. i-th of these lines contains three integers vi, ui and ti (1ββ€βvi,βuiββ€βn, 0ββ€βtiββ€β1), where vi and ui denote start and destination towns indices of the i-th road, and ti decribes the type of i-th road (0 for a pedestrian road, 1 for a bike road). It is guaranteed that for each pair of distinct indices i, j such that 1ββ€βi,βjββ€βm, either viββ βvj, or uiββ βuj, or tiββ βtj holds.OutputIf it is possible to find a route with length strictly greater than 1018, print -1. Otherwise, print the maximum length of a suitable path.ExamplesInput2 21 2 02 2 1Output3Input2 31 2 02 2 12 2 0Output-1NoteIn the first sample we can obtain a route of length 3 by travelling along the road 1 from town 1 to town 2, and then following the road 2 twice from town 2 to itself.In the second sample we can obtain an arbitrarily long route by travelling the road 1 first, and then choosing road 2 or 3 depending on the necessary type. | Input2 21 2 02 2 1 | Output3 | 5 seconds | 256 megabytes | ['bitmasks', 'dp', 'graphs', 'matrices', '*2400'] |
E. Underground Labtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most vertices.InputThe first line contains three integers n, m, and k (1ββ€βnββ€β2Β·105, nβ-β1ββ€βmββ€β2Β·105, 1ββ€βkββ€βn)Β β the number of vertices and edges in the lab, and the number of clones.Each of the next m lines contains two integers xi and yi (1ββ€βxi,βyiββ€βn)Β β indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges.The graph is guaranteed to be connected.OutputYou should print k lines. i-th of these lines must start with an integer ci ()Β β the number of vertices visited by i-th clone, followed by ci integersΒ β indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not.It is guaranteed that a valid answer exists.ExamplesInput3 2 12 13 1Output3 2 1 3Input5 4 21 21 31 41 5Output3 2 1 33 4 1 5NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone. | Input3 2 12 13 1 | Output3 2 1 3 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', '*2100'] |
D. Innokenty and a Football Leaguetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInnokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. InputThe first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league.Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.OutputIt it is not possible to choose short names and satisfy all constraints, print a single line "NO".Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input.If there are multiple answers, print any of them.ExamplesInput2DINAMO BYTECITYFOOTBALL MOSCOWOutputYESDINFOOInput2DINAMO BYTECITYDINAMO BITECITYOutputNOInput3PLAYFOOTBALL MOSCOWPLAYVOLLEYBALL SPBGOGO TECHNOCUPOutputYESPLMPLSGOGInput3ABC DEFABC EFGABD OOOOutputYESABDABEABONoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Input2DINAMO BYTECITYFOOTBALL MOSCOW | OutputYESDINFOO | 2 seconds | 256 megabytes | ['2-sat', 'graphs', 'greedy', 'implementation', 'shortest paths', 'strings', '*1900'] |
C. Andryusha and Colored Balloonstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.The park consists of n squares connected with (nβ-β1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.Andryusha wants to use as little different colors as possible. Help him to choose the colors!InputThe first line contains single integer n (3ββ€βnββ€β2Β·105)Β β the number of squares in the park.Each of the next (nβ-β1) lines contains two integers x and y (1ββ€βx,βyββ€βn)Β β the indices of two squares directly connected by a path.It is guaranteed that any square is reachable from any other using the paths.OutputIn the first line print single integer kΒ β the minimum number of colors Andryusha has to use.In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.ExamplesInput32 31 3Output31 3 2 Input52 35 34 31 3Output51 3 2 5 4 Input52 13 24 35 4Output31 2 3 1 2 NoteIn the first sample the park consists of three squares: 1βββ3βββ2. Thus, the balloon colors have to be distinct. Illustration for the first sample. In the second example there are following triples of consequently connected squares: 1βββ3βββ2 1βββ3βββ4 1βββ3βββ5 2βββ3βββ4 2βββ3βββ5 4βββ3βββ5 We can see that each pair of squares is encountered in some triple, so all colors have to be distinct. Illustration for the second sample. In the third example there are following triples: 1βββ2βββ3 2βββ3βββ4 3βββ4βββ5 We can see that one or two colors is not enough, but there is an answer that uses three colors only. Illustration for the third sample. | Input32 31 3 | Output31 3 2 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'greedy', 'trees', '*1600'] |
B. The Meeting Place Cannot Be Changedtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate. InputThe first line contains single integer n (2ββ€βnββ€β60β000)Β β the number of friends.The second line contains n integers x1,βx2,β...,βxn (1ββ€βxiββ€β109)Β β the current coordinates of the friends, in meters.The third line contains n integers v1,βv2,β...,βvn (1ββ€βviββ€β109)Β β the maximum speeds of the friends, in meters per second.OutputPrint the minimum time (in seconds) needed for all the n friends to meet at some point on the road. Your answer will be considered correct, if its absolute or relative error isn't greater than 10β-β6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if holds.ExamplesInput37 1 31 2 1Output2.000000000000Input45 10 3 22 3 2 4Output1.400000000000NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds. | Input37 1 31 2 1 | Output2.000000000000 | 5 seconds | 256 megabytes | ['binary search', '*1600'] |
A. Andryusha and Sockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time? InputThe first line contains the single integer n (1ββ€βnββ€β105)Β β the number of sock pairs.The second line contains 2n integers x1,βx2,β...,βx2n (1ββ€βxiββ€βn), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi.It is guaranteed that Andryusha took exactly two socks of each pair.OutputPrint single integerΒ β the maximum number of socks that were on the table at the same time.ExamplesInput11 1Output1Input32 1 1 3 2 3Output2NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows: Initially the table was empty, he took out a sock from pair 2 and put it on the table. Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table. Socks (1,β2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe. Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table. Socks (2,β3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe. Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe. Thus, at most two socks were on the table at the same time. | Input11 1 | Output1 | 2 seconds | 256 megabytes | ['implementation', '*800'] |
C. Dishonest Sellerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.InputIn the first line there are two positive integer numbers n and k (1ββ€βnββ€β2Β·105, 0ββ€βkββ€βn) β total number of items to buy and minimal number of items Igor wants to by right now.The second line contains sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β104) β prices of items during discounts (i.e. right now).The third line contains sequence of integers b1,βb2,β...,βbn (1ββ€βbiββ€β104) β prices of items after discounts (i.e. after a week).OutputPrint the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.ExamplesInput3 15 4 63 1 5Output10Input5 33 4 7 10 34 5 5 12 5Output25NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6β+β3β+β1β=β10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3β+β4β+β10β+β3β+β5β=β25. | Input3 15 4 63 1 5 | Output10 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'sortings', '*1200'] |
B. Weird Roundingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is crazy about round numbers. He especially likes the numbers divisible by 10k.In the given number of n Polycarp wants to remove the least number of digits to get a number that is divisible by 10k. For example, if kβ=β3, in the number 30020 it is enough to delete a single digit (2). In this case, the result is 3000 that is divisible by 103β=β1000.Write a program that prints the minimum number of digits to be deleted from the given integer number n, so that the result is divisible by 10k. The result should not start with the unnecessary leading zero (i.e., zero can start only the number 0, which is required to be written as exactly one digit).It is guaranteed that the answer exists.InputThe only line of the input contains two integer numbers n and k (0ββ€βnββ€β2β000β000β000, 1ββ€βkββ€β9).It is guaranteed that the answer exists. All numbers in the input are written in traditional notation of integers, that is, without any extra leading zeros.OutputPrint w β the required minimal number of digits to erase. After removing the appropriate w digits from the number n, the result should have a value that is divisible by 10k. The result can start with digit 0 in the single case (the result is zero and written by exactly the only digit 0).ExamplesInput30020 3Output1Input100 9Output2Input10203049 2Output3NoteIn the example 2 you can remove two digits: 1 and any 0. The result is number 0 which is divisible by any number. | Input30020 3 | Output1 | 1 second | 256 megabytes | ['brute force', 'greedy', '*1100'] |
A. Pupils Redistributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Berland each high school student is characterized by academic performance β integer value between 1 and 5.In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known β integer value between 1 and 5.The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups.Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.InputThe first line of the input contains integer number n (1ββ€βnββ€β100) β number of students in both groups.The second line contains sequence of integer numbers a1,βa2,β...,βan (1ββ€βaiββ€β5), where ai is academic performance of the i-th student of the group A.The third line contains sequence of integer numbers b1,βb2,β...,βbn (1ββ€βbiββ€β5), where bi is academic performance of the i-th student of the group B.OutputPrint the required minimum number of exchanges or -1, if the desired distribution of students can not be obtained.ExamplesInput45 4 4 45 5 4 5Output1Input61 1 1 1 1 15 5 5 5 5 5Output3Input153Output-1Input93 2 5 5 2 3 3 3 24 1 4 1 1 2 4 4 1Output4 | Input45 4 4 45 5 4 5 | Output1 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*1000'] |
E. Selling Numberstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBoris really likes numbers and even owns a small shop selling interesting numbers. He has n decimal numbers Bi. Cost of the number in his shop is equal to the sum of costs of its digits. You are given the values cd, where cd is the cost of the digit d. Of course, Boris is interested in that numbers he owns have the maximum cost possible.Recently Boris got hold of the magical artifact A, which can allow him to increase the cost of his collection. Artifact is a string, consisting of digits and '?' symbols. To use the artifact, Boris must replace all '?' with digits to get a decimal number without leading zeros (it is also not allowed to get number 0). After that, the resulting number is added to all numbers Bi in Boris' collection. He uses the artifact exactly once.What is the maximum cost of the collection Boris can achieve after using the artifact?InputFirst line contains artifact A, consisting of digits '0'β'9' and '?' symbols (1ββ€β|A|ββ€β1000). Next line contains nΒ β the amount of numbers in Boris' collection (1ββ€βnββ€β1000). Next n lines contain integers Bi (1ββ€βBiβ<β101000). A doesn't start with '0'.Last line contains ten integersΒ β costs of digits c0,βc1,β...,βc9 (0ββ€βciββ€β1000).OutputOutput one integerΒ β the maximum possible cost of the collection after using the artifact.ExamplesInput4238919580 0 1 1 2 2 3 3 4 4Output4Input?5?42203522927662432 1 6 1 1 2 5 2 2 3Output62NoteIn the second sample input, the optimal way is to compose the number 453. After adding this number, Boris will have numbers 2656, 5682, 729 and 6696. The total cost of all digits in them is equal to 18β+β15β+β11β+β18β=β62. | Input4238919580 0 1 1 2 2 3 3 4 4 | Output4 | 2 seconds | 512 megabytes | ['dp', 'sortings', '*3000'] |
D. Parquet Re-layingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPeter decided to lay a parquet in the room of size nβΓβm, the parquet consists of tiles of size 1βΓβ2. When the workers laid the parquet, it became clear that the tiles pattern looks not like Peter likes, and workers will have to re-lay it.The workers decided that removing entire parquet and then laying it again is very difficult task, so they decided to make such an operation every hour: remove two tiles, which form a 2βΓβ2 square, rotate them 90 degrees and put them back on the same place. They have no idea how to obtain the desired configuration using these operations, and whether it is possible at all.Help Peter to make a plan for the workers or tell that it is impossible. The plan should contain at most 100β000 commands.InputThe first line contains integer n and m, size of the room (1ββ€βn,βmββ€β50). At least one of them is even number.The following n lines contain m characters each, the description of the current configuration of the parquet tiles. Each character represents the position of the half-tile. Characters 'L', 'R', 'U' and 'D' correspond to the left, right, upper and lower halves, respectively.The following n lines contain m characters each, describing the desired configuration in the same format.OutputIn the first line output integer k, the number of operations. In the next k lines output description of operations. The operation is specified by coordinates (row and column) of the left upper half-tile on which the operation is performed.If there is no solution, output -1 in the first line.ExamplesInput2 3ULRDLRLRULRDOutput21 21 1Input4 3ULRDLRLRULRDULRDUUUDDDLROutput33 13 22 2NoteIn the first sample test first operation is to rotate two rightmost tiles, after this all tiles lie vertically. Second operation is to rotate two leftmost tiles, after this we will get desired configuration. | Input2 3ULRDLRLRULRD | Output21 21 1 | 2 seconds | 512 megabytes | ['constructive algorithms', '*2700'] |
C. Peterson Polyglottime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPeterson loves to learn new languages, but his favorite hobby is making new ones. Language is a set of words, and word is a sequence of lowercase Latin letters.Peterson makes new language every morning. It is difficult task to store the whole language, so Peterson have invented new data structure for storing his languages which is called broom. Broom is rooted tree with edges marked with letters. Initially broom is represented by the only vertexΒ β the root of the broom. When Peterson wants to add new word to the language he stands at the root and processes the letters of new word one by one. Consider that Peterson stands at the vertex u. If there is an edge from u marked with current letter, Peterson goes through this edge. Otherwise Peterson adds new edge from u to the new vertex v, marks it with the current letter and goes through the new edge. Size of broom is the number of vertices in it.In the evening after working day Peterson can't understand the language he made this morning. It is too difficult for bored Peterson and he tries to make it simpler. Simplification of the language is the process of erasing some letters from some words of this language. Formally, Peterson takes some positive integer p and erases p-th letter from all the words of this language having length at least p. Letters in words are indexed starting by 1. Peterson considers that simplification should change at least one word, i.e. there has to be at least one word of length at least p. Peterson tries to make his language as simple as possible, so he wants to choose p such that the size of the broom for his simplified language is as small as possible.Peterson is pretty annoyed with this task so he asks you for help. Write a program to find the smallest possible size of the broom and integer p.InputThe first line of input contains integer n (2ββ€βnββ€β3Β·105)Β β the size of the broom.Next nβ-β1 lines describe the broom: i-th of them contains integers ui, vi and letter xiΒ β describing the edge from ui to vi marked with letter xi.Vertices are numbered from 1 to n. All xi are lowercase latin letters. Vertex 1 is the root of the broom.Edges describe correct broom which is made from Peterson's language.OutputThe first line of output should contain the minimum possible size of the broom after its simplification. The second line of output should contain integer p to choose. If there are several suitable p values, print the smallest one.ExamplesInput51 2 c2 3 a3 4 t2 5 tOutput32Input161 2 o2 3 f1 4 p4 5 i5 6 e6 7 c7 8 e4 9 r9 10 e10 11 t11 12 t12 13 y10 14 f14 15 i15 16 xOutput122NoteBroom from the second sample test can be built using language "piece", "of", "pie", "pretty", "prefix". Its simplification with pβ=β2 obtains the language of words "pece", "o", "pe", "petty", "pefix". This language gives us the broom with minimum possible size. | Input51 2 c2 3 a3 4 t2 5 t | Output32 | 4 seconds | 512 megabytes | ['brute force', 'dfs and similar', 'dsu', 'hashing', 'strings', 'trees', '*2500'] |
B. Bitwise Formulatime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, Bob computes the values of n variables. Each variable is assigned either a constant m-bit number or result of bitwise operation. Operands of the operation may be either variables defined before, or the number, chosen by Peter. After that, Peter's score equals to the sum of all variable values.Bob wants to know, what number Peter needs to choose to get the minimum possible score, and what number he needs to choose to get the maximum possible score. In both cases, if there are several ways to get the same score, find the minimum number, which he can choose.InputThe first line contains two integers n and m, the number of variables and bit depth, respectively (1ββ€βnββ€β5000; 1ββ€βmββ€β1000). The following n lines contain descriptions of the variables. Each line describes exactly one variable. Description has the following format: name of a new variable, space, sign ":=", space, followed by one of: Binary number of exactly m bits. The first operand, space, bitwise operation ("AND", "OR" or "XOR"), space, the second operand. Each operand is either the name of variable defined before or symbol '?', indicating the number chosen by Peter. Variable names are strings consisting of lowercase Latin letters with length at most 10. All variable names are different.OutputIn the first line output the minimum number that should be chosen by Peter, to make the sum of all variable values minimum possible, in the second line output the minimum number that should be chosen by Peter, to make the sum of all variable values maximum possible. Both numbers should be printed as m-bit binary numbers.ExamplesInput3 3a := 101b := 011c := ? XOR bOutput011100Input5 1a := 1bb := 0cx := ? OR ad := ? XOR ?e := d AND bbOutput00NoteIn the first sample if Peter chooses a number 0112, then aβ=β1012,βbβ=β0112,βcβ=β0002, the sum of their values is 8. If he chooses the number 1002, then aβ=β1012,βbβ=β0112,βcβ=β1112, the sum of their values is 15.For the second test, the minimum and maximum sum of variables a, bb, cx, d and e is 2, and this sum doesn't depend on the number chosen by Peter, so the minimum Peter can choose is 0. | Input3 3a := 101b := 011c := ? XOR b | Output011100 | 3 seconds | 512 megabytes | ['bitmasks', 'brute force', 'dfs and similar', 'expression parsing', 'implementation', '*1800'] |
A. String Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLittle Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her.Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain order (one after another, in this order strictly), which is specified by permutation of letters' indices of the word t: a1... a|t|. We denote the length of word x as |x|. Note that after removing one letter, the indices of other letters don't change. For example, if tβ=β"nastya" and aβ=β[4,β1,β5,β3,β2,β6] then removals make the following sequence of words "nastya" "nastya" "nastya" "nastya" "nastya" "nastya" "nastya".Sergey knows this permutation. His goal is to stop his sister at some point and continue removing by himself to get the word p. Since Nastya likes this activity, Sergey wants to stop her as late as possible. Your task is to determine, how many letters Nastya can remove before she will be stopped by Sergey.It is guaranteed that the word p can be obtained by removing the letters from word t.InputThe first and second lines of the input contain the words t and p, respectively. Words are composed of lowercase letters of the Latin alphabet (1ββ€β|p|β<β|t|ββ€β200β000). It is guaranteed that the word p can be obtained by removing the letters from word t.Next line contains a permutation a1,βa2,β...,βa|t| of letter indices that specifies the order in which Nastya removes letters of t (1ββ€βaiββ€β|t|, all ai are distinct).OutputPrint a single integer number, the maximum number of letters that Nastya can remove.ExamplesInputababcbaabb5 3 4 1 7 6 2Output3Inputbbbabbbb1 6 3 4 2 5Output4NoteIn the first sample test sequence of removing made by Nastya looks like this:"ababcba" "ababcba" "ababcba" "ababcba" Nastya can not continue, because it is impossible to get word "abb" from word "ababcba".So, Nastya will remove only three letters. | Inputababcbaabb5 3 4 1 7 6 2 | Output3 | 2 seconds | 512 megabytes | ['binary search', 'greedy', 'strings', '*1700'] |
E. Hanoi Factorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOf course you have heard the famous task about Hanoi Towers, but did you know that there is a special factory producing the rings for this wonderful game? Once upon a time, the ruler of the ancient Egypt ordered the workers of Hanoi Factory to create as high tower as possible. They were not ready to serve such a strange order so they had to create this new tower using already produced rings.There are n rings in factory's stock. The i-th ring has inner radius ai, outer radius bi and height hi. The goal is to select some subset of rings and arrange them such that the following conditions are satisfied: Outer radiuses form a non-increasing sequence, i.e. one can put the j-th ring on the i-th ring only if bjββ€βbi. Rings should not fall one into the the other. That means one can place ring j on the ring i only if bjβ>βai. The total height of all rings used should be maximum possible. InputThe first line of the input contains a single integer n (1ββ€βnββ€β100β000)Β β the number of rings in factory's stock.The i-th of the next n lines contains three integers ai, bi and hi (1ββ€βai,βbi,βhiββ€β109, biβ>βai)Β β inner radius, outer radius and the height of the i-th ring respectively.OutputPrint one integerΒ β the maximum height of the tower that can be obtained.ExamplesInput31 5 12 6 23 7 3Output6Input41 2 11 3 34 6 25 7 1Output4NoteIn the first sample, the optimal solution is to take all the rings and put them on each other in order 3, 2, 1.In the second sample, one can put the ring 3 on the ring 4 and get the tower of height 3, or put the ring 1 on the ring 2 and get the tower of height 4. | Input31 5 12 6 23 7 3 | Output6 | 1 second | 256 megabytes | ['brute force', 'data structures', 'dp', 'greedy', 'sortings', '*2000'] |
D. Cloud of Hashtagstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.InputThe first line of the input contains a single integer n (1ββ€βnββ€β500β000)Β β the number of hashtags being edited now.Each of the next n lines contains exactly one hashtag of positive length.It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500β000.OutputPrint the resulting hashtags in any of the optimal solutions.ExamplesInput3#book#bigtown#bigOutput#b#big#bigInput3#book#cool#coldOutput#book#co#coldInput4#car#cart#art#atOutput###art#atInput3#apple#apple#fruitOutput#apple#apple#fruitNoteWord a1,βa2,β...,βam of length m is lexicographically not greater than word b1,βb2,β...,βbk of length k, if one of two conditions hold: at first position i, such that aiββ βbi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ; if there is no such position i and mββ€βk, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two. | Input3#book#bigtown#big | Output#b#big#big | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'implementation', 'strings', '*1800'] |
C. Alyona and Spreadsheettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the lesson small girl Alyona works with one famous spreadsheet computer program and learns how to edit tables.Now she has a table filled with integers. The table consists of n rows and m columns. By ai,βj we will denote the integer located at the i-th row and the j-th column. We say that the table is sorted in non-decreasing order in the column j if ai,βjββ€βaiβ+β1,βj for all i from 1 to nβ-β1.Teacher gave Alyona k tasks. For each of the tasks two integers l and r are given and Alyona has to answer the following question: if one keeps the rows from l to r inclusive and deletes all others, will the table be sorted in non-decreasing order in at least one column? Formally, does there exist such j that ai,βjββ€βaiβ+β1,βj for all i from l to rβ-β1 inclusive.Alyona is too small to deal with this task and asks you to help!InputThe first line of the input contains two positive integers n and m (1ββ€βnΒ·mββ€β100β000)Β β the number of rows and the number of columns in the table respectively. Note that your are given a constraint that bound the product of these two integers, i.e. the number of elements in the table.Each of the following n lines contains m integers. The j-th integers in the i of these lines stands for ai,βj (1ββ€βai,βjββ€β109).The next line of the input contains an integer k (1ββ€βkββ€β100β000)Β β the number of task that teacher gave to Alyona.The i-th of the next k lines contains two integers li and ri (1ββ€βliββ€βriββ€βn).OutputPrint "Yes" to the i-th line of the output if the table consisting of rows from li to ri inclusive is sorted in non-decreasing order in at least one column. Otherwise, print "No".ExampleInput5 41 2 3 53 1 3 24 5 2 35 5 3 24 4 3 461 12 54 53 51 31 5OutputYesNoYesYesYesNoNoteIn the sample, the whole table is not sorted in any column. However, rows 1β3 are sorted in column 1, while rows 4β5 are sorted in column 3. | Input5 41 2 3 53 1 3 24 5 2 35 5 3 24 4 3 461 12 54 53 51 31 5 | OutputYesNoYesYesYesNo | 1 second | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'implementation', 'two pointers', '*1600'] |
B. Game of Credit Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if nβ=β3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.InputThe first line of the input contains a single integer n (1ββ€βnββ€β1000)Β β the number of digits in the cards Sherlock and Moriarty are going to use.The second line contains n digitsΒ β Sherlock's credit card number.The third line contains n digitsΒ β Moriarty's credit card number.OutputFirst print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.ExamplesInput3123321Output02Input28800Output20NoteFirst sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks. | Input3123321 | Output02 | 2 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'sortings', '*1300'] |
A. Shell Gametime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess the current position of the ball.Bomboslav noticed that guys are not very inventive, so the operator always swaps the left shell with the middle one during odd moves (first, third, fifth, etc.) and always swaps the middle shell with the right one during even moves (second, fourth, etc.).Let's number shells from 0 to 2 from left to right. Thus the left shell is assigned number 0, the middle shell is 1 and the right shell is 2. Bomboslav has missed the moment when the ball was placed beneath the shell, but he knows that exactly n movements were made by the operator and the ball was under shell x at the end. Now he wonders, what was the initial position of the ball?InputThe first line of the input contains an integer n (1ββ€βnββ€β2Β·109)Β β the number of movements made by the operator.The second line contains a single integer x (0ββ€βxββ€β2)Β β the index of the shell where the ball was found after n movements.OutputPrint one integer from 0 to 2Β β the index of the shell where the ball was initially placed.ExamplesInput42Output1Input11Output0NoteIn the first sample, the ball was initially placed beneath the middle shell and the operator completed four movements. During the first move operator swapped the left shell and the middle shell. The ball is now under the left shell. During the second move operator swapped the middle shell and the right one. The ball is still under the left shell. During the third move operator swapped the left shell and the middle shell again. The ball is again in the middle. Finally, the operators swapped the middle shell and the right shell. The ball is now beneath the right shell. | Input42 | Output1 | 0.5 seconds | 256 megabytes | ['constructive algorithms', 'implementation', 'math', '*1000'] |
G. Sherlock and the Encrypted Datatime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSherlock found a piece of encrypted data which he thinks will be useful to catch Moriarty. The encrypted data consists of two integer l and r. He noticed that these integers were in hexadecimal form.He takes each of the integers from l to r, and performs the following operations: He lists the distinct digits present in the given number. For example: for 101416, he lists the digits as 1,β0,β4. Then he sums respective powers of two for each digit listed in the step above. Like in the above example sumβ=β21β+β20β+β24β=β1910. He changes the initial number by applying bitwise xor of the initial number and the sum. Example: . Note that xor is done in binary notation. One more example: for integer 1e the sum is sumβ=β21β+β214. Letters a, b, c, d, e, f denote hexadecimal digits 10, 11, 12, 13, 14, 15, respertively.Sherlock wants to count the numbers in the range from l to r (both inclusive) which decrease on application of the above four steps. He wants you to answer his q queries for different l and r.InputFirst line contains the integer q (1ββ€βqββ€β10000).Each of the next q lines contain two hexadecimal integers l and r (0ββ€βlββ€βrβ<β1615).The hexadecimal integers are written using digits from 0 to 9 and/or lowercase English letters a, b, c, d, e, f.The hexadecimal integers do not contain extra leading zeros.OutputOutput q lines, i-th line contains answer to the i-th query (in decimal notation).ExamplesInput11014 1014Output1Input21 1e1 fOutput10Input21 abcd0e fe23Output41228464NoteFor the second input,1416β=β2010sumβ=β21β+β24β=β18 Thus, it reduces. And, we can verify that it is the only number in range 1 to 1e that reduces. | Input11014 1014 | Output1 | 2 seconds | 512 megabytes | ['bitmasks', 'combinatorics', 'dp', '*2900'] |
F. Sherlock's bet to Moriartytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSherlock met Moriarty for a final battle of wits. He gave him a regular n sided convex polygon. In addition to it, he gave him certain diagonals to form regions on the polygon. It was guaranteed that the diagonals did not intersect in interior points.He took each of the region and calculated its importance value. Importance value for a region formed by vertices a1,βa2,β... ,βax of the polygon will be given by 2a1β+β2a2β+β...β+β2ax. Then, he sorted these regions on the basis of their importance value in ascending order. After that he assigned each region an index from 1 to k, where k is the number of regions, and index of region is its position in the sorted array calculated above.He wants Moriarty to color the regions using not more than 20 colors, such that two regions have same color only if all the simple paths between these two regions have at least one region with color value less than the color value assigned to these regions. Simple path between two regions f and h is a sequence of regions r1,βr2,β... rt such that r1β=βf, rtβ=βh, for each 1ββ€βiβ<βt regions ri and riβ+β1 share an edge, and riβ=βrj if and only if iβ=βj.Moriarty couldn't answer and asks Sherlock to solve it himself. Help Sherlock in doing so.InputFirst line contains two integers n and m (3ββ€βnββ€β100000, 0ββ€βmββ€βnβ-β3), the number of vertices in the polygon and the number of diagonals added.Each of the next m lines contains two integers a and b (1ββ€βa,βbββ€βn), describing a diagonal between vertices a and b. It is guaranteed that the diagonals are correct, i.Β e. a and b don't coincide and are not neighboring. It is guaranteed that the diagonals do not intersect.OutputLet the number of regions be k.Output k space-separated integers, each between 1 and 20, representing the colors of the regions in the order of increasing importance.If there are multiple answers, print any of them. It can be shown that at least one answer exists.ExamplesInput4 11 3Output1 2Input6 31 31 41 5Output2 1 2 3NoteIn 2nd input, regions formed in order after sorting will be (1,β2,β3), (1,β3,β4), (1,β4,β5), (1,β5,β6), i.e, region (1,β2,β3) is first region followed by region (1,β3,β4) and so on.So, we can color regions 1 and 3 with same color, as region number 2 is on the path from 1 to 3 and it has color 1 which is less than color of 1 and 3, i.e., color number 2. | Input4 11 3 | Output1 2 | 2 seconds | 512 megabytes | ['constructive algorithms', 'data structures', 'divide and conquer', 'geometry', 'graphs', 'implementation', 'trees', '*2800'] |
E. The Holmes Childrentime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Holmes children are fighting over who amongst them is the cleverest.Mycroft asked Sherlock and Eurus to find value of f(n), where f(1)β=β1 and for nββ₯β2, f(n) is the number of distinct ordered positive integer pairs (x,βy) that satisfy xβ+βyβ=βn and gcd(x,βy)β=β1. The integer gcd(a,βb) is the greatest common divisor of a and b.Sherlock said that solving this was child's play and asked Mycroft to instead get the value of . Summation is done over all positive integers d that divide n.Eurus was quietly observing all this and finally came up with her problem to astonish both Sherlock and Mycroft.She defined a k-composite function Fk(n) recursively as follows:She wants them to tell the value of Fk(n) modulo 1000000007.InputA single line of input contains two space separated integers n (1ββ€βnββ€β1012) and k (1ββ€βkββ€β1012) indicating that Eurus asks Sherlock and Mycroft to find the value of Fk(n) modulo 1000000007.OutputOutput a single integerΒ β the value of Fk(n) modulo 1000000007.ExamplesInput7 1Output6Input10 2Output4NoteIn the first case, there are 6 distinct ordered pairs (1,β6), (2,β5), (3,β4), (4,β3), (5,β2) and (6,β1) satisfying xβ+βyβ=β7 and gcd(x,βy)β=β1. Hence, f(7)β=β6. So, F1(7)β=βf(g(7))β=βf(f(7)β+βf(1))β=βf(6β+β1)β=βf(7)β=β6. | Input7 1 | Output6 | 2 seconds | 256 megabytes | ['math', 'number theory', '*2100'] |
D. The Door Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMoriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by exactly two switches.You are given the initial configuration of the doors. Toggling any switch, that is, turning it ON when it is OFF, or turning it OFF when it is ON, toggles the condition of the doors that this switch controls. Say, we toggled switch 1, which was connected to room 1, 2 and 3 which were respectively locked, unlocked and unlocked. Then, after toggling the switch, they become unlocked, locked and locked.You need to tell Sherlock, if there exists a way to unlock all doors at the same time.InputFirst line of input contains two integers n and m (2ββ€βnββ€β105, 2ββ€βmββ€β105)Β β the number of rooms and the number of switches.Next line contains n space-separated integers r1,βr2,β...,βrn (0ββ€βriββ€β1) which tell the status of room doors. The i-th room is locked if riβ=β0, otherwise it is unlocked.The i-th of next m lines contains an integer xi (0ββ€βxiββ€βn) followed by xi distinct integers separated by space, denoting the number of rooms controlled by the i-th switch followed by the room numbers that this switch controls. It is guaranteed that the room numbers are in the range from 1 to n. It is guaranteed that each door is controlled by exactly two switches.OutputOutput "YES" without quotes, if it is possible to open all doors at the same time, otherwise output "NO" without quotes.ExamplesInput3 31 0 12 1 32 1 22 2 3OutputNOInput3 31 0 13 1 2 31 22 1 3OutputYESInput3 31 0 13 1 2 32 1 21 3OutputNONoteIn the second example input, the initial statuses of the doors are [1,β0,β1] (0 means locked, 1Β β unlocked).After toggling switch 3, we get [0,β0,β0] that means all doors are locked.Then, after toggling switch 1, we get [1,β1,β1] that means all doors are unlocked.It can be seen that for the first and for the third example inputs it is not possible to make all doors unlocked. | Input3 31 0 12 1 32 1 22 2 3 | OutputNO | 2 seconds | 256 megabytes | ['2-sat', 'dfs and similar', 'dsu', 'graphs', '*2000'] |
C. Molly's Chemicalstime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMolly Hooper has n different kinds of chemicals arranged in a line. Each of the chemicals has an affection value, The i-th of them has affection value ai.Molly wants Sherlock to fall in love with her. She intends to do this by mixing a contiguous segment of chemicals together to make a love potion with total affection value as a non-negative integer power of k. Total affection value of a continuous segment of chemicals is the sum of affection values of each chemical in that segment.Help her to do so in finding the total number of such segments.InputThe first line of input contains two integers, n and k, the number of chemicals and the number, such that the total affection value is a non-negative power of this number k. (1ββ€βnββ€β105, 1ββ€β|k|ββ€β10).Next line contains n integers a1,βa2,β...,βan (β-β109ββ€βaiββ€β109)Β β affection values of chemicals.OutputOutput a single integerΒ β the number of valid segments.ExamplesInput4 22 2 2 2Output8Input4 -33 -6 -3 12Output3NoteDo keep in mind that k0β=β1.In the first sample, Molly can get following different affection values: 2: segments [1,β1], [2,β2], [3,β3], [4,β4]; 4: segments [1,β2], [2,β3], [3,β4]; 6: segments [1,β3], [2,β4]; 8: segments [1,β4]. Out of these, 2, 4 and 8 are powers of kβ=β2. Therefore, the answer is 8.In the second sample, Molly can choose segments [1,β2], [3,β3], [3,β4]. | Input4 22 2 2 2 | Output8 | 2.5 seconds | 512 megabytes | ['binary search', 'brute force', 'data structures', 'implementation', 'math', '*1800'] |
B. Sherlock and his girlfriendtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to iβ+β1, that is, the prices of the jewelry are 2,β3,β4,β... nβ+β1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.InputThe only line contains single integer n (1ββ€βnββ€β100000)Β β the number of jewelry pieces.OutputThe first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints.The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price.If there are multiple ways to color the pieces using k colors, you can output any of them.ExamplesInput3Output21 1 2 Input4Output22 1 1 2NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct. | Input3 | Output21 1 2 | 1 second | 256 megabytes | ['constructive algorithms', 'number theory', '*1200'] |
A. A Serial Killertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOur beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.InputFirst line of input contains two names (length of each of them doesn't exceed 10), the two initials potential victims. Next line contains integer n (1ββ€βnββ€β1000), the number of days.Next n lines contains two names (length of each of them doesn't exceed 10), first being the person murdered on this day and the second being the one who replaced that person.The input format is consistent, that is, a person murdered is guaranteed to be from the two potential victims at that time. Also, all the names are guaranteed to be distinct and consists of lowercase English letters.OutputOutput nβ+β1 lines, the i-th line should contain the two persons from which the killer selects for the i-th murder. The (nβ+β1)-th line should contain the two persons from which the next victim is selected. In each line, the two names can be printed in any order.ExamplesInputross rachel4ross joeyrachel phoebephoebe monicamonica chandlerOutputross racheljoey racheljoey phoebejoey monicajoey chandlerInputicm codeforces1codeforces technexOutputicm codeforcesicm technexNoteIn first example, the killer starts with ross and rachel. After day 1, ross is killed and joey appears. After day 2, rachel is killed and phoebe appears. After day 3, phoebe is killed and monica appears. After day 4, monica is killed and chandler appears. | Inputross rachel4ross joeyrachel phoebephoebe monicamonica chandler | Outputross racheljoey racheljoey phoebejoey monicajoey chandler | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'strings', '*900'] |
A. University Scheduletime limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem your task is to come up with a week schedule of classes in university for professors and student groups. Consider that there are 6 educational days in week and maximum number of classes per educational day is 7 (classes numerated from 1 to 7 for each educational day).It is known that in university n students study, m professors work and there are a classrooms for conducting classes. Also you have two-dimensional array with nβΓβm size which contains the following information. The number which stays in i-th row and j-th column equals to the number of classes which professor j must conduct with the group i in a single week. The schedule which you output must satisfy to array described above.There are several other conditions for schedule. Single professor can not conduct more than one class. Similarly, single student group can not be on more than one class at the same time.Let define a fatigue function for professors and student groups. Call this function f.To single professor fatigue calculated in the following way. Let look on classes which this professor must conduct in each of the 6-th educational days. Let x be the number of class which professor will firstly conduct in day i and let y β the last class for this professor. Then the value (2β+βyβ-βxβ+β1)Β·(2β+βyβ-βxβ+β1) must be added to professor's fatigue. If professor has no classes in day i, nothing is added to professor's fatigue. For single student group fatigue is calculated similarly. Lets look at classes of this group in each of the 6 educational days. Let x be the number of first class for this group on day i and let y β the last class for this group. Then the value (2β+βyβ-βxβ+β1)Β·(2β+βyβ-βxβ+β1) must be added to this group's fatigue. If student group has no classes in day i, nothing is added to group's fatigue.So the value of function f equals to total {fatigue} for all n student groups and for all m professors.Your task is to come up with such a schedule which minimizes the value of function f.Jury prepared some solution of this problem. For each test you will get a certain number of points. It equals to result of division of the value of function f from the jury solution by the value of function f for schedule which your program output (i. e. the smaller value of {fatigue} function your program find the more points you will get), multiplied by 100. In the other words if the value of f for jury solution equals to p and for your solution β to q, you will get 100Β·pβ/βq points (note, that the number of points is a real number). The points will be added together for all tests. The goal is to score as many points as possible. InputThe first line contains three integers n, m and a (1ββ€βn,βm,βaββ€β60) β the number of groups, the number of professors and the number of classrooms.Each of the following n lines contains m integers from 0 to 24 β j-th number in i-th line equals to the number of classes with the professor j must conduct with the i-th student group.It is guaranteed that the number of classes in week for each professor and for each student group does not exceed 24. Also guaranteed that the total number of classes in week does not exceed 75% from a maximum number of classes which can be conducted based on the number of classrooms. For all tests there is at least one schedule satisfying all described conditions.OutputIn the first line print the minimized value of function f.After that print blank line.After that print the schedule for each student group in increasing order of group number. For each student group print 7 lines. Each line must contains 6 numbers. Let the number at i-th line and j-th column equals to x. If in j-th day current group has no class number i, x must be equals to zero. Otherwise x must be equals to the number of professor who will conduct the corresponding class with the corresponding student group. The number of classes which will be conducted simultaneously must not exceeds the number of classrooms a.Separate the description of the schedules for groups with a blank line.ExamplesInput3 3 11 0 00 1 00 0 1Output541 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Input3 1 1111Output521 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Input5 7 101 3 6 0 1 2 40 3 0 6 5 1 43 5 1 2 3 2 42 3 1 1 4 1 22 4 3 2 4 3 2Output15120 0 6 0 0 2 0 7 6 3 3 7 3 1 2 3 2 7 3 7 0 0 0 0 5 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 7 6 4 5 7 4 5 5 7 2 4 4 5 5 7 2 0 4 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 0 7 2 5 7 5 0 2 5 7 1 2 4 1 2 7 1 2 3 0 0 0 0 0 6 0 0 0 0 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 5 3 5 0 2 4 7 2 6 0 5 7 0 0 0 1 5 1 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 5 7 2 3 0 1 3 2 6 3 5 7 6 5 6 4 5 4 2 2 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 NoteDuring the main part of the competition (one week) you solution will be judged on 100 preliminary tests. The first 10 preliminary tests are available for download by a link http://assets.codeforces.com/files/vk/vkcup-2017-wr2-materials-v1.tar.gz.After the end of the contest (i.e., a week after its start) the last solution you sent (having positive score) will be chosen to be launched on the extended final tests. | Input3 3 11 0 00 1 00 0 1 | Output541 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 | 10 seconds | 256 megabytes | ['*special problem', '*2900'] |
L. Barstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp's workday lasts exactly n minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has k bars at the beginning of the workday.In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either eat or not eat one chocolate bar. It is guaranteed, that in the first and in the last minutes of the workday Polycarp has no important things to do and he will always eat bars in this minutes to gladden himself at the begining and at the end of the workday. Also it is guaranteed, that k is strictly greater than 1.Your task is to determine such an order of eating chocolate bars that the maximum break time between eating bars is as minimum as possible.Consider that Polycarp eats a bar in the minute x and the next bar in the minute y (x < y). Then the break time is equal to y - x - 1 minutes. It is not necessary for Polycarp to eat all bars he has.InputThe first line contains two integers n and k (2 \le n \le 200\,000, 2 \le k \le n) β the length of the workday in minutes and the number of chocolate bars, which Polycarp has in the beginning of the workday.The second line contains the string with length n consisting of zeros and ones. If the i-th symbol in the string equals to zero, Polycarp has no important things to do in the minute i and he can eat a chocolate bar. In the other case, Polycarp is busy in the minute i and can not eat a chocolate bar. It is guaranteed, that the first and the last characters of the string are equal to zero, and Polycarp always eats chocolate bars in these minutes.OutputPrint the minimum possible break in minutes between eating chocolate bars.ExamplesInput3 3010Output1Input8 301010110Output3NoteIn the first example Polycarp can not eat the chocolate bar in the second minute, so the time of the break equals to one minute.In the second example Polycarp will eat bars in the minutes 1 and 8 anyway, also he needs to eat the chocolate bar in the minute 5, so that the time of the maximum break will be equal to 3 minutes. | Input3 3010 | Output1 | 2 seconds | 256 megabytes | ['*special problem', 'binary search', '*2000'] |
K. Stepan and Vowelstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".Sergey is very busy and asks you to help him and write the required program.InputThe first line contains the integer n (1ββ€βnββ€β100β000) β the number of letters in the word written by Stepan.The second line contains the string s which has length that equals to n and contains only lowercase English letters β the word written by Stepan.OutputPrint the single string β the word written by Stepan converted according to the rules described in the statement.ExamplesInput13pobeeeedaaaaaOutputpobedaInput22iiiimpleeemeentatiioonOutputimplemeentatioonInput18aeiouyaaeeiioouuyyOutputaeiouyaeeioouyInput24aaaoooiiiuuuyyyeeeggghhhOutputaoiuyeggghhh | Input13pobeeeedaaaaa | Outputpobeda | 1 second | 256 megabytes | ['*special problem', 'implementation', 'strings', '*1600'] |
J. Stepan's Seriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWell, the series which Stepan watched for a very long time, ended. In total, the series had n episodes. For each of them, Stepan remembers either that he definitely has watched it, or that he definitely hasn't watched it, or he is unsure, has he watched this episode or not. Stepan's dissatisfaction is the maximum number of consecutive series that Stepan did not watch.Your task is to determine according to Stepan's memories if his dissatisfaction could be exactly equal to k.InputThe first line contains two integers n and k (1ββ€βnββ€β100, 0ββ€βkββ€βn) β the number of episodes in the series and the dissatisfaction which should be checked. The second line contains the sequence which consists of n symbols "Y", "N" and "?". If the i-th symbol equals "Y", Stepan remembers that he has watched the episode number i. If the i-th symbol equals "N", Stepan remembers that he hasn't watched the epizode number i. If the i-th symbol equals "?", Stepan doesn't exactly remember if he has watched the episode number i or not.OutputIf Stepan's dissatisfaction can be exactly equal to k, then print "YES" (without qoutes). Otherwise print "NO" (without qoutes).ExamplesInput5 2NYNNYOutputYESInput6 1????NNOutputNONoteIn the first test Stepan remembers about all the episodes whether he has watched them or not. His dissatisfaction is 2, because he hasn't watch two episodes in a row β the episode number 3 and the episode number 4. The answer is "YES", because kβ=β2.In the second test kβ=β1, Stepan's dissatisfaction is greater than or equal to 2 (because he remembers that he hasn't watch at least two episodes in a row β number 5 and number 6), even if he has watched the episodes from the first to the fourth, inclusive. | Input5 2NYNNY | OutputYES | 2 seconds | 256 megabytes | ['*special problem', 'dp', '*2000'] |
I. Composing Of Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan has a set of n strings. Also, he has a favorite string s. Stepan wants to do the following. He will take some strings of his set and write them down one after another. It is possible that he will take some strings more than once, and will not take some of them at all.Your task is to determine the minimum number of strings in the set which Stepan needs to take and write so that the string s appears as a subsequence in the resulting written down string. For example, in the string "abcd" strings "ad", "acd", "abcd" appear as subsequences, and strings "ba", "abdc" don't appear as subsequences. InputThe first line contains the integer n (1ββ€βnββ€β50) β the number of strings in Stepan's set.The next n lines contain n non-empty strings consisting of lowercase letters of the English alphabet. The length of each of these strings does not exceed 50 symbols. It is possible that some strings from Stepan's set are the same.The next line contains the non-empty string s, consisting of lowercase letters of the English alphabet β Stepan's favorite string. The length of this string doesn't exceed 2500 symbols.OutputPrint the minimum number of strings which Stepan should take from the set and write them down one after another so that the string s appears as a subsequence in the resulting written down string. Each string from the set should be counted as many times as Stepan takes it from the set. If the answer doesn't exsist, print -1.ExamplesInput3aaaaaaaOutput2Input4abaabaabbbaaabOutput3Input2aaabbbaaacbbbOutput-1NoteIn the first test, Stepan can take, for example, the third and the second strings from the set, write them down, and get exactly his favorite string.In the second example Stepan can take, for example, the second, the third and again the second strings from the set and write them down. Then he will get a string "aabaaaab", in which his favorite string "baaab" is a subsequence.In the third test Stepan can not get his favorite string, because it contains the letter "c", which is not presented in any of the strings in the set. | Input3aaaaaaa | Output2 | 2 seconds | 256 megabytes | ['*special problem', 'dp', '*2300'] |
H. Repairing Of Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet. After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1,βc2,β...,βcn, where n equals the length of the string s, and ci equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.For example, if the Stepan's favorite string is equal to "tttesst", the sequence c looks like: cβ=β[7,β3,β1,β0,β0,β0,β0].Stepan asks you to help to repair his favorite string s according to the given sequence c1,βc2,β...,βcn. InputThe first line contains the integer n (1ββ€βnββ€β2000) β the length of the Stepan's favorite string.The second line contains the sequence of integers c1,βc2,β...,βcn (0ββ€βciββ€β2000), where ci equals the number of substrings of the string s with the length i, consisting of the same letters.It is guaranteed that the input data is such that the answer always exists.OutputPrint the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet. ExamplesInput66 3 1 0 0 0OutputkkrrrqInput44 0 0 0OutputabcdNoteIn the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3). | Input66 3 1 0 0 0 | Outputkkrrrq | 2 seconds | 256 megabytes | ['*special problem', 'constructive algorithms', '*2200'] |
G. Perfectionist Arkadiytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkadiy has lots square photos with size aβΓβa. He wants to put some of them on a rectangular wall with size hβΓβw. The photos which Arkadiy will put on the wall must form a rectangular grid and the distances between neighboring vertically and horizontally photos and also the distances between outside rows and columns of photos to the nearest bound of the wall must be equal to x, where x is some non-negative real number. Look on the picture below for better understanding of the statement. Arkadiy haven't chosen yet how many photos he would put on the wall, however, he want to put at least one photo. Your task is to determine the minimum value of x which can be obtained after putting photos, or report that there is no way to put positive number of photos and satisfy all the constraints. Suppose that Arkadiy has enough photos to make any valid arrangement according to the constraints.Note that Arkadiy wants to put at least one photo on the wall. The photos should not overlap, should completely lie inside the wall bounds and should have sides parallel to the wall sides.InputThe first line contains three integers a, h and w (1ββ€βa,βh,βwββ€β109) β the size of photos and the height and the width of the wall.OutputPrint one non-negative real number β the minimum value of x which can be obtained after putting the photos on the wall. The absolute or the relative error of the answer must not exceed 10β-β6.Print -1 if there is no way to put positive number of photos and satisfy the constraints.ExamplesInput2 18 13Output0.5Input4 4 4Output0Input3 4 3Output-1NoteIn the first example Arkadiy can put 7 rows of photos with 5 photos in each row, so the minimum value of x equals to 0.5.In the second example Arkadiy can put only 1 photo which will take the whole wall, so the minimum value of x equals to 0.In the third example there is no way to put positive number of photos and satisfy the constraints described in the statement, so the answer is -1. | Input2 18 13 | Output0.5 | 1 second | 256 megabytes | ['*special problem', 'number theory', '*2700'] |
F. Pens And Days Of Weektime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan has n pens. Every day he uses them, and on the i-th day he uses the pen number i. On the (nβ+β1)-th day again he uses the pen number 1, on the (nβ+β2)-th β he uses the pen number 2 and so on.On every working day (from Monday to Saturday, inclusive) Stepan spends exactly 1 milliliter of ink of the pen he uses that day. On Sunday Stepan has a day of rest, he does not stend the ink of the pen he uses that day. Stepan knows the current volume of ink in each of his pens. Now it's the Monday morning and Stepan is going to use the pen number 1 today. Your task is to determine which pen will run out of ink before all the rest (that is, there will be no ink left in it), if Stepan will use the pens according to the conditions described above.InputThe first line contains the integer n (1ββ€βnββ€β50β000) β the number of pens Stepan has.The second line contains the sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β109), where ai is equal to the number of milliliters of ink which the pen number i currently has.OutputPrint the index of the pen which will run out of ink before all (it means that there will be no ink left in it), if Stepan will use pens according to the conditions described above. Pens are numbered in the order they are given in input data. The numeration begins from one. Note that the answer is always unambiguous, since several pens can not end at the same time.ExamplesInput33 3 3Output2Input55 4 5 4 4Output5NoteIn the first test Stepan uses ink of pens as follows: on the day number 1 (Monday) Stepan will use the pen number 1, after that there will be 2 milliliters of ink in it; on the day number 2 (Tuesday) Stepan will use the pen number 2, after that there will be 2 milliliters of ink in it; on the day number 3 (Wednesday) Stepan will use the pen number 3, after that there will be 2 milliliters of ink in it; on the day number 4 (Thursday) Stepan will use the pen number 1, after that there will be 1 milliliters of ink in it; on the day number 5 (Friday) Stepan will use the pen number 2, after that there will be 1 milliliters of ink in it; on the day number 6 (Saturday) Stepan will use the pen number 3, after that there will be 1 milliliters of ink in it; on the day number 7 (Sunday) Stepan will use the pen number 1, but it is a day of rest so he will not waste ink of this pen in it; on the day number 8 (Monday) Stepan will use the pen number 2, after that this pen will run out of ink. So, the first pen which will not have ink is the pen number 2. | Input33 3 3 | Output2 | 3 seconds | 256 megabytes | ['*special problem', 'binary search', 'number theory', '*2700'] |
E. Big Number and Remaindertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan has a very big positive integer.Let's consider all cyclic shifts of Stepan's integer (if we look at his integer like at a string) which are also integers (i.e. they do not have leading zeros). Let's call such shifts as good shifts. For example, for the integer 10203 the good shifts are the integer itself 10203 and integers 20310 and 31020.Stepan wants to know the minimum remainder of the division by the given number m among all good shifts. Your task is to determine the minimum remainder of the division by m.InputThe first line contains the integer which Stepan has. The length of Stepan's integer is between 2 and 200β000 digits, inclusive. It is guaranteed that Stepan's integer does not contain leading zeros.The second line contains the integer m (2ββ€βmββ€β108) β the number by which Stepan divides good shifts of his integer.OutputPrint the minimum remainder which Stepan can get if he divides all good shifts of his integer by the given number m.ExamplesInput5213Output2Input10015Output0Input567890123456789012345678910000Output123NoteIn the first example all good shifts of the integer 521 (good shifts are equal to 521, 215 and 152) has same remainder 2 when dividing by 3.In the second example there are only two good shifts: the Stepan's integer itself and the shift by one position to the right. The integer itself is 1001 and the remainder after dividing it by 5 equals 1. The shift by one position to the right equals to 1100 and the remainder after dividing it by 5 equals 0, which is the minimum possible remainder. | Input5213 | Output2 | 3 seconds | 256 megabytes | ['*special problem', 'math', 'number theory', '*2300'] |
D. Lie or Truthtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1,βa2,β...,βan.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1,βb2,β...,βbn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.InputThe first line contains three integers n, l, r (1ββ€βnββ€β105, 1ββ€βlββ€βrββ€βn) β the number of Vasya's cubes and the positions told by Stepan.The second line contains the sequence a1,βa2,β...,βan (1ββ€βaiββ€βn) β the sequence of integers written on cubes in the Vasya's order.The third line contains the sequence b1,βb2,β...,βbn (1ββ€βbiββ€βn) β the sequence of integers written on cubes after Stepan rearranged their order.It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.OutputPrint "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).ExamplesInput5 2 43 4 2 3 13 2 3 4 1OutputTRUTHInput3 1 21 2 33 1 2OutputLIEInput4 2 41 1 1 11 1 1 1OutputTRUTHNoteIn the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.In the third example for any values l and r there is a situation when Stepan said the truth. | Input5 2 43 4 2 3 13 2 3 4 1 | OutputTRUTH | 2 seconds | 256 megabytes | ['*special problem', 'constructive algorithms', 'implementation', 'sortings', '*1500'] |
C. Maximum Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below. So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.InputThe first line contains the integer n (2ββ€βnββ€β100β000) β the maximum number of sections which can be highlighted on the display.OutputPrint the maximum integer which can be shown on the display of Stepan's newest device.ExamplesInput2Output1Input3Output7 | Input2 | Output1 | 1 second | 256 megabytes | ['*special problem', 'constructive algorithms', 'greedy', 'implementation', '*1200'] |
B. Significant Cupstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters β its significance ci and width wi.Stepan decided to expose some of his cups on a shelf with width d in such a way, that: there is at least one Physics cup and at least one Informatics cup on the shelf, the total width of the exposed cups does not exceed d, from each subjects (Physics and Informatics) some of the most significant cups are exposed (i. e. if a cup for some subject with significance x is exposed, then all the cups for this subject with significance greater than x must be exposed too). Your task is to determine the maximum possible total significance, which Stepan can get when he exposes cups on the shelf with width d, considering all the rules described above. The total significance is the sum of significances of all the exposed cups.InputThe first line contains three integers n, m and d (1ββ€βn,βmββ€β100β000, 1ββ€βdββ€β109) β the number of cups for Physics olympiads, the number of cups for Informatics olympiads and the width of the shelf.Each of the following n lines contains two integers ci and wi (1ββ€βci,βwiββ€β109) β significance and width of the i-th cup for Physics olympiads.Each of the following m lines contains two integers cj and wj (1ββ€βcj,βwjββ€β109) β significance and width of the j-th cup for Informatics olympiads.OutputPrint the maximum possible total significance, which Stepan can get exposing cups on the shelf with width d, considering all the rules described in the statement.If there is no way to expose cups on the shelf, then print 0.ExamplesInput3 1 84 25 54 23 2Output8Input4 3 123 42 43 53 43 55 23 4Output11Input2 2 25 36 34 28 1Output0NoteIn the first example Stepan has only one Informatics cup which must be exposed on the shelf. Its significance equals 3 and width equals 2, so after Stepan exposes it, the width of free space on the shelf becomes equal to 6. Also, Stepan must expose the second Physics cup (which has width 5), because it is the most significant cup for Physics (its significance equals 5). After that Stepan can not expose more cups on the shelf, because there is no enough free space. Thus, the maximum total significance of exposed cups equals to 8. | Input3 1 84 25 54 23 2 | Output8 | 3 seconds | 256 megabytes | ['*special problem', 'binary search', 'data structures', 'two pointers', '*2100'] |
A. Amusement Parktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPupils decided to go to amusement park. Some of them were with parents. In total, n people came to the park and they all want to get to the most extreme attraction and roll on it exactly once.Tickets for group of x people are sold on the attraction, there should be at least one adult in each group (it is possible that the group consists of one adult). The ticket price for such group is c1β+βc2Β·(xβ-β1)2 (in particular, if the group consists of one person, then the price is c1). All pupils who came to the park and their parents decided to split into groups in such a way that each visitor join exactly one group, and the total price of visiting the most extreme attraction is as low as possible. You are to determine this minimum possible total price. There should be at least one adult in each group. InputThe first line contains three integers n, c1 and c2 (1ββ€βnββ€β200β000, 1ββ€βc1,βc2ββ€β107)Β β the number of visitors and parameters for determining the ticket prices for a group.The second line contains the string of length n, which consists of zeros and ones. If the i-th symbol of the string is zero, then the i-th visitor is a pupil, otherwise the i-th person is an adult. It is guaranteed that there is at least one adult. It is possible that there are no pupils.OutputPrint the minimum price of visiting the most extreme attraction for all pupils and their parents. Each of them should roll on the attraction exactly once.ExamplesInput3 4 1011Output8Input4 7 21101Output18NoteIn the first test one group of three people should go to the attraction. Then they have to pay 4β+β1β*β(3β-β1)2β=β8.In the second test it is better to go to the attraction in two groups. The first group should consist of two adults (for example, the first and the second person), the second should consist of one pupil and one adult (the third and the fourth person). Then each group will have a size of two and for each the price of ticket is 7β+β2β*β(2β-β1)2β=β9. Thus, the total price for two groups is 18. | Input3 4 1011 | Output8 | 2 seconds | 256 megabytes | ['*special problem', 'ternary search', '*2100'] |
F. Test Data Generationtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTest data generation is not an easy task! Often, generating big random test cases is not enough to ensure thorough testing of solutions for correctness.For example, consider a problem from an old Codeforces round. Its input format looks roughly as follows:The first line contains a single integer n (1ββ€βnββ€βmaxn)Β β the size of the set. The second line contains n distinct integers a1,βa2,β...,βan (1ββ€βaiββ€βmaxa)Β β the elements of the set in increasing order.If you don't pay attention to the problem solution, it looks fairly easy to generate a good test case for this problem. Let nβ=βmaxn, take random distinct ai from 1 to maxa, sort them... Soon you understand that it's not that easy.Here is the actual problem solution. Let g be the greatest common divisor of a1,βa2,β...,βan. Let xβ=βanβ/βgβ-βn. Then the correct solution outputs "Alice" if x is odd, and "Bob" if x is even.Consider two wrong solutions to this problem which differ from the correct one only in the formula for calculating x.The first wrong solution calculates x as xβ=βanβ/βg (without subtracting n).The second wrong solution calculates x as xβ=βanβ-βn (without dividing by g).A test case is interesting if it makes both wrong solutions output an incorrect answer.Given maxn, maxa and q, find the number of interesting test cases satisfying the constraints, and output it modulo q.InputThe only line contains three integers maxn, maxa and q (1ββ€βmaxnββ€β30β000; maxnββ€βmaxaββ€β109; 104ββ€βqββ€β105β+β129).OutputOutput a single integerΒ β the number of test cases which satisfy the constraints and make both wrong solutions output an incorrect answer, modulo q.ExamplesInput3 6 100000Output4Input6 21 100129Output154Input58 787788 50216Output46009NoteIn the first example, interesting test cases look as follows: 1 1 1 32 4 6 2 4 6 | Input3 6 100000 | Output4 | 5 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'dp', 'fft', 'math', 'number theory', '*3400'] |
E. Blog Post Ratingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's well-known that blog posts are an important part of Codeforces platform. Every blog post has a global characteristic changing over timeΒ β its community rating. A newly created blog post's community rating is 0. Codeforces users may visit the blog post page and rate it, changing its community rating by +1 or -1.Consider the following model of Codeforces users' behavior. The i-th user has his own estimated blog post rating denoted by an integer ai. When a user visits a blog post page, he compares his estimated blog post rating to its community rating. If his estimated rating is higher, he rates the blog post with +1 (thus, the blog post's community rating increases by 1). If his estimated rating is lower, he rates the blog post with -1 (decreasing its community rating by 1). If the estimated rating and the community rating are equal, user doesn't rate the blog post at all (in this case we'll say that user rates the blog post for 0). In any case, after this procedure user closes the blog post page and never opens it again.Consider a newly created blog post with the initial community rating of 0. For each of n Codeforces users, numbered from 1 to n, his estimated blog post rating ai is known.For each k from 1 to n, inclusive, the following question is asked. Let users with indices from 1 to k, in some order, visit the blog post page, rate the blog post and close the page. Each user opens the blog post only after the previous user closes it. What could be the maximum possible community rating of the blog post after these k visits?InputThe first line contains a single integer n (1ββ€βnββ€β5Β·105)Β β the number of Codeforces users.The second line contains n integers a1,βa2,β...,βan (β-β5Β·105ββ€βaiββ€β5Β·105)Β β estimated blog post ratings for users in order from 1 to n.OutputFor each k from 1 to n, output a single integer equal to the maximum possible community rating of the blog post after users with indices from 1 to k, in some order, visit the blog post page, rate the blog post, and close the page.ExamplesInput42 0 2 2Output1122Input72 -3 -2 5 0 -3 1Output10-10112 | Input42 0 2 2 | Output1122 | 4 seconds | 256 megabytes | ['data structures', 'sortings', '*3000'] |
D. Perishable Roadstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the country of Never, there are n cities and a well-developed road system. There is exactly one bidirectional road between every pair of cities, thus, there are as many as roads! No two roads intersect, and no road passes through intermediate cities. The art of building tunnels and bridges has been mastered by Neverians.An independent committee has evaluated each road of Never with a positive integer called the perishability of the road. The lower the road's perishability is, the more pleasant it is to drive through this road.It's the year of transport in Never. It has been decided to build a museum of transport in one of the cities, and to set a single signpost directing to some city (not necessarily the one with the museum) in each of the other cities. The signposts must satisfy the following important condition: if any Neverian living in a city without the museum starts travelling from that city following the directions of the signposts, then this person will eventually arrive in the city with the museum.Neverians are incredibly positive-minded. If a Neverian travels by a route consisting of several roads, he considers the perishability of the route to be equal to the smallest perishability of all the roads in this route.The government of Never has not yet decided where to build the museum, so they consider all n possible options. The most important is the sum of perishabilities of the routes to the museum city from all the other cities of Never, if the travelers strictly follow the directions of the signposts. The government of Never cares about their citizens, so they want to set the signposts in a way which minimizes this sum. Help them determine the minimum possible sum for all n possible options of the city where the museum can be built.InputThe first line contains a single integer n (2ββ€βnββ€β2000)Β β the number of cities in Never.The following nβ-β1 lines contain the description of the road network. The i-th of these lines contains nβ-βi integers. The j-th integer in the i-th line denotes the perishability of the road between cities i and iβ+βj.All road perishabilities are between 1 and 109, inclusive.OutputFor each city in order from 1 to n, output the minimum possible sum of perishabilities of the routes to this city from all the other cities of Never if the signposts are set in a way which minimizes this sum.ExamplesInput31 23Output223Input62 9 9 6 67 1 9 109 2 54 108Output6575711NoteThe first example is explained by the picture below. From left to right, there is the initial road network and the optimal directions of the signposts in case the museum is built in city 1, 2 and 3, respectively. The museum city is represented by a blue circle, the directions of the signposts are represented by green arrows.For instance, if the museum is built in city 3, then the signpost in city 1 must be directed to city 3, while the signpost in city 2 must be directed to city 1. Then the route from city 1 to city 3 will have perishability 2, while the route from city 2 to city 3 will have perishability 1. The sum of perishabilities of these routes is 3. | Input31 23 | Output223 | 3 seconds | 256 megabytes | ['dp', 'graphs', 'shortest paths', '*2700'] |
C. Prairie Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt can be shown that any positive integer x can be uniquely represented as xβ=β1β+β2β+β4β+β...β+β2kβ-β1β+βr, where k and r are integers, kββ₯β0, 0β<βrββ€β2k. Let's call that representation prairie partition of x.For example, the prairie partitions of 12, 17, 7 and 1 are: 12β=β1β+β2β+β4β+β5,17β=β1β+β2β+β4β+β8β+β2,7β=β1β+β2β+β4,1β=β1. Alice took a sequence of positive integers (possibly with repeating elements), replaced every element with the sequence of summands in its prairie partition, arranged the resulting numbers in non-decreasing order and gave them to Borys. Now Borys wonders how many elements Alice's original sequence could contain. Find all possible options!InputThe first line contains a single integer n (1ββ€βnββ€β105)Β β the number of numbers given from Alice to Borys.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β1012; a1ββ€βa2ββ€β...ββ€βan)Β β the numbers given from Alice to Borys.OutputOutput, in increasing order, all possible values of m such that there exists a sequence of positive integers of length m such that if you replace every element with the summands in its prairie partition and arrange the resulting numbers in non-decreasing order, you will get the sequence given in the input.If there are no such values of m, output a single integer -1.ExamplesInput81 1 2 2 3 4 5 8Output2 Input61 1 1 2 2 2Output2 3 Input51 2 4 4 4Output-1NoteIn the first example, Alice could get the input sequence from [6,β20] as the original sequence.In the second example, Alice's original sequence could be either [4,β5] or [3,β3,β3]. | Input81 1 2 2 3 4 5 8 | Output2 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'math', '*2200'] |
B. Dynamic Problem Scoringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends on the ratio of the number of participants who solved the problem to the total number of round participants. Everyone who made at least one submission is considered to be participating in the round.Pay attention to the range bounds. For example, if 40 people are taking part in the round, and 10 of them solve a particular problem, then the solvers fraction is equal to 1β/β4, and the problem's maximum point value is equal to 1500.If the problem's maximum point value is equal to x, then for each whole minute passed from the beginning of the contest to the moment of the participant's correct submission, the participant loses xβ/β250 points. For example, if the problem's maximum point value is 2000, and the participant submits a correct solution to it 40 minutes into the round, this participant will be awarded with 2000Β·(1β-β40β/β250)β=β1680 points for this problem.There are n participants in the round, including Vasya and Petya. For each participant and each problem, the number of minutes which passed between the beginning of the contest and the submission of this participant to this problem is known. It's also possible that this participant made no submissions to this problem.With two seconds until the end of the round, all participants' submissions have passed pretests, and not a single hack attempt has been made. Vasya believes that no more submissions or hack attempts will be made in the remaining two seconds, and every submission will pass the system testing.Unfortunately, Vasya is a cheater. He has registered 109β+β7 new accounts for the round. Now Vasya can submit any of his solutions from these new accounts in order to change the maximum point values of the problems. Vasya can also submit any wrong solutions to any problems. Note that Vasya can not submit correct solutions to the problems he hasn't solved.Vasya seeks to score strictly more points than Petya in the current round. Vasya has already prepared the scripts which allow to obfuscate his solutions and submit them into the system from any of the new accounts in just fractions of seconds. However, Vasya doesn't want to make his cheating too obvious, so he wants to achieve his goal while making submissions from the smallest possible number of new accounts.Find the smallest number of new accounts Vasya needs in order to beat Petya (provided that Vasya's assumptions are correct), or report that Vasya can't achieve his goal.InputThe first line contains a single integer n (2ββ€βnββ€β120)Β β the number of round participants, including Vasya and Petya.Each of the next n lines contains five integers ai,β1,βai,β2...,βai,β5 (β-β1ββ€βai,βjββ€β119)Β β the number of minutes passed between the beginning of the round and the submission of problem j by participant i, or -1 if participant i hasn't solved problem j.It is guaranteed that each participant has made at least one successful submission.Vasya is listed as participant number 1, Petya is listed as participant number 2, all the other participants are listed in no particular order.OutputOutput a single integerΒ β the number of new accounts Vasya needs to beat Petya, or -1 if Vasya can't achieve his goal.ExamplesInput25 15 40 70 11550 45 40 30 15Output2Input355 80 10 -1 -115 -1 79 60 -142 -1 13 -1 -1Output3Input5119 119 119 119 1190 0 0 0 -120 65 12 73 7778 112 22 23 111 78 60 111 62Output27Input4-1 20 40 77 11930 10 73 50 10721 29 -1 64 98117 65 -1 -1 -1Output-1NoteIn the first example, Vasya's optimal strategy is to submit the solutions to the last three problems from two new accounts. In this case the first two problems will have the maximum point value of 1000, while the last three problems will have the maximum point value of 500. Vasya's score will be equal to 980β+β940β+β420β+β360β+β270β=β2970 points, while Petya will score just 800β+β820β+β420β+β440β+β470β=β2950 points.In the second example, Vasya has to make a single unsuccessful submission to any problem from two new accounts, and a single successful submission to the first problem from the third new account. In this case, the maximum point values of the problems will be equal to 500, 1500, 1000, 1500, 3000. Vasya will score 2370 points, while Petya will score just 2294 points.In the third example, Vasya can achieve his goal by submitting the solutions to the first four problems from 27 new accounts. The maximum point values of the problems will be equal to 500, 500, 500, 500, 2000. Thanks to the high cost of the fifth problem, Vasya will manage to beat Petya who solved the first four problems very quickly, but couldn't solve the fifth one. | Input25 15 40 70 11550 45 40 30 15 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'greedy', '*2000'] |
A. Success Ratetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to xβ/βy.Your favorite rational number in the [0;1] range is pβ/βq. Now you wonder: what is the smallest number of submissions you have to make if you want your success rate to be pβ/βq?InputThe first line contains a single integer t (1ββ€βtββ€β1000)Β β the number of test cases.Each of the next t lines contains four integers x, y, p and q (0ββ€βxββ€βyββ€β109; 0ββ€βpββ€βqββ€β109; yβ>β0; qβ>β0).It is guaranteed that pβ/βq is an irreducible fraction.Hacks. For hacks, an additional constraint of tββ€β5 must be met.OutputFor each test case, output a single integer equal to the smallest number of submissions you have to make if you want your success rate to be equal to your favorite rational number, or -1 if this is impossible to achieve.ExampleInput43 10 1 27 14 3 820 70 2 75 6 1 1Output4100-1NoteIn the first example, you have to make 4 successful submissions. Your success rate will be equal to 7β/β14, or 1β/β2.In the second example, you have to make 2 successful and 8 unsuccessful submissions. Your success rate will be equal to 9β/β24, or 3β/β8.In the third example, there is no need to make any new submissions. Your success rate is already equal to 20β/β70, or 2β/β7.In the fourth example, the only unsuccessful submission breaks your hopes of having the success rate equal to 1. | Input43 10 1 27 14 3 820 70 2 75 6 1 1 | Output4100-1 | 2 seconds | 256 megabytes | ['binary search', 'math', '*1700'] |
E. Verifying Kingdomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.The judge has a hidden rooted full binary tree with n leaves. A full binary tree is one where every node has either 0 or 2 children. The nodes with 0 children are called the leaves of the tree. Since this is a full binary tree, there are exactly 2nβ-β1 nodes in the tree. The leaves of the judge's tree has labels from 1 to n. You would like to reconstruct a tree that is isomorphic to the judge's tree. To do this, you can ask some questions.A question consists of printing the label of three distinct leaves a1,βa2,βa3. Let the depth of a node be the shortest distance from the node to the root of the tree. Let LCA(a,βb) denote the node with maximum depth that is a common ancestor of the nodes a and b.Consider Xβ=βLCA(a1,βa2),βYβ=βLCA(a2,βa3),βZβ=βLCA(a3,βa1). The judge will tell you which one of X,βY,βZ has the maximum depth. Note, this pair is uniquely determined since the tree is a binary tree; there can't be any ties. More specifically, if X (or Y, Z respectively) maximizes the depth, the judge will respond with the string "X" (or "Y", "Z" respectively). You may only ask at most 10Β·n questions.InputThe first line of input will contain a single integer n (3ββ€βnββ€β1β000)Β β the number of leaves in the tree.OutputTo print the final answer, print out the string "-1" on its own line. Then, the next line should contain 2nβ-β1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root.Your answer will be judged correct if your output is isomorphic to the judge's tree. In particular, the labels of the leaves do not need to be labeled from 1 to n. Here, isomorphic means that there exists a permutation Ο such that node i is the parent of node j in the judge tree if and only node Ο(i) is the parent of node Ο(j) in your tree.InteractionTo ask a question, print out three distinct integers a1,βa2,βa3. These integers should be between 1 and n, inclusive.The judge will respond with a single character, either "X", "Y", "Z". If the string is "X" (or "Y", "Z" respectively), that means the pair (a1,βa2) (or (a2,βa3), (a3,βa1) respectively) has the deepest LCA among the three pairs.You may only ask a question at most 10Β·n times, otherwise, you will get Wrong Answer.When you are ready to answer, print out a single integer "-1" on its own line. The next line should contain 2nβ-β1 integers. The i-th integer should be the parent of the i-th node, or -1, if it is the root. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.You will get Wrong Answer verdict if Your question or answers are not in the format described in this statement. You ask strictly more than 10Β·n questions. Your question contains duplicate indices. Your final answer is not isomorphic to the judge tree. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. If at any moment your program reads -1 as an answer, it should immediately exit normally (for example, by calling exit(0)). You will get Wrong Answer in this case, it means that you made more queries than allowed, or made an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.Hacking To hack someone, use the following format np_1 p_2 ... p_{2n-1}This denotes a tree where the parent of the i-th node is pi (piβ=ββ-β1 or nβ<βpiββ€β2nβ-β1). If pi is equal to -1, then node i is the root. This input must describe a valid full rooted binary tree.Of course, contestant programs will not be able to see this input.ExampleInput5XZYYXOutput1 4 21 2 42 4 12 3 52 4 3-1-1 1 1 2 2 3 3 6 6NoteFor the first sample, the judge has the hidden tree:Here is a more readable format of the interaction: The last line can also be 8 6 9 8 9 7 -1 6 7. | Input5XZYYX | Output1 4 21 2 42 4 12 3 52 4 3-1-1 1 1 2 2 3 3 6 6 | 2 seconds | 256 megabytes | ['binary search', 'divide and conquer', 'interactive', 'trees', '*3200'] |
D. Varying Kibibitstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a1,βa2,β...,βan. Denote this list of integers as T.Let f(L) be a function that takes in a non-empty list of integers L.The function will output another integer as follows: First, all integers in L are padded with leading zeros so they are all the same length as the maximum length number in L. We will construct a string where the i-th character is the minimum of the i-th character in padded input numbers. The output is the number representing the string interpreted in base 10. For example f(10,β9)β=β0, f(123,β321)β=β121, f(530,β932,β81)β=β30.Define the function Here, denotes a subsequence.In other words, G(x) is the sum of squares of sum of elements of nonempty subsequences of T that evaluate to x when plugged into f modulo 1β000β000β007, then multiplied by x. The last multiplication is not modded. You would like to compute G(0),βG(1),β...,βG(999β999). To reduce the output size, print the value , where denotes the bitwise XOR operator.InputThe first line contains the integer n (1ββ€βnββ€β1β000β000)Β β the size of list T.The next line contains n space-separated integers, a1,βa2,β...,βan (0ββ€βaiββ€β999β999)Β β the elements of the list. OutputOutput a single integer, the answer to the problem.ExamplesInput3123 321 555Output292711924Input1999999Output997992010006992Input101 1 1 1 1 1 1 1 1 1Output28160NoteFor the first sample, the nonzero values of G are G(121)β=β144β611β577, G(123)β=β58β401β999, G(321)β=β279β403β857, G(555)β=β170β953β875. The bitwise XOR of these numbers is equal to 292β711β924.For example, , since the subsequences [123] and [123,β555] evaluate to 123 when plugged into f.For the second sample, we have For the last sample, we have , where is the binomial coefficient. | Input3123 321 555 | Output292711924 | 3 seconds | 256 megabytes | ['bitmasks', 'dp', '*2700'] |
C. Vulnerable Kerbalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer m, and a list of n distinct integers between 0 and mβ-β1.You would like to construct a sequence satisfying the properties: Each element is an integer between 0 and mβ-β1, inclusive. All prefix products of the sequence modulo m are distinct. No prefix product modulo m appears as an element of the input list. The length of the sequence is maximized. Construct any sequence satisfying the properties above.InputThe first line of input contains two integers n and m (0ββ€βnβ<βmββ€β200β000)Β β the number of forbidden prefix products and the modulus.If n is non-zero, the next line of input contains n distinct integers between 0 and mβ-β1, the forbidden prefix products. If n is zero, this line doesn't exist.OutputOn the first line, print the number k, denoting the length of your sequence.On the second line, print k space separated integers, denoting your sequence.ExamplesInput0 5Output51 2 4 3 0Input3 102 9 1Output63 9 2 9 8 0NoteFor the first case, the prefix products of this sequence modulo m are [1,β2,β3,β4,β0].For the second case, the prefix products of this sequence modulo m are [3,β7,β4,β6,β8,β0]. | Input0 5 | Output51 2 4 3 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dp', 'graphs', 'math', 'number theory', '*2300'] |
B. Volatile Kitetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a convex polygon P with n distinct vertices p1,βp2,β...,βpn. Vertex pi has coordinates (xi,βyi) in the 2D plane. These vertices are listed in clockwise order.You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.Find the maximum value of D such that no matter how you move the vertices, the polygon does not intersect itself and stays convex.InputThe first line has one integer n (4ββ€βnββ€β1β000)Β β the number of vertices.The next n lines contain the coordinates of the vertices. Line i contains two integers xi and yi (β-β109ββ€βxi,βyiββ€β109)Β β the coordinates of the i-th vertex. These points are guaranteed to be given in clockwise order, and will form a strictly convex polygon (in particular, no three consecutive points lie on the same straight line).OutputPrint one real number D, which is the maximum real number such that no matter how you move the vertices, the polygon stays convex.Your answer will be considered correct if its absolute or relative error does not exceed 10β-β6.Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput40 00 11 11 0Output0.3535533906Input65 010 012 -410 -85 -83 -4Output1.0000000000NoteHere is a picture of the first sampleHere is an example of making the polygon non-convex.This is not an optimal solution, since the maximum distance we moved one point is βββ0.4242640687, whereas we can make it non-convex by only moving each point a distance of at most βββ0.3535533906. | Input40 00 11 11 0 | Output0.3535533906 | 2 seconds | 256 megabytes | ['geometry', '*1800'] |
A. Voltage Keepsaketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n devices that you want to use simultaneously.The i-th device uses ai units of power per second. This usage is continuous. That is, in Ξ» seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for Ξ» seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.InputThe first line contains two integers, n and p (1ββ€βnββ€β100β000, 1ββ€βpββ€β109)Β β the number of devices and the power of the charger.This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1ββ€βai,βbiββ€β100β000)Β β the power of the device and the amount of power stored in the device in the beginning.OutputIf you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.Your answer will be considered correct if its absolute or relative error does not exceed 10β-β4.Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .ExamplesInput2 12 22 1000Output2.0000000000Input1 1001 1Output-1Input3 54 35 26 1Output0.5000000000NoteIn sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.In sample test 2, you can use the device indefinitely.In sample test 3, we can charge the third device for 2β/β5 of a second, then switch to charge the second device for a 1β/β10 of a second. | Input2 12 22 1000 | Output2.0000000000 | 2 seconds | 256 megabytes | ['binary search', 'math', '*1800'] |
F. Bear and Isomorphic Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBearland is a big square on the plane. It contains all points with coordinates not exceeding 106 by the absolute value.There are n houses in Bearland. The i-th of them is located at the point (xi,βyi). The n points are distinct, but some subsets of them may be collinear.Bear Limak lives in the first house. He wants to destroy his house and build a new one somewhere in Bearland.Bears don't like big changes. For every three points (houses) pi, pj and pk, the sign of their cross product (pjβ-βpi)βΓβ(pkβ-βpi) should be the same before and after the relocation. If it was negative/positive/zero, it should still be negative/positive/zero respectively. This condition should be satisfied for all triples of indices (i,βj,βk), possibly equal to each other or different than 1. Additionally, Limak isn't allowed to build the house at the point where some other house already exists (but it can be the point where his old house was).In the formula above, we define the difference and the cross product of points (ax,βay) and (bx,βby) as: (ax,βay)β-β(bx,βby)β=β(axβ-βbx,βayβ-βby),β (ax,βay)βΓβ(bx,βby)β=βaxΒ·byβ-βayΒ·bx.Consider a set of possible new placements of Limak's house. Your task is to find the area of that set of points.Formally, let's say that Limak chooses the new placement randomly (each coordinate is chosen independently uniformly at random from the interval [β-β106,β106]). Let p denote the probability of getting the allowed placement of new house. Let S denote the area of Bearland (Sβ=β4Β·1012). Your task is to find pΒ·S.InputThe first line of the input contains an integer T (1ββ€βTββ€β500)Β β the number of test cases. The description of the test cases follows.The first line of the description of a test case contains an integer n (3ββ€βnββ€β200β000)Β β the number of houses.The i-th of the next n lines contains two integers xi and yi (β-β106ββ€βxi,βyiββ€β106)Β β coordinates of the i-th house. No two houses are located at the same point in the same test case. Limak lives in the first house.The sum of n won't exceed 200β000.OutputPrint one real value, denoting the area of the set of points that are possible new placements of Limak's house.Your answer will be considered correct if its absolute or relative error doesn't exceed 10β-β6. More precisely, let the jury's answer be b, and your answer be a. Then your answer will be accepted if and only if .ExampleInput445 30 110 13 513-999123 700000-950000 123456-950000 98765432 310 -1-4 651 35 26 14 4-3 3Output250.000000000000100000000000.0000000000000.0000000000006.562500000000NoteIn the sample test, there are 4 test cases.In the first test case, there are four houses and Limak's one is in (5,β3). The set of valid new placements form a triangle with vertices in points (0,β1), (10,β1) and (3,β51), without its sides. The area of such a triangle is 250.In the second test case, the set of valid new placements form a rectangle of width 50β000 and height 2β000β000. Don't forget that the new placement must be inside the big square that represents Bearland.In the third test case, the three given points are collinear. Each cross product is equal to 0 and it should be 0 after the relocation as well. Hence, Limak's new house must lie on the line that goes through the given points. Since it must also be inside the big square, new possible placements are limited to some segment (excluding the two points where the other houses are). The area of any segment is 0. | Input445 30 110 13 513-999123 700000-950000 123456-950000 98765432 310 -1-4 651 35 26 14 4-3 3 | Output250.000000000000100000000000.0000000000000.0000000000006.562500000000 | 2 seconds | 256 megabytes | ['geometry', 'two pointers', '*3300'] |
E. Bear and Rectangle Stripstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak has a grid that consists of 2 rows and n columns. The j-th cell in the i-th row contains an integer ti,βj which can be positive, negative or zero.A non-empty rectangle of cells is called nice if and only if the sum of numbers in its cells is equal to 0.Limak wants to choose some nice rectangles and give them to his friends, as gifts. No two chosen rectangles should share a cell. What is the maximum possible number of nice rectangles Limak can choose?InputThe first line of the input contains an integer n (1ββ€βnββ€β300β000)Β β the number of columns in the grid.The next two lines contain numbers in the grid. The i-th of those two lines contains n integers ti,β1,βti,β2,β...,βti,βn (β-β109ββ€βti,βjββ€β109).OutputPrint one integer, denoting the maximum possible number of cell-disjoint nice rectangles.ExamplesInput670 70 70 70 70 -1590 -60 -30 30 -30 15Output3Input40 -1 0 00 0 1 0Output6Input31000000000 999999999 -1000000000999999999 -1000000000 -999999998Output1NoteIn the first sample, there are four nice rectangles: Limak can't choose all of them because they are not disjoint. He should take three nice rectangles: those denoted as blue frames on the drawings.In the second sample, it's optimal to choose six nice rectangles, each consisting of one cell with a number 0.In the third sample, the only nice rectangle is the whole gridΒ β the sum of all numbers is 0. Clearly, Limak can choose at most one nice rectangle, so the answer is 1. | Input670 70 70 70 70 -1590 -60 -30 30 -30 15 | Output3 | 3 seconds | 256 megabytes | ['dp', 'greedy', '*3000'] |
D. Bear and Companytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBear Limak prepares problems for a programming competition. Of course, it would be unprofessional to mention the sponsor name in the statement. Limak takes it seriously and he is going to change some words. To make it still possible to read, he will try to modify each word as little as possible.Limak has a string s that consists of uppercase English letters. In one move he can swap two adjacent letters of the string. For example, he can transform a string "ABBC" into "BABC" or "ABCB" in one move.Limak wants to obtain a string without a substring "VK" (i.e. there should be no letter 'V' immediately followed by letter 'K'). It can be easily proved that it's possible for any initial string s.What is the minimum possible number of moves Limak can do?InputThe first line of the input contains an integer n (1ββ€βnββ€β75)Β β the length of the string.The second line contains a string s, consisting of uppercase English letters. The length of the string is equal to n.OutputPrint one integer, denoting the minimum possible number of moves Limak can do, in order to obtain a string without a substring "VK".ExamplesInput4VKVKOutput3Input5BVVKVOutput2Input7VVKEVKKOutput3Input20VKVKVVVKVOVKVQKKKVVKOutput8Input5LIMAKOutput0NoteIn the first sample, the initial string is "VKVK". The minimum possible number of moves is 3. One optimal sequence of moves is: Swap two last letters. The string becomes "VKKV". Swap first two letters. The string becomes "KVKV". Swap the second and the third letter. The string becomes "KKVV". Indeed, this string doesn't have a substring "VK".In the second sample, there are two optimal sequences of moves. One is "BVVKV"βββββ"VBVKV"βββββ"VVBKV". The other is "BVVKV"βββββ"BVKVV"βββββ"BKVVV".In the fifth sample, no swaps are necessary. | Input4VKVK | Output3 | 1 second | 256 megabytes | ['dp', '*2500'] |
C. Bear and Tree Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.For a pair of vertices (s,βt) we define f(s,βt) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s,βt) over all pairs of vertices (s,βt) such that sβ<βt.InputThe first line of the input contains two integers n and k (2ββ€βnββ€β200β000, 1ββ€βkββ€β5)Β β the number of vertices in the tree and the maximum allowed jump distance respectively.The next nβ-β1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1ββ€βai,βbiββ€βn)Β β the indices on vertices connected with i-th edge.It's guaranteed that the given edges form a tree.OutputPrint one integer, denoting the sum of f(s,βt) over all pairs of vertices (s,βt) such that sβ<βt.ExamplesInput6 21 21 32 42 54 6Output20Input13 31 23 24 25 23 610 66 76 135 85 99 1111 12Output114Input3 52 13 1Output3NoteIn the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). There are pairs of vertices (s,βt) such that sβ<βt. For 5 of those pairs Limak would need two jumps: (1,β6),β(3,β4),β(3,β5),β(3,β6),β(5,β6). For other 10 pairs one jump is enough. So, the answer is 5Β·2β+β10Β·1β=β20.In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (sβ<βt), so the answer is 3Β·1β=β3. | Input6 21 21 32 42 54 6 | Output20 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'trees', '*2100'] |
B. Bear and Different Namestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1, each either "YES" or "NO". The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise). The string s2 describes a group of soldiers 2 through kβ+β1. And so on, till the string snβ-βkβ+β1 that describes a group of soldiers nβ-βkβ+β1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing namesΒ β it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution.InputThe first line of the input contains two integers n and k (2ββ€βkββ€βnββ€β50)Β β the number of soldiers and the size of a group respectively.The second line contains nβ-βkβ+β1 strings s1,βs2,β...,βsnβ-βkβ+β1. The string si is "YES" if the group of soldiers i through iβ+βkβ-β1 is effective, and "NO" otherwise.OutputFind any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10.If there are multiple valid solutions, print any of them.ExamplesInput8 3NO NO YES YES YES NOOutputAdam Bob Bob Cpqepqwer Limak Adam Bob AdamInput9 8YES NOOutputR Q Ccccccccc Ccocc Ccc So Strong Samples CccInput3 2NO NOOutputNa Na NaNoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output: First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO". Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO". Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES". ..., Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO". | Input8 3NO NO YES YES YES NO | OutputAdam Bob Bob Cpqepqwer Limak Adam Bob Adam | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1500'] |
A. Bear and Friendship Conditiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.InputThe first line of the input contain two integers n and m (3ββ€βnββ€β150β000, )Β β the number of members and the number of pairs of members that are friends.The i-th of the next m lines contains two distinct integers ai and bi (1ββ€βai,βbiββ€βn,βaiββ βbi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.OutputIf the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).ExamplesInput4 31 33 41 4OutputYESInput4 43 12 33 41 2OutputNOInput10 44 35 108 91 2OutputYESInput3 21 22 3OutputNONoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2,β3) are friends and members (3,β4) are friends, while members (2,β4) are not. | Input4 31 33 41 4 | OutputYES | 1 second | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1500'] |
D. Draw Brackets!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" β are regular, at the same time "][", "[[]" and "[[]]][" β are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height β use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: +- -++- -+ |+- -++- -+|| ||| || ||| ||+- -++- -+|| |+- -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique. InputThe first line contains an even integer n (2ββ€βnββ€β100) β the length of the sequence of brackets.The second line contains the sequence of brackets β these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular. OutputPrint the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces. ExamplesInput8[[][]][]Output+- -++- -+|+- -++- -+|| ||| || ||| ||+- -++- -+|| |+- -++- -+Input6[[[]]]Output+- -+|+- -+|||+- -+||||| |||||+- -+|||+- -+|+- -+Input6[[][]]Output+- -+|+- -++- -+||| || |||+- -++- -+|+- -+Input2[]Output+- -+| |+- -+Input4[][]Output+- -++- -+| || |+- -++- -+ | Input8[[][]][] | Output+- -++- -+|+- -++- -+|| ||| || ||| ||+- -++- -+|| |+- -++- -+ | 1 second | 256 megabytes | ['*special problem', 'implementation', '*1400'] |
C. Online Courses In BSUtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage.The situation is complicated by the dependence of online courses, for each course there is a list of those that must be passed before starting this online course (the list can be empty, it means that there is no limitation).Help Polycarp to pass the least number of courses in total to get the specialty (it means to pass all main and necessary courses). Write a program which prints the order of courses. Polycarp passes courses consistently, he starts the next course when he finishes the previous one. Each course can't be passed more than once. InputThe first line contains n and k (1ββ€βkββ€βnββ€β105) β the number of online-courses and the number of main courses of Polycarp's specialty. The second line contains k distinct integers from 1 to n β numbers of main online-courses of Polycarp's specialty. Then n lines follow, each of them describes the next course: the i-th of them corresponds to the course i. Each line starts from the integer ti (0ββ€βtiββ€βnβ-β1) β the number of courses on which the i-th depends. Then there follows the sequence of ti distinct integers from 1 to n β numbers of courses in random order, on which the i-th depends. It is guaranteed that no course can depend on itself. It is guaranteed that the sum of all values ti doesn't exceed 105. OutputPrint -1, if there is no the way to get a specialty. Otherwise, in the first line print the integer m β the minimum number of online-courses which it is necessary to pass to get a specialty. In the second line print m distinct integers β numbers of courses which it is necessary to pass in the chronological order of their passage. If there are several answers it is allowed to print any of them.ExamplesInput6 25 30002 2 11 41 5Output51 2 3 4 5 Input9 33 9 5003 9 4 5001 81 61 22 1 2Output61 2 9 4 5 3 Input3 31 2 31 21 31 1Output-1NoteIn the first test firstly you can take courses number 1 and 2, after that you can take the course number 4, then you can take the course number 5, which is the main. After that you have to take only the course number 3, which is the last not passed main course. | Input6 25 30002 2 11 41 5 | Output51 2 3 4 5 | 2 seconds | 256 megabytes | ['*special problem', 'dfs and similar', 'graphs', 'implementation', '*1500'] |
B. Maximize Sum of Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits.Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. InputThe first line contains the positive integer x (1ββ€βxββ€β1018) β the integer which Anton has. OutputPrint the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros.ExamplesInput100Output99Input48Output48Input521Output499 | Input100 | Output99 | 1 second | 256 megabytes | ['*special problem', 'implementation', 'math', '*1300'] |
A. New Passwordtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInnokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: the length of the password must be equal to n, the password should consist only of lowercase Latin letters, the number of distinct symbols in the password must be equal to k, any two consecutive symbols in the password must be distinct. Your task is to help Innokentiy and to invent a new password which will satisfy all given conditions. InputThe first line contains two positive integers n and k (2ββ€βnββ€β100, 2ββ€βkββ€βmin(n,β26)) β the length of the password and the number of distinct symbols in it. Pay attention that a desired new password always exists.OutputPrint any password which satisfies all conditions given by Innokentiy.ExamplesInput4 3OutputjavaInput6 6OutputpythonInput5 2OutputphphpNoteIn the first test there is one of the appropriate new passwords β java, because its length is equal to 4 and 3 distinct lowercase letters a, j and v are used in it.In the second test there is one of the appropriate new passwords β python, because its length is equal to 6 and it consists of 6 distinct lowercase letters.In the third test there is one of the appropriate new passwords β phphp, because its length is equal to 5 and 2 distinct lowercase letters p and h are used in it.Pay attention the condition that no two identical symbols are consecutive is correct for all appropriate passwords in tests. | Input4 3 | Outputjava | 1 second | 256 megabytes | ['*special problem', 'implementation', '*800'] |
D. k-Interesting Pairs Of Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if kβ=β2, the pair of integers xβ=β5 and yβ=β3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that iβ<βj and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number.InputThe first line contains two integers n and k (2ββ€βnββ€β105, 0ββ€βkββ€β14) β the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ.The second line contains the sequence a1,βa2,β...,βan (0ββ€βaiββ€β104), which Vasya has.OutputPrint the number of pairs (i, j) so that iβ<βj and the pair of integers ai and aj is k-interesting.ExamplesInput4 10 3 2 1Output4Input6 0200 100 100 100 200 200Output6NoteIn the first test there are 4 k-interesting pairs: (1, 3), (1, 4), (2, 3), (2, 4). In the second test kβ=β0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs: (1, 5), (1, 6), (2, 3), (2, 4), (3, 4), (5, 6). | Input4 10 3 2 1 | Output4 | 2 seconds | 256 megabytes | ['*special problem', 'bitmasks', 'brute force', 'meet-in-the-middle', '*1700'] |
C. Cycle In Mazetime limit per test15 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Robot is in a rectangular maze of size nβΓβm. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.InputThe first line contains three integers n, m and k (1ββ€βn,βmββ€β1000, 1ββ€βkββ€β106) β the size of the maze and the length of the cycle. Each of the following n lines contains m symbols β the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once. OutputPrint the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).ExamplesInput2 3 2.**X..OutputRLInput5 6 14..***.*...X...*.....*.**....*.OutputDLDDLLLRRRUURUInput3 3 4****X****OutputIMPOSSIBLENoteIn the first sample two cyclic ways for the Robot with the length 2 exist β "UD" and "RL". The second cycle is lexicographically less. In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up. In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | Input2 3 2.**X.. | OutputRL | 15 seconds | 256 megabytes | ['*special problem', 'dfs and similar', 'graphs', 'greedy', 'shortest paths', '*1700'] |
B. News About Credittime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai β the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that: the student i sends no more than ai messages (for all i from 1 to n); all students knew the news about the credit (initially only Polycarp knew it); the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above. InputThe first line contains the positive integer n (2ββ€βnββ€β100) β the number of students. The second line contains the sequence a1,βa2,β...,βan (0ββ€βaiββ€β100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.OutputPrint -1 to the first line if it is impossible to inform all students about credit. Otherwise, in the first line print the integer k β the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit. If there are several answers, it is acceptable to print any of them. ExamplesInput41 2 1 0Output31 22 42 3Input62 0 1 3 2 0Output61 33 41 24 55 64 6Input30 2 2Output-1NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit. | Input41 2 1 0 | Output31 22 42 3 | 1 second | 256 megabytes | ['*special problem', 'greedy', 'two pointers', '*1200'] |
A. Year of University Entrancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university. Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than x from the year of university entrance of this student, where x β some non-negative integer. A value x is not given, but it can be uniquely determined from the available data. Note that students don't join other groups. You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.InputThe first line contains the positive odd integer n (1ββ€βnββ€β5) β the number of groups which Igor joined. The next line contains n distinct integers a1,βa2,β...,βan (2010ββ€βaiββ€β2100) β years of student's university entrance for each group in which Igor is the member.It is guaranteed that the input data is correct and the answer always exists. Groups are given randomly.OutputPrint the year of Igor's university entrance. ExamplesInput32014 2016 2015Output2015Input12050Output2050NoteIn the first test the value xβ=β1. Igor entered the university in 2015. So he joined groups members of which are students who entered the university in 2014, 2015 and 2016.In the second test the value xβ=β0. Igor entered only the group which corresponds to the year of his university entrance. | Input32014 2016 2015 | Output2015 | 1 second | 256 megabytes | ['*special problem', 'implementation', 'sortings', '*800'] |
G. The Winds of Wintertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a rooted tree with n nodes. The Night King removes exactly one node from the tree and all the edges associated with it. Doing this splits the tree and forms a forest. The node which is removed is not a part of the forest.The root of a tree in the forest is the node in that tree which does not have a parent. We define the strength of the forest as the size of largest tree in forest.Jon Snow wants to minimize the strength of the forest. To do this he can perform the following operation at most once.He removes the edge between a node and its parent and inserts a new edge between this node and any other node in forest such that the total number of trees in forest remain same.For each node v you need to find the minimum value of strength of the forest formed when node v is removed.InputThe first line of the input contains an integer n (1βββ€ββnβββ€ββ105) β the number of vertices in the tree. Each of the next n lines contains a pair of vertex indices ui and vi (1βββ€ββui,ββviβββ€ββn) where ui is the parent of vi. If uiβ=β0 then vi is the root.OutputPrint n line each containing a single integer. The i-th of them should be equal to minimum value of strength of forest formed when i-th node is removed and Jon Snow performs the operation described above at most once.ExamplesInput100 11 21 31 42 52 63 74 84 95 10Output3455599999Input22 10 2Output11NoteThe tree for first test case is depicted below. When you remove the first node, the tree splits to form the following forest. The strength of this forest is 4. Jon Snow now changes the parent of vertex 10 from 5 to 3. The strength of forest now becomes 3. | Input100 11 21 31 42 52 63 74 84 95 10 | Output3455599999 | 2 seconds | 512 megabytes | ['binary search', 'data structures', '*3300'] |
F. Barrels and boxestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two stacks of wine barrels are together.The height of a stack is defined as the number of items in the stack. Two stacks are considered different if either their heights are different or one of them contains food and other contains wine.Jon Snow doesn't like an arrangement if any stack of wine barrels has height less than or equal to h. What is the probability that Jon Snow will like the arrangement if all arrangement are equiprobably?Two arrangement of stacks are considered different if exists such i, that i-th stack of one arrangement is different from the i-th stack of the other arrangement.InputThe first line of input contains three integers f, w, h (0ββ€βf,βw,βhββ€β105) β number of food boxes, number of wine barrels and h is as described above. It is guaranteed that he has at least one food box or at least one wine barrel.OutputOutput the probability that Jon Snow will like the arrangement. The probability is of the form , then you need to output a single integer pΒ·qβ-β1 mod (109β+β7).ExamplesInput1 1 1Output0Input1 2 1Output666666672NoteIn the first example fββ=ββ1, wβ=β1 and hβ=β1, there are only two possible arrangement of stacks and Jon Snow doesn't like any of them.In the second example fβ=β1, wβ=β2 and hβ=β1, there are three arrangements. Jon Snow likes the (1) and (3) arrangement. So the probabilty is . | Input1 1 1 | Output0 | 2 seconds | 256 megabytes | ['brute force', 'combinatorics', 'math', 'number theory', 'probabilities', '*2300'] |
E. Game of Stonestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones. The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move. The player who is unable to make a move loses.Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again.Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.InputFirst line consists of a single integer n (1ββ€βnββ€β106) β the number of piles.Each of next n lines contains an integer si (1ββ€βsiββ€β60) β the number of stones in i-th pile.OutputPrint a single line containing "YES" (without quotes) if Jon wins, otherwise print "NO" (without quotes)ExamplesInput15OutputNOInput212OutputYESNoteIn the first case, Sam removes all the stones and Jon loses.In second case, the following moves are possible by Sam: In each of these cases, last move can be made by Jon to win the game as follows: | Input15 | OutputNO | 3 seconds | 256 megabytes | ['bitmasks', 'dp', 'games', '*2100'] |
D. Jon and Orbstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he wants to know the minimum number of days he should wait before sending a ranger to collect the orbs such that the probability of him getting at least one of each kind of orb is at least , where Ξ΅β<β10β-β7.To better prepare himself, he wants to know the answer for q different values of pi. Since he is busy designing the battle strategy with Sam, he asks you for your help.InputFirst line consists of two space separated integers k, q (1ββ€βk,βqββ€β1000) β number of different kinds of orbs and number of queries respectively.Each of the next q lines contain a single integer pi (1ββ€βpiββ€β1000) β i-th query.OutputOutput q lines. On i-th of them output single integer β answer for i-th query.ExamplesInput1 11Output1Input2 212Output22 | Input1 11 | Output1 | 2 seconds | 256 megabytes | ['dp', 'math', 'probabilities', '*2200'] |
C. Jon Snow and his Favourite Numbertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now thinks that if he takes the bitwise XOR of strengths of some of rangers with his favourite number x, he might get soldiers of high strength. So, he decided to do the following operation k times: Arrange all the rangers in a straight line in the order of increasing strengths. Take the bitwise XOR (is written as ) of the strength of each alternate ranger with x and update it's strength. Suppose, Jon has 5 rangers with strengths [9,β7,β11,β15,β5] and he performs the operation 1 time with xβ=β2. He first arranges them in the order of their strengths, [5,β7,β9,β11,β15]. Then he does the following: The strength of first ranger is updated to , i.e. 7. The strength of second ranger remains the same, i.e. 7. The strength of third ranger is updated to , i.e. 11. The strength of fourth ranger remains the same, i.e. 11. The strength of fifth ranger is updated to , i.e. 13. The new strengths of the 5 rangers are [7,β7,β11,β11,β13]Now, Jon wants to know the maximum and minimum strength of the rangers after performing the above operations k times. He wants your help for this task. Can you help him?InputFirst line consists of three integers n, k, x (1ββ€βnββ€β105, 0ββ€βkββ€β105, 0ββ€βxββ€β103) β number of rangers Jon has, the number of times Jon will carry out the operation and Jon's favourite number respectively.Second line consists of n integers representing the strengths of the rangers a1,βa2,β...,βan (0ββ€βaiββ€β103).OutputOutput two integers, the maximum and the minimum strength of the rangers after performing the operation k times.ExamplesInput5 1 29 7 11 15 5Output13 7Input2 100000 569605 986Output986 605 | Input5 1 29 7 11 15 5 | Output13 7 | 4 seconds | 256 megabytes | ['brute force', 'dp', 'implementation', 'sortings', '*1800'] |
B. Code For 1time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility. Initially Sam has a list with a single element n. Then he has to perform certain operations on this list. In each operation Sam must remove any element x, such that xβ>β1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.Now the masters want the total number of 1s in the range l to r (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?InputThe first line contains three integers n, l, r (0ββ€βnβ<β250, 0ββ€βrβ-βlββ€β105, rββ₯β1, lββ₯β1) β initial element and the range l to r.It is guaranteed that r is not greater than the length of the final list.OutputOutput the total number of 1s in the range l to r in the final sequence.ExamplesInput7 2 5Output4Input10 3 10Output5NoteConsider first example:Elements on positions from 2-nd to 5-th in list is [1,β1,β1,β1]. The number of ones is 4.For the second example:Elements on positions from 3-rd to 10-th in list is [1,β1,β1,β0,β1,β0,β1,β0]. The number of ones is 5. | Input7 2 5 | Output4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'divide and conquer', '*1600'] |
Subsets and Splits