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. The Contesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lxββ€βTββ€βrx.Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.InputThe first line contains one integer nΒ (1ββ€βnββ€β1000) β the number of problems. The second line contains n integers aiΒ (1ββ€βaiββ€β105) β the time Pasha needs to solve ith problem.The third line contains one integer mΒ (0ββ€βmββ€β1000) β the number of periods of time when the website is working. Next m lines represent these periods. jth line contains two numbers lj and rjΒ (1ββ€βljβ<βrjββ€β105) β the starting and the ending moment of jth period.It is guaranteed that the periods are not intersecting and are given in chronological order, so for every jβ>β1 the condition ljβ>βrjβ-β1 is met.OutputIf Pasha can solve and submit all the problems before the end of the contest, print the minimal moment of time by which he can have all the solutions submitted.Otherwise print "-1" (without brackets).ExamplesInput23 421 47 9Output7Input1511 4Output-1Input1511 5Output5NoteIn the first example Pasha can act like this: he solves the second problem in 4 units of time and sends it immediately. Then he spends 3 time units to solve the first problem and sends it 7 time units after the contest starts, because at this moment the website starts working again.In the second example Pasha invents the solution only after the website stops working for the last time.In the third example Pasha sends the solution exactly at the end of the first period. | Input23 421 47 9 | Output7 | 2 seconds | 256 megabytes | ['implementation', '*1100'] |
E. Sagheer and Apple Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u,βv) and (v,βu) are considered to be the same pair.InputThe first line will contain one integer n (2ββ€βnββ€β105) β the number of nodes in the apple tree.The second line will contain n integers a1,βa2,β...,βan (1ββ€βaiββ€β107) β the number of apples on each node of the tree.The third line will contain nβ-β1 integers p2,βp3,β...,βpn (1ββ€βpiββ€βn) β the parent of each node of the tree. Node i has parent pi (for 2ββ€βiββ€βn). Node 1 is the root of the tree.It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.OutputOn a single line, print the number of different pairs of nodes (u,βv), uββ βv such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u,βv) and (v,βu) are considered to be the same pair.ExamplesInput32 2 31 1Output1Input31 2 31 1Output0Input87 2 2 5 4 3 1 11 1 1 4 4 5 6Output4NoteIn the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.In the second sample, There is no swap that will make Sagheer win the game.Note that Sagheer must make the swap even if he can win with the initial tree. | Input32 2 31 1 | Output1 | 2 seconds | 256 megabytes | ['games', 'trees', '*2300'] |
D. Sagheer and Kindergartentime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys: Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set. If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever. Children request toys at distinct moments of time. No two children request a toy at the same time. If a child is granted a toy, he never gives it back until he finishes playing with his lovely set. If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting. If two children are waiting for the same toy, then the child who requested it first will take the toy first.Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request.InputThe first line contains four integers n, m, k, q (1ββ€βn,βm,βk,βqββ€β105)Β β the number of children, toys, scenario requests and queries.Each of the next k lines contains two integers a, b (1ββ€βaββ€βn and 1ββ€βbββ€βm)Β β a scenario request meaning child a requests toy b. The requests are given in the order they are made by children.Each of the next q lines contains two integers x, y (1ββ€βxββ€βn and 1ββ€βyββ€βm)Β β the request to be added to the scenario meaning child x will request toy y just after getting the toy he is waiting for (if any).It is guaranteed that the scenario requests are consistent and no child is initially crying. All the scenario requests are distinct and no query coincides with a scenario request.OutputFor each query, print on a single line the number of children who will start crying when child x makes his last request for toy y. Please answer all queries independent of each other.ExamplesInput3 3 5 11 12 23 31 22 33 1Output3Input5 4 7 21 12 22 15 13 34 44 15 35 4Output02NoteIn the first example, child 1 is waiting for toy 2, which child 2 has, while child 2 is waiting for top 3, which child 3 has. When child 3 makes his last request, the toy he requests is held by child 1. Each of the three children is waiting for a toy held by another child and no one is playing, so all the three will start crying.In the second example, at the beginning, child i is holding toy i for 1ββ€βiββ€β4. Children 1 and 3 have completed their lovely sets. After they finish playing, toy 3 will be free while toy 1 will be taken by child 2 who has just completed his lovely set. After he finishes, toys 1 and 2 will be free and child 5 will take toy 1. Now: In the first query, child 5 will take toy 3 and after he finishes playing, child 4 can play. In the second query, child 5 will request toy 4 which is held by child 4. At the same time, child 4 is waiting for toy 1 which is now held by child 5. None of them can play and they will start crying. | Input3 3 5 11 12 23 31 22 33 1 | Output3 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', 'trees', '*2700'] |
C. Sagheer and Nubian Markettime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1,βx2,β...,βxk, then the cost of item xj is axjβ+βxjΒ·k for 1ββ€βjββ€βk. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?InputThe first line contains two integers n and S (1ββ€βnββ€β105 and 1ββ€βSββ€β109)Β β the number of souvenirs in the market and Sagheer's budget.The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β105)Β β the base costs of the souvenirs.OutputOn a single line, print two integers k, TΒ β the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.ExamplesInput3 112 3 5Output2 11Input4 1001 2 5 6Output4 54Input1 77Output0 0NoteIn the first example, he cannot take the three items because they will cost him [5,β9,β14] with total cost 28. If he decides to take only two items, then the costs will be [4,β7,β11]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5,β10,β17,β22].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it. | Input3 112 3 5 | Output2 11 | 2 seconds | 256 megabytes | ['binary search', 'sortings', '*1500'] |
B. Sagheer, the Hausmeistertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSome people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and mβ+β2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.InputThe first line contains two integers n and m (1ββ€βnββ€β15 and 1ββ€βmββ€β100) β the number of floors and the number of rooms in each floor, respectively.The next n lines contains the building description. Each line contains a binary string of length mβ+β2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor.The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.OutputPrint a single integer β the minimum total time needed to turn off all the lights.ExamplesInput2 200100100Output5Input3 4001000000010000010Output12Input4 301110011100111001110Output18NoteIn the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor. | Input2 200100100 | Output5 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'dp', '*1600'] |
A. Sagheer and Crossroadstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane getting into the intersection (l β left, s β straight, r β right) and a light p for a pedestrian crossing. An accident is possible if a car can hit a pedestrian. This can happen if the light of a pedestrian crossing of some part and the light of a lane that can get to or from that same part are green at the same time.Now, Sagheer is monitoring the configuration of the traffic lights. Your task is to help him detect whether an accident is possible.InputThe input consists of four lines with each line describing a road part given in a counter-clockwise order.Each line contains four integers l, s, r, p β for the left, straight, right and pedestrian lights, respectively. The possible values are 0 for red light and 1 for green light.OutputOn a single line, print "YES" if an accident is possible, and "NO" otherwise.ExamplesInput1 0 0 10 1 0 00 0 1 00 0 0 1OutputYESInput0 1 1 01 0 1 01 1 0 00 0 0 1OutputNOInput1 0 0 00 0 0 10 0 0 01 0 1 0OutputNONoteIn the first example, some accidents are possible because cars of part 1 can hit pedestrians of parts 1 and 4. Also, cars of parts 2 and 3 can hit pedestrians of part 4.In the second example, no car can pass the pedestrian crossing of part 4 which is the only green pedestrian light. So, no accident can occur. | Input1 0 0 10 1 0 00 0 1 00 0 0 1 | OutputYES | 1 second | 256 megabytes | ['implementation', '*1200'] |
E. Vladik and Entertaining Flagstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix nβΓβm which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1,βl) and (n,βr), where conditions 1ββ€βlββ€βrββ€βm are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.InputFirst line contains three space-separated integers n, m, q (1ββ€βnββ€β10, 1ββ€βm,βqββ€β105)Β β dimensions of flag matrix and number of segments respectively.Each of next n lines contains m space-separated integersΒ β description of flag matrix. All elements of flag matrix is positive integers not exceeding 106.Each of next q lines contains two space-separated integers l, r (1ββ€βlββ€βrββ€βm)Β β borders of segment which beauty Vladik wants to know.OutputFor each segment print the result on the corresponding line.ExampleInput4 5 41 1 1 1 11 2 2 3 31 1 1 2 54 4 5 5 51 52 51 24 5Output6734NotePartitioning on components for every segment from first test case: | Input4 5 41 1 1 1 11 2 2 3 31 1 1 2 54 4 5 5 51 52 51 24 5 | Output6734 | 2 seconds | 256 megabytes | ['data structures', 'dsu', 'graphs', '*2600'] |
D. Vladik and Favorite Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Vladik has favorite game, in which he plays all his free time.Game field could be represented as nβΓβm matrix which consists of cells of three types: Β«.Β» β normal cell, player can visit it. Β«FΒ» β finish cell, player has to finish his way there to win. There is exactly one cell of this type. Β«*Β» β dangerous cell, if player comes to this cell, he loses. Initially player is located in the left top cell with coordinates (1,β1). Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.But itβs not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.Help Vladik win the game!InputFirst line contains two space-separated integers n and m (1ββ€βn,βmββ€β100) β number of rows and columns respectively.Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above.Guaranteed that cell with coordinates (1,β1) is normal and there is at least one way from initial cell to finish cell without dangerous cells. InteractionYou can press buttons no more than 2Β·nΒ·m times.To press a button you should print "U", "D", "L", "R" in new line. Itβs necessary to print newline character and flush output. After flushing buffer you should read answer from input data. Answer is the pair of space-separated integers x, y β new position of player. In case, if there is no cell in direction of moving, position will not change. If after any move player lost, in other words player move to dangerous cell, then x and y will be equal to β-β1.If after any move player is in finish or dangerous cell, then you should terminate your program.To finish output buffer (i. e. for operation flush) right after printing direction and newline you should do next: fflush(stdout) in C++ System.out.flush() in Java stdout.flush() in Python flush(output) in Pascal read documentation for other languages. Hacks To perform a hack you should use this format:n m swapLR swapUD a_1 a_2 ... a_n Where n, mΒ β number of rows and columns in game field. swapLR is equal to 1 in case, when directions "Lββ and "Rββ is swapped, and equal to 0 otherwise. swapUD is equal to 1, when directions "Uββ and "Dββ is swapped, and equal to 0 otherwise. a1,βa2,β...,βan β description of corresponding rows of game field.ExampleInput4 3...**.F*....1 11 21 31 32 33 34 34 24 13 1OutputRLLDUUURRDNoteIn first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:This test could be presenter for hack in following way: 4 3 1 1...**.F*.... | Input4 3...**.F*....1 11 21 31 32 33 34 34 24 13 1 | OutputRLLDUUURRD | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', 'interactive', '*2100'] |
C. Vladik and Memorable Triptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they canβt belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.InputFirst line contains single integer n (1ββ€βnββ€β5000)Β β number of people.Second line contains n space-separated integers a1,βa2,β...,βan (0ββ€βaiββ€β5000), where ai denotes code of the city to which i-th person is going.OutputThe output should contain a single integerΒ β maximal possible total comfort.ExamplesInput64 4 2 5 2 3Output14Input95 1 3 1 5 2 4 2 5Output9NoteIn the first test case best partition into segments is: [4,β4] [2,β5,β2] [3], answer is calculated as follows: 4β+β(2 xor 5)β+β3β=β4β+β7β+β3β=β14In the second test case best partition into segments is: 5 1 [3] 1 5 [2,β4,β2] 5, answer calculated as follows: 3β+β(2 xor 4)β=β3β+β6β=β9. | Input64 4 2 5 2 3 | Output14 | 2 seconds | 256 megabytes | ['dp', 'implementation', '*1900'] |
B. Vladik and Complicated Booktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation Pβ=β[p1,βp2,β...,βpn], where pi denotes the number of page that should be read i-th in turn.Sometimes Vladikβs mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number xΒ β what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has px changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.InputFirst line contains two space-separated integers n, m (1ββ€βn,βmββ€β104)Β β length of permutation and number of times Vladik's mom sorted some subsegment of the book.Second line contains n space-separated integers p1,βp2,β...,βpn (1ββ€βpiββ€βn)Β β permutation P. Note that elements in permutation are distinct.Each of the next m lines contains three space-separated integers li, ri, xi (1ββ€βliββ€βxiββ€βriββ€βn)Β β left and right borders of sorted subsegment in i-th sorting and position that is interesting to Vladik.OutputFor each momβs sorting on itβs own line print "Yes", if page which is interesting to Vladik hasn't changed, or "No" otherwise.ExamplesInput5 55 4 3 2 11 5 31 3 12 4 34 4 42 5 3OutputYesNoYesYesNoInput6 51 4 3 2 5 62 4 31 6 24 5 41 3 32 6 3OutputYesNoYesNoYesNoteExplanation of first test case: [1,β2,β3,β4,β5]Β β permutation after sorting, 3-rd element hasnβt changed, so answer is "Yes". [3,β4,β5,β2,β1]Β β permutation after sorting, 1-st element has changed, so answer is "No". [5,β2,β3,β4,β1]Β β permutation after sorting, 3-rd element hasnβt changed, so answer is "Yes". [5,β4,β3,β2,β1]Β β permutation after sorting, 4-th element hasnβt changed, so answer is "Yes". [5,β1,β2,β3,β4]Β β permutation after sorting, 3-rd element has changed, so answer is "No". | Input5 55 4 3 2 11 5 31 3 12 4 34 4 42 5 3 | OutputYesNoYesYesNo | 2 seconds | 256 megabytes | ['implementation', 'sortings', '*1200'] |
A. Vladik and Courtesytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.More formally, the guys take turns giving each other one candy more than they received in the previous turn.This continued until the moment when one of them couldnβt give the right amount of candy. Candies, which guys got from each other, they donβt consider as their own. You need to know, who is the first who canβt give the right amount of candy.InputSingle line of input data contains two space-separated integers a, b (1ββ€βa,βbββ€β109) β number of Vladik and Valera candies respectively.OutputPring a single line "Vladikββ in case, if Vladik first who canβt give right amount of candy, or "Valeraββ otherwise.ExamplesInput1 1OutputValeraInput7 6OutputVladikNoteIllustration for first test case:Illustration for second test case: | Input1 1 | OutputValera | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*800'] |
B. Summer sell-offtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSummer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2Β·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.InputThe first line contains two integers n and f (1ββ€βnββ€β105,β0ββ€βfββ€βn) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out.Each line of the following n subsequent lines contains two integers ki,βli (0ββ€βki,βliββ€β109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.OutputPrint a single integer denoting the maximal number of products that shop can sell.ExamplesInput4 22 13 52 31 5Output10Input4 10 20 33 50 6Output5NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2,β6,β2,β2] respectively. So on the first day shop will sell 1 product, on the secondΒ β 5, on the thirdΒ β 2, on the fourthΒ β 2. In total 1β+β5β+β2β+β2β=β10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out. | Input4 22 13 52 31 5 | Output10 | 1 second | 256 megabytes | ['greedy', 'sortings', '*1300'] |
A. Straight Β«AΒ»time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNoora is a student of one famous high school. It's her final year in schoolΒ β she is going to study in university next year. However, she has to get an Β«AΒ» graduation certificate in order to apply to a prestigious one.In school, where Noora is studying, teachers are putting down marks to the online class register, which are integers from 1 to k. The worst mark is 1, the best is k. Mark that is going to the certificate, is calculated as an average of all the marks, rounded to the closest integer. If several answers are possible, rounding up is produced. For example, 7.3 is rounded to 7, but 7.5 and 7.8784Β β to 8. For instance, if Noora has marks [8,β9], then the mark to the certificate is 9, because the average is equal to 8.5 and rounded to 9, but if the marks are [8,β8,β9], Noora will have graduation certificate with 8.To graduate with Β«AΒ» certificate, Noora has to have mark k.Noora got n marks in register this year. However, she is afraid that her marks are not enough to get final mark k. Noora decided to ask for help in the internet, where hacker Leha immediately responded to her request. He is ready to hack class register for Noora and to add Noora any number of additional marks from 1 to k. At the same time, Leha want his hack be unseen to everyone, so he decided to add as less as possible additional marks. Please help Leha to calculate the minimal number of marks he has to add, so that final Noora's mark will become equal to k.InputThe first line contains two integers n and k (1ββ€βnββ€β100,β1ββ€βkββ€β100) denoting the number of marks, received by Noora and the value of highest possible mark.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€βk) denoting marks received by Noora before Leha's hack.OutputPrint a single integerΒ β minimal number of additional marks, that Leha has to add in order to change Noora's final mark to k.ExamplesInput2 108 9Output4Input3 54 4 4Output3NoteConsider the first example testcase.Maximal mark is 10, Noora received two marksΒ β 8 and 9, so current final mark is 9. To fix it, Leha can add marks [10,β10,β10,β10] (4 marks in total) to the registry, achieving Noora having average mark equal to . Consequently, new final mark is 10. Less number of marks won't fix the situation.In the second example Leha can add [5,β5,β5] to the registry, so that making average mark equal to 4.5, which is enough to have 5 in the certificate. | Input2 108 9 | Output4 | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
E. Surprise me!time limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring dates, Leha and Noora decided to play a game.Leha found a tree with n vertices numbered from 1 to n. We remind you that tree is an undirected graph without cycles. Each vertex v of a tree has a number av written on it. Quite by accident it turned out that all values written on vertices are distinct and are natural numbers between 1 and n.The game goes in the following way. Noora chooses some vertex u of a tree uniformly at random and passes a move to Leha. Leha, in his turn, chooses (also uniformly at random) some vertex v from remaining vertices of a tree (vββ βu). As you could guess there are n(nβ-β1) variants of choosing vertices by players. After that players calculate the value of a function f(u,βv)β=βΟ(auΒ·av) Β· d(u,βv) of the chosen vertices where Ο(x) is Euler's totient function and d(x,βy) is the shortest distance between vertices x and y in a tree.Soon the game became boring for Noora, so Leha decided to defuse the situation and calculate expected value of function f over all variants of choosing vertices u and v, hoping of at least somehow surprise the girl.Leha asks for your help in calculating this expected value. Let this value be representable in the form of an irreducible fraction . To further surprise Noora, he wants to name her the value . Help Leha!InputThe first line of input contains one integer number n (2ββ€βnββ€β2Β·105) Β β number of vertices in a tree.The second line contains n different numbers a1,βa2,β...,βan (1ββ€βaiββ€βn) separated by spaces, denoting the values written on a tree vertices.Each of the next nβ-β1 lines contains two integer numbers x and y (1ββ€βx,βyββ€βn), describing the next edge of a tree. It is guaranteed that this set of edges describes a tree.OutputIn a single line print a number equal to PΒ·Qβ-β1 modulo 109β+β7.ExamplesInput31 2 31 22 3Output333333338Input55 4 3 1 23 51 24 32 5Output8NoteEuler's totient function Ο(n) is the number of such i that 1ββ€βiββ€βn,and gcd(i,βn)β=β1, where gcd(x,βy) is the greatest common divisor of numbers x and y.There are 6 variants of choosing vertices by Leha and Noora in the first testcase: uβ=β1, vβ=β2, f(1,β2)β=βΟ(a1Β·a2)Β·d(1,β2)β=βΟ(1Β·2)Β·1β=βΟ(2)β=β1 uβ=β2, vβ=β1, f(2,β1)β=βf(1,β2)β=β1 uβ=β1, vβ=β3, f(1,β3)β=βΟ(a1Β·a3)Β·d(1,β3)β=βΟ(1Β·3)Β·2β=β2Ο(3)β=β4 uβ=β3, vβ=β1, f(3,β1)β=βf(1,β3)β=β4 uβ=β2, vβ=β3, f(2,β3)β=βΟ(a2Β·a3)Β·d(2,β3)β=βΟ(2Β·3)Β·1β=βΟ(6)β=β2 uβ=β3, vβ=β2, f(3,β2)β=βf(2,β3)β=β2 Expected value equals to . The value Leha wants to name Noora is 7Β·3β-β1β=β7Β·333333336β=β333333338 .In the second testcase expected value equals to , so Leha will have to surprise Hoora by number 8Β·1β-β1β=β8 . | Input31 2 31 22 3 | Output333333338 | 8 seconds | 256 megabytes | ['divide and conquer', 'math', 'number theory', 'trees', '*3100'] |
D. Hitchhiking in the Baltic Statestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking.In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri.What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li,βri]. After that Noora choses some subsequence of towns id1,βid2,β...,βidk, which friends are going to visit, that at first they are strictly increasing, i.e idiβ<βidiβ+β1 is for all integers i from 1 to kβ-β1, but also the dates of the friends visits are strictly increasing, i.e xidiβ<βxidiβ+β1 is true for all integers i from 1 to kβ-β1.Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1,βid2,β...,βidk, so that friends can visit maximal number of towns.You may assume, that Leha and Noora can start the trip any day.InputThe first line contains a single integer n (1ββ€βnββ€β3Β·105) denoting the number of towns Leha and Noora intended to visit.Each line i of the n subsequent lines contains two integers li, ri (1ββ€βliββ€βriββ€β109), denoting that sights in i-th town are open for visitors on any day .OutputPrint a single integer denoting the maximal number of towns, that Leha and Noora can visit.ExampleInput56 61 23 42 21 4Output3NoteConsider the first example.Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. | Input56 61 23 42 21 4 | Output3 | 2 seconds | 256 megabytes | ['data structures', 'dp', '*2900'] |
C. Find a cartime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.Formally the parking can be represented as a matrix 109βΓβ109. There is exactly one car in every cell of the matrix. All cars have their own machine numbers represented as a positive integer. Let's index the columns of the matrix by integers from 1 to 109 from left to right and the rows by integers from 1 to 109 from top to bottom. By coincidence it turned out, that for every cell (x,βy) the number of the car, which stands in this cell, is equal to the minimum positive integer, which can't be found in the cells (i,βy) and (x,βj), 1ββ€βiβ<βx,β1ββ€βjβ<βy. The upper left fragment 5βΓβ5 of the parking Leha wants to ask the watchman q requests, which can help him to find his car. Every request is represented as five integers x1,βy1,βx2,βy2,βk. The watchman have to consider all cells (x,βy) of the matrix, such that x1ββ€βxββ€βx2 and y1ββ€βyββ€βy2, and if the number of the car in cell (x,βy) does not exceed k, increase the answer to the request by the number of the car in cell (x,βy). For each request Leha asks the watchman to tell him the resulting sum. Due to the fact that the sum can turn out to be quite large, hacker asks to calculate it modulo 109β+β7.However the requests seem to be impracticable for the watchman. Help the watchman to answer all Leha's requests.InputThe first line contains one integer q (1ββ€βqββ€β104)Β β the number of Leha's requests.The next q lines contain five integers x1,βy1,βx2,βy2,βk (1ββ€βx1ββ€βx2ββ€β109,β1ββ€βy1ββ€βy2ββ€β109,β1ββ€βkββ€β2Β·109)Β β parameters of Leha's requests.OutputPrint exactly q linesΒ β in the first line print the answer to the first request, in the secondΒ β the answer to the second request and so on.ExampleInput41 1 1 1 13 2 5 4 51 1 5 5 100001 4 2 5 2Output113930NoteLet's analyze all the requests. In each case the requested submatrix is highlighted in blue.In the first request (kβ=β1) Leha asks only about the upper left parking cell. In this cell the car's number is 1. Consequentally the answer is 1.In the second request (kβ=β5) suitable numbers are 4,β1,β2,β3,β2,β1. Consequentally the answer is 4β+β1β+β2β+β3β+β2β+β1β=β13.In the third request (kβ=β10000) Leha asks about the upper left frament 5βΓβ5 of the parking. Since k is big enough, the answer is equal to 93.In the last request (kβ=β2) none of the cur's numbers are suitable, so the answer is 0. | Input41 1 1 1 13 2 5 4 51 1 5 5 100001 4 2 5 2 | Output113930 | 4 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'dp', '*2600'] |
B. Glad to see you!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. In the output section below you will see the information about flushing the output.On Sunday Leha the hacker took Nura from the house where she lives and went with her to one of the most luxurious restaurants in ViΔkopolis. Upon arrival, they left the car in a huge parking lot near the restaurant and hurried inside the building.In the restaurant a polite waiter immediately brought the menu to Leha and Noora, consisting of n dishes. It is interesting that all dishes in the menu are numbered with integers from 1 to n. After a little thought, the girl ordered exactly k different dishes from available in the menu. To pass the waiting time while the chefs prepare ordered dishes, the girl invited the hacker to play a game that will help them get to know each other better.The game itself is very simple: Noora wants Leha to guess any two dishes among all ordered. At the same time, she is ready to answer only one type of questions. Leha can say two numbers x and y (1ββ€βx,βyββ€βn). After that Noora chooses some dish a for the number x such that, at first, a is among the dishes Noora ordered (x can be equal to a), and, secondly, the value is the minimum possible. By the same rules the girl chooses dish b for y. After that Noora says Β«TAKΒ» to Leha, if , and Β«NIEΒ» otherwise. However, the restaurant is preparing quickly, so Leha has enough time to ask no more than 60 questions. After that he should name numbers of any two dishes Noora ordered.Help Leha to solve this problem!InputThere are two numbers n and k (2ββ€βkββ€βnββ€β105) in the single line of input denoting the number of dishes in the menu and the number of dishes Noora ordered.OutputIf you want to provide an answer, output a string of the form 2 x y (1ββ€βx,βyββ€βn,βxββ βy), if you think the dishes x and y was among dishes ordered by Noora. After that, flush the output and terminate your program.InteractionWhile helping Leha, you can ask queries to Noora no more than 60 times. Each query should be printed in it's own line and have the form 1 x y (1ββ€βx,βyββ€βn). You have to both print the end-of-line character and flush the output. After flushing you should read the answer for this query from input.After each query jury's program will print one line Β«TAKΒ» or Β«NIEΒ» (without quotes) in input stream depending on the girl's answer.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.HackingFor hacking you should write numbers n and k (2ββ€βkββ€βnββ€β105) in the first line and, for describing dishes Noora ordered, k different integers a1,βa2,β...,βak (1ββ€βaiββ€βn), written in ascending order in the second line. Of course, solution you want to hack won't be able to read the numbers of ordered dishes.ExampleInput3 2NIETAKNIETAKTAKTAKOutput1 1 21 2 11 1 31 3 11 2 31 3 22 2 3NoteThere are three dishes in sample. Noora ordered dished numberes 2 and 3, which Leha should guess. If Noora receive requests for the first dish (xβ=β1), then she'll choose the second dish (aβ=β2) as the dish with the minimum value . For the second (xβ=β2) and the third (xβ=β3) dishes themselves will be optimal, because in that case . Let Leha asks Noora about the next couple of dishes: xβ=β1, yβ=β2, then he'll recieve Β«NIEΒ» answer, because |1β-β2|β>β|2β-β2| xβ=β2, yβ=β1, then he'll recieve Β«TAKΒ» answer, because |2β-β2|ββ€β|1β-β2| xβ=β1, yβ=β3, then he'll recieve Β«NIEΒ» answer, because |1β-β2|β>β|3β-β3| xβ=β3, yβ=β1, then he'll recieve Β«TAKΒ» answer, because |3β-β3|ββ€β|1β-β2| xβ=β2, yβ=β3, then he'll recieve Β«TAKΒ» answer, because |2β-β2|ββ€β|3β-β3| xβ=β3, yβ=β2, then he'll recieve Β«TAKΒ» answer, because |3β-β3|ββ€β|2β-β2| According to the available information, it is possible to say that Nura ordered dishes with numbers 2 and 3. | Input3 2NIETAKNIETAKTAKTAK | Output1 1 21 2 11 1 31 3 11 2 31 3 22 2 3 | 2 seconds | 256 megabytes | ['binary search', 'interactive', '*2200'] |
A. Do you want a date?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLeha decided to move to a quiet town ViΔkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in ViΔkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109β+β7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.InputThe first line contains one integer n (1ββ€βnββ€β3Β·105) denoting the number of hacked computers.The second line contains n integers x1,βx2,β...,βxn (1ββ€βxiββ€β109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.OutputPrint a single integerΒ β the required sum modulo 109β+β7.ExamplesInput24 7Output3Input34 3 1Output9NoteThere are three non-empty subsets in the first sample test:, and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7β-β4β=β3. In total the answer is 0β+β0β+β3β=β3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4β-β3)β+β(4β-β1)β+β(3β-β1)β+β(4β-β1)β=β9. | Input24 7 | Output3 | 2 seconds | 256 megabytes | ['implementation', 'math', 'sortings', '*1500'] |
G. Anthem of Berlandtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.Note that the occurrences of string t in s can overlap. Check the third example for clarification.InputThe first line contains string of small Latin letters and question marks s (1ββ€β|s|ββ€β105).The second line contains string of small Latin letters t (1ββ€β|t|ββ€β105).Product of lengths of strings |s|Β·|t| won't exceed 107.OutputOutput the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.ExamplesInputwinlose???winl???w??winOutput5Inputglo?yto?e??an?orOutput3Input??c?????abcabOutput2NoteIn the first example the resulting string s is "winlosewinwinlwinwin"In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab". | Inputwinlose???winl???w??win | Output5 | 3 seconds | 256 megabytes | ['dp', 'strings', '*2300'] |
F. Card Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDigital collectible card games have become very popular recently. So Vova decided to try one of these.Vova has n cards in his collection. Each of these cards is characterised by its power pi, magic number ci and level li. Vova wants to build a deck with total power not less than k, but magic numbers may not allow him to do so β Vova can't place two cards in a deck if the sum of the magic numbers written on these cards is a prime number. Also Vova cannot use a card if its level is greater than the level of Vova's character.At the moment Vova's character's level is 1. Help Vova to determine the minimum level he needs to reach in order to build a deck with the required total power.InputThe first line contains two integers n and k (1ββ€βnββ€β100, 1ββ€βkββ€β100000).Then n lines follow, each of these lines contains three numbers that represent the corresponding card: pi, ci and li (1ββ€βpiββ€β1000, 1ββ€βciββ€β100000, 1ββ€βliββ€βn).OutputIf Vova won't be able to build a deck with required power, print β-β1. Otherwise print the minimum level Vova has to reach in order to build a deck.ExamplesInput5 85 5 11 5 44 6 31 12 43 12 1Output4Input3 74 4 15 8 25 3 3Output2 | Input5 85 5 11 5 44 6 31 12 43 12 1 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'flows', 'graphs', '*2400'] |
E. Selling Souvenirstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter several latest reforms many tourists are planning to visit Berland, and Berland people understood that it's an opportunity to earn money and changed their jobs to attract tourists. Petya, for example, left the IT corporation he had been working for and started to sell souvenirs at the market.This morning, as usual, Petya will come to the market. Petya has n different souvenirs to sell; ith souvenir is characterised by its weight wi and cost ci. Petya knows that he might not be able to carry all the souvenirs to the market. So Petya wants to choose a subset of souvenirs such that its total weight is not greater than m, and total cost is maximum possible.Help Petya to determine maximum possible total cost.InputThe first line contains two integers n and m (1ββ€βnββ€β100000, 1ββ€βmββ€β300000) β the number of Petya's souvenirs and total weight that he can carry to the market.Then n lines follow. ith line contains two integers wi and ci (1ββ€βwiββ€β3, 1ββ€βciββ€β109) β the weight and the cost of ith souvenir.OutputPrint one number β maximum possible total cost of souvenirs that Petya can carry to the market.ExamplesInput1 12 1Output0Input2 21 32 2Output3Input4 33 102 72 81 1Output10 | Input1 12 1 | Output0 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', 'ternary search', '*2300'] |
D. Array Divisiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element before dividing the array (Vasya will erase some element and insert it into an arbitrary position).Inserting an element in the same position he was erased from is also considered moving.Can Vasya divide the array after choosing the right element to move and its new position?InputThe first line contains single integer n (1ββ€βnββ€β100000) β the size of the array.The second line contains n integers a1,βa2... an (1ββ€βaiββ€β109) β the elements of the array.OutputPrint YES if Vasya can divide the array after moving one element. Otherwise print NO.ExamplesInput31 3 2OutputYESInput51 2 3 4 5OutputNOInput52 2 3 4 5OutputYESNoteIn the first example Vasya can move the second element to the end of the array.In the second example no move can make the division possible.In the third example Vasya can move the fourth element by one position to the left. | Input31 3 2 | OutputYES | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', '*1900'] |
C. Tea Partytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a1,βa2,β...,βan. His teapot stores w milliliters of tea (wββ€βa1β+βa2β+β...β+βan). Polycarp wants to pour tea in cups in such a way that: Every cup will contain tea for at least half of its volume Every cup will contain integer number of milliliters of tea All the tea from the teapot will be poured into cups All friends will be satisfied. Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but aiβ>βaj.For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.InputThe first line contains two integer numbers n and w (1ββ€βnββ€β100, ).The second line contains n numbers a1,βa2,β...,βan (1ββ€βaiββ€β100).OutputOutput how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.If it's impossible to pour all the tea and satisfy all conditions then output -1.ExamplesInput2 108 7Output6 4 Input4 41 1 1 1Output1 1 1 1 Input3 109 8 10Output-1NoteIn the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available. | Input2 108 7 | Output6 4 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'sortings', '*1400'] |
B. Average Sleep Timetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1,βa2,β...,βan, where ai is the sleep time on the i-th day.The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be nβ-βkβ+β1 weeks to take into consideration. For example, if kβ=β2, nβ=β3 and aβ=β[3,β4,β7], then the result is .You should write a program which will calculate average sleep times of Polycarp over all weeks.InputThe first line contains two integer numbers n and k (1ββ€βkββ€βnββ€β2Β·105).The second line contains n integer numbers a1,βa2,β...,βan (1ββ€βaiββ€β105).OutputOutput average sleeping time over all weeks. The answer is considered to be correct if its absolute or relative error does not exceed 10β-β6. In particular, it is enough to output real number with at least 6 digits after the decimal point.ExamplesInput3 23 4 7Output9.0000000000Input1 110Output10.0000000000Input8 21 2 4 100000 123 456 789 1Output28964.2857142857NoteIn the third example there are nβ-βkβ+β1β=β7 weeks, so the answer is sums of all weeks divided by 7. | Input3 23 4 7 | Output9.0000000000 | 1 second | 256 megabytes | ['data structures', 'implementation', 'math', '*1300'] |
A. Lucky Yeartime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputApart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not.You are given current year in Berland. Your task is to find how long will residents of Berland wait till the next lucky year.InputThe first line contains integer number n (1ββ€βnββ€β109) β current year in Berland.OutputOutput amount of years from the current year to the next lucky one.ExamplesInput4Output1Input201Output99Input4000Output1000NoteIn the first example next lucky year is 5. In the second one β 300. In the third β 5000. | Input4 | Output1 | 1 second | 256 megabytes | ['implementation', '*900'] |
B. T-Shirt Hunttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNot so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p.Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let s be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed: i := (s div 50) mod 475repeat 25 times: i := (i * 96 + 42) mod 475 print (26 + i)Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator.As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of s.You're in the lead of the elimination round of 8VC Venture Cup 2017, having x points. You believe that having at least y points in the current round will be enough for victory.To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?InputThe only line contains three integers p, x and y (26ββ€βpββ€β500; 1ββ€βyββ€βxββ€β20000)Β β your place in Codecraft-17, your current score in the elimination round of 8VC Venture Cup 2017, and the smallest number of points you consider sufficient for winning the current round.OutputOutput a single integerΒ β the smallest number of successful hacks you have to do in order to both win the elimination round of 8VC Venture Cup 2017 and ensure getting a Codecraft-17 T-shirt.It's guaranteed that your goal is achievable for any valid input data.ExamplesInput239 10880 9889Output0Input26 7258 6123Output2Input493 8000 8000Output24Input101 6800 6500Output0Input329 19913 19900Output8NoteIn the first example, there is no need to do any hacks since 10880 points already bring the T-shirt to the 239-th place of Codecraft-17 (that is, you). In this case, according to the pseudocode, the T-shirts will be given to the participants at the following places: 475 422 84 411 453 210 157 294 146 188 420 367 29 356 398 155 102 239 91 133 365 312 449 301 343In the second example, you have to do two successful and one unsuccessful hack to make your score equal to 7408.In the third example, you need to do as many as 24 successful hacks to make your score equal to 10400.In the fourth example, it's sufficient to do 6 unsuccessful hacks (and no successful ones) to make your score equal to 6500, which is just enough for winning the current round and also getting the T-shirt. | Input239 10880 9889 | Output0 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*1300'] |
A. Is it rated?time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIs it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.InputThe first line contains a single integer n (2ββ€βnββ€β1000)Β β the number of round participants.Each of the next n lines contains two integers ai and bi (1ββ€βai,βbiββ€β4126)Β β the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.OutputIf the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".ExamplesInput63060 30602194 21942876 29032624 26243007 29912884 2884OutputratedInput41500 15001300 13001200 12001400 1400OutputunratedInput53123 31232777 27772246 22462246 22461699 1699OutputmaybeNoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not. | Input63060 30602194 21942876 29032624 26243007 29912884 2884 | Outputrated | 2 seconds | 256 megabytes | ['implementation', 'sortings', '*900'] |
B. 3-palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick.He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substring. For example, the strings "abc" and "abca" suit him, while the string "aba" doesn't. He also want the number of letters 'c' in his string to be as little as possible.InputThe first line contains single integer n (1ββ€βnββ€β2Β·105)Β β the length of the string.OutputPrint the string that satisfies all the constraints.If there are multiple answers, print any of them.ExamplesInput2OutputaaInput3OutputbbaNoteA palindrome is a sequence of characters which reads the same backward and forward. | Input2 | Outputaa | 1 second | 256 megabytes | ['constructive algorithms', '*1000'] |
A. Fake NPtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path.You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times.Solve the problem to show that it's not a NP problem.InputThe first line contains two integers l and r (2ββ€βlββ€βrββ€β109).OutputPrint single integer, the integer that appears maximum number of times in the divisors. If there are multiple answers, print any of them.ExamplesInput19 29Output2Input3 6Output3NoteDefinition of a divisor: https://www.mathsisfun.com/definitions/divisor-of-an-integer-.htmlThe first example: from 19 to 29 these numbers are divisible by 2: {20,β22,β24,β26,β28}.The second example: from 3 to 6 these numbers are divisible by 3: {3,β6}. | Input19 29 | Output2 | 1 second | 256 megabytes | ['greedy', 'math', '*1000'] |
F. Fake bullionstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn Isart people don't die. There are n gangs of criminals. The i-th gang contains si evil people numerated from 0 to siβ-β1. Some of these people took part in a big mine robbery and picked one gold bullion each (these people are given in the input). That happened 10100 years ago and then all of the gangs escaped to a remote area, far from towns.During the years, they were copying some gold bullions according to an organized plan in order to not get arrested. They constructed a tournament directed graph (a graph where there is exactly one directed edge between every pair of vertices) of gangs (the graph is given in the input). In this graph an edge from u to v means that in the i-th hour the person of the gang u can send a fake gold bullion to person of gang v. He sends it if he has some bullion (real or fake), while the receiver doesn't have any. Thus, at any moment each of the gangsters has zero or one gold bullion. Some of them have real bullions, and some of them have fake ones.In the beginning of this year, the police has finally found the gangs, but they couldn't catch them, as usual. The police decided to open a jewelry store so that the gangsters would sell the bullions. Thus, every gangster that has a bullion (fake or real) will try to sell it. If he has a real gold bullion, he sells it without problems, but if he has a fake one, there is a choice of two events that can happen: The person sells the gold bullion successfully. The person is arrested by police. The power of a gang is the number of people in it that successfully sold their bullion. After all selling is done, the police arrests b gangs out of top gangs. Sort the gangs by powers, we call the first a gang top gangs(you can sort the equal powers in each order). Consider all possible results of selling fake gold bullions and all possible choice of b gangs among the top gangs. Count the number of different sets of these b gangs modulo 109β+β7. Two sets X and Y are considered different if some gang is in X and isn't in Y.InputThe first line contains four integers n, a and b (1ββ€βbββ€βaββ€βnββ€β5Β·103)Β β the number of gangs, the constants a and b from the statement.Then n lines follow, each line contains a string of size n consisting of zeros and ones. The j-th character in the i-th of these lines is equal to 1, then the vertex i have a directed edge to the vertex j. It is guaranteed that aiiβ=β0 and aijβ+βajiβ=β1 if iββ βj.Then n lines follow, each line starts with the integer si (1ββ€βsiββ€β2Β·106)Β β the number of gangsters in the i-th gang, and then contains a string of zeros and ones with length si. The j-th character is 0 if the j-th person of the i-th gang had a real gold bullion initially, otherwise it is 1. It is guaranteed that the sum of si does not exceed 2Β·106.OutputPrint single integer: the number of different sets of b gangs the police can arrest modulo 109β+β7.ExamplesInput2 2 101005 110006 100000Output2Input5 2 100000100001101111000110102 001 16 1001101 01 0Output5 | Input2 2 101005 110006 100000 | Output2 | 3 seconds | 512 megabytes | ['combinatorics', 'dfs and similar', 'dp', 'graphs', 'number theory', '*3400'] |
E. The same permutation time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSeyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i,βj), where iβ<βj, exactly once. MoJaK doesn't like to upset Sajjad.Given the permutation, determine whether it is possible to swap all pairs of positions so that the permutation stays the same. If it is possible find how to do that. InputThe first line contains single integer n (1ββ€βnββ€β1000)Β β the size of the permutation.As the permutation is not important, you can consider aiβ=βi, where the permutation is a1,βa2,β...,βan.OutputIf it is not possible to swap all pairs of positions so that the permutation stays the same, print "NO",Otherwise print "YES", then print lines: the i-th of these lines should contain two integers a and b (aβ<βb)Β β the positions where the i-th swap is performed.ExamplesInput3OutputNOInput1OutputYES | Input3 | OutputNO | 2 seconds | 256 megabytes | ['constructive algorithms', '*3100'] |
D. Expected diameter of a treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha is a good student and one of MoJaK's best friends. He always have a problem to think about. Today they had a talk about the following problem.We have a forest (acyclic undirected graph) with n vertices and m edges. There are q queries we should answer. In each query two vertices v and u are given. Let V be the set of vertices in the connected component of the graph that contains v, and U be the set of vertices in the connected component of the graph that contains u. Let's add an edge between some vertex and some vertex in and compute the value d of the resulting component. If the resulting component is a tree, the value d is the diameter of the component, and it is equal to -1 otherwise. What is the expected value of d, if we choose vertices a and b from the sets uniformly at random?Can you help Pasha to solve this problem?The diameter of the component is the maximum distance among some pair of vertices in the component. The distance between two vertices is the minimum number of edges on some path between the two vertices.Note that queries don't add edges to the initial forest. InputThe first line contains three integers n, m and q(1ββ€βn,βm,βqββ€β105)Β β the number of vertices, the number of edges in the graph and the number of queries.Each of the next m lines contains two integers ui and vi (1ββ€βui,βviββ€βn), that means there is an edge between vertices ui and vi.It is guaranteed that the given graph is a forest.Each of the next q lines contains two integers ui and vi (1ββ€βui,βviββ€βn)Β β the vertices given in the i-th query.OutputFor each query print the expected value of d as described in the problem statement.Your answer will be considered correct if its absolute or relative error does not exceed 10β-β6. Let's assume that your answer is a, and the jury's answer is b. The checker program will consider your answer correct, if .ExamplesInput3 1 21 33 12 3Output-12.0000000000Input5 2 32 44 34 24 12 5Output-12.66666666672.6666666667NoteIn the first example the vertices 1 and 3 are in the same component, so the answer for the first query is -1. For the second query there are two options to add the edge: one option is to add the edge 1β-β2, the other one is 2β-β3. In both ways the resulting diameter is 2, so the answer is 2.In the second example the answer for the first query is obviously -1. The answer for the second query is the average of three cases: for added edges 1β-β2 or 1β-β3 the diameter is 3, and for added edge 1β-β4 the diameter is 2. Thus, the answer is . | Input3 1 21 33 12 3 | Output-12.0000000000 | 3 seconds | 256 megabytes | ['binary search', 'brute force', 'dfs and similar', 'dp', 'sortings', 'trees', '*2500'] |
C. Ice cream coloringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIsart and Modsart were trying to solve an interesting problem when suddenly Kasra arrived. Breathless, he asked: "Can you solve a problem I'm stuck at all day?"We have a tree T with n vertices and m types of ice cream numerated from 1 to m. Each vertex i has a set of si types of ice cream. Vertices which have the i-th (1ββ€βiββ€βm) type of ice cream form a connected subgraph. We build a new graph G with m vertices. We put an edge between the v-th and the u-th (1ββ€βu,βvββ€βm, uββ βv) vertices in G if and only if there exists a vertex in T that has both the v-th and the u-th types of ice cream in its set. The problem is to paint the vertices of G with minimum possible number of colors in a way that no adjacent vertices have the same color.Please note that we consider that empty set of vertices form a connected subgraph in this problem.As usual, Modsart don't like to abandon the previous problem, so Isart wants you to solve the new problem.InputThe first line contains two integer n and m (1ββ€βn,βmββ€β3Β·105)Β β the number of vertices in T and the number of ice cream types.n lines follow, the i-th of these lines contain single integer si (0ββ€βsiββ€β3Β·105) and then si distinct integers, each between 1 and mΒ β the types of ice cream in the i-th vertex. The sum of si doesn't exceed 5Β·105.nβ-β1 lines follow. Each of these lines describes an edge of the tree with two integers u and v (1ββ€βu,βvββ€βn)Β β the indexes of connected by this edge vertices.OutputPrint single integer c in the first lineΒ β the minimum number of colors to paint the vertices in graph G.In the second line print m integers, the i-th of which should be the color of the i-th vertex. The colors should be between 1 and c. If there are some answers, print any of them.ExamplesInput3 31 12 2 31 21 22 3Output21 1 2 Input4 501 11 33 2 4 52 13 24 3Output31 1 1 2 3 NoteIn the first example the first type of ice cream is present in the first vertex only, so we can color it in any color. The second and the third ice cream are both presented in the second vertex, so we should paint them in different colors.In the second example the colors of the second, the fourth and the fifth ice cream should obviously be distinct. | Input3 31 12 2 31 21 22 3 | Output21 1 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'greedy', '*2200'] |
B. Minimum number of stepstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109β+β7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.InputThe first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.OutputPrint the minimum number of steps modulo 109β+β7.ExamplesInputabOutput1InputaabOutput3NoteThe first example: "ab" βββ "bba".The second example: "aab" βββ "abba" βββ "bbaba" βββ "bbbbaa". | Inputab | Output1 | 1 second | 256 megabytes | ['combinatorics', 'greedy', 'implementation', 'math', '*1400'] |
A. Find Amirtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends.There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j costs and can be used multiple times. Help Sajjad to find the minimum cost he needs to pay for tickets to visit all schools. He can start and finish in any school.InputThe first line contains a single integer n (1ββ€βnββ€β105)Β β the number of schools.OutputPrint single integer: the minimum cost of tickets needed to visit all schools.ExamplesInput2Output0Input10Output4NoteIn the first example we can buy a ticket between the schools that costs . | Input2 | Output0 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1000'] |
G. Periodic RMQ Problemtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of positive integers and q queries to this array. There are two types of queries: 1 l r x β for each index i such that lββ€βiββ€βr set aiβ=βx. 2 l r β find the minimum among such ai that lββ€βiββ€βr. We decided that this problem is too easy. So the array a is given in a compressed form: there is an array b consisting of n elements and a number k in the input, and before all queries a is equal to the concatenation of k arrays b (so the size of a is nΒ·k).InputThe first line contains two integers n and k (1ββ€βnββ€β105, 1ββ€βkββ€β104).The second line contains n integers β elements of the array b (1ββ€βbiββ€β109).The third line contains one integer q (1ββ€βqββ€β105).Then q lines follow, each representing a query. Each query is given either as 1 l r x β set all elements in the segment from l till r (including borders) to x (1ββ€βlββ€βrββ€βnΒ·k, 1ββ€βxββ€β109) or as 2 l r β find the minimum among all elements in the segment from l till r (1ββ€βlββ€βrββ€βnΒ·k).OutputFor each query of type 2 print the answer to this query β the minimum on the corresponding segment.ExamplesInput3 11 2 332 1 31 1 2 42 1 3Output13Input3 21 2 352 4 41 4 4 52 4 41 1 6 12 6 6Output151 | Input3 11 2 332 1 31 1 2 42 1 3 | Output13 | 4 seconds | 512 megabytes | ['data structures', '*2300'] |
F. Coprime Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a non-empty sequence of positive integers a1,βa2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109β+β7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1,β1] there are 3 different subsequences: [1], [1] and [1,β1].InputThe first line contains one integer number n (1ββ€βnββ€β100000).The second line contains n integer numbers a1,βa2... an (1ββ€βaiββ€β100000).OutputPrint the number of coprime subsequences of a modulo 109β+β7.ExamplesInput31 2 3Output5Input41 1 1 1Output15Input71 3 5 15 3 105 35Output100NoteIn the first example coprime subsequences are: 1 1,β2 1,β3 1,β2,β3 2,β3 In the second example all subsequences are coprime. | Input31 2 3 | Output5 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'number theory', '*2000'] |
E. Roma and Pokertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.Last evening Roma started to play poker. He decided to spend no more than k virtual bourles β he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: In the end the absolute difference between the number of wins and loses is equal to k; There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.InputThe first line contains two numbers n (the length of Roma's sequence) and k (1ββ€βn,βkββ€β1000).The second line contains the sequence s consisting of characters W, L, D and ?. There are exactly n characters in this sequence.OutputIf there is no valid sequence that can be obtained from s by replacing all ? characters by W, L or D, print NO.Otherwise print this sequence. If there are multiple answers, print any of them.ExamplesInput3 2L??OutputLDLInput3 1W??OutputNOInput20 5?LLLLLWWWWW?????????OutputWLLLLLWWWWWWWWLWLWDW | Input3 2L?? | OutputLDL | 2 seconds | 256 megabytes | ['dp', 'graphs', '*2000'] |
D. Magazine Adtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:There are space-separated non-empty words of lowercase and uppercase Latin letters.There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen. It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word. When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.The ad can occupy no more that k lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.You should write a program that will find minimal width of the ad.InputThe first line contains number k (1ββ€βkββ€β105).The second line contains the text of the ad β non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters.OutputOutput minimal width of the ad.ExamplesInput4garage for sa-leOutput7Input4Edu-ca-tion-al Ro-unds are so funOutput10NoteHere all spaces are replaced with dots.In the first example one of possible results after all word wraps looks like this:garage.for.sa-leThe second example:Edu-ca-tion-al.Ro-unds.are.so.fun | Input4garage for sa-le | Output7 | 1 second | 256 megabytes | ['binary search', 'greedy', '*1900'] |
C. Maximal GCDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1,βa2,β...,βak, that their sum is equal to n and greatest common divisor is maximal.Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them.If there is no possible sequence then output -1.InputThe first line consists of two numbers n and k (1ββ€βn,βkββ€β1010).OutputIf the answer exists then output k numbers β resulting sequence. Otherwise output -1. If there are multiple answers, print any of them.ExamplesInput6 3Output1 2 3Input8 2Output2 6Input5 3Output-1 | Input6 3 | Output1 2 3 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1900'] |
B. Distances to Zerotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the array of integer numbers a0,βa1,β...,βanβ-β1. For each element find the distance to the nearest zero (to the element which equals to zero). There is at least one zero element in the given array.InputThe first line contains integer n (1ββ€βnββ€β2Β·105) β length of the array a. The second line contains integer elements of the array separated by single spaces (β-β109ββ€βaiββ€β109).OutputPrint the sequence d0,βd1,β...,βdnβ-β1, where di is the difference of indices between i and nearest j such that ajβ=β0. It is possible that iβ=βj.ExamplesInput92 1 0 3 0 0 3 2 4Output2 1 0 1 0 0 1 2 3 Input50 1 2 3 4Output0 1 2 3 4 Input75 6 0 1 -2 3 4Output2 1 0 1 2 3 4 | Input92 1 0 3 0 0 3 2 4 | Output2 1 0 1 0 0 1 2 3 | 2 seconds | 256 megabytes | ['constructive algorithms', '*1200'] |
A. Maximal Binary Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal.One matrix is lexicographically greater than the other if the first different number in the first different row from the top in the first matrix is greater than the corresponding number in the second one.If there exists no such matrix then output -1.InputThe first line consists of two numbers n and k (1ββ€βnββ€β100, 0ββ€βkββ€β106).OutputIf the answer exists then output resulting matrix. Otherwise output -1.ExamplesInput2 1Output1 0 0 0 Input3 2Output1 0 0 0 1 0 0 0 0 Input2 5Output-1 | Input2 1 | Output1 0 0 0 | 1 second | 256 megabytes | ['constructive algorithms', '*1400'] |
O. April Fools' Problem (hard)time limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe plans for HC2 are rather far-fetched: we are just over 500 000 days away from HC2 3387, for example, and accordingly we are planning to have a couple hundred thousand problems in that edition (we hope that programming contests will become wildly more popular). The marmots need to get to work, and they could use a good plan...InputSame as the medium version, but the limits have changed: 1ββ€βkββ€βnββ€β500β000.OutputSame as the medium version.ExampleInput8 43 8 7 9 9 4 6 82 5 9 4 3 8 9 1Output32 | Input8 43 8 7 9 9 4 6 82 5 9 4 3 8 9 1 | Output32 | 10 seconds | 256 megabytes | ['binary search', 'data structures', 'flows', '*2900'] |
N. April Fools' Problem (medium)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe marmots need to prepare k problems for HC2 over n days. Each problem, once prepared, also has to be printed.The preparation of a problem on day i (at most one per day) costs ai CHF, and the printing of a problem on day i (also at most one per day) costs bi CHF. Of course, a problem cannot be printed before it has been prepared (but doing both on the same day is fine).What is the minimum cost of preparation and printing?InputThe first line of input contains two space-separated integers n and k (1ββ€βkββ€βnββ€β2200). The second line contains n space-separated integers a1,β...,βan () β the preparation costs. The third line contains n space-separated integers b1,β...,βbn () β the printing costs.OutputOutput the minimum cost of preparation and printing k problems β that is, the minimum possible sum ai1β+βai2β+β...β+βaikβ+βbj1β+βbj2β+β...β+βbjk, where 1ββ€βi1β<βi2β<β...β<βikββ€βn, 1ββ€βj1β<βj2β<β...β<βjkββ€βn and i1ββ€βj1, i2ββ€βj2, ..., ikββ€βjk.ExampleInput8 43 8 7 9 9 4 6 82 5 9 4 3 8 9 1Output32NoteIn the sample testcase, one optimum solution is to prepare the first problem on day 1 and print it on day 1, prepare the second problem on day 2 and print it on day 4, prepare the third problem on day 3 and print it on day 5, and prepare the fourth problem on day 6 and print it on day 8. | Input8 43 8 7 9 9 4 6 82 5 9 4 3 8 9 1 | Output32 | 4 seconds | 256 megabytes | ['binary search', 'flows', 'graphs', '*2400'] |
M. April Fools' Problem (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe marmots have prepared a very easy problem for this year's HC2 β this one. It involves numbers n, k and a sequence of n positive integers a1,βa2,β...,βan. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also reads like a good criminal.However I, Heidi, will have none of that. As my joke for today, I am removing the story from the statement and replacing it with these two unhelpful paragraphs. Now solve the problem, fools!InputThe first line of the input contains two space-separated integers n and k (1ββ€βkββ€βnββ€β2200). The second line contains n space-separated integers a1,β...,βan (1ββ€βaiββ€β104).OutputOutput one number.ExamplesInput8 51 1 1 1 1 1 1 1Output5Input10 316 8 2 4 512 256 32 128 64 1Output7Input5 120 10 50 30 46Output10Input6 66 6 6 6 6 6Output36Input1 1100Output100 | Input8 51 1 1 1 1 1 1 1 | Output5 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1200'] |
L. Send the Fool Further! (hard)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi is terrified by your estimate and she found it unrealistic that her friends would collaborate to drive her into debt. She expects that, actually, each person will just pick a random friend to send Heidi to. (This randomness assumption implies, however, that she can now visit the same friend an arbitrary number of times...) Moreover, if a person only has one friend in common with Heidi (i.e., if that person is in a leaf of the tree), then that person will not send Heidi back (so that Heidi's travel will end at some point).Heidi also found unrealistic the assumption that she can make all the travels in one day. Therefore now she assumes that every time she travels a route between two friends, she needs to buy a new ticket. She wants to know: how much should she expect to spend on the trips?For what it's worth, Heidi knows that Jenny has at least two friends.InputThe first line contains the number of friends n (3ββ€βnββ€β105). The next nβ-β1 lines each contain three space-separated integers u, v and c (0ββ€βu,βvββ€βnβ-β1, 1ββ€βcββ€β104) meaning that u and v are friends and the cost for traveling between u and v is c (paid every time!).It is again guaranteed that the social network of the input forms a tree.OutputAssume that the expected cost of the trips is written as an irreducible fraction aβ/βb (that is, a and b are coprime). Then Heidi, the weird cow that she is, asks you to output . (Output a single integer between 0 and 109β+β6.)ExamplesInput30 1 100 2 20Output15Input40 1 30 2 90 3 27Output13Input70 1 30 5 71 2 21 3 11 4 55 6 8Output400000019Input111 0 66462 0 88163 2 93754 2 59505 1 87026 2 26577 2 8858 7 26609 2 536910 6 3798Output153869806Input60 1 80 2 241 3 401 4 164 5 8Output39NoteIn the first example, with probability 1β/β2 Heidi will go to 1 from 0, and with probability 1β/β2 she will go to 2. In the first case the cost would be 10, and in the second it would be 20. After reaching 1 or 2 she will stop, as 1 and 2 are leaves of the social tree. Hence, the expected cost she has to pay is 10Β·1β/β2β+β20Β·1β/β2β=β15.In the third example, the expected cost is 81β/β5. You should output 400000019.In her travels, Heidi has learned an intriguing fact about the structure of her social network. She tells you the following: The mysterious determinant that you might be wondering about is such that it does not cause strange errors in your reasonable solution... Did we mention that Heidi is a weird cow? | Input30 1 100 2 20 | Output15 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'math', 'trees', '*2400'] |
K. Send the Fool Further! (medium)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThank you for helping Heidi! It is now the second of April, but she has been summoned by Jenny again. The pranks do not seem to end...In the meantime, Heidi has decided that she does not trust her friends anymore. Not too much, anyway. Her relative lack of trust is manifested as follows: whereas previously she would not be made to visit the same person twice, now she can only be sure that she will not be made to visit the same person more than k times. (In the case of Jenny, this includes her first visit in the beginning. The situation from the easy version corresponds to setting kβ=β1.)This is not as bad as it looks, since a single ticket for a route between two friends allows Heidi to travel between this pair of friends the whole day (in both directions). In other words, once she pays for travel between a pair of friends, all further travels between that pair are free.How much money will Heidi waste now, in a worst-case scenario?InputThe first line contains two space-separated integers β the number of friends n () and the parameter k (1ββ€βkββ€β105). The next nβ-β1 lines each contain three space-separated integers u, v and c (0ββ€βu,βvββ€βnβ-β1, 1ββ€βcββ€β104) meaning that u and v are friends and the cost for traveling between u and v is c.It is again guaranteed that the social network of the input forms a tree.OutputAgain, output a single integer β the maximum sum of costs of tickets.ExamplesInput9 30 1 10 2 11 3 21 4 21 5 22 6 32 7 32 8 3Output15Input9 50 1 10 2 11 3 21 4 21 5 22 6 32 7 32 8 3Output17Input11 61 0 79322 1 19523 2 22274 0 91125 4 60676 0 67867 6 38838 4 71379 1 279610 5 6200Output54092NoteIn the first example, the worst-case scenario for Heidi is to visit the friends in the following order: 0,β1,β5,β1,β3,β1,β0,β2,β6,β2,β7,β2,β8. Observe that no friend is visited more than 3 times. | Input9 30 1 10 2 11 3 21 4 21 5 22 6 32 7 32 8 3 | Output15 | 2 seconds | 256 megabytes | ['dp', 'trees', '*2100'] |
J. Send the Fool Further! (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?Heidi's n friends are labeled 0 through nβ-β1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly nβ-β1 pairs of friends who know each other directly.Jenny is given the number 0.InputThe first line of the input contains the number of friends n (3ββ€βnββ€β100). The next nβ-β1 lines each contain three space-separated integers u, v and c (0ββ€βu,βvββ€βnβ-β1, 1ββ€βcββ€β104), meaning that u and v are friends (know each other directly) and the cost for travelling between u and v is c.It is guaranteed that the social network of the input forms a tree.OutputOutput a single integer β the maximum sum of costs.ExamplesInput40 1 40 2 22 3 3Output5Input61 2 30 2 1001 4 20 3 73 5 10Output105Input111 0 16642 0 8813 2 46704 2 15555 1 18706 2 12657 2 2888 7 22669 2 153610 6 3378Output5551NoteIn the second example, the worst-case scenario goes like this: Jenny sends Heidi to the friend labeled by number 2 (incurring a cost of 100), then friend 2 sends her to friend 1 (costing Heidi 3), and finally friend 1 relays her to friend 4 (incurring an additional cost of 2). | Input40 1 40 2 22 3 3 | Output5 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', 'trees', '*1400'] |
I. Fake News (hard)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that you have proposed a fake post for the HC2 Facebook page, Heidi wants to measure the quality of the post before actually posting it. She recently came across a (possibly fake) article about the impact of fractal structure on multimedia messages and she is now trying to measure the self-similarity of the message, which is defined aswhere the sum is over all nonempty strings p and is the number of occurences of p in s as a substring. (Note that the sum is infinite, but it only has a finite number of nonzero summands.)Heidi refuses to do anything else until she knows how to calculate this self-similarity. Could you please help her? (If you would like to instead convince Heidi that a finite string cannot be a fractal anyway β do not bother, we have already tried.)InputThe input starts with a line indicating the number of test cases T (1ββ€βTββ€β10). After that, T test cases follow, each of which consists of one line containing a string s (1ββ€β|s|ββ€β100β000) composed of lowercase letters (a-z).OutputOutput T lines, every line containing one number β the answer to the corresponding test case.ExampleInput4aaabcdcccabccOutput5101412NoteA string s contains another string p as a substring if p is a contiguous subsequence of s. For example, ab is a substring of cab but not of acb. | Input4aaabcdcccabcc | Output5101412 | 5 seconds | 256 megabytes | ['string suffix structures', '*2300'] |
H. Fake News (medium)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she wants the phrase to appear n times in the post. She is asking you to design a post (string) s and a hidden phrase p such that p appears in s as a subsequence exactly n times.InputThe first and only line of input contains a single integer n (1ββ€βnββ€β1β000β000).OutputThe output should contain two nonempty strings s and p separated by a single space. Each string should be composed of letters (a-z and A-Z: both lowercase and uppercase are allowed) and have length at most 200. The number of occurrences of p in s as a subsequence should be exactly n. If there are many possible solutions, output any of them. It is guaranteed that at least one solution exists.ExamplesInput2OutputhHheidi HeiInput4Outputbbbba baInput6Outputaaabb abNoteAn occurrence of p as a subsequence in s should be thought of as a set of positions in s such that the letters at these positions, in order, form p. The number of occurences is thus the number of such sets. For example, ab appears 6 times as a subsequence in aaabb, for the following sets of positions: {1,β4},β{1,β5},β{2,β4},β{2,β5},β{3,β4},β{3,β5} (that is, we should choose one of the a's and one of the b's). | Input2 | OutputhHheidi Hei | 1 second | 256 megabytes | ['constructive algorithms', 'strings', '*2200'] |
G. Fake News (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...InputThe first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).OutputOutput YES if the string s contains heidi as a subsequence and NO otherwise.ExamplesInputabcheaibcdiOutputYESInputhiediOutputNONoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p. | Inputabcheaibcdi | OutputYES | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
D. Marmots (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHeidi is a statistician to the core, and she likes to study the evolution of marmot populations in each of V (1ββ€βVββ€β100) villages! So it comes that every spring, when Heidi sees the first snowdrops sprout in the meadows around her barn, she impatiently dons her snowshoes and sets out to the Alps, to welcome her friends the marmots to a new season of thrilling adventures.Arriving in a village, Heidi asks each and every marmot she comes across for the number of inhabitants of that village. This year, the marmots decide to play an April Fools' joke on Heidi. Instead of consistently providing the exact number of inhabitants P (10ββ€βPββ€β1000) of the village, they respond with a random non-negative integer k, drawn from one of two types of probability distributions: Poisson (d'avril) distribution: the probability of getting an answer k is for kβ=β0,β1,β2,β3,β..., Uniform distribution: the probability of getting an answer k is for kβ=β0,β1,β2,β...,β2P. Heidi collects exactly 250 answers per village. Every village follows either the Poisson or the uniform distribution. Heidi cannot tell marmots apart, so she may query some marmots several times, and each time the marmot will answer with a new number drawn from the village's distribution.Can you help Heidi to find out whether a village follows a Poisson or a uniform distribution?InputThe first line of input will contain the number of villages V (1ββ€βVββ€β100). The following V lines each describe one village. The description of each village consists of 250 space-separated integers k, drawn from one of the above distributions.OutputOutput one line per village, in the same order as provided in the input. The village's line shall state poisson if the village's distribution is of the Poisson type, and uniform if the answer came from a uniform distribution.ExampleInput292 100 99 109 93 105 103 106 101 99 ... (input is truncated)28 180 147 53 84 80 180 85 8 16 ... (input is truncated)OutputpoissonuniformNoteThe full example input is visually represented below, along with the probability distribution function it was drawn from (the y-axis is labeled by its values multiplied by 250). | Input292 100 99 109 93 105 103 106 101 99 ... (input is truncated)28 180 147 53 84 80 180 85 8 16 ... (input is truncated) | Outputpoissonuniform | 2 seconds | 256 megabytes | ['math', '*2100'] |
C. Heidi and Library (hard)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe good times at Heidi's library are over. Marmots finally got their internet connections and stopped coming to the library altogether. Not only that, but the bookstore has begun charging extortionate prices for some books. Namely, whereas in the previous versions each book could be bought for 1 CHF, now the price of book i is ci CHF.InputThe first line of input will contain two integers n and k (). The second line will contain n integers a1,βa2,β...,βan (1ββ€βaiββ€βn) β the sequence of book requests. The third line contains n integers c1,βc2,β...,βcn (0ββ€βciββ€β106) β the costs of the books.OutputOn a single line print the minimum cost of buying books at the store so as to satisfy all requests.ExamplesInput4 801 2 2 11 1 1 1Output2Input4 11 2 2 11 1 1 1Output3Input4 21 2 3 11 1 1 1Output3Input7 21 2 3 1 1 1 21 10 1 0 0 0 0Output13NoteThe first three sample cases are repeated, but the fourth one is new.In the fourth test case, when buying book 3, Heidi should discard either book 1 or 2. Even though book 2 will be requested later than book 1, she should keep it, because it is so expensive to buy again. | Input4 801 2 2 11 1 1 1 | Output2 | 2 seconds | 256 megabytes | ['flows', '*2600'] |
B. Heidi and Library (medium)time limit per test10 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.InputSame as the easy version, but the limits have changed: 1ββ€βn,βkββ€β400β000.OutputSame as the easy version.ExamplesInput4 1001 2 2 1Output2Input4 11 2 2 1Output3Input4 21 2 3 1Output3 | Input4 1001 2 2 1 | Output2 | 10 seconds | 256 megabytes | ['data structures', 'greedy', '*1800'] |
A. Heidi and Library (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour search for Heidi is over β you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n.We will look at the library's operation during n consecutive days. Heidi knows in advance that on the i-th day (1ββ€βiββ€βn) precisely one person will come to the library, request to borrow the book ai, read it in a few hours, and return the book later on the same day.Heidi desperately wants to please all her guests, so she will make sure to always have the book ai available in the library on the i-th day. During the night before the i-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books.There is a problem, though. The capacity of the library is k β this means that at any time, there can be at most k books at the library. If buying a new book would cause Heidi to have more than k books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again.You are given k and the sequence of requests for books a1,βa2,β...,βan. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?InputThe first line of input will contain two integers n and k (1ββ€βn,βkββ€β80). The second line will contain n integers a1,βa2,β...,βan (1ββ€βaiββ€βn) β the sequence of book requests.OutputOn a single line print the minimum cost of buying books at the store so as to satisfy all requests.ExamplesInput4 801 2 2 1Output2Input4 11 2 2 1Output3Input4 21 2 3 1Output3NoteIn the first test case, Heidi is able to keep all books forever. Therefore, she only needs to buy the book 1 before the first day and the book 2 before the second day.In the second test case, she can only keep one book at a time. Therefore she will need to buy new books on the first, second and fourth day.In the third test case, before buying book 3 on the third day, she must decide which of the books 1 and 2 she should get rid of. Of course, she should keep the book 1, which will be requested on the fourth day. | Input4 801 2 2 1 | Output2 | 2 seconds | 256 megabytes | ['greedy', '*1800'] |
B. Valued Keystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length.The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1 and the i-th character of s2.For example, f("ab", "ba") = "aa", and f("nzwzl", "zizez") = "niwel".You found two strings x and y of the same length and consisting of only lowercase English letters. Find any string z such that f(x,βz)β=βy, or print -1 if no such string z exists.InputThe first line of input contains the string x.The second line of input contains the string y.Both x and y consist only of lowercase English letters, x and y have same length and this length is between 1 and 100.OutputIf there is no string z such that f(x,βz)β=βy, print -1.Otherwise, print a string z such that f(x,βz)β=βy. If there are multiple possible answers, print any of them. The string z should be the same length as x and y and consist only of lowercase English letters.ExamplesInputabaaOutputbaInputnzwzlniwelOutputxiyezInputabbaOutput-1NoteThe first case is from the statement.Another solution for the second case is "zizez"There is no solution for the third case. That is, there is no z such that f("ab", z)β=β "ba". | Inputabaa | Outputba | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'strings', '*900'] |
A. Vicious Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTonio has a keyboard with only two letters, "V" and "K".One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i.Β e. a letter "K" right after a letter "V") in the resulting string.InputThe first line will contain a string s consisting only of uppercase English letters "V" and "K" with length not less than 1 and not greater than 100.OutputOutput a single integer, the maximum number of times "VK" can appear as a substring of the given string after changing at most one character.ExamplesInputVKOutput1InputVVOutput1InputVOutput0InputVKKKKKKKKKVVVVVVVVVKOutput3InputKVKVOutput1NoteFor the first case, we do not change any letters. "VK" appears once, which is the maximum number of times it could appear.For the second case, we can change the second character from a "V" to a "K". This will give us the string "VK". This has one occurrence of the string "VK" as a substring.For the fourth case, we can change the fourth character from a "K" to a "V". This will give us the string "VKKVKKKKKKVVVVVVVVVK". This has three occurrences of the string "VK" as a substring. We can check no other moves can give us strictly more occurrences. | InputVK | Output1 | 2 seconds | 256 megabytes | ['brute force', '*1100'] |
G. Cut the pietime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady reached the n-th level in Township game, so Masha decided to bake a pie for him! Of course, the pie has a shape of convex n-gon, i.e. a polygon with n vertices.Arkady decided to cut the pie in two equal in area parts by cutting it by a straight line, so that he can eat one of them and give the other to Masha. There is a difficulty because Arkady has already put a knife at some point of the pie, so he now has to cut the pie by a straight line passing trough this point.Help Arkady: find a line that passes through the point Arkady has put a knife into and cuts the pie into two parts of equal area, or determine that it's impossible. Your program has to quickly answer many queries with the same pie, but different points in which Arkady puts a knife.InputThe first line contains two integers n and q (3ββ€βnββ€β104, 1ββ€βqββ€β105)Β β the number of vertices in the pie and the number of queries.n line follow describing the polygon vertices in clockwise order. The i-th of these line contains two integers xi and yi (β-β106ββ€βxi,βyiββ€β106)Β β the coordinates of the i-th vertex. It is guaranteed that the polygon is strictly convex, in particular, no three vertices line on the same line.An empty line follows.q lines follow describing the query points. The i-th of these lines contain two integers xi and yi (β-β106ββ€βxi,βyiββ€β106)Β β the coordinates of the point in which Arkady puts the knife in the i-th query. In is guaranteed that in each query the given point is strictly inside the polygon, in particular, is not on its edges.OutputFor each query print single integerΒ β the polar angle of the line that is the answer for the corresponding query, in radians. The angle should be in the segment [0;Ο], the angles are measured from the direction of OX axis in counter-clockwise order. For example, the polar angle of the OY axis is . If there is no answer in that query, print -1.If there are several answers, print any of them. Your answer is considered correct if the difference between the areas of the parts divided by the total area of the polygon doesn't exceed 10β-β4 by absolute value. In other words, if a and b are the areas of the parts after the cut, then your answer is correct if and only of .ExamplesInput3 10 00 33 01 1Output2.67794504460098710000Input5 36 56 35 00 00 55 43 35 2Output0.602287346126900490001.279339532264735800002.85805511179015910000 | Input3 10 00 33 01 1 | Output2.67794504460098710000 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'geometry', '*3500'] |
F. Beautiful fountains rowstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputButler Ostin wants to show Arkady that rows of odd number of fountains are beautiful, while rows of even number of fountains are not.The butler wants to show Arkady n gardens. Each garden is a row of m cells, the i-th garden has one fountain in each of the cells between li and ri inclusive, and there are no more fountains in that garden. The issue is that some of the gardens contain even number of fountains, it is wrong to show them to Arkady.Ostin wants to choose two integers aββ€βb and show only part of each of the gardens that starts at cell a and ends at cell b. Of course, only such segments suit Ostin that each garden has either zero or odd number of fountains on this segment. Also, it is necessary that at least one garden has at least one fountain on the segment from a to b.Help Ostin to find the total length of all such segments, i.e. sum up the value (bβ-βaβ+β1) for each suitable pair (a,βb).InputThe first line contains two integers n and m (1ββ€βn,βmββ€β2Β·105)Β β the number of gardens and the length of each garden.n lines follow. The i-th of these lines contains two integers li and ri (1ββ€βliββ€βriββ€βm)Β β the bounds of the segment that contains fountains in the i-th garden.OutputPrint one integer: the total length of all suitable segments.ExamplesInput1 52 4Output23Input3 62 43 64 4Output19NoteIn the first example the following pairs suit Ostin: (a,βb): (1,β2), (1,β4), (1,β5), (2,β2), (2,β4), (2,β5), (3,β3), (4,β4), (4,β5).In the second example the following pairs suit Ostin: (a,βb): (1,β2), (1,β5), (2,β2), (2,β5), (3,β3), (4,β4), (4,β6), (5,β5), (6,β6). | Input1 52 4 | Output23 | 3 seconds | 256 megabytes | ['data structures', '*3500'] |
E. Aquarium decorationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady and Masha want to choose decorations for thier aquarium in Fishdom game. They have n decorations to choose from, each of them has some cost. To complete a task Arkady and Masha need to choose exactly m decorations from given, and they want to spend as little money as possible.There is one difficulty: Masha likes some a of the given decorations, Arkady likes some b of the given decorations. Some decorations may be liked by both Arkady and Masha, or not be liked by both. The friends want to choose such decorations so that each of them likes at least k decorations among the chosen. Help Masha and Arkady find the minimum sum of money they need to spend.InputThe first line contains three integers n, m and k (1ββ€βnββ€β200000, 1ββ€βmββ€βn, 1ββ€βkββ€βn)Β β the number of decorations, how many decorations the friends should choose, how many decorations each of them should like among the chosen.The second line contains n integers c1,βc2,β...,βcn (1ββ€βciββ€β109)Β β decorations costs.The third line contains single integer a (1ββ€βaββ€βn)Β β the number of decorations liked by Masha. The fourth line contains a distinct integers x1,βx2,β...,βxa (1ββ€βxiββ€βn)Β β the ids of decorations liked by Masha.The next two lines describe decorations liked by Arkady in the same format.OutputPrint single integer: the minimum sum of money the friends should spend to fulfill all constraints. If it is not possible, print -1.ExamplesInput4 3 23 2 2 121 221 3Output7Input4 3 23 2 2 121 234 1 3Output6Input4 2 23 2 2 121 234 1 3Output-1NoteIn the first example the only possible variant to choose 3 decorations having all conditions satisfied is to choose decorations 1, 2, 3.In the second example friends can choose decoration 4 instead of decoration 3, because this one is one coin cheaper.In the third example it's not possible to choose 2 decorations in a way that both are liked by both Masha and Arkady. | Input4 3 23 2 2 121 221 3 | Output7 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'two pointers', '*2500'] |
D. Field expansiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one of the games Arkady is fond of the game process happens on a rectangular field. In the game process Arkady can buy extensions for his field, each extension enlarges one of the field sizes in a particular number of times. Formally, there are n extensions, the i-th of them multiplies the width or the length (by Arkady's choice) by ai. Each extension can't be used more than once, the extensions can be used in any order.Now Arkady's field has size hβΓβw. He wants to enlarge it so that it is possible to place a rectangle of size aβΓβb on it (along the width or along the length, with sides parallel to the field sides). Find the minimum number of extensions needed to reach Arkady's goal.InputThe first line contains five integers a, b, h, w and n (1ββ€βa,βb,βh,βw,βnββ€β100β000)Β β the sizes of the rectangle needed to be placed, the initial sizes of the field and the number of available extensions.The second line contains n integers a1,βa2,β...,βan (2ββ€βaiββ€β100β000), where ai equals the integer a side multiplies by when the i-th extension is applied.OutputPrint the minimum number of extensions needed to reach Arkady's goal. If it is not possible to place the rectangle on the field with all extensions, print -1. If the rectangle can be placed on the initial field, print 0.ExamplesInput3 3 2 4 42 5 4 10Output1Input3 3 3 3 52 3 5 4 2Output0Input5 5 1 2 32 2 3Output-1Input3 4 1 1 32 3 2Output3NoteIn the first example it is enough to use any of the extensions available. For example, we can enlarge h in 5 times using the second extension. Then h becomes equal 10 and it is now possible to place the rectangle on the field. | Input3 3 2 4 42 5 4 10 | Output1 | 1 second | 256 megabytes | ['brute force', 'dp', 'meet-in-the-middle', '*2100'] |
C. Fountainstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady plays Gardenscapes a lot. Arkady wants to build two new fountains. There are n available fountains, for each fountain its beauty and cost are known. There are two types of money in the game: coins and diamonds, so each fountain cost can be either in coins or diamonds. No money changes between the types are allowed.Help Arkady to find two fountains with maximum total beauty so that he can buy both at the same time.InputThe first line contains three integers n, c and d (2ββ€βnββ€β100β000, 0ββ€βc,βdββ€β100β000)Β β the number of fountains, the number of coins and diamonds Arkady has.The next n lines describe fountains. Each of these lines contain two integers bi and pi (1ββ€βbi,βpiββ€β100β000)Β β the beauty and the cost of the i-th fountain, and then a letter "C" or "D", describing in which type of money is the cost of fountain i: in coins or in diamonds, respectively.OutputPrint the maximum total beauty of exactly two fountains Arkady can build. If he can't build two fountains, print 0.ExamplesInput3 7 610 8 C4 3 C5 6 DOutput9Input2 4 52 5 C2 1 DOutput0Input3 10 105 5 C5 5 C10 11 DOutput10NoteIn the first example Arkady should build the second fountain with beauty 4, which costs 3 coins. The first fountain he can't build because he don't have enough coins. Also Arkady should build the third fountain with beauty 5 which costs 6 diamonds. Thus the total beauty of built fountains is 9.In the second example there are two fountains, but Arkady can't build both of them, because he needs 5 coins for the first fountain, and Arkady has only 4 coins. | Input3 7 610 8 C4 3 C5 6 D | Output9 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', '*1800'] |
B. T-shirt buyingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.You are to compute the prices each buyer will pay for t-shirts.InputThe first line contains single integer n (1ββ€βnββ€β200β000)Β β the number of t-shirts.The following line contains sequence of integers p1,βp2,β...,βpn (1ββ€βpiββ€β1β000β000β000), where pi equals to the price of the i-th t-shirt.The following line contains sequence of integers a1,βa2,β...,βan (1ββ€βaiββ€β3), where ai equals to the front color of the i-th t-shirt.The following line contains sequence of integers b1,βb2,β...,βbn (1ββ€βbiββ€β3), where bi equals to the back color of the i-th t-shirt.The next line contains single integer m (1ββ€βmββ€β200β000)Β β the number of buyers. The following line contains sequence c1,βc2,β...,βcm (1ββ€βcjββ€β3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served. OutputPrint to the first line m integers β the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.ExamplesInput5300 200 400 500 9111 2 1 2 32 1 3 2 162 3 1 2 1 1Output200 400 300 500 911 -1 Input21000000000 11 11 222 1Output1 1000000000 | Input5300 200 400 500 9111 2 1 2 32 1 3 2 162 3 1 2 1 1 | Output200 400 300 500 911 -1 | 3 seconds | 256 megabytes | ['data structures', 'implementation', '*1400'] |
A. Carrot Cakestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can build one more similar oven to make the process faster, it would take d minutes to build the oven. While the new oven is being built, only old one can bake cakes, after the new oven is built, both ovens bake simultaneously. Arkady can't build more than one oven.Determine if it is reasonable to build the second oven, i.e. will it decrease the minimum time needed to get n cakes or not. If the time needed with the second oven is the same as with one oven, then it is unreasonable.InputThe only line contains four integers n, t, k, d (1ββ€βn,βt,βk,βdββ€β1β000)Β β the number of cakes needed, the time needed for one oven to bake k cakes, the number of cakes baked at the same time, the time needed to build the second oven. OutputIf it is reasonable to build the second oven, print "YES". Otherwise print "NO".ExamplesInput8 6 4 5OutputYESInput8 6 4 6OutputNOInput10 3 11 4OutputNOInput4 2 1 4OutputYESNoteIn the first example it is possible to get 8 cakes in 12 minutes using one oven. The second oven can be built in 5 minutes, so after 6 minutes the first oven bakes 4 cakes, the second oven bakes 4 more ovens after 11 minutes. Thus, it is reasonable to build the second oven. In the second example it doesn't matter whether we build the second oven or not, thus it takes 12 minutes to bake 8 cakes in both cases. Thus, it is unreasonable to build the second oven.In the third example the first oven bakes 11 cakes in 3 minutes, that is more than needed 10. It is unreasonable to build the second oven, because its building takes more time that baking the needed number of cakes using the only oven. | Input8 6 4 5 | OutputYES | 1 second | 256 megabytes | ['brute force', 'implementation', '*1100'] |
E. Mike and code of a permutationtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMike has discovered a new way to encode permutations. If he has a permutation Pβ=β[p1,βp2,β...,βpn], he will encode it in the following way:Denote by Aβ=β[a1,βa2,β...,βan] a sequence of length n which will represent the code of the permutation. For each i from 1 to n sequentially, he will choose the smallest unmarked j (1ββ€βjββ€βn) such that piβ<βpj and will assign to ai the number j (in other words he performs aiβ=βj) and will mark j. If there is no such j, he'll assign to ai the number β-β1 (he performs aiβ=ββ-β1). Mike forgot his original permutation but he remembers its code. Your task is simple: find any permutation such that its code is the same as the code of Mike's original permutation.You may assume that there will always be at least one valid permutation.InputThe first line contains single integer n (1ββ€βnββ€β500β000) β length of permutation.The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€βn or aiβ=ββ-β1) β the code of Mike's permutation.You may assume that all positive values from A are different.OutputIn first and only line print n numbers p1,βp2,β...,βpn (1ββ€βpiββ€βn) β a permutation P which has the same code as the given one. Note that numbers in permutation are distinct.ExamplesInput62 -1 1 5 -1 4Output2 6 1 4 5 3Input82 -1 4 -1 6 -1 8 -1Output1 8 2 7 3 6 4 5NoteFor the permutation from the first example:iβ=β1, the smallest j is 2 because p2β=β6β>βp1β=β2.iβ=β2, there is no j because p2β=β6 is the greatest element in the permutation.iβ=β3, the smallest j is 1 because p1β=β2β>βp3β=β1.iβ=β4, the smallest j is 5 (2 was already marked) because p5β=β5β>βp4β=β4.iβ=β5, there is no j because 2 is already marked.iβ=β6, the smallest j is 4 because p4β=β4β>βp6β=β3. | Input62 -1 1 5 -1 4 | Output2 6 1 4 5 3 | 4 seconds | 512 megabytes | ['constructive algorithms', 'data structures', 'graphs', 'sortings', '*3000'] |
D. Mike and distributiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers Aβ=β[a1,βa2,β...,βan] and Bβ=β[b1,βb2,β...,βbn] of length n each which he uses to ask people some quite peculiar questions.To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select k numbers Pβ=β[p1,βp2,β...,βpk] such that 1ββ€βpiββ€βn for 1ββ€βiββ€βk and elements in P are distinct. Sequence P will represent indices of elements that you'll select from both sequences. He calls such a subset P "unfair" if and only if the following conditions are satisfied: 2Β·(ap1β+β...β+βapk) is greater than the sum of all elements from sequence A, and 2Β·(bp1β+β...β+βbpk) is greater than the sum of all elements from the sequence B. Also, k should be smaller or equal to because it will be to easy to find sequence P if he allowed you to select too many elements!Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!InputThe first line contains integer n (1ββ€βnββ€β105) β the number of elements in the sequences. On the second line there are n space-separated integers a1,β...,βan (1ββ€βaiββ€β109) β elements of sequence A.On the third line there are also n space-separated integers b1,β...,βbn (1ββ€βbiββ€β109) β elements of sequence B.OutputOn the first line output an integer k which represents the size of the found subset. k should be less or equal to .On the next line print k integers p1,βp2,β...,βpk (1ββ€βpiββ€βn) β the elements of sequence P. You can print the numbers in any order you want. Elements in sequence P should be distinct.ExampleInput58 7 4 8 34 2 5 3 7Output31 4 5 | Input58 7 4 8 34 2 5 3 7 | Output31 4 5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'sortings', '*2400'] |
C. Mike and gcd problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike has a sequence Aβ=β[a1,βa2,β...,βan] of length n. He considers the sequence Bβ=β[b1,βb2,β...,βbn] beautiful if the gcd of all its elements is bigger than 1, i.e. . Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1ββ€βiβ<βn), delete numbers ai,βaiβ+β1 and put numbers aiβ-βaiβ+β1,βaiβ+βaiβ+β1 in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence A beautiful if it's possible, or tell him that it is impossible to do so. is the biggest non-negative number d such that d divides bi for every i (1ββ€βiββ€βn).InputThe first line contains a single integer n (2ββ€βnββ€β100β000) β length of sequence A.The second line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109) β elements of sequence A.OutputOutput on the first line "YES" (without quotes) if it is possible to make sequence A beautiful by performing operations described above, and "NO" (without quotes) otherwise.If the answer was "YES", output the minimal number of moves needed to make sequence A beautiful.ExamplesInput21 1OutputYES1Input36 2 4OutputYES0Input21 3OutputYES1NoteIn the first example you can simply make one move to obtain sequence [0,β2] with .In the second example the gcd of the sequence is already greater than 1. | Input21 1 | OutputYES1 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'number theory', '*1700'] |
B. Mike and stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike has n strings s1,βs2,β...,βsn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?InputThe first line contains integer n (1ββ€βnββ€β50) β the number of strings.This is followed by n lines which contain a string each. The i-th line corresponding to string si. Lengths of strings are equal. Lengths of each string is positive and don't exceed 50.OutputPrint the minimal number of moves Mike needs in order to make all the strings equal or print β-β1 if there is no solution.ExamplesInput4xzzwozwoxzzzwoxxzzwoOutput5Input2molzvlzvmoOutput2Input3kckckcOutput0Input3aaaaabOutput-1NoteIn the first sample testcase the optimal scenario is to perform operations in such a way as to transform all strings into "zwoxz". | Input4xzzwozwoxzzzwoxxzzwo | Output5 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'strings', '*1300'] |
A. Mike and palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome. A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.InputThe first and single line contains string s (1ββ€β|s|ββ€β15).OutputPrint "YES" (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or "NO" (without quotes) otherwise. ExamplesInputabccaaOutputYESInputabbccaOutputNOInputabcdaOutputYES | Inputabccaa | OutputYES | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'strings', '*1000'] |
F. Mice and Holestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Masha came home and noticed n mice in the corridor of her flat. Of course, she shouted loudly, so scared mice started to run to the holes in the corridor.The corridor can be represeted as a numeric axis with n mice and m holes on it. ith mouse is at the coordinate xi, and jth hole β at coordinate pj. jth hole has enough room for cj mice, so not more than cj mice can enter this hole.What is the minimum sum of distances that mice have to go through so that they all can hide in the holes? If ith mouse goes to the hole j, then its distance is |xiβ-βpj|.Print the minimum sum of distances.InputThe first line contains two integer numbers n, m (1ββ€βn,βmββ€β5000) β the number of mice and the number of holes, respectively.The second line contains n integers x1,βx2,β...,βxn (β-β109ββ€βxiββ€β109), where xi is the coordinate of ith mouse.Next m lines contain pairs of integer numbers pj,βcj (β-β109ββ€βpjββ€β109,β1ββ€βcjββ€β5000), where pj is the coordinate of jth hole, and cj is the maximum number of mice that can hide in the hole j.OutputPrint one integer number β the minimum sum of distances. If there is no solution, print -1 instead.ExamplesInput4 56 2 8 93 62 13 64 74 7Output11Input7 210 20 30 40 50 45 35-1000000000 101000000000 1Output7000000130 | Input4 56 2 8 93 62 13 64 74 7 | Output11 | 1.5 seconds | 256 megabytes | ['data structures', 'dp', 'greedy', 'sortings', '*2600'] |
E. Array Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputa is an array of n positive integers, all of which are not greater than n.You have to process q queries to this array. Each query is represented by two numbers p and k. Several operations are performed in each query; each operation changes p to pβ+βapβ+βk. There operations are applied until p becomes greater than n. The answer to the query is the number of performed operations.InputThe first line contains one integer n (1ββ€βnββ€β100000).The second line contains n integers β elements of a (1ββ€βaiββ€βn for each i from 1 to n).The third line containts one integer q (1ββ€βqββ€β100000).Then q lines follow. Each line contains the values of p and k for corresponding query (1ββ€βp,βkββ€βn).OutputPrint q integers, ith integer must be equal to the answer to ith query.ExampleInput31 1 131 12 13 1Output211NoteConsider first example:In first query after first operation pβ=β3, after second operation pβ=β5.In next two queries p is greater than n after the first operation. | Input31 1 131 12 13 1 | Output211 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', '*2000'] |
D. Broken BSTtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet T be arbitrary binary tree β tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent β it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: Set pointer to the root of a tree. Return success if the value in the current vertex is equal to the number you are looking for Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for Return fail if you try to go to the vertex that doesn't exist Here is the pseudo-code of the described algorithm: bool find(TreeNode t, int x) { if (t == null) return false; if (t.value == x) return true; if (x < t.value) return find(t.left, x); else return find(t.right, x);}find(root, x);The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.InputFirst line contains integer number n (1ββ€βnββ€β105) β number of vertices in the tree.Each of the next n lines contains 3 numbers v, l, r (0ββ€βvββ€β109) β value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number β-β1 is set instead. Note that different vertices of the tree may contain the same values.OutputPrint number of times when search algorithm will fail.ExamplesInput315 -1 -110 1 35 -1 -1Output2Input86 2 33 4 512 6 71 -1 84 -1 -15 -1 -114 -1 -12 -1 -1Output1NoteIn the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for. | Input315 -1 -110 1 35 -1 -1 | Output2 | 1 second | 256 megabytes | ['data structures', 'dfs and similar', '*2100'] |
C. Minimal stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: Extract the first character of s and append t with this character. Extract the last character of t and append u with this character. Petya wants to get strings s and t empty and string u lexicographically minimal.You should write a program that will help Petya win the game.InputFirst line contains non-empty string s (1ββ€β|s|ββ€β105), consisting of lowercase English letters.OutputPrint resulting string u.ExamplesInputcabOutputabcInputacdbOutputabdc | Inputcab | Outputabc | 1 second | 256 megabytes | ['data structures', 'greedy', 'strings', '*1700'] |
B. Odd sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given sequence a1,βa2,β...,βan of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You should write a program which finds sum of the best subsequence.InputThe first line contains integer number n (1ββ€βnββ€β105).The second line contains n integer numbers a1,βa2,β...,βan (β-β104ββ€βaiββ€β104). The sequence contains at least one subsequence with odd sum.OutputPrint sum of resulting subseqeuence.ExamplesInput4-2 2 -3 1Output3Input32 -5 -3Output-1NoteIn the first example sum of the second and the fourth elements is 3. | Input4-2 2 -3 1 | Output3 | 1 second | 256 megabytes | ['dp', 'greedy', 'implementation', '*1400'] |
A. k-Factorizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.InputThe first line contains two integers n and k (2ββ€βnββ€β100000, 1ββ€βkββ€β20).OutputIf it's impossible to find the representation of n as a product of k numbers, print -1.Otherwise, print k integers in any order. Their product must be equal to n. If there are multiple answers, print any of them.ExamplesInput100000 2Output2 50000 Input100000 20Output-1Input1024 5Output2 64 2 2 2 | Input100000 2 | Output2 50000 | 2 seconds | 256 megabytes | ['implementation', 'math', 'number theory', '*1100'] |
F. Sequence Recoverytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZane once had a good sequence a consisting of n integers a1,βa2,β...,βanΒ β but he has lost it.A sequence is said to be good if and only if all of its integers are non-negative and do not exceed 109 in value. However, Zane remembers having played around with his sequence by applying m operations to it.There are two types of operations:1. Find the maximum value of integers with indices i such that lββ€βiββ€βr, given l and r.2. Assign d as the value of the integer with index k, given k and d.After he finished playing, he restored his sequence to the state it was before any operations were applied. That is, sequence a was no longer affected by the applied type 2 operations. Then, he lost his sequence at some time between now and then.Fortunately, Zane remembers all the operations and the order he applied them to his sequence, along with the distinct results of all type 1 operations. Moreover, among all good sequences that would produce the same results when the same operations are applied in the same order, he knows that his sequence a has the greatest cuteness.We define cuteness of a sequence as the bitwise OR result of all integers in such sequence. For example, the cuteness of Zane's sequence a is a1 OR a2 OR ... OR an.Zane understands that it might not be possible to recover exactly the lost sequence given his information, so he would be happy to get any good sequence b consisting of n integers b1,βb2,β...,βbn that:1. would give the same results when the same operations are applied in the same order, and2. has the same cuteness as that of Zane's original sequence a.If there is such a sequence, find it. Otherwise, it means that Zane must have remembered something incorrectly, which is possible.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β3Β·105)Β β the number of integers in Zane's original sequence and the number of operations that have been applied to the sequence, respectively.The i-th of the following m lines starts with one integer ti ()Β β the type of the i-th operation.If the operation is type 1 (tiβ=β1), then three integers li, ri, and xi follow (1ββ€βliββ€βriββ€βn, 0ββ€βxiββ€β109)Β β the leftmost index to be considered, the rightmost index to be considered, and the maximum value of all integers with indices between li and ri, inclusive, respectively.If the operation is type 2 (tiβ=β2), then two integers ki and di follow (1ββ€βkiββ€βn, 0ββ€βdiββ€β109)Β β meaning that the integer with index ki should become di after this operation.It is guaranteed that xiββ βxj for all pairs (i,βj) where 1ββ€βiβ<βjββ€βm and tiβ=βtjβ=β1.The operations are given in the same order they were applied. That is, the operation that is given first was applied first, the operation that is given second was applied second, and so on.OutputIf there does not exist a valid good sequence, print "NO" (without quotation marks) in the first line.Otherwise, print "YES" (without quotation marks) in the first line, and print n space-separated integers b1,βb2,β...,βbn (0ββ€βbiββ€β109) in the second line.If there are multiple answers, print any of them.ExamplesInput5 41 1 5 191 2 5 12 5 1001 1 5 100OutputYES19 0 0 0 1Input5 21 1 5 01 1 5 100OutputNONoteIn the first sample, it is easy to verify that this good sequence is valid. In particular, its cuteness is 19 OR 0 OR 0 OR 0 OR 1 β=β 19.In the second sample, the two operations clearly contradict, so there is no such good sequence. | Input5 41 1 5 191 2 5 12 5 1001 1 5 100 | OutputYES19 0 0 0 1 | 2 seconds | 256 megabytes | ['bitmasks', 'data structures', 'greedy', '*2800'] |
E. Exam Cheatingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZane and Zane's crush have just decided to date! However, the girl is having a problem with her Physics final exam, and needs your help.There are n questions, numbered from 1 to n. Question i comes before question iβ+β1 (1ββ€βiβ<βn). Each of the questions cannot be guessed on, due to the huge penalty for wrong answers. The girl luckily sits in the middle of two geniuses, so she is going to cheat. However, the geniuses have limitations. Each of them may or may not know the answers to some questions. Anyway, it is safe to assume that the answers on their answer sheets are absolutely correct.To make sure she will not get caught by the proctor, the girl will glance at most p times, each time looking at no more than k consecutive questions on one of the two geniuses' answer sheet. When the girl looks at some question on an answer sheet, she copies the answer to that question if it is on that answer sheet, or does nothing otherwise.Help the girl find the maximum number of questions she can get correct.InputThe first line contains three integers n, p, and k (1ββ€βn,βpββ€β1,β000, 1ββ€βkββ€βmin(n,β50))Β β the number of questions, the maximum number of times the girl can glance, and the maximum number of consecutive questions that can be looked at in one time glancing, respectively.The second line starts with one integer r (0ββ€βrββ€βn), denoting the number of questions the first genius has answered on his answer sheet. Then follow r integers a1,βa2,β...,βar (1ββ€βaiββ€βn)Β β the answered questions, given in a strictly-increasing order (that is, aiβ<βaiβ+β1).The third line starts with one integer s (0ββ€βsββ€βn), denoting the number of questions the second genius has answered on his answer sheet. Then follow s integers b1,βb2,β...,βbs (1ββ€βbiββ€βn)Β β the answered questions, given in a strictly-increasing order (that is, biβ<βbiβ+β1).OutputPrint one integerΒ β the maximum number of questions the girl can answer correctly.ExamplesInput6 2 33 1 3 64 1 2 5 6Output4Input8 3 34 1 3 5 65 2 4 6 7 8Output7NoteLet (x,βl,βr) denote the action of looking at all questions i such that lββ€βiββ€βr on the answer sheet of the x-th genius.In the first sample, the girl could get 4 questions correct by performing sequence of actions (1,β1,β3) and (2,β5,β6).In the second sample, the girl could perform sequence of actions (1,β3,β5), (2,β2,β4), and (2,β6,β8) to get 7 questions correct. | Input6 2 33 1 3 64 1 2 5 6 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'dp', '*2400'] |
D. Police Stationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInzane finally found Zane with a lot of money to spare, so they together decided to establish a country of their own.Ruling a country is not an easy job. Thieves and terrorists are always ready to ruin the country's peace. To fight back, Zane and Inzane have enacted a very effective law: from each city it must be possible to reach a police station by traveling at most d kilometers along the roads. There are n cities in the country, numbered from 1 to n, connected only by exactly nβ-β1 roads. All roads are 1 kilometer long. It is initially possible to travel from a city to any other city using these roads. The country also has k police stations located in some cities. In particular, the city's structure satisfies the requirement enforced by the previously mentioned law. Also note that there can be multiple police stations in one city.However, Zane feels like having as many as nβ-β1 roads is unnecessary. The country is having financial issues, so it wants to minimize the road maintenance cost by shutting down as many roads as possible.Help Zane find the maximum number of roads that can be shut down without breaking the law. Also, help him determine such roads.InputThe first line contains three integers n, k, and d (2ββ€βnββ€β3Β·105, 1ββ€βkββ€β3Β·105, 0ββ€βdββ€βnβ-β1)Β β the number of cities, the number of police stations, and the distance limitation in kilometers, respectively.The second line contains k integers p1,βp2,β...,βpk (1ββ€βpiββ€βn)Β β each denoting the city each police station is located in.The i-th of the following nβ-β1 lines contains two integers ui and vi (1ββ€βui,βviββ€βn, uiββ βvi)Β β the cities directly connected by the road with index i.It is guaranteed that it is possible to travel from one city to any other city using only the roads. Also, it is possible from any city to reach a police station within d kilometers.OutputIn the first line, print one integer s that denotes the maximum number of roads that can be shut down.In the second line, print s distinct integers, the indices of such roads, in any order.If there are multiple answers, print any of them.ExamplesInput6 2 41 61 22 33 44 55 6Output15Input6 3 21 5 61 21 31 41 55 6Output24 5 NoteIn the first sample, if you shut down road 5, all cities can still reach a police station within kβ=β4 kilometers.In the second sample, although this is the only largest valid set of roads that can be shut down, you can print either 4 5 or 5 4 in the second line. | Input6 2 41 61 22 33 44 55 6 | Output15 | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'graphs', 'shortest paths', 'trees', '*2100'] |
C. Bank Hackingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlthough Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks. There are n banks, numbered from 1 to n. There are also nβ-β1 wires connecting the banks. All banks are initially online. Each bank also has its initial strength: bank i has initial strength ai.Let us define some keywords before we proceed. Bank i and bank j are neighboring if and only if there exists a wire directly connecting them. Bank i and bank j are semi-neighboring if and only if there exists an online bank k such that bank i and bank k are neighboring and bank k and bank j are neighboring.When a bank is hacked, it becomes offline (and no longer online), and other banks that are neighboring or semi-neighboring to it have their strengths increased by 1.To start his plan, Inzane will choose a bank to hack first. Indeed, the strength of such bank must not exceed the strength of his computer. After this, he will repeatedly choose some bank to hack next until all the banks are hacked, but he can continue to hack bank x if and only if all these conditions are met: Bank x is online. That is, bank x is not hacked yet. Bank x is neighboring to some offline bank. The strength of bank x is less than or equal to the strength of Inzane's computer. Determine the minimum strength of the computer Inzane needs to hack all the banks.InputThe first line contains one integer n (1ββ€βnββ€β3Β·105)Β β the total number of banks.The second line contains n integers a1,βa2,β...,βan (β-β109ββ€βaiββ€β109)Β β the strengths of the banks.Each of the next nβ-β1 lines contains two integers ui and vi (1ββ€βui,βviββ€βn, uiββ βvi)Β β meaning that there is a wire directly connecting banks ui and vi.It is guaranteed that the wires connect the banks in such a way that Inzane can somehow hack all the banks using a computer with appropriate strength.OutputPrint one integerΒ β the minimum strength of the computer Inzane needs to accomplish the goal.ExamplesInput51 2 3 4 51 22 33 44 5Output5Input738 -29 87 93 39 28 -551 22 53 22 41 77 6Output93Input51 2 7 6 71 55 33 42 4Output8NoteIn the first sample, Inzane can hack all banks using a computer with strength 5. Here is how: Initially, strengths of the banks are [1,β2,β3,β4,β5]. He hacks bank 5, then strengths of the banks become [1,β2,β4,β5,ββ-β]. He hacks bank 4, then strengths of the banks become [1,β3,β5,ββ-β,ββ-β]. He hacks bank 3, then strengths of the banks become [2,β4,ββ-β,ββ-β,ββ-β]. He hacks bank 2, then strengths of the banks become [3,ββ-β,ββ-β,ββ-β,ββ-β]. He completes his goal by hacking bank 1. In the second sample, Inzane can hack banks 4, 2, 3, 1, 5, 7, and 6, in this order. This way, he can hack all banks using a computer with strength 93. | Input51 2 3 4 51 22 33 44 5 | Output5 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'dp', 'trees', '*1900'] |
B. Find The Bonetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position xβ=βi.The problematic bone is initially at the position xβ=β1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions xβ=βui and xβ=βvi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at xβ=β4 and the one at xβ=β6, they will not be at the position xβ=β5 at any moment during the operation. Zaneβs puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.InputThe first line contains three integers n, m, and k (2ββ€βnββ€β106, 1ββ€βmββ€βn, 1ββ€βkββ€β3Β·105)Β β the number of cups, the number of holes on the table, and the number of swapping operations, respectively.The second line contains m distinct integers h1,βh2,β...,βhm (1ββ€βhiββ€βn)Β β the positions along the x-axis where there is a hole on the table.Each of the next k lines contains two integers ui and vi (1ββ€βui,βviββ€βn, uiββ βvi)Β β the positions of the cups to be swapped.OutputPrint one integerΒ β the final position along the x-axis of the bone.ExamplesInput7 3 43 4 61 22 55 77 1Output1Input5 1 221 22 4Output2NoteIn the first sample, after the operations, the bone becomes at xβ=β2, xβ=β5, xβ=β7, and xβ=β1, respectively.In the second sample, after the first operation, the bone becomes at xβ=β2, and falls into the hole onto the ground. | Input7 3 43 4 61 22 55 77 1 | Output1 | 2 seconds | 256 megabytes | ['implementation', '*1300'] |
A. Buying A Housetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us. The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: house i and house iβ+β1 (1ββ€βiβ<βn) are exactly 10 meters away. In this village, some houses are occupied, and some are not. Indeed, unoccupied houses can be purchased.You will be given n integers a1,βa2,β...,βan that denote the availability and the prices of the houses. If house i is occupied, and therefore cannot be bought, then ai equals 0. Otherwise, house i can be bought, and ai represents the money required to buy it, in dollars.As Zane has only k dollars to spare, it becomes a challenge for him to choose the house to purchase, so that he could live as near as possible to his crush. Help Zane determine the minimum distance from his crush's house to some house he can afford, to help him succeed in his love.InputThe first line contains three integers n, m, and k (2ββ€βnββ€β100, 1ββ€βmββ€βn, 1ββ€βkββ€β100)Β β the number of houses in the village, the house where the girl lives, and the amount of money Zane has (in dollars), respectively.The second line contains n integers a1,βa2,β...,βan (0ββ€βaiββ€β100)Β β denoting the availability and the prices of the houses.It is guaranteed that amβ=β0 and that it is possible to purchase some house with no more than k dollars.OutputPrint one integerΒ β the minimum distance, in meters, from the house where the girl Zane likes lives to the house Zane can buy.ExamplesInput5 1 200 27 32 21 19Output40Input7 3 5062 0 0 0 99 33 22Output30Input10 5 1001 0 1 0 0 0 0 0 1 1Output20NoteIn the first sample, with kβ=β20 dollars, Zane can buy only house 5. The distance from house mβ=β1 to house 5 is 10β+β10β+β10β+β10β=β40 meters.In the second sample, Zane can buy houses 6 and 7. It is better to buy house 6 than house 7, since house mβ=β3 and house 6 are only 30 meters away, while house mβ=β3 and house 7 are 40 meters away. | Input5 1 200 27 32 21 19 | Output40 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*800'] |
G. Replace Alltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor the analyst is at work. He learned about a feature in his text editor called "Replace All". Igor is too bored at work and thus he came up with the following problem:Given two strings x and y which consist of the English letters 'A' and 'B' only, a pair of strings (s,βt) is called good if: s and t consist of the characters '0' and '1' only. 1ββ€β|s|,β|t|ββ€βn, where |z| denotes the length of string z, and n is a fixed positive integer. If we replace all occurrences of 'A' in x and y with the string s, and replace all occurrences of 'B' in x and y with the string t, then the two obtained from x and y strings are equal. For example, if xβ=βAAB, yβ=βBB and nβ=β4, then (01, 0101) is one of good pairs of strings, because both obtained after replacing strings are "01010101".The flexibility of a pair of strings x and y is the number of pairs of good strings (s,βt). The pairs are ordered, for example the pairs (0, 1) and (1, 0) are different.You're given two strings c and d. They consist of characters 'A', 'B' and '?' only. Find the sum of flexibilities of all possible pairs of strings (c',βd') such that c' and d' can be obtained from c and d respectively by replacing the question marks with either 'A' or 'B', modulo 109β+β7.InputThe first line contains the string c (1ββ€β|c|ββ€β3Β·105).The second line contains the string d (1ββ€β|d|ββ€β3Β·105).The last line contains a single integer n (1ββ€βnββ€β3Β·105).OutputOutput a single integer: the answer to the problem, modulo 109β+β7.ExamplesInputA??3Output2InputAB10Output2046NoteFor the first sample, there are four possible pairs of (c',βd').If (c',βd')β=β(AA,βA), then the flexibility is 0.If (c',βd')β=β(AB,βA), then the flexibility is 0.If (c',βd')β=β(AA,βB), then the flexibility is 2, as the pairs of binary strings (1,β11), (0,β00) are the only good pairs.If (c',βd')β=β(AB,βB), then the flexibility is 0.Thus, the total flexibility is 2.For the second sample, there are 21β+β22β+β...β+β210β=β2046 possible binary strings of length not greater 10, and the set of pairs of good strings is precisely the set of pairs (s,βs), where s is a binary string of length not greater than 10. | InputA??3 | Output2 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', '*3400'] |
F. Leha and security systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBankopolis, the city you already know, finally got a new bank opened! Unfortunately, its security system is not yet working fine... Meanwhile hacker Leha arrived in Bankopolis and decided to test the system!Bank has n cells for clients' money. A sequence from n numbers a1,βa2,β...,βan describes the amount of money each client has. Leha wants to make requests to the database of the bank, finding out the total amount of money on some subsegments of the sequence and changing values of the sequence on some subsegments. Using a bug in the system, Leha can requests two types of queries to the database: 1 l r x y denoting that Leha changes each digit x to digit y in each element of sequence ai, for which lββ€βiββ€βr is holds. For example, if we change in number 11984381 digit 8 to 4, we get 11944341. It's worth noting that Leha, in order to stay in the shadow, never changes digits in the database to 0, i.e. yββ β0. 2 l r denoting that Leha asks to calculate and print the sum of such elements of sequence ai, for which lββ€βiββ€βr holds. As Leha is a white-hat hacker, he don't want to test this vulnerability on a real database. You are to write a similar database for Leha to test.InputThe first line of input contains two integers n and q (1ββ€βnββ€β105, 1ββ€βqββ€β105) denoting amount of cells in the bank and total amount of queries respectively. The following line contains n integers a1,βa2,β...,βan (1ββ€βaiβ<β109) denoting the amount of money in each cell initially. These integers do not contain leading zeros.Each of the following q lines has one of the formats: 1 l r x y (1ββ€βlββ€βrββ€βn, 0ββ€βxββ€β9, 1ββ€βyββ€β9), denoting Leha asks to change each digit x on digit y for each element ai of the sequence for which lββ€βiββ€βr holds; 2 l r (1ββ€βlββ€βrββ€βn), denoting you have to calculate and print the sum of elements ai for which lββ€βiββ€βr holds. OutputFor each second type query print a single number denoting the required sum.ExamplesInput5 538 43 4 12 701 1 3 4 82 2 41 4 5 0 81 2 5 8 72 1 5Output103207Input5 525 36 39 40 8991 1 3 2 72 1 21 3 5 9 11 4 4 0 92 1 5Output1111002NoteLet's look at the example testcase.Initially the sequence is [38,β43,β4,β12,β70]. After the first change each digit equal to 4 becomes 8 for each element with index in interval [1;Β 3]. Thus, the new sequence is [38,β83,β8,β12,β70].The answer for the first sum's query is the sum in the interval [2;Β 4], which equal 83β+β8β+β12β=β103, so the answer to this query is 103.The sequence becomes [38,β83,β8,β12,β78] after the second change and [38,β73,β7,β12,β77] after the third.The answer for the second sum's query is 38β+β73β+β7β+β12β+β77β=β207. | Input5 538 43 4 12 701 1 3 4 82 2 41 4 5 0 81 2 5 8 72 1 5 | Output103207 | 2 seconds | 512 megabytes | ['data structures', '*2800'] |
E. Choosing Carrottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present.There are n carrots arranged in a line. The i-th carrot from the left has juiciness ai. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose.To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS.Oleg is a sneaky bank client. When Igor goes to a restroom, he performs k moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each k such that 0ββ€βkββ€βnβ-β1, what is the juiciness of the carrot they will give to ZS if he makes k extra moves beforehand and both players play optimally?InputThe first line of input contains a single integer n (1ββ€βnββ€β3Β·105)Β β the total number of carrots.The next line contains n space-separated integers a1,βa2,β...,βan (1ββ€βaiββ€β109). Here ai denotes the juiciness of the i-th carrot from the left of the line.OutputOutput n space-separated integers x0,βx1,β...,βxnβ-β1. Here, xi denotes the juiciness of the carrot the friends will present to ZS if kβ=βi.ExamplesInput41 2 3 5Output3 3 5 5Input51000000000 1000000000 1000000000 1000000000 1Output1000000000 1000000000 1000000000 1000000000 1000000000NoteFor the first example, When kβ=β0, one possible optimal game is as follows: Oleg eats the carrot with juiciness 1. Igor eats the carrot with juiciness 5. Oleg eats the carrot with juiciness 2. The remaining carrot has juiciness 3.When kβ=β1, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2. Igor eats the carrot with juiciness 5. The remaining carrot has juiciness 3.When kβ=β2, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3. The remaining carrot has juiciness 5.When kβ=β3, one possible optimal play is as follows: Oleg eats the carrot with juiciness 1 beforehand. Oleg eats the carrot with juiciness 2 beforehand. Oleg eats the carrot with juiciness 3 beforehand. The remaining carrot has juiciness 5.Thus, the answer is 3,β3,β5,β5.For the second sample, Oleg can always eat the carrot with juiciness 1 since he always moves first. So, the remaining carrot will always have juiciness 1000000000. | Input41 2 3 5 | Output3 3 5 5 | 2 seconds | 256 megabytes | ['games', 'math', '*2800'] |
D. Labelling Citiestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg the bank client lives in Bankopolia. There are n cities in Bankopolia and some pair of cities are connected directly by bi-directional roads. The cities are numbered from 1 to n. There are a total of m roads in Bankopolia, the i-th road connects cities ui and vi. It is guaranteed that from each city it is possible to travel to any other city using some of the roads.Oleg wants to give a label to each city. Suppose the label of city i is equal to xi. Then, it must hold that for all pairs of cities (u,βv) the condition |xuβ-βxv|ββ€β1 holds if and only if there is a road connecting u and v.Oleg wonders if such a labeling is possible. Find an example of such labeling if the task is possible and state that it is impossible otherwise.InputThe first line of input contains two space-separated integers n and m (2ββ€βnββ€β3Β·105, 1ββ€βmββ€β3Β·105)Β β the number of cities and the number of roads.Next, m lines follow. The i-th line contains two space-separated integers ui and vi (1ββ€βui,βviββ€βn, uiββ βvi)Β β the cities connected by the i-th road. It is guaranteed that there is at most one road between each pair of cities and it is possible to travel from any city to any other city using some roads.OutputIf the required labeling is not possible, output a single line containing the string "NO" (without quotes).Otherwise, output the string "YES" (without quotes) on the first line. On the next line, output n space-separated integers, x1,βx2,β...,βxn. The condition 1ββ€βxiββ€β109 must hold for all i, and for all pairs of cities (u,βv) the condition |xuβ-βxv|ββ€β1 must hold if and only if there is a road connecting u and v.ExamplesInput4 41 21 31 43 4OutputYES2 3 1 1 Input5 101 21 31 41 52 32 42 53 43 55 4OutputYES1 1 1 1 1 Input4 31 21 31 4OutputNONoteFor the first sample, x1β=β2, x2β=β3, x3β=βx4β=β1 is a valid labeling. Indeed, (3,β4), (1,β2), (1,β3), (1,β4) are the only pairs of cities with difference of labels not greater than 1, and these are precisely the roads of Bankopolia.For the second sample, all pairs of cities have difference of labels not greater than 1 and all pairs of cities have a road connecting them.For the last sample, it is impossible to construct a labeling satisfying the given constraints. | Input4 41 21 31 43 4 | OutputYES2 3 1 1 | 3 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'hashing', '*2400'] |
C. Naming Companytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi)InputThe first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially.The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.OutputThe output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.ExamplesInputtinkoffzscoderOutputfzfsirkInputxxxxxxxxxxxxOutputxxxxxxInputioiimoOutputioiNoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Inputtinkoffzscoder | Outputfzfsirk | 2 seconds | 256 megabytes | ['games', 'greedy', 'sortings', '*1800'] |
B. Cutting Carrottime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make nβ-β1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area? Illustration to the first example. InputThe first and only line of input contains two space-separated integers, n and h (2ββ€βnββ€β1000, 1ββ€βhββ€β105).OutputThe output should contain nβ-β1 real numbers x1,βx2,β...,βxnβ-β1. The number xi denotes that the i-th cut must be made xi units away from the apex of the carrot. In addition, 0β<βx1β<βx2β<β...β<βxnβ-β1β<βh must hold. Your output will be considered correct if absolute or relative error of every number in your output doesn't exceed 10β-β6.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput3 2Output1.154700538379 1.632993161855Input2 100000Output70710.678118654752NoteDefinition of isosceles triangle: https://en.wikipedia.org/wiki/Isosceles_triangle. | Input3 2 | Output1.154700538379 1.632993161855 | 2 seconds | 256 megabytes | ['geometry', 'math', '*1200'] |
A. Bank Robberytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that bβ<βa, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that cβ>βa, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.InputThe first line of input contains three space-separated integers, a, b and c (1ββ€βbβ<βaβ<βcββ€β109), denoting the positions of Oleg, the first security guard and the second security guard, respectively.The next line of input contains a single integer n (1ββ€βnββ€β105), denoting the number of banknotes.The next line of input contains n space-separated integers x1,βx2,β...,βxn (1ββ€βxiββ€β109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.OutputOutput a single integer: the maximum number of banknotes Oleg can take.ExamplesInput5 3 784 7 5 5 3 6 2 8Output4Input6 5 751 5 7 92 3Output0NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards. | Input5 3 784 7 5 5 3 6 2 8 | Output4 | 2 seconds | 256 megabytes | ['brute force', 'implementation', '*800'] |
G. Oleg and chesstime limit per test6.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg the bank client solves an interesting chess problem: place on nβΓβn chessboard the maximum number of rooks so that they don't beat each other. Of course, no two rooks can share the same cell.Remind that a rook standing in the cell (a,βb) beats a rook standing in the cell (x,βy) if and only if aβ=βx or bβ=βy.Unfortunately (of fortunately?) for Oleg the answer in this problem was always n, so the task bored Oleg soon. He decided to make it more difficult by removing some cells from the board. If a cell is deleted, Oleg can't put a rook there, but rooks do beat each other "through" deleted cells.Oleg deletes the cells in groups, namely, he repeatedly choose a rectangle with sides parallel to the board sides and deletes all the cells inside the rectangle. Formally, if he chooses a rectangle, lower left cell of which has coordinates (x1,βy1), and upper right cell of which has coordinates (x2,βy2), then he deletes all such cells with coordinates (x,βy) that x1ββ€βxββ€βx2 and y1ββ€βyββ€βy2. It is guaranteed that no cell is deleted twice, i.e. the chosen rectangles do not intersect.This version of the problem Oleg can't solve, and his friend Igor is busy at a conference, so he can't help Oleg.You are the last hope for Oleg! Help him: given the size of the board and the deleted rectangles find the maximum possible number of rooks that could be placed on the board so that no two rooks beat each other.InputThe first line contains single integer n (1βββ€ββnββ€ββ10000)Β β the size of the board.The second line contains single integer q (0βββ€ββqβββ€ββ10000)Β β the number of deleted rectangles.The next q lines contain the information about the deleted rectangles.Each of these lines contains four integers x1, y1, x2 and y2 (1βββ€βx1ββ€βx2ββ€βn, 1βββ€βy1ββ€βy2ββ€βn)Β β the coordinates of the lower left and the upper right cells of a deleted rectangle.If is guaranteed that the rectangles do not intersect.OutputIn the only line print the maximum number of rooks Oleg can place on the board so that no two rooks beat each other.ExamplesInput551 1 2 11 3 1 54 1 5 52 5 2 53 2 3 5Output3Input842 2 4 61 8 1 87 1 8 25 4 6 8Output8NoteHere is the board and the example of rooks placement in the first example: | Input551 1 2 11 3 1 54 1 5 52 5 2 53 2 3 5 | Output3 | 6.5 seconds | 256 megabytes | ['data structures', 'divide and conquer', 'flows', 'graph matchings', '*3400'] |
F. Julia the snailtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAfter hard work Igor decided to have some rest.He decided to have a snail. He bought an aquarium with a slippery tree trunk in the center, and put a snail named Julia into the aquarium.Igor noticed that sometimes Julia wants to climb onto the trunk, but can't do it because the trunk is too slippery. To help the snail Igor put some ropes on the tree, fixing the lower end of the i-th rope on the trunk on the height li above the ground, and the higher end on the height ri above the ground.For some reason no two ropes share the same position of the higher end, i.e. all ri are distinct. Now Julia can move down at any place of the trunk, and also move up from the lower end of some rope to its higher end. Igor is proud of his work, and sometimes think about possible movements of the snail. Namely, he is interested in the following questions: Β«Suppose the snail is on the trunk at height x now. What is the highest position on the trunk the snail can get on if it would never be lower than x or higher than y?Β» Please note that Julia can't move from a rope to the trunk before it reaches the higher end of the rope, and Igor is interested in the highest position on the tree trunk.Igor is interested in many questions, and not always can answer them. Help him, write a program that answers these questions.InputThe first line contains single integer n (1βββ€ββnββ€ββ100000)Β β the height of the trunk.The second line contains single integer m (1βββ€ββmβββ€ββ100000)Β β the number of ropes.The next m lines contain information about the ropes.The i-th of these lines contains two integers li and ri (1βββ€βliββ€βriββ€βn)Β β the heights on which the lower and the higher ends of the i-th rope are fixed, respectively. It is guaranteed that all ri are distinct.The next line contains single integer q (1βββ€ββqβββ€ββ100000)Β β the number of questions.The next q lines contain information about the questions.Each of these lines contain two integers x and y (1βββ€βxββ€βyββ€βn), where x is the height where Julia starts (and the height Julia can't get lower than), and y is the height Julia can't get higher than.OutputFor each question print the maximum reachable for Julia height.ExamplesInput841 23 42 56 751 21 41 62 76 8Output22557Input10103 71 41 65 51 13 97 81 23 37 10102 41 73 43 52 82 55 53 57 73 10Output27332253710NoteThe picture of the first sample is on the left, the picture of the second sample is on the right. Ropes' colors are just for clarity, they don't mean anything. | Input841 23 42 56 751 21 41 62 76 8 | Output22557 | 2 seconds | 512 megabytes | ['data structures', 'divide and conquer', 'dp', '*3000'] |
E. Problem of officestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEarlier, when there was no Internet, each bank had a lot of offices all around Bankopolis, and it caused a lot of problems. Namely, each day the bank had to collect cash from all the offices.Once Oleg the bank client heard a dialogue of two cash collectors. Each day they traveled through all the departments and offices of the bank following the same route every day. The collectors started from the central department and moved between some departments or between some department and some office using special roads. Finally, they returned to the central department. The total number of departments and offices was n, the total number of roads was nβ-β1. In other words, the special roads system was a rooted tree in which the root was the central department, the leaves were offices, the internal vertices were departments. The collectors always followed the same route in which the number of roads was minimum possible, that is 2nβ-β2.One of the collectors said that the number of offices they visited between their visits to offices a and then b (in the given order) is equal to the number of offices they visited between their visits to offices b and then a (in this order). The other collector said that the number of offices they visited between their visits to offices c and then d (in this order) is equal to the number of offices they visited between their visits to offices d and then c (in this order). The interesting part in this talk was that the shortest path (using special roads only) between any pair of offices among a, b, c and d passed through the central department.Given the special roads map and the indexes of offices a, b, c and d, determine if the situation described by the collectors was possible, or not.InputThe first line contains single integer n (5ββ€βnββ€β5000)Β β the total number of offices and departments. The departments and offices are numbered from 1 to n, the central office has index 1.The second line contains four integers a, b, c and d (2ββ€βa,βb,βc,βdββ€βn)Β β the indexes of the departments mentioned in collector's dialogue. It is guaranteed that these indexes are offices (i.e. leaves of the tree), not departments. It is guaranteed that the shortest path between any pair of these offices passes through the central department.On the third line nβ-β1 integers follow: p2,βp3,β...,βpn (1ββ€βpiβ<βi), where pi denotes that there is a special road between the i-th office or department and the pi-th department.Please note the joint enumeration of departments and offices.It is guaranteed that the given graph is a tree. The offices are the leaves, the departments are the internal vertices.OutputIf the situation described by the cash collectors was possible, print "YES". Otherwise, print "NO".ExamplesInput52 3 4 51 1 1 1OutputYESInput103 8 9 101 2 2 2 2 2 1 1 1OutputNOInput1313 12 9 71 1 1 1 5 5 2 2 2 3 3 4OutputYESNoteIn the first example the following collector's route was possible: . We can note that between their visits to offices a and b the collectors visited the same number of offices as between visits to offices b and a; the same holds for c and d (the collectors' route is infinite as they follow it each day).In the second example there is no route such that between their visits to offices c and d the collectors visited the same number of offices as between visits to offices d and c. Thus, there situation is impossible. In the third example one of the following routes is: . | Input52 3 4 51 1 1 1 | OutputYES | 2 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'trees', '*2900'] |
D. Presents in Bankopolistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBankopolis is an incredible city in which all the n crossroads are located on a straight line and numbered from 1 to n along it. On each crossroad there is a bank office.The crossroads are connected with m oriented bicycle lanes (the i-th lane goes from crossroad ui to crossroad vi), the difficulty of each of the lanes is known.Oleg the bank client wants to gift happiness and joy to the bank employees. He wants to visit exactly k offices, in each of them he wants to gift presents to the employees.The problem is that Oleg don't want to see the reaction on his gifts, so he can't use a bicycle lane which passes near the office in which he has already presented his gifts (formally, the i-th lane passes near the office on the x-th crossroad if and only if min(ui,βvi)β<βxβ<βmax(ui,βvi))). Of course, in each of the offices Oleg can present gifts exactly once. Oleg is going to use exactly kβ-β1 bicycle lane to move between offices. Oleg can start his path from any office and finish it in any office.Oleg wants to choose such a path among possible ones that the total difficulty of the lanes he will use is minimum possible. Find this minimum possible total difficulty.InputThe first line contains two integers n and k (1ββ€βn,βkββ€β80)Β β the number of crossroads (and offices) and the number of offices Oleg wants to visit.The second line contains single integer m (0ββ€βmββ€β2000)Β β the number of bicycle lanes in Bankopolis.The next m lines contain information about the lanes.The i-th of these lines contains three integers ui, vi and ci (1ββ€βui,βviββ€βn, 1ββ€βciββ€β1000), denoting the crossroads connected by the i-th road and its difficulty.OutputIn the only line print the minimum possible total difficulty of the lanes in a valid path, or -1 if there are no valid paths.ExamplesInput7 441 6 26 2 22 4 22 7 1Output6Input4 342 1 21 3 23 4 24 1 1Output3NoteIn the first example Oleg visiting banks by path 1βββ6βββ2βββ4.Path 1βββ6βββ2βββ7 with smaller difficulity is incorrect because crossroad 2βββ7 passes near already visited office on the crossroad 6.In the second example Oleg can visit banks by path 4βββ1βββ3. | Input7 441 6 26 2 22 4 22 7 1 | Output6 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'shortest paths', '*2100'] |
C. Mice problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIgor the analyst fell asleep on the work and had a strange dream. In the dream his desk was crowded with computer mice, so he bought a mousetrap to catch them.The desk can be considered as an infinite plane, then the mousetrap is a rectangle which sides are parallel to the axes, and which opposite sides are located in points (x1,βy1) and (x2,βy2).Igor wants to catch all mice. Igor has analysed their behavior and discovered that each mouse is moving along a straight line with constant speed, the speed of the i-th mouse is equal to (vix,βviy), that means that the x coordinate of the mouse increases by vix units per second, while the y coordinates increases by viy units. The mousetrap is open initially so that the mice are able to move freely on the desk. Igor can close the mousetrap at any moment catching all the mice that are strictly inside the mousetrap.Igor works a lot, so he is busy in the dream as well, and he asks you to write a program that by given mousetrap's coordinates, the initial coordinates of the mice and their speeds determines the earliest time moment in which he is able to catch all the mice. Please note that Igor can close the mousetrap only once.InputThe first line contains single integer n (1ββ€βnββ€β100β000)Β β the number of computer mice on the desk.The second line contains four integers x1, y1, x2 and y2 (0ββ€βx1ββ€βx2ββ€β100β000), (0ββ€βy1ββ€βy2ββ€β100β000)Β β the coordinates of the opposite corners of the mousetrap.The next n lines contain the information about mice.The i-th of these lines contains four integers rix, riy, vix and viy, (0ββ€βrix,βriyββ€β100β000, β-β100β000ββ€βvix,βviyββ€β100β000), where (rix,βriy) is the initial position of the mouse, and (vix,βviy) is its speed.OutputIn the only line print minimum possible non-negative number t such that if Igor closes the mousetrap at t seconds from the beginning, then all the mice are strictly inside the mousetrap. If there is no such t, print -1.Your answer is considered correct if its absolute or relative error doesn't exceed 10β-β6. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .ExamplesInput47 7 9 83 5 7 57 5 2 43 3 7 86 6 3 2Output0.57142857142857139685Input47 7 9 80 3 -5 45 0 5 49 9 -1 -610 5 -7 -10Output-1NoteHere is a picture of the first samplePoints A, B, C, D - start mice positions, segments are their paths.Then, at first time when all mice will be in rectangle it will be looks like this:Here is a picture of the second samplePoints A, D, B will never enter rectangle. | Input47 7 9 83 5 7 57 5 2 43 3 7 86 6 3 2 | Output0.57142857142857139685 | 2 seconds | 256 megabytes | ['geometry', 'implementation', 'math', 'sortings', '*2300'] |
B. Igor and his way to worktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWoken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel, so he can make no more than two turns on his way to his office in bank.Bankopolis looks like a grid of n rows and m columns. Igor should find a way from his home to the bank that has no more than two turns and doesn't contain cells with road works, or determine that it is impossible and he should work from home. A turn is a change in movement direction. Igor's car can only move to the left, to the right, upwards and downwards. Initially Igor can choose any direction. Igor is still sleepy, so you should help him.InputThe first line contains two integers n and m (1ββ€βn,βmββ€β1000)Β β the number of rows and the number of columns in the grid.Each of the next n lines contains m characters denoting the corresponding row of the grid. The following characters can occur: "." β an empty cell; "*" β a cell with road works; "S" β the cell where Igor's home is located; "T" β the cell where Igor's office is located. It is guaranteed that "S" and "T" appear exactly once each.OutputIn the only line print "YES" if there is a path between Igor's home and Igor's office with no more than two turns, and "NO" otherwise.ExamplesInput5 5..S..****.T....****......OutputYESInput5 5S....****.......****..T..OutputNONoteThe first sample is shown on the following picture: In the second sample it is impossible to reach Igor's office using less that 4 turns, thus there exists no path using no more than 2 turns. The path using exactly 4 turns is shown on this picture: | Input5 5..S..****.T....****...... | OutputYES | 3 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'implementation', 'shortest paths', '*1600'] |
A. Oleg and sharestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?InputThe first line contains two integers n and k (1ββ€βnββ€β105,β1ββ€βkββ€β109)Β β the number of share prices, and the amount of rubles some price decreases each second.The second line contains n integers a1,βa2,β...,βan (1ββ€βaiββ€β109)Β β the initial prices.OutputPrint the only line containing the minimum number of seconds needed for prices to become equal, of Β«-1Β» if it is impossible.ExamplesInput3 312 9 15Output3Input2 210 9Output-1Input4 11 1000000000 1000000000 1000000000Output2999999997NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999β*β3β=β2999999997 seconds. We can note that this is the minimum possible time. | Input3 312 9 15 | Output3 | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
F. Mages and Monsterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi β damage per second and mana cost per second, respectively. Vova doesn't have to use a spell for an integer amount of seconds. More formally, if he uses a spell with damage x and mana cost y for z seconds, then he will deal xΒ·z damage and spend yΒ·z mana (no rounding). If there is no mana left (mana amount is set in the start of the game and it remains the same at the beginning of every fight), then character won't be able to use any spells. It is prohibited to use multiple spells simultaneously.Also Vova can fight monsters. Every monster is characterized by two values tj and hj β monster kills Vova's character in tj seconds and has hj health points. Mana refills after every fight (or Vova's character revives with full mana reserve), so previous fights have no influence on further ones.Vova's character kills a monster, if he deals hj damage to it in no more than tj seconds using his spells (it is allowed to use more than one spell in a fight) and spending no more mana than he had at the beginning of the fight. If monster's health becomes zero exactly in tj seconds (it means that the monster and Vova's character kill each other at the same time), then Vova wins the fight.You have to write a program which can answer two types of queries: 1 x y β Vova's character learns new spell which deals x damage per second and costs y mana per second. 2 t h β Vova fights the monster which kills his character in t seconds and has h health points. Note that queries are given in a different form. Also remember that Vova's character knows no spells at the beginning of the game.For every query of second type you have to determine if Vova is able to win the fight with corresponding monster.InputThe first line contains two integer numbers q and m (2ββ€βqββ€β105,β1ββ€βmββ€β1012) β the number of queries and the amount of mana at the beginning of every fight.i-th of each next q lines contains three numbers ki, ai and bi (1ββ€βkiββ€β2,β1ββ€βai,βbiββ€β106). Using them you can restore queries this way: let j be the index of the last query of second type with positive answer (jβ=β0 if there were none of these). If kiβ=β1, then character learns spell with xβ=β(aiβ+βj) mod 106β+β1, yβ=β(biβ+βj) mod 106β+β1. If kiβ=β2, then you have to determine if Vova is able to win the fight against monster with tβ=β(aiβ+βj) mod 106β+β1, hβ=β(biβ+βj) mod 106β+β1. OutputFor every query of second type print YES if Vova is able to win the fight with corresponding monster and NO otherwise.ExampleInput3 1001 4 92 19 492 19 49OutputYESNONoteIn first example Vova's character at first learns the spell with 5 damage and 10 mana cost per second. Next query is a fight with monster which can kill character in 20 seconds and has 50 health points. Vova kills it in 10 seconds (spending 100 mana). Next monster has 52 health, so Vova can't deal that much damage with only 100 mana. | Input3 1001 4 92 19 492 19 49 | OutputYESNO | 2 seconds | 256 megabytes | ['data structures', 'geometry', '*3100'] |
E. Colored Ballstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that: each ball belongs to exactly one of the sets, there are no empty sets, there is no set containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.InputThe first line contains one integer number n (1ββ€βnββ€β500).The second line contains n integer numbers a1,βa2,β... ,βan (1ββ€βaiββ€β109).OutputPrint one integer number β the minimum possible number of sets.ExamplesInput34 7 8Output5Input22 7Output4NoteIn the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color. | Input34 7 8 | Output5 | 1 second | 256 megabytes | ['greedy', 'math', 'number theory', '*2500'] |
D. Paths in a Complete Binary Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputT is a complete binary tree consisting of n vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So n is a number such that nβ+β1 is a power of 2.In the picture you can see a complete binary tree with nβ=β15. Vertices are numbered from 1 to n in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.You have to write a program that for given n answers q queries to the tree.Each query consists of an integer number ui (1ββ€βuiββ€βn) and a string si, where ui is the number of vertex, and si represents the path starting from this vertex. String si doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from si have to be processed from left to right, considering that ui is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by si ends.For example, if uiβ=β4 and siβ=βΒ«UURLΒ», then the answer is 10.InputThe first line contains two integer numbers n and q (1ββ€βnββ€β1018, qββ₯β1). n is such that nβ+β1 is a power of 2.The next 2q lines represent queries; each query consists of two consecutive lines. The first of these two lines contains ui (1ββ€βuiββ€βn), the second contains non-empty string si. si doesn't contain any characters other than 'L', 'R' and 'U'.It is guaranteed that the sum of lengths of si (for each i such that 1ββ€βiββ€βq) doesn't exceed 105.OutputPrint q numbers, i-th number must be the answer to the i-th query.ExampleInput15 24UURL8LRLLLLLLLLOutput105 | Input15 24UURL8LRLLLLLLLL | Output105 | 3 seconds | 256 megabytes | ['bitmasks', 'trees', '*1900'] |
C. Divide by Threetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.InputThe first line of input contains n β a positive integer number without leading zeroes (1ββ€βnβ<β10100000).OutputPrint one number β any beautiful number obtained by erasing as few as possible digits. If there is no answer, print β-β1.ExamplesInput1033Output33Input10Output0Input11Output-1NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | Input1033 | Output33 | 1 second | 256 megabytes | ['dp', 'greedy', 'math', 'number theory', '*2000'] |
B. Counting-out Rhymetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputn children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8,β10,β13,β14,β16] currently in the circle, the leader is child 13 and aiβ=β12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.InputThe first line contains two integer numbers n and k (2ββ€βnββ€β100, 1ββ€βkββ€βnβ-β1).The next line contains k integer numbers a1,βa2,β...,βak (1ββ€βaiββ€β109).OutputPrint k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.ExamplesInput7 510 4 11 4 1Output4 2 5 6 1 Input3 22 5Output3 2 NoteLet's consider first example: In the first step child 4 is eliminated, child 5 becomes the leader. In the second step child 2 is eliminated, child 3 becomes the leader. In the third step child 5 is eliminated, child 6 becomes the leader. In the fourth step child 6 is eliminated, child 7 becomes the leader. In the final step child 1 is eliminated, child 3 becomes the leader. | Input7 510 4 11 4 1 | Output4 2 5 6 1 | 1 second | 256 megabytes | ['implementation', '*1300'] |
Subsets and Splits