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. Tennis Tournamenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tennis tournament with n participants is running. The participants are playing by an olympic system, so the winners move on and the losers drop out.The tournament takes place in the following way (below, m is the number of the participants of the current round): let k be the maximal power of the number 2 such that k ≀ m, k participants compete in the current round and a half of them passes to the next round, the other m - k participants pass to the next round directly, when only one participant remains, the tournament finishes. Each match requires b bottles of water for each participant and one bottle for the judge. Besides p towels are given to each participant for the whole tournament.Find the number of bottles and towels needed for the tournament.Note that it's a tennis tournament so in each match two participants compete (one of them will win and the other will lose).InputThe only line contains three integers n, b, p (1 ≀ n, b, p ≀ 500) β€” the number of participants and the parameters described in the problem statement.OutputPrint two integers x and y β€” the number of bottles and towels need for the tournament.ExamplesInput5 2 3Output20 15Input8 2 4Output35 32NoteIn the first example will be three rounds: in the first round will be two matches and for each match 5 bottles of water are needed (two for each of the participants and one for the judge), in the second round will be only one match, so we need another 5 bottles of water, in the third round will also be only one match, so we need another 5 bottles of water. So in total we need 20 bottles of water.In the second example no participant will move on to some round directly.
Input5 2 3
Output20 15
1 second
256 megabytes
['implementation', 'math', '*1000']
F. Island Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA remote island chain contains n islands, with some bidirectional bridges between them. The current bridge network forms a tree. In other words, a total of n - 1 bridges connect pairs of islands in a way that it's possible to reach any island from any other island using the bridge network. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: first, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.It is often impossible to rearrange statues in the desired order using only the operation described above. The islanders would like to build one additional bridge in order to make this achievable in the fewest number of movements possible. Find the bridge to construct and the minimum number of statue movements necessary to arrange the statues in the desired position.InputThe first line contains a single integer n (2 ≀ n ≀ 200 000)Β β€” the total number of islands.The second line contains n space-separated integers ai (0 ≀ ai ≀ n - 1)Β β€” the statue currently located on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct.The third line contains n space-separated integers bi (0 ≀ bi ≀ n - 1)Β β€” the desired statues of the i-th island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.The next n - 1 lines each contain two distinct space-separated integers ui and vi (1 ≀ ui, vi ≀ n)Β β€” the endpoints of the i-th bridge. Bridges form a tree, and it is guaranteed that no bridge is listed twice in the input.OutputPrint a single line of integers:If the rearrangement can be done in the existing network, output 0 t, where t is the number of moves necessary to perform the rearrangement.Otherwise, print u, v, and t (1 ≀ u < v ≀ n)Β β€” the two endpoints of the new bridge, and the minimum number of statue movements needed to perform the rearrangement.If the rearrangement cannot be done no matter how the new bridge is built, print a single line containing  - 1.ExamplesInput31 0 22 0 11 22 3Output1 3 3Input21 00 11 2Output0 1Input40 1 2 30 2 3 11 21 31 4Output-1NoteIn the first sample, the islanders can build a bridge connecting islands 1 and 3 and then make the following sequence of moves: first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3 for a total of 3 moves.In the second sample, the islanders can simply move statue 1 from island 1 to island 2. No new bridges need to be built and only 1 move needs to be made.In the third sample, no added bridge and subsequent movements result in the desired position.
Input31 0 22 0 11 22 3
Output1 3 3
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'trees', '*3400']
E. Orchestratime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPaul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count the number of possible pictures that Paul can take.Two pictures are considered to be different if the coordinates of corresponding rectangles are different.InputThe first line of input contains four space-separated integers r, c, n, k (1 ≀ r, c, n ≀ 3000, 1 ≀ k ≀ min(n, 10))Β β€” the number of rows and columns of the string section, the total number of violas, and the minimum number of violas Paul would like in his photograph, respectively.The next n lines each contain two integers xi and yi (1 ≀ xi ≀ r, 1 ≀ yi ≀ c): the position of the i-th viola. It is guaranteed that no location appears more than once in the input.OutputPrint a single integerΒ β€” the number of photographs Paul can take which include at least k violas. ExamplesInput2 2 1 11 2Output4Input3 2 3 31 13 12 2Output1Input3 2 3 21 13 12 2Output4NoteWe will use '*' to denote violinists and '#' to denote violists.In the first sample, the orchestra looks as follows: *#** Paul can take a photograph of just the viola, the 1 × 2 column containing the viola, the 2 × 1 row containing the viola, or the entire string section, for 4 pictures total.In the second sample, the orchestra looks as follows: #**##* Paul must take a photograph of the entire section.In the third sample, the orchestra looks the same as in the second sample.
Input2 2 1 11 2
Output4
2 seconds
256 megabytes
['two pointers', '*3000']
D. Preorder Testtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor his computer science class, Jacob builds a model tree with sticks and balls containing n nodes in the shape of a tree. Jacob has spent ai minutes building the i-th ball in the tree.Jacob's teacher will evaluate his model and grade Jacob based on the effort he has put in. However, she does not have enough time to search his whole tree to determine this; Jacob knows that she will examine the first k nodes in a DFS-order traversal of the tree. She will then assign Jacob a grade equal to the minimum ai she finds among those k nodes.Though Jacob does not have enough time to rebuild his model, he can choose the root node that his teacher starts from. Furthermore, he can rearrange the list of neighbors of each node in any order he likes. Help Jacob find the best grade he can get on this assignment.A DFS-order traversal is an ordering of the nodes of a rooted tree, built by a recursive DFS-procedure initially called on the root of the tree. When called on a given node v, the procedure does the following: Print v. Traverse the list of neighbors of the node v in order and iteratively call DFS-procedure on each one. Do not call DFS-procedure on node u if you came to node v directly from u. InputThe first line of the input contains two positive integers, n and k (2 ≀ n ≀ 200 000, 1 ≀ k ≀ n)Β β€” the number of balls in Jacob's tree and the number of balls the teacher will inspect.The second line contains n integers, ai (1 ≀ ai ≀ 1 000 000), the time Jacob used to build the i-th ball.Each of the next n - 1 lines contains two integers ui, vi (1 ≀ ui, vi ≀ n, ui ≠ vi) representing a connection in Jacob's tree between balls ui and vi.OutputPrint a single integerΒ β€” the maximum grade Jacob can get by picking the right root of the tree and rearranging the list of neighbors.ExamplesInput5 33 6 1 4 21 22 42 51 3Output3Input4 21 5 5 51 21 31 4Output1NoteIn the first sample, Jacob can root the tree at node 2 and order 2's neighbors in the order 4, 1, 5 (all other nodes have at most two neighbors). The resulting preorder traversal is 2, 4, 1, 3, 5, and the minimum ai of the first 3 nodes is 3.In the second sample, it is clear that any preorder traversal will contain node 1 as either its first or second node, so Jacob cannot do better than a grade of 1.
Input5 33 6 1 4 21 22 42 51 3
Output3
7 seconds
256 megabytes
['binary search', 'dfs and similar', 'dp', 'graphs', 'greedy', 'trees', '*2600']
C. Package Deliverytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.InputThe first line of input contains three space separated integers d, n, and m (1 ≀ n ≀ d ≀ 109, 1 ≀ m ≀ 200 000)Β β€” the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively.Each of the next m lines contains two integers xi, pi (1 ≀ xi ≀ d - 1, 1 ≀ pi ≀ 106)Β β€” the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.OutputPrint a single integerΒ β€” the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.ExamplesInput10 4 43 55 86 38 4Output22Input16 5 28 25 1Output-1NoteIn the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2Β·5 + 4Β·3 = 22 dollars.In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.
Input10 4 43 55 86 38 4
Output22
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'greedy', '*2200']
B. Factory Repairstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.InputThe first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b < a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively.The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.OutputFor each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.ExamplesInput5 2 2 1 81 1 21 5 31 2 12 21 4 21 3 22 12 3Output364Input5 4 10 1 61 1 51 5 51 3 21 5 22 12 2Output71NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Input5 2 2 1 81 1 21 5 31 2 12 21 4 21 3 22 12 3
Output364
4 seconds
256 megabytes
['data structures', '*1700']
A. XOR Equationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)?InputThe first line of the input contains two integers s and x (2 ≀ s ≀ 1012, 0 ≀ x ≀ 1012), the sum and bitwise xor of the pair of positive integers, respectively.OutputPrint a single integer, the number of solutions to the given conditions. If no solutions exist, print 0.ExamplesInput9 5Output4Input3 3Output2Input5 2Output0NoteIn the first sample, we have the following solutions: (2, 7), (3, 6), (6, 3), (7, 2).In the second sample, the only solutions are (1, 2) and (2, 1).
Input9 5
Output4
2 seconds
256 megabytes
['dp', 'math', '*1700']
G. Rafflestime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohnny is at a carnival which has n raffles. Raffle i has a prize with value pi. Each participant can put tickets in whichever raffles they choose (they may have more than one ticket in a single raffle). At the end of the carnival, one ticket is selected at random from each raffle, and the owner of the ticket wins the associated prize. A single person can win multiple prizes from different raffles. However, county rules prevent any one participant from owning more than half the tickets in a single raffle, i.e. putting more tickets in the raffle than all the other participants combined. To help combat this (and possibly win some prizes), the organizers started by placing a single ticket in each raffle, which they will never remove.Johnny bought t tickets and is wondering where to place them. Currently, there are a total of li tickets in the i-th raffle. He watches as other participants place tickets and modify their decisions and, at every moment in time, wants to know how much he can possibly earn. Find the maximum possible expected value of Johnny's winnings at each moment if he distributes his tickets optimally. Johnny may redistribute all of his tickets arbitrarily between each update, but he may not place more than t tickets total or have more tickets in a single raffle than all other participants combined.InputThe first line contains two integers n, t, and q (1 ≀ n, t, q ≀ 200 000) β€” the number of raffles, the number of tickets Johnny has, and the total number of updates, respectively.The second line contains n space-separated integers pi (1 ≀ pi ≀ 1000) β€” the value of the i-th prize.The third line contains n space-separated integers li (1 ≀ li ≀ 1000) β€” the number of tickets initially in the i-th raffle.The last q lines contain the descriptions of the updates. Each description contains two integers tk, rk (1 ≀ tk ≀ 2, 1 ≀ rk ≀ n) β€” the type of the update and the raffle number. An update of type 1 represents another participant adding a ticket to raffle rk. An update of type 2 represents another participant removing a ticket from raffle rk.It is guaranteed that, after each update, each raffle has at least 1 ticket (not including Johnny's) in it.OutputPrint q lines, each containing a single real numberΒ β€” the maximum expected value of Johnny's winnings after the k-th update. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2 1 34 51 21 11 22 1Output1.6666666671.3333333332.000000000Input3 20 56 8 106 6 61 11 21 32 32 3Output12.00000000012.00000000011.76923076912.00000000012.000000000NoteIn the first case, Johnny only has one ticket to distribute. The prizes are worth 4 and 5, and the raffles initially have 1 and 2 tickets, respectively. After the first update, each raffle has 2 tickets, so Johnny has expected value of winning by placing his ticket into the second raffle. The second update adds a ticket to the second raffle, so Johnny can win in the first raffle. After the final update, Johnny keeps his ticket in the first raffle and wins .In the second case, Johnny has more tickets than he is allowed to spend. In particular, after the first update, there are 7, 6, and 6 tickets in each raffle, respectively, so Johnny can only put in 19 tickets, winning each prize with probability . Also, note that after the last two updates, Johnny must remove a ticket from the last raffle in order to stay under the tickets in the third raffle.
Input2 1 34 51 21 11 22 1
Output1.6666666671.3333333332.000000000
5 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'math', '*3100']
F. Group Projectstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students in a class working on group projects. The students will divide into groups (some students may be in groups alone), work on their independent pieces, and then discuss the results together. It takes the i-th student ai minutes to finish his/her independent piece.If students work at different paces, it can be frustrating for the faster students and stressful for the slower ones. In particular, the imbalance of a group is defined as the maximum ai in the group minus the minimum ai in the group. Note that a group containing a single student has an imbalance of 0. How many ways are there for the students to divide into groups so that the total imbalance of all groups is at most k?Two divisions are considered distinct if there exists a pair of students who work in the same group in one division but different groups in the other.InputThe first line contains two space-separated integers n and k (1 ≀ n ≀ 200, 0 ≀ k ≀ 1000)Β β€” the number of students and the maximum total imbalance allowed, respectively.The second line contains n space-separated integers ai (1 ≀ ai ≀ 500)Β β€” the time it takes the i-th student to complete his/her independent piece of work.OutputPrint a single integer, the number of ways the students can form groups. As the answer may be large, print its value modulo 109 + 7.ExamplesInput3 22 4 5Output3Input4 37 8 9 10Output13Input4 05 10 20 21Output1NoteIn the first sample, we have three options: The first and second students form a group, and the third student forms a group. Total imbalance is 2 + 0 = 2. The first student forms a group, and the second and third students form a group. Total imbalance is 0 + 1 = 1. All three students form their own groups. Total imbalance is 0. In the third sample, the total imbalance must be 0, so each student must work individually.
Input3 22 4 5
Output3
2 seconds
256 megabytes
['dp', '*2400']
E. Simple Skewnesstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDefine the simple skewness of a collection of numbers to be the collection's mean minus its median. You are given a list of n (not necessarily distinct) integers. Find the non-empty subset (with repetition) with the maximum simple skewness.The mean of a collection is the average of its elements. The median of a collection is its middle element when all of its elements are sorted, or the average of its two middle elements if it has even size.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of elements in the list.The second line contains n integers xi (0 ≀ xi ≀ 1 000 000)Β β€” the ith element of the list.OutputIn the first line, print a single integer kΒ β€” the size of the subset.In the second line, print k integersΒ β€” the elements of the subset in any order.If there are multiple optimal subsets, print any.ExamplesInput41 2 3 12Output31 2 12 Input41 1 2 2Output31 1 2 Input21 2Output21 2NoteIn the first case, the optimal subset is , which has mean 5, median 2, and simple skewness of 5 - 2 = 3.In the second case, the optimal subset is . Note that repetition is allowed.In the last case, any subset has the same median and mean, so all have simple skewness of 0.
Input41 2 3 12
Output31 2 12
3 seconds
256 megabytes
['binary search', 'math', 'ternary search', '*2400']
D. Jerry's Protesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?InputThe first line of input contains a single integer n (2 ≀ n ≀ 2000) β€” the number of balls in the jar.The second line contains n integers ai (1 ≀ ai ≀ 5000) β€” the number written on the ith ball. It is guaranteed that no two balls have the same number.OutputPrint a single real value β€” the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput21 2Output0.0000000000Input31 2 10Output0.0740740741NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes β€” 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability .
Input21 2
Output0.0000000000
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'probabilities', '*1800']
C. Block Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStudents in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.The students don’t want to use too many blocks, but they also want to be unique, so no two students’ towers may contain the same number of blocks. Find the minimum height necessary for the tallest of the students' towers.InputThe first line of the input contains two space-separated integers n and m (0 ≀ n, m ≀ 1 000 000, n + m > 0)Β β€” the number of students using two-block pieces and the number of students using three-block pieces, respectively.OutputPrint a single integer, denoting the minimum possible height of the tallest tower.ExamplesInput1 3Output9Input3 2Output8Input5 0Output10NoteIn the first case, the student using two-block pieces can make a tower of height 4, and the students using three-block pieces can make towers of height 3, 6, and 9 blocks. The tallest tower has a height of 9 blocks.In the second case, the students can make towers of heights 2, 4, and 8 with two-block pieces and towers of heights 3 and 6 with three-block pieces, for a maximum height of 8 blocks.
Input1 3
Output9
2 seconds
256 megabytes
['brute force', 'greedy', 'math', 'number theory', '*1600']
B. Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCatherine has a deck of n cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions: take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color. She repeats this process until there is only one card left. What are the possible colors for the final card?InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200)Β β€” the total number of cards.The next line contains a string s of length n β€” the colors of the cards. s contains only the characters 'B', 'G', and 'R', representing blue, green, and red, respectively.OutputPrint a single string of up to three charactersΒ β€” the possible colors of the final card (using the same symbols as the input) in alphabetical order.ExamplesInput2RBOutputGInput3GRGOutputBRInput5BBBBBOutputBNoteIn the first sample, Catherine has one red card and one blue card, which she must exchange for a green card.In the second sample, Catherine has two green cards and one red card. She has two options: she can exchange the two green cards for a green card, then exchange the new green card and the red card for a blue card. Alternatively, she can exchange a green and a red card for a blue card, then exchange the blue card and remaining green card for a red card.In the third sample, Catherine only has blue cards, so she can only exchange them for more blue cards.
Input2RB
OutputG
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'math', '*1300']
A. Robot Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCalvin the robot lies in an infinite rectangular grid. Calvin's source code contains a list of n commands, each either 'U', 'R', 'D', or 'L'Β β€” instructions to move a single square up, right, down, or left, respectively. How many ways can Calvin execute a non-empty contiguous substrings of commands and return to the same square he starts in? Two substrings are considered different if they have different starting or ending indices.InputThe first line of the input contains a single positive integer, n (1 ≀ n ≀ 200)Β β€” the number of commands.The next line contains n characters, each either 'U', 'R', 'D', or 'L'Β β€” Calvin's source code.OutputPrint a single integerΒ β€” the number of contiguous substrings that Calvin can execute and return to his starting square.ExamplesInput6URLLDROutput2Input4DLUUOutput0Input7RLRLRLROutput12NoteIn the first case, the entire source code works, as well as the "RL" substring in the second and third characters.Note that, in the third case, the substring "LR" appears three times, and is therefore counted three times to the total result.
Input6URLLDR
Output2
2 seconds
256 megabytes
['brute force', 'implementation', '*1000']
E. Frog Fightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOstap Bender recently visited frog farm and was inspired to create his own frog game.Number of frogs are places on a cyclic gameboard, divided into m cells. Cells are numbered from 1 to m, but the board is cyclic, so cell number 1 goes right after the cell number m in the direction of movement. i-th frog during its turn can jump for ai cells.Frogs move in turns, game starts with a move by frog 1. On its turn i-th frog moves ai cells forward, knocking out all the frogs on its way. If there is a frog in the last cell of the path of the i-th frog, that frog is also knocked out. After this the value ai is decreased by the number of frogs that were knocked out during this turn. If ai is zero or goes negative, then i-th frog doesn't make moves anymore.After frog number 1 finishes its turn, frog number 2 starts to move, then frog number 3 and so on. After the frog number n makes its move, frog 1 starts to move again, then frog 2 and so on this process goes forever. If some frog was already knocked out from the board, we consider that it skips all its moves.Help Ostap to identify, what frogs will stay on the board at the end of a game?InputFirst line of the input contains two integers n and m (1 ≀ n ≀ 100000, 1 ≀ m ≀ 109, n ≀ m)Β β€” number of frogs and gameboard size, respectively.Following n lines contains frogs descriptionsΒ β€” two integers pi and ai (1 ≀ pi, ai ≀ m)Β β€” the number of cell occupied by i-th frog initially and initial jump length. All pi are guaranteed to be distinct.OutputIn the first line output number of frogs on the final gameboard. In the second line output their numbers in any order.ExamplesInput3 52 15 34 3Output13 Input5 61 23 42 55 16 1Output21 4 NoteIn the first sample first frog jumps 1 cell and finishes in cell number 3. Second frog jumps for 3 cells and finishes on cell number 3, knocking out frog number 1. Current jump length for frog number 2 is now 2. Third frog jumps to cell 2, then second frog jumps to cell 5. Third frog in turn finishes in cell 5 and removes frog 2 from the gameboard. Now, it's the only remaining frog in the game.In the second sample first frog jumps 2 cells and knocks out frogs in cells 2 and 3. Its value ai is now 0. Then fourth frog jumps and knocks out fifth frog and its ai is now 0 too. These two frogs will remains on the gameboard forever.
Input3 52 15 34 3
Output13
2 seconds
256 megabytes
['data structures', 'greedy', '*2800']
D. Finals in arithmetictime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVitya is studying in the third grade. During the last math lesson all the pupils wrote on arithmetic quiz. Vitya is a clever boy, so he managed to finish all the tasks pretty fast and Oksana Fillipovna gave him a new one, that is much harder.Let's denote a flip operation of an integer as follows: number is considered in decimal notation and then reverted. If there are any leading zeroes afterwards, they are thrown away. For example, if we flip 123 the result is the integer 321, but flipping 130 we obtain 31, and by flipping 31 we come to 13.Oksana Fillipovna picked some number a without leading zeroes, and flipped it to get number ar. Then she summed a and ar, and told Vitya the resulting value n. His goal is to find any valid a.As Oksana Fillipovna picked some small integers as a and ar, Vitya managed to find the answer pretty fast and became interested in finding some general algorithm to deal with this problem. Now, he wants you to write the program that for given n finds any a without leading zeroes, such that a + ar = n or determine that such a doesn't exist.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 10100 000).OutputIf there is no such positive integer a without leading zeroes that a + ar = n then print 0. Otherwise, print any valid a. If there are many possible answers, you are allowed to pick any.ExamplesInput4Output2Input11Output10Input5Output0Input33Output21NoteIn the first sample 4 = 2 + 2, a = 2 is the only possibility.In the second sample 11 = 10 + 1, a = 10Β β€” the only valid solution. Note, that a = 01 is incorrect, because a can't have leading zeroes.It's easy to check that there is no suitable a in the third sample.In the fourth sample 33 = 30 + 3 = 12 + 21, so there are three possibilities for a: a = 30, a = 12, a = 21. Any of these is considered to be correct answer.
Input4
Output2
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'math', '*2400']
C. K-special Tablestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeople do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied: every integer from 1 to n2 appears in the table exactly once; in each row numbers are situated in increasing order; the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.InputThe first line of the input contains two integers n and k (1 ≀ n ≀ 500, 1 ≀ k ≀ n)Β β€” the size of the table Alice is looking for and the column that should have maximum possible sum.OutputFirst print the sum of the integers in the k-th column of the required table.Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on.If there are multiple suitable table, you are allowed to print any.ExamplesInput4 1Output281 2 3 45 6 7 89 10 11 1213 14 15 16Input5 3Output855 6 17 18 199 10 23 24 257 8 20 21 223 4 14 15 161 2 11 12 13
Input4 1
Output281 2 3 45 6 7 89 10 11 1213 14 15 16
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1300']
B. War of the Corporationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.InputThe first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.OutputPrint the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.ExamplesInputintellecttellOutput1InputgoogleappleOutput0InputsirisirisirOutput2NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".
Inputintellecttell
Output1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1200']
A. Guest From the Pasttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated.Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plastic liter bottle, that costs a rubles, or in glass liter bottle, that costs b rubles. Also, you may return empty glass bottle and get c (c < b) rubles back, but you cannot return plastic bottles.Kolya has n rubles and he is really hungry, so he wants to drink as much kefir as possible. There were no plastic bottles in his 1984, so Kolya doesn't know how to act optimally and asks for your help.InputFirst line of the input contains a single integer n (1 ≀ n ≀ 1018)Β β€” the number of rubles Kolya has at the beginning.Then follow three lines containing integers a, b and c (1 ≀ a ≀ 1018, 1 ≀ c < b ≀ 1018)Β β€” the cost of one plastic liter bottle, the cost of one glass liter bottle and the money one can get back by returning an empty glass bottle, respectively.OutputPrint the only integerΒ β€” maximum number of liters of kefir, that Kolya can drink.ExamplesInput101198Output2Input10561Output2NoteIn the first sample, Kolya can buy one glass bottle, then return it and buy one more glass bottle. Thus he will drink 2 liters of kefir.In the second sample, Kolya can buy two plastic bottle and get two liters of kefir, or he can buy one liter glass bottle, then return it and buy one plastic bottle. In both cases he will drink two liters of kefir.
Input101198
Output2
1 second
256 megabytes
['implementation', 'math', '*1700']
B. Making a Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied: the i-th letter occurs in the string no more than ai times; the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once. InputThe first line of the input contains a single integer n (2  ≀  n  ≀  26)Β β€” the number of letters in the alphabet.The next line contains n integers ai (1 ≀ ai ≀ 109)Β β€” i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.OutputPrint a single integer β€” the maximum length of the string that meets all the requirements.ExamplesInput32 5 5Output11Input31 1 2Output3NoteFor convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".
Input32 5 5
Output11
1 second
256 megabytes
['greedy', 'sortings', '*1100']
A. Save Luketime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other with speed v1 and v2, respectively. Luke has width d and is able to choose any position between the presses. Luke dies as soon as the distance between the presses is less than his width. Your task is to determine for how long Luke can stay alive.InputThe first line of the input contains four integers d, L, v1, v2 (1 ≀ d, L, v1, v2 ≀ 10 000, d < L)Β β€” Luke's width, the initial position of the second press and the speed of the first and second presses, respectively.OutputPrint a single real valueΒ β€” the maximum period of time Luke can stay alive for. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2 6 2 2Output1.00000000000000000000Input1 9 1 2Output2.66666666666666650000NoteIn the first sample Luke should stay exactly in the middle of the segment, that is at coordinates [2;4], as the presses move with the same speed.In the second sample he needs to occupy the position . In this case both presses move to his edges at the same time.
Input2 6 2 2
Output1.00000000000000000000
1 second
256 megabytes
['math', '*800']
E. Transforming Sequencetime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the transformation P of a sequence of integers a1, a2, ..., an as b1, b2, ..., bn, where bi = a1Β |Β a2Β |Β ...Β |Β ai for all i = 1, 2, ..., n, where | is the bitwise OR operation.Vasya consequently applies the transformation P to all sequences of length n consisting of integers from 1 to 2k - 1 inclusive. He wants to know how many of these sequences have such property that their transformation is a strictly increasing sequence. Help him to calculate this number modulo 109 + 7.InputThe only line of the input contains two integers n and k (1 ≀ n ≀ 1018, 1 ≀ k ≀ 30 000).OutputPrint a single integerΒ β€” the answer to the problem modulo 109 + 7.ExamplesInput1 2Output3Input2 3Output30Input3 3Output48
Input1 2
Output3
7 seconds
256 megabytes
['combinatorics', 'dp', 'fft', 'math', '*3300']
D. Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA MIPT student named Misha has a birthday today, and he decided to celebrate it in his country house in suburban Moscow. n friends came by, and after a typical party they decided to play blind man's buff.The birthday boy gets blindfolded and the other players scatter around the house. The game is played in several rounds. In each round, Misha catches exactly one of his friends and has to guess who it is. The probability of catching the i-th friend does not change between rounds and is equal to pi percent (as we know, it is directly proportional to the amount of alcohol consumed by the i-th friend) and p1 + p2 + ... + pn = 100 holds. Misha has no information about who he caught. After Misha makes an attempt to guess the caught person, the round ends. Even then, Misha isn't told whether he guessed correctly, and a new round begins.The game ends when Misha guesses every friend at least once, that is, there exists such set of rounds k1, k2, ..., kn, that during round number ki Misha caught the i-th friend and guessed him. Misha wants to minimize the expectation of the number of rounds of the game. Despite the fact that at any point in the game Misha has no information about who he has already guessed, his friends are honest, and if they see that the condition for the end of the game is fulfilled, the game ends immediately. Find the expectation of the number of rounds in the game if Misha plays optimally.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100)Β β€” the number of Misha's friends.The second line contains n integers pi (), giving the probability to catch the i-th friend in one particular round in percent.OutputPrint a single real valueΒ β€” the expectation of the number of rounds provided that Misha plays optimally. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput250 50Output5.0000000000Input450 20 20 10Output39.2846263444NoteThe optimal strategy in the first sample is to guess friends alternately.
Input250 50
Output5.0000000000
2 seconds
256 megabytes
['greedy', 'math', 'probabilities', '*2700']
C. Electric Chargestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgrammer Sasha is a student at MIPT (Moscow Institute of Physics and Technology) and he needs to make a laboratory work to pass his finals.A laboratory unit is a plane with standard coordinate axes marked on it. Physicists from Moscow Institute of Physics and Technology charged the axes by large electric charges: axis X is positive and axis Y is negative.Experienced laboratory worker marked n points with integer coordinates (xi, yi) on the plane and stopped the time. Sasha should use "atomic tweezers" to place elementary particles in these points. He has an unlimited number of electrons (negatively charged elementary particles) and protons (positively charged elementary particles). He can put either an electron or a proton at each marked point. As soon as all marked points are filled with particles, laboratory worker will turn on the time again and the particles will come in motion and after some time they will stabilize in equilibrium. The objective of the laboratory work is to arrange the particles in such a way, that the diameter of the resulting state (the maximum distance between the pairs of points of the set) is as small as possible.Since Sasha is a programmer, he naively thinks that all the particles will simply "fall" into their projections on the corresponding axes: electrons will fall on axis X, while protons will fall on axis Y. As we are programmers too, we will consider the same model as Sasha. That is, a particle gets from point (x, y) to point (x, 0) if it is an electron and to point (0, y) if it is a proton.As the laboratory has high background radiation and Sasha takes care of his laptop, he did not take it with him, and now he can't write a program that computes the minimum possible diameter of the resulting set. Therefore, you will have to do it for him.Print a square of the minimum possible diameter of the set.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of points marked on the plane.Each of the next n lines contains two integers xi and yi ( - 108 ≀ xi, yi ≀ 108)Β β€” the coordinates of the i-th point. It is guaranteed that no two points coincide.OutputPrint a single integerΒ β€” the square of the minimum possible diameter of the set.ExamplesInput31 101 201 30Output0Input21 1010 1Output2NoteIn the first sample Sasha puts electrons at all points, all particles eventually fall at a single point (1, 0).In the second sample Sasha puts an electron at point (1, 10), and a proton at point (10, 1). The result is a set of two points (1, 0) and (0, 1), which has a diameter of .
Input31 101 201 30
Output0
2 seconds
256 megabytes
['binary search', 'dp', '*2900']
B. Array GCDtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given array ai of length n. You may consecutively apply two operations to this array: remove some subsegment (continuous subsequence) of length m < n and pay for it mΒ·a coins; change some elements of the array by at most 1, and pay b coins for each change. Please note that each of operations may be applied at most once (and may be not applied at all) so you can remove only one segment and each number may be changed (increased or decreased) by at most 1. Also note, that you are not allowed to delete the whole array.Your goal is to calculate the minimum number of coins that you need to spend in order to make the greatest common divisor of the elements of the resulting array be greater than 1.InputThe first line of the input contains integers n, a and b (1 ≀ n ≀ 1 000 000, 0 ≀ a, b ≀ 109)Β β€” the length of the array, the cost of removing a single element in the first operation and the cost of changing an element, respectively.The second line contains n integers ai (2 ≀ ai ≀ 109)Β β€” elements of the array.OutputPrint a single numberΒ β€” the minimum cost of changes needed to obtain an array, such that the greatest common divisor of all its elements is greater than 1.ExamplesInput3 1 44 2 3Output1Input5 3 25 17 13 5 6Output8Input8 3 43 7 5 4 3 12 9 4Output13NoteIn the first sample the optimal way is to remove number 3 and pay 1 coin for it.In the second sample you need to remove a segment [17, 13] and then decrease number 6. The cost of these changes is equal to 2Β·3 + 2 = 8 coins.
Input3 1 44 2 3
Output1
3 seconds
256 megabytes
['dp', 'greedy', 'number theory', '*2300']
A. Graph and Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: G has exactly n vertices, numbered from 1 to n. For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.InputThe first line of the input contains two integers n and m Β β€” the number of vertices and edges in the graph found by Petya, respectively.Each of the next m lines contains two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.OutputIn the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise.If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.ExamplesInput2 11 2OutputYesaaInput4 31 21 31 4OutputNoNoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.
Input2 11 2
OutputYesaa
2 seconds
256 megabytes
['constructive algorithms', 'graphs', '*1800']
F. The Sum of the k-th Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are well-known formulas: , , . Also mathematicians found similar formulas for higher degrees.Find the value of the sum modulo 109 + 7 (so you should find the remainder after dividing the answer by the value 109 + 7).InputThe only line contains two integers n, k (1 ≀ n ≀ 109, 0 ≀ k ≀ 106).OutputPrint the only integer a β€” the remainder after dividing the value of the sum by the value 109 + 7.ExamplesInput4 1Output10Input4 2Output30Input4 3Output100Input4 0Output4
Input4 1
Output10
2 seconds
256 megabytes
['math', '*2600']
E. Ants in Leavestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTree is a connected graph without cycles. A leaf of a tree is any vertex connected with exactly one other vertex.You are given a tree with n vertices and a root in the vertex 1. There is an ant in each leaf of the tree. In one second some ants can simultaneously go to the parent vertex from the vertex they were in. No two ants can be in the same vertex simultaneously except for the root of the tree.Find the minimal time required for all ants to be in the root of the tree. Note that at start the ants are only in the leaves of the tree.InputThe first line contains integer n (2 ≀ n ≀ 5Β·105) β€” the number of vertices in the tree.Each of the next n - 1 lines contains two integers xi, yi (1 ≀ xi, yi ≀ n) β€” the ends of the i-th edge. It is guaranteed that you are given the correct undirected tree.OutputPrint the only integer t β€” the minimal time required for all ants to be in the root of the tree.ExamplesInput121 21 31 42 52 63 73 83 98 108 118 12Output6Input22 1Output1
Input121 21 31 42 52 63 73 83 98 108 118 12
Output6
2 seconds
256 megabytes
['dfs and similar', 'greedy', 'sortings', 'trees', '*2200']
D. Optimal Number Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have array a that contains all integers from 1 to n twice. You can arbitrary permute any numbers in a.Let number i be in positions xi, yi (xi < yi) in the permuted array a. Let's define the value di = yi - xi β€” the distance between the positions of the number i. Permute the numbers in array a to minimize the value of the sum .InputThe only line contains integer n (1 ≀ n ≀ 5Β·105).OutputPrint 2n integers β€” the permuted array a that minimizes the value of the sum s.ExamplesInput2Output1 1 2 2Input1Output1 1
Input2
Output1 1 2 2
1 second
256 megabytes
['constructive algorithms', '*1900']
C. Not Equal on a Segmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.For the i-th query find any position pi (li ≀ pi ≀ ri) so that api ≠ xi.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the number of elements in a and the number of queries.The second line contains n integers ai (1 ≀ ai ≀ 106) β€” the elements of the array a.Each of the next m lines contains three integers li, ri, xi (1 ≀ li ≀ ri ≀ n, 1 ≀ xi ≀ 106) β€” the parameters of the i-th query.OutputPrint m lines. On the i-th line print integer pi β€” the position of any number not equal to xi in segment [li, ri] or the value  - 1 if there is no such number.ExamplesInput6 41 2 1 1 3 51 4 12 6 23 4 13 4 2Output26-14
Input6 41 2 1 1 3 51 4 12 6 23 4 13 4 2
Output26-14
1 second
256 megabytes
['data structures', 'implementation', '*1700']
B. The Timetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the current time in 24-hour format hh:mm. Find and print the time after a minutes.Note that you should find only the time after a minutes, see the examples to clarify the problem statement.You can read more about 24-hour format here https://en.wikipedia.org/wiki/24-hour_clock.InputThe first line contains the current time in the format hh:mm (0 ≀ hh < 24, 0 ≀ mm < 60). The hours and the minutes are given with two digits (the hours or the minutes less than 10 are given with the leading zeroes).The second line contains integer a (0 ≀ a ≀ 104) β€” the number of the minutes passed.OutputThe only line should contain the time after a minutes in the format described in the input. Note that you should print exactly two digits for the hours and the minutes (add leading zeroes to the numbers if needed).See the examples to check the input/output format.ExamplesInput23:5910Output00:09Input20:20121Output22:21Input10:100Output10:10
Input23:5910
Output00:09
1 second
256 megabytes
['implementation', '*900']
A. Infinite Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).Find the number on the n-th position of the sequence.InputThe only line contains integer n (1 ≀ n ≀ 1014) β€” the position of the number to find.Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.OutputPrint the element in the n-th position of the sequence (the elements are numerated from one).ExamplesInput3Output2Input5Output2Input10Output4Input55Output10Input56Output1
Input3
Output2
1 second
256 megabytes
['implementation', 'math', '*1000']
E. Wet Shark and Blockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second block, he gets the integer 12. Wet Shark then takes this number modulo x. Please, tell him how many ways he can choose one digit from each block so that he gets exactly k as the final result. As this number may be too large, print it modulo 109 + 7.Note, that the number of ways to choose some digit in the block is equal to the number of it's occurrences. For example, there are 3 ways to choose digit 5 from block 3 5 6 7 8 9 5 1 1 1 1 5.InputThe first line of the input contains four space-separated integers, n, b, k and x (2 ≀ n ≀ 50 000, 1 ≀ b ≀ 109, 0 ≀ k < x ≀ 100, x β‰₯ 2)Β β€” the number of digits in one block, the number of blocks, interesting remainder modulo x and modulo x itself.The next line contains n space separated integers ai (1 ≀ ai ≀ 9), that give the digits contained in each block.OutputPrint the number of ways to pick exactly one digit from each blocks, such that the resulting integer equals k modulo x.ExamplesInput12 1 5 103 5 6 7 8 9 5 1 1 1 1 5Output3Input3 2 1 26 2 2Output0Input3 2 1 23 1 2Output6NoteIn the second sample possible integers are 22, 26, 62 and 66. None of them gives the remainder 1 modulo 2.In the third sample integers 11, 13, 21, 23, 31 and 33 have remainder 1 modulo 2. There is exactly one way to obtain each of these integers, so the total answer is 6.
Input12 1 5 103 5 6 7 8 9 5 1 1 1 1 5
Output3
2 seconds
256 megabytes
['dp', 'matrices', '*2000']
D. Rat Kwesh and Cheesetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWet Shark asked Rat Kwesh to generate three positive real numbers x, y and z, from 0.1 to 200.0, inclusive. Wet Krash wants to impress Wet Shark, so all generated numbers will have exactly one digit after the decimal point.Wet Shark knows Rat Kwesh will want a lot of cheese. So he will give the Rat an opportunity to earn a lot of cheese. He will hand the three numbers x, y and z to Rat Kwesh, and Rat Kwesh will pick one of the these twelve options: a1 = xyz; a2 = xzy; a3 = (xy)z; a4 = (xz)y; a5 = yxz; a6 = yzx; a7 = (yx)z; a8 = (yz)x; a9 = zxy; a10 = zyx; a11 = (zx)y; a12 = (zy)x. Let m be the maximum of all the ai, and c be the smallest index (from 1 to 12) such that ac = m. Rat's goal is to find that c, and he asks you to help him. Rat Kwesh wants to see how much cheese he gets, so he you will have to print the expression corresponding to that ac. InputThe only line of the input contains three space-separated real numbers x, y and z (0.1 ≀ x, y, z ≀ 200.0). Each of x, y and z is given with exactly one digit after the decimal point.OutputFind the maximum value of expression among xyz, xzy, (xy)z, (xz)y, yxz, yzx, (yx)z, (yz)x, zxy, zyx, (zx)y, (zy)x and print the corresponding expression. If there are many maximums, print the one that comes first in the list. xyz should be outputted as x^y^z (without brackets), and (xy)z should be outputted as (x^y)^z (quotes for clarity). ExamplesInput1.1 3.4 2.5Outputz^y^xInput2.0 2.0 2.0Outputx^y^zInput1.9 1.8 1.7Output(x^y)^z
Input1.1 3.4 2.5
Outputz^y^x
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'math', '*2400']
C. Wet Shark and Flowerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product siΒ·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.InputThe first line of the input contains two space-separated integers n and p (3 ≀ n ≀ 100 000, 2 ≀ p ≀ 109)Β β€” the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime.The i-th of the following n lines contains information about i-th sharkΒ β€” two space-separated integers li and ri (1 ≀ li ≀ ri ≀ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.OutputPrint a single real number β€” the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 21 2420 421420420 420421Output4500.0Input3 51 42 311 14Output0.0NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0Β·s1 = 420, s1Β·s2 = 176576400, and s2Β·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2Β·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000 (1, 421, 420421): total is 0. (2, 420, 420420): total is 6000. (2, 420, 420421): total is 6000. (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.
Input3 21 2420 421420420 420421
Output4500.0
2 seconds
256 megabytes
['combinatorics', 'math', 'number theory', 'probabilities', '*1700']
B. Wet Shark and Bishopstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.InputThe first line of the input contains n (1 ≀ n ≀ 200 000)Β β€” the number of bishops.Each of next n lines contains two space separated integers xi and yi (1 ≀ xi, yi ≀ 1000)Β β€” the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.OutputOutput one integerΒ β€” the number of pairs of bishops which attack each other. ExamplesInput51 11 53 35 15 5Output6Input31 12 33 5Output0NoteIn the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
Input51 11 53 35 15 5
Output6
2 seconds
256 megabytes
['combinatorics', 'implementation', '*1300']
A. Wet Shark and Odd and Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.InputThe first line of the input contains one integer, n (1 ≀ n ≀ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive. OutputPrint the maximum possible even sum that can be obtained if we use some of the given integers. ExamplesInput31 2 3Output6Input5999999999 999999999 999999999 999999999 999999999Output3999999996NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.
Input31 2 3
Output6
2 seconds
256 megabytes
['implementation', '*900']
F. Xors on Segmentstime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array with n integers ai and m queries. Each query is described by two integers (lj, rj).Let's define the function . The function is defined for only u ≀ v.For each query print the maximal value of the function f(ax, ay) over all lj ≀ x, y ≀ rj,  ax ≀ ay.InputThe first line contains two integers n, m (1 ≀ n ≀ 5Β·104,  1 ≀ m ≀ 5Β·103) β€” the size of the array and the number of the queries.The second line contains n integers ai (1 ≀ ai ≀ 106) β€” the elements of the array a.Each of the next m lines contains two integers lj, rj (1 ≀ lj ≀ rj ≀ n) – the parameters of the j-th query.OutputFor each query print the value aj on a separate line β€” the maximal value of the function f(ax, ay) over all lj ≀ x, y ≀ rj,  ax ≀ ay.ExamplesInput6 31 2 3 4 5 61 62 53 4Output777Input1 111 1Output1Input6 2010 21312 2314 214 1 3221 11 21 31 41 51 62 22 32 42 52 63 43 53 64 44 54 65 55 66 6Output10213132131321313213132131321312213132131321313213132314231523152142153231323322
Input6 31 2 3 4 5 61 62 53 4
Output777
10 seconds
512 megabytes
['data structures', 'strings', 'trees', '*2800']
E. New Year Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.The New Year tree is an undirected tree with n vertices and root in the vertex 1.You should process the queries of the two types: Change the colours of all vertices in the subtree of the vertex v to the colour c. Find the number of different colours in the subtree of the vertex v. InputThe first line contains two integers n, m (1 ≀ n, m ≀ 4Β·105) β€” the number of vertices in the tree and the number of the queries.The second line contains n integers ci (1 ≀ ci ≀ 60) β€” the colour of the i-th vertex.Each of the next n - 1 lines contains two integers xj, yj (1 ≀ xj, yj ≀ n) β€” the vertices of the j-th edge. It is guaranteed that you are given correct undirected tree.The last m lines contains the description of the queries. Each description starts with the integer tk (1 ≀ tk ≀ 2) β€” the type of the k-th query. For the queries of the first type then follows two integers vk, ck (1 ≀ vk ≀ n, 1 ≀ ck ≀ 60) β€” the number of the vertex whose subtree will be recoloured with the colour ck. For the queries of the second type then follows integer vk (1 ≀ vk ≀ n) β€” the number of the vertex for which subtree you should find the number of different colours.OutputFor each query of the second type print the integer a β€” the number of different colours in the subtree of the vertex given in the query.Each of the numbers should be printed on a separate line in order of query appearing in the input.ExamplesInput7 101 1 1 1 1 1 11 21 31 43 53 63 71 3 22 11 4 32 11 2 52 11 6 42 12 22 3Output234512Input23 301 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 61 21 31 42 52 63 73 84 94 104 116 126 137 147 157 168 178 1810 1910 2010 2111 2211 232 12 52 62 72 82 92 102 112 41 12 11 13 11 14 11 15 11 16 11 17 11 18 11 19 11 20 11 21 11 22 11 23 12 12 52 62 72 82 92 102 112 4Output613321235512211123
Input7 101 1 1 1 1 1 11 21 31 43 53 63 71 3 22 11 4 32 11 2 52 11 6 42 12 22 3
Output234512
3 seconds
256 megabytes
['bitmasks', 'data structures', 'trees', '*2100']
D. Professor GukiZ and Two Arraystime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ has two arrays of integers, a and b. Professor wants to make the sum of the elements in the array a sa as close as possible to the sum of the elements in the array b sb. So he wants to minimize the value v = |sa - sb|.In one operation professor can swap some element from the array a and some element from the array b. For example if the array a is [5, 1, 3, 2, 4] and the array b is [3, 3, 2] professor can swap the element 5 from the array a and the element 2 from the array b and get the new array a [2, 1, 3, 2, 4] and the new array b [3, 3, 5].Professor doesn't want to make more than two swaps. Find the minimal value v and some sequence of no more than two swaps that will lead to the such value v. Professor makes swaps one by one, each new swap he makes with the new arrays a and b.InputThe first line contains integer n (1 ≀ n ≀ 2000) β€” the number of elements in the array a.The second line contains n integers ai ( - 109 ≀ ai ≀ 109) β€” the elements of the array a.The third line contains integer m (1 ≀ m ≀ 2000) β€” the number of elements in the array b.The fourth line contains m integers bj ( - 109 ≀ bj ≀ 109) β€” the elements of the array b.OutputIn the first line print the minimal value v = |sa - sb| that can be got with no more than two swaps.The second line should contain the number of swaps k (0 ≀ k ≀ 2).Each of the next k lines should contain two integers xp, yp (1 ≀ xp ≀ n, 1 ≀ yp ≀ m) β€” the index of the element in the array a and the index of the element in the array b in the p-th swap.If there are several optimal solutions print any of them. Print the swaps in order the professor did them.ExamplesInput55 4 3 2 141 1 1 1Output121 14 2Input51 2 3 4 5115Output00Input51 2 3 4 541 2 3 4Output113 1
Input55 4 3 2 141 1 1 1
Output121 14 2
3 seconds
256 megabytes
['binary search', 'two pointers', '*2200']
C. Pearls in a Rowtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains integer n (1 ≀ n ≀ 3Β·105) β€” the number of pearls in a row.The second line contains n integers ai (1 ≀ ai ≀ 109) – the type of the i-th pearl.OutputOn the first line print integer k β€” the maximal number of segments in a partition of the row.Each of the next k lines should contain two integers lj, rj (1 ≀ lj ≀ rj ≀ n) β€” the number of the leftmost and the rightmost pearls in the j-th segment.Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type.If there are several optimal solutions print any of them. You can print the segments in any order.If there are no correct partitions of the row print the number "-1".ExamplesInput51 2 3 4 1Output11 5Input51 2 3 4 5Output-1Input71 2 1 3 1 2 1Output21 34 7
Input51 2 3 4 1
Output11 5
2 seconds
256 megabytes
['greedy', '*1500']
B. Grandfather Dovlet’s calculatortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (https://en.wikipedia.org/wiki/Seven-segment_display). Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.For example if a = 1 and b = 3 then at first the calculator will print 2 segments, then β€” 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.InputThe only line contains two integers a, b (1 ≀ a ≀ b ≀ 106) β€” the first and the last number typed by Max.OutputPrint the only integer a β€” the total number of printed segments.ExamplesInput1 3Output12Input10 15Output39
Input1 3
Output12
1 second
256 megabytes
['implementation', '*1000']
A. Professor GukiZ's Robottime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps the robot should make to get the finish position.InputThe first line contains two integers x1, y1 ( - 109 ≀ x1, y1 ≀ 109) β€” the start position of the robot.The second line contains two integers x2, y2 ( - 109 ≀ x2, y2 ≀ 109) β€” the finish position of the robot.OutputPrint the only integer d β€” the minimal number of steps to get the finish position.ExamplesInput0 04 5Output5Input3 46 1Output3NoteIn the first example robot should increase both of its coordinates by one four times, so it will be in position (4, 4). After that robot should simply increase its y coordinate and get the finish position.In the second example robot should simultaneously increase x coordinate and decrease y coordinate by one three times.
Input0 04 5
Output5
0.5 seconds
256 megabytes
['implementation', 'math', '*800']
G. Combining Slimestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend recently gave you some slimes for your birthday. You have a very large amount of slimes with value 1 and 2, and you decide to invent a game using these slimes.You initialize a row with n empty spaces. You also choose a number p to be used in the game. Then, you will perform the following steps while the last space is empty. With probability , you will choose a slime with value 1, and with probability , you will choose a slime with value 2. You place the chosen slime on the last space of the board. You will push the slime to the left as far as possible. If it encounters another slime, and they have the same value v, you will merge the slimes together to create a single slime with value v + 1. This continues on until the slime reaches the end of the board, or encounters a slime with a different value than itself. You have played the game a few times, but have gotten bored of it. You are now wondering, what is the expected sum of all values of the slimes on the board after you finish the game.InputThe first line of the input will contain two integers n, p (1 ≀ n ≀ 109, 1 ≀ p < 109).OutputPrint the expected sum of all slimes on the board after the game finishes. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput2 500000000Output3.562500000000000Input10 1Output64.999983360007620Input100 123456789Output269.825611298854770NoteIn the first sample, we have a board with two squares, and there is a 0.5 probability of a 1 appearing and a 0.5 probability of a 2 appearing.Our final board states can be 1 2 with probability 0.25, 2 1 with probability 0.375, 3 2 with probability 0.1875, 3 1 with probability 0.1875. The expected value is thus (1 + 2)Β·0.25 + (2 + 1)Β·0.375 + (3 + 2)Β·0.1875 + (3 + 1)Β·0.1875 = 3.5625.
Input2 500000000
Output3.562500000000000
2 seconds
256 megabytes
['dp', 'math', 'matrices', 'probabilities', '*3300']
F. Double Knapsacktime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two multisets A and B. Each multiset has exactly n integers each between 1 and n inclusive. Multisets may contain multiple copies of the same number.You would like to find a nonempty subset of A and a nonempty subset of B such that the sum of elements in these subsets are equal. Subsets are also multisets, i.e. they can contain elements with equal values.If no solution exists, print  - 1. Otherwise, print the indices of elements in any such subsets of A and B that have the same sum.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 1 000 000)Β β€” the size of both multisets.The second line contains n integers, denoting the elements of A. Each element will be between 1 and n inclusive.The third line contains n integers, denoting the elements of B. Each element will be between 1 and n inclusive.OutputIf there is no solution, print a single integer  - 1. Otherwise, your solution should be printed on four lines.The first line should contain a single integer ka, the size of the corresponding subset of A. The second line should contain ka distinct integers, the indices of the subset of A.The third line should contain a single integer kb, the size of the corresponding subset of B. The fourth line should contain kb distinct integers, the indices of the subset of B.Elements in both sets are numbered from 1 to n. If there are multiple possible solutions, print any of them.ExamplesInput1010 10 10 10 10 10 10 10 10 1010 9 8 7 6 5 4 3 2 1Output1235 8 10Input54 4 3 3 32 2 2 2 5Output22 323 5
Input1010 10 10 10 10 10 10 10 10 1010 9 8 7 6 5 4 3 2 1
Output1235 8 10
2.5 seconds
256 megabytes
['constructive algorithms', 'two pointers', '*3000']
E. Robot Armtime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRoger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segment is touching the red endpoint of the (i + 1)-th segment for all valid i.Roger can move his arm in two different ways: He can choose some segment and some value. This is denoted as choosing the segment number i and picking some positive l. This change happens as follows: the red endpoint of segment number i and segments from 1 to i - 1 are all fixed in place. Imagine a ray from the red endpoint to the blue endpoint. The blue endpoint and segments i + 1 through n are translated l units in the direction of this ray. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B gets translated. He can choose a segment and rotate it. This is denoted as choosing the segment number i, and an angle a. The red endpoint of the i-th segment will stay fixed in place. The blue endpoint of that segment and segments i + 1 to n will rotate clockwise by an angle of a degrees around the red endpoint. In this picture, the red point labeled A and segments before A stay in place, while the blue point labeled B and segments after B get rotated around point A. Roger will move his arm m times. These transformations are a bit complicated, and Roger easily loses track of where the blue endpoint of the last segment is. Help him compute the coordinates of the blue endpoint of the last segment after applying each operation. Note that these operations are cumulative, and Roger's arm may intersect itself arbitrarily during the moves.InputThe first line of the input will contain two integers n and m (1 ≀ n, m ≀ 300 000)Β β€” the number of segments and the number of operations to perform.Each of the next m lines contains three integers xi, yi and zi describing a move. If xi = 1, this line describes a move of type 1, where yi denotes the segment number and zi denotes the increase in the length. If xi = 2, this describes a move of type 2, where yi denotes the segment number, and zi denotes the angle in degrees. (1 ≀ xi ≀ 2, 1 ≀ yi ≀ n, 1 ≀ zi ≀ 359)OutputPrint m lines. The i-th line should contain two real values, denoting the coordinates of the blue endpoint of the last segment after applying operations 1, ..., i. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if for all coordinates.ExamplesInput5 41 1 32 3 902 5 481 4 1Output8.0000000000 0.00000000005.0000000000 -3.00000000004.2568551745 -2.66913060644.2568551745 -3.6691306064NoteThe following pictures shows the state of the arm after each operation. The coordinates of point F are printed after applying each operation. For simplicity, we only show the blue endpoints of a segment (with the exception for the red endpoint of the first segment). For instance, the point labeled B is the blue endpoint for segment 1 and also the red endpoint for segment 2.Initial state: Extend segment 1 by 3. Rotate segment 3 by 90 degrees clockwise. Rotate segment 5 by 48 degrees clockwise. Extend segment 4 by 1.
Input5 41 1 32 3 902 5 481 4 1
Output8.0000000000 0.00000000005.0000000000 -3.00000000004.2568551745 -2.66913060644.2568551745 -3.6691306064
8 seconds
256 megabytes
['data structures', 'geometry', '*2500']
D. Hamiltonian Spanning Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA group of n cities is connected by a network of roads. There is an undirected road between every pair of cities, so there are roads in total. It takes exactly y seconds to traverse any single road.A spanning tree is a set of roads containing exactly n - 1 roads such that it's possible to travel between any two cities using only these roads.Some spanning tree of the initial network was chosen. For every road in this tree the time one needs to traverse this road was changed from y to x seconds. Note that it's not guaranteed that x is smaller than y.You would like to travel through all the cities using the shortest path possible. Given n, x, y and a description of the spanning tree that was chosen, find the cost of the shortest path that starts in any city, ends in any city and visits all cities exactly once.InputThe first line of the input contains three integers n, x and y (2 ≀ n ≀ 200 000, 1 ≀ x, y ≀ 109).Each of the next n - 1 lines contains a description of a road in the spanning tree. The i-th of these lines contains two integers ui and vi (1 ≀ ui, vi ≀ n)Β β€” indices of the cities connected by the i-th road. It is guaranteed that these roads form a spanning tree.OutputPrint a single integerΒ β€” the minimum number of seconds one needs to spend in order to visit all the cities exactly once.ExamplesInput5 2 31 21 33 45 3Output9Input5 3 21 21 33 45 3Output8NoteIn the first sample, roads of the spanning tree have cost 2, while other roads have cost 3. One example of an optimal path is .In the second sample, we have the same spanning tree, but roads in the spanning tree cost 3, while other roads cost 2. One example of an optimal path is .
Input5 2 31 21 33 45 3
Output9
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graph matchings', 'greedy', 'trees', '*2200']
C. Constellationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.InputThe first line of the input contains a single integer n (3 ≀ n ≀ 100 000).Each of the next n lines contains two integers xi and yi ( - 109 ≀ xi, yi ≀ 109).It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.OutputPrint three distinct integers on a single lineΒ β€” the indices of the three points that form a triangle that satisfies the conditions stated in the problem.If there are multiple possible answers, you may print any of them.ExamplesInput30 11 01 1Output1 2 3Input50 00 22 02 21 1Output1 3 5NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture. Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).
Input30 11 01 1
Output1 2 3
2 seconds
256 megabytes
['geometry', 'implementation', '*1600']
B. Guess the Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.InputThe first line of the input will contain a single integer n (2 ≀ n ≀ 50).The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.OutputPrint n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.ExamplesInput20 11 0Output2 1Input50 2 2 1 22 0 4 1 32 4 0 1 31 1 1 0 12 3 3 1 0Output2 5 4 1 3NoteIn the first case, the answer can be {1, 2} or {2, 1}.In the second case, another possible answer is {2, 4, 5, 1, 3}.
Input20 11 0
Output2 1
2 seconds
256 megabytes
['constructive algorithms', '*1100']
A. Slime Combiningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1.You would like to see what the final state of the row is after you've added all n slimes. Please print the values of the slimes in the row from left to right.InputThe first line of the input will contain a single integer, n (1 ≀ n ≀ 100 000).OutputOutput a single line with k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left.ExamplesInput1Output1Input2Output2Input3Output2 1Input8Output4NoteIn the first sample, we only have a single slime with value 1. The final state of the board is just a single slime with value 1.In the second sample, we perform the following steps:Initially we place a single slime in a row by itself. Thus, row is initially 1.Then, we will add another slime. The row is now 1 1. Since two rightmost slimes have the same values, we should replace these slimes with one with value 2. Thus, the final state of the board is 2.In the third sample, after adding the first two slimes, our row is 2. After adding one more slime, the row becomes 2 1.In the last sample, the steps look as follows: 1 2 2 1 3 3 1 3 2 3 2 1 4
Input1
Output1
2 seconds
256 megabytes
['implementation', '*800']
E. XOR and Favorite Numbertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≀ i ≀ j ≀ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k.InputThe first line of the input contains integers n, m and k (1 ≀ n, m ≀ 100 000, 0 ≀ k ≀ 1 000 000)Β β€” the length of the array, the number of queries and Bob's favorite number respectively.The second line contains n integers ai (0 ≀ ai ≀ 1 000 000)Β β€” Bob's array.Then m lines follow. The i-th line contains integers li and ri (1 ≀ li ≀ ri ≀ n)Β β€” the parameters of the i-th query.OutputPrint m lines, answer the queries in the order they appear in the input. ExamplesInput6 2 31 2 1 1 0 31 63 5Output70Input5 3 11 1 1 1 11 52 41 3Output944NoteIn the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query.In the second sample xor equals 1 for all subarrays of an odd length.
Input6 2 31 2 1 1 0 31 63 5
Output70
4 seconds
256 megabytes
['data structures', '*2200']
D. Polylinetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.InputEach of the three lines of the input contains two integers. The i-th line contains integers xi and yi ( - 109 ≀ xi, yi ≀ 109)Β β€” the coordinates of the i-th point. It is guaranteed that all points are distinct.OutputPrint a single numberΒ β€” the minimum possible number of segments of the polyline.ExamplesInput1 -11 11 2Output1Input-1 -1-1 34 3Output2Input1 12 33 2Output3NoteThe variant of the polyline in the first sample: The variant of the polyline in the second sample: The variant of the polyline in the third sample:
Input1 -11 11 2
Output1
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1700']
C. Watering Flowerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1 β‰₯ 0) and r2(r2 β‰₯ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.InputThe first line of the input contains integers n, x1, y1, x2, y2 (1 ≀ n ≀ 2000,  - 107 ≀ x1, y1, x2, y2 ≀ 107)Β β€” the number of flowers, the coordinates of the first and the second fountain.Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≀ xi, yi ≀ 107)Β β€” the coordinates of the i-th flower.It is guaranteed that all n + 2 points in the input are distinct.OutputPrint the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.ExamplesInput2 -1 0 5 30 25 2Output6Input4 0 0 5 09 48 3-1 01 4Output33NoteThe first sample is (r12 = 5, r22 = 1): The second sample is (r12 = 1, r22 = 32):
Input2 -1 0 5 30 25 2
Output6
2 seconds
256 megabytes
['implementation', '*1600']
B. Chocolatetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces.You are asked to calculate the number of ways he can do it. Two ways to break chocolate are considered distinct if one of them contains a break between some two adjacent pieces and the other one doesn't. Please note, that if Bob doesn't make any breaks, all the bar will form one piece and it still has to have exactly one nut.InputThe first line of the input contains integer n (1 ≀ n ≀ 100)Β β€” the number of pieces in the chocolate bar.The second line contains n integers ai (0 ≀ ai ≀ 1), where 0 represents a piece without the nut and 1 stands for a piece with the nut.OutputPrint the number of ways to break the chocolate into multiple parts so that each part would contain exactly one nut.ExamplesInput30 1 0Output1Input51 0 1 0 1Output4NoteIn the first sample there is exactly one nut, so the number of ways equals 1Β β€” Bob shouldn't make any breaks.In the second sample you can break the bar in four ways:10|10|11|010|110|1|011|01|01
Input30 1 0
Output1
1 second
256 megabytes
['combinatorics', '*1300']
A. Elephanttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order to get to his friend's house.InputThe first line of the input contains an integer x (1 ≀ x ≀ 1 000 000)Β β€” The coordinate of the friend's house.OutputPrint the minimum number of steps that elephant needs to make to get from point 0 to point x.ExamplesInput5Output1Input12Output3NoteIn the first sample the elephant needs to make one step of length 5 to reach the point x.In the second sample the elephant can get to point x if he moves by 3, 5 and 4. There are other ways to get the optimal answer but the elephant cannot reach x in less than three moves.
Input5
Output1
1 second
256 megabytes
['math', '*800']
F. Expensive Stringstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n strings ti. Each string has cost ci.Let's define the function of string , where ps, i is the number of occurrences of s in ti, |s| is the length of the string s. Find the maximal value of function f(s) over all strings.Note that the string s is not necessarily some string from t.InputThe first line contains the only integer n (1 ≀ n ≀ 105) β€” the number of strings in t.Each of the next n lines contains contains a non-empty string ti. ti contains only lowercase English letters.It is guaranteed that the sum of lengths of all strings in t is not greater than 5Β·105.The last line contains n integers ci ( - 107 ≀ ci ≀ 107) β€” the cost of the i-th string.OutputPrint the only integer a β€” the maximal value of the function f(s) over all strings s. Note one more time that the string s is not necessarily from t.ExamplesInput2aabb2 1Output4Input2aaab2 1Output5
Input2aabb2 1
Output4
6 seconds
512 megabytes
['string suffix structures', 'strings', '*2700']
E. Sum of Remainderstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCalculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.InputThe only line contains two integers n, m (1 ≀ n, m ≀ 1013) β€” the parameters of the sum.OutputPrint integer s β€” the value of the required sum modulo 109 + 7.ExamplesInput3 4Output4Input4 4Output1Input1 1Output0
Input3 4
Output4
2 seconds
256 megabytes
['implementation', 'math', 'number theory', '*2200']
D. Longest k-Good Segmenttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains two integers n, k (1 ≀ k ≀ n ≀ 5Β·105) β€” the number of elements in a and the parameter k.The second line contains n integers ai (0 ≀ ai ≀ 106) β€” the elements of the array a.OutputPrint two integers l, r (1 ≀ l ≀ r ≀ n) β€” the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.ExamplesInput5 51 2 3 4 5Output1 5Input9 36 5 1 2 3 2 1 4 5Output3 7Input3 11 2 3Output1 1
Input5 51 2 3 4 5
Output1 5
1 second
256 megabytes
['binary search', 'data structures', 'two pointers', '*1600']
C. The Labyrinthtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit β€”- the answer modulo 10. The matrix should be printed without any spaces.To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 1000) β€” the number of rows and columns in the field.Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.OutputPrint the answer as a matrix as described above. See the examples to precise the format of the output.ExamplesInput3 3*.*.*.*.*Output3.3.5.3.3Input4 5**..*..***.*.*.*.*.*Output46..3..732.6.4.5.4.3NoteIn first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner).
Input3 3*.*.*.*.*
Output3.3.5.3.3
1 second
256 megabytes
['dfs and similar', '*1600']
B. Dinner with Emmatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.InputThe first line contains two integers n, m (1 ≀ n, m ≀ 100) β€” the number of streets and avenues in Munhattan.Each of the next n lines contains m integers cij (1 ≀ cij ≀ 109) β€” the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.OutputPrint the only integer a β€” the cost of the dinner for Jack and Emma.ExamplesInput3 44 1 3 52 2 2 25 4 5 1Output2Input3 31 2 32 3 13 1 2Output1NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.
Input3 44 1 3 52 2 2 25 4 5 1
Output2
1 second
256 megabytes
['games', 'greedy', '*1000']
A. Comparing Two Long Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().InputThe first line contains a non-negative integer a.The second line contains a non-negative integer b.The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.OutputPrint the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".ExamplesInput910Output<Input1110Output>Input0001234512345Output=Input01239Output>Input0123111Output>
Input910
Output<
2 seconds
256 megabytes
['implementation', 'strings', '*900']
E. Hexagonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyrat is looking for the perfect code. He decided to start his search from an infinite field tiled by hexagons. For convenience the coordinate system is introduced, take a look at the picture to see how the coordinates of hexagon are defined: Ayrat is searching through the field. He started at point (0, 0) and is moving along the spiral (see second picture). Sometimes he forgets where he is now. Help Ayrat determine his location after n moves.InputThe only line of the input contains integer n (0 ≀ n ≀ 1018)Β β€” the number of Ayrat's moves.OutputPrint two integers x and yΒ β€” current coordinates of Ayrat coordinates.ExamplesInput3Output-2 0Input7Output3 2
Input3
Output-2 0
1 second
256 megabytes
['binary search', 'implementation', 'math', '*2100']
D. Multiplierstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1Β·p2Β·...Β·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.InputThe first line of the input contains a single integer m (1 ≀ m ≀ 200 000)Β β€” the number of primes in factorization of n. The second line contains m primes numbers pi (2 ≀ pi ≀ 200 000).OutputPrint one integerΒ β€” the product of all divisors of n modulo 109 + 7.ExamplesInput22 3Output36Input32 3 2Output1728NoteIn the first sample n = 2Β·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1Β·2Β·3Β·6 = 36.In the second sample 2Β·3Β·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1Β·2Β·3Β·4Β·6Β·12 = 1728.
Input22 3
Output36
2 seconds
256 megabytes
['math', 'number theory', '*2000']
C. Running Tracktime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.InputFirst line of the input contains the string sΒ β€” the coating that is present in the shop. Second line contains the string tΒ β€” the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.OutputThe first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating.If the answer is not -1, then the following n lines should contain two integers xi and yiΒ β€” numbers of ending blocks in the corresponding piece. If xi ≀ yi then this piece is used in the regular order, and if xi > yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.ExamplesInputabccbaabcOutput23 11 3InputaaabrytaaaayratOutput31 16 58 7InputaminoOutput-1NoteIn the first sample string "cbaabc" = "cba" + "abc".In the second sample: "ayrat" = "a" + "yr" + "at".
Inputabccbaabc
Output23 11 3
1 second
512 megabytes
['dp', 'greedy', 'strings', 'trees', '*2000']
B. Longtail Hedgehogtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions: Only segments already presented on the picture can be painted; The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment; The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.InputFirst line of the input contains two integers n and m(2 ≀ n ≀ 100 000, 1 ≀ m ≀ 200 000)Β β€” the number of points and the number segments on the picture respectively. Then follow m lines, each containing two integers ui and vi (1 ≀ ui, vi ≀ n, ui ≠ vi)Β β€” the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.OutputPrint the maximum possible value of the hedgehog's beauty.ExamplesInput8 64 53 52 51 22 86 7Output9Input4 61 21 31 42 32 43 4Output12NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3Β·3 = 9.
Input8 64 53 52 51 22 86 7
Output9
3 seconds
256 megabytes
['dp', 'graphs', '*1600']
A. Bulbstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.InputThe first line of the input contains integers n and m (1 ≀ n, m ≀ 100)Β β€” the number of buttons and the number of bulbs respectively. Each of the next n lines contains xi (0 ≀ xi ≀ m)Β β€” the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≀ yij ≀ m)Β β€” the numbers of these bulbs.OutputIf it's possible to turn on all m bulbs print "YES", otherwise print "NO".ExamplesInput3 42 1 43 1 3 11 2OutputYESInput3 31 11 21 1OutputNONoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.
Input3 42 1 43 1 3 11 2
OutputYES
1 second
256 megabytes
['implementation', '*800']
B. Gena's Codetime limit per test0.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.InputThe first line of the input contains the number of countries n (1 ≀ n ≀ 100 000). The second line contains n non-negative integers ai without leading zeroesΒ β€” the number of tanks of the i-th country.It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.OutputPrint a single number without leading zeroesΒ β€” the product of the number of tanks presented by each country.ExamplesInput35 10 1Output50Input41 1 10 11Output110Input50 3 1 100 1Output0NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful.
Input35 10 1
Output50
0.5 seconds
256 megabytes
['implementation', 'math', '*1400']
A. Link/Cut Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputProgrammer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!InputThe first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).OutputPrint all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).ExamplesInput1 10 2Output1 2 4 8 Input2 4 5Output-1NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Input1 10 2
Output1 2 4 8
2 seconds
256 megabytes
['brute force', 'implementation', '*1500']
E. Puzzle Lovertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOleg Petrov loves crossword puzzles and every Thursday he buys his favorite magazine with crosswords and other word puzzles. In the last magazine Oleg found a curious puzzle, and the magazine promised a valuable prize for it's solution. We give a formal description of the problem below.The puzzle field consists of two rows, each row contains n cells. Each cell contains exactly one small English letter. You also are given a word w, which consists of k small English letters. A solution of the puzzle is a sequence of field cells c1, ..., ck, such that: For all i from 1 to k the letter written in the cell ci matches the letter wi; All the cells in the sequence are pairwise distinct; For all i from 1 to k - 1 cells ci and ci + 1 have a common side.Oleg Petrov quickly found a solution for the puzzle. Now he wonders, how many distinct solutions are there for this puzzle. Oleg Petrov doesn't like too large numbers, so calculate the answer modulo 109 + 7.Two solutions ci and c'i are considered distinct if the sequences of cells do not match in at least one position, that is there is such j in range from 1 to k, such that cj ≠ c'j.InputThe first two lines contain the state of the field for the puzzle. Each of these non-empty lines contains exactly n small English letters.The next line is left empty.The next line is non-empty and contains word w, consisting of small English letters.The length of each line doesn't exceed 2 000.OutputPrint a single integer β€” the number of distinct solutions for the puzzle modulo 109 + 7.ExamplesInputcodeedoccodeOutput4InputaaaaaaaaOutput14
Inputcodeedoccode
Output4
2 seconds
256 megabytes
['dp', 'hashing', 'strings', '*3200']
D. Kingdom and its Citiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMeanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.The kingdom currently consists of n cities. Cities are connected by n - 1 bidirectional road, such that one can get from any city to any other city. As the King had to save a lot, there is only one path between any two cities.What is the point of the reform? The key ministries of the state should be relocated to distinct cities (we call such cities important). However, due to the fact that there is a high risk of an attack by barbarians it must be done carefully. The King has made several plans, each of which is described by a set of important cities, and now wonders what is the best plan.Barbarians can capture some of the cities that are not important (the important ones will have enough protection for sure), after that the captured city becomes impassable. In particular, an interesting feature of the plan is the minimum number of cities that the barbarians need to capture in order to make all the important cities isolated, that is, from all important cities it would be impossible to reach any other important city.Help the King to calculate this characteristic for each of his plan.InputThe first line of the input contains integer n (1 ≀ n ≀ 100 000)Β β€” the number of cities in the kingdom.Each of the next n - 1 lines contains two distinct integers ui, vi (1 ≀ ui, vi ≀ n)Β β€” the indices of the cities connected by the i-th road. It is guaranteed that you can get from any city to any other one moving only along the existing roads.The next line contains a single integer q (1 ≀ q ≀ 100 000)Β β€” the number of King's plans.Each of the next q lines looks as follows: first goes number kiΒ β€” the number of important cities in the King's plan, (1 ≀ ki ≀ n), then follow exactly ki space-separated pairwise distinct numbers from 1 to nΒ β€” the numbers of important cities in this plan.The sum of all ki's does't exceed 100 000.OutputFor each plan print a single integer β€” the minimum number of cities that the barbarians need to capture, or print  - 1 if all the barbarians' attempts to isolate important cities will not be effective.ExamplesInput41 32 34 342 1 23 2 3 43 1 2 44 1 2 3 4Output1-11-1Input71 22 33 41 55 65 714 2 4 6 7Output2NoteIn the first sample, in the first and the third King's plan barbarians can capture the city 3, and that will be enough. In the second and the fourth plans all their attempts will not be effective.In the second sample the cities to capture are 3 and 5.
Input41 32 34 342 1 23 2 3 43 1 2 44 1 2 3 4
Output1-11-1
2 seconds
256 megabytes
['dfs and similar', 'divide and conquer', 'dp', 'graphs', 'sortings', 'trees', '*2800']
C. Necklacetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvan wants to make a necklace as a present to his beloved girl. A necklace is a cyclic sequence of beads of different colors. Ivan says that necklace is beautiful relative to the cut point between two adjacent beads, if the chain of beads remaining after this cut is a palindrome (reads the same forward and backward). Ivan has beads of n colors. He wants to make a necklace, such that it's beautiful relative to as many cuts as possible. He certainly wants to use all the beads. Help him to make the most beautiful necklace.InputThe first line of the input contains a single number n (1 ≀ n ≀ 26) β€” the number of colors of beads. The second line contains after n positive integers ai Β  β€” the quantity of beads of i-th color. It is guaranteed that the sum of ai is at least 2 and does not exceed 100 000.OutputIn the first line print a single numberΒ β€” the maximum number of beautiful cuts that a necklace composed from given beads may have. In the second line print any example of such necklace.Each color of the beads should be represented by the corresponding lowercase English letter (starting with a). As the necklace is cyclic, print it starting from any point.ExamplesInput34 2 1Output1abacabaInput14Output4aaaaInput21 1Output0abNoteIn the first sample a necklace can have at most one beautiful cut. The example of such a necklace is shown on the picture.In the second sample there is only one way to compose a necklace.
Input34 2 1
Output1abacaba
2 seconds
256 megabytes
['constructive algorithms', 'math', '*2500']
B. Skillstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer aiΒ β€” the current skill level. All skills have the same maximum level A.Along with the skills, global ranking of all players was added. Players are ranked according to the so-called Force. The Force of a player is the sum of the following values: The number of skills that a character has perfected (i.e., such that ai = A), multiplied by coefficient cf. The minimum skill level among all skills (min ai), multiplied by coefficient cm. Now Lesha has m hacknetian currency units, which he is willing to spend. Each currency unit can increase the current level of any skill by 1 (if it's not equal to A yet). Help him spend his money in order to achieve the maximum possible value of the Force.InputThe first line of the input contains five space-separated integers n, A, cf, cm and m (1 ≀ n ≀ 100 000, 1 ≀ A ≀ 109, 0 ≀ cf, cm ≀ 1000, 0 ≀ m ≀ 1015).The second line contains exactly n integers ai (0 ≀ ai ≀ A), separated by spaces,Β β€” the current levels of skills.OutputOn the first line print the maximum value of the Force that the character can achieve using no more than m currency units.On the second line print n integers a'i (ai ≀ a'i ≀ A), skill levels which one must achieve in order to reach the specified value of the Force, while using no more than m currency units. Numbers should be separated by spaces.ExamplesInput3 5 10 1 51 3 1Output122 5 2 Input3 5 10 1 3391 3 1Output355 5 5 NoteIn the first test the optimal strategy is to increase the second skill to its maximum, and increase the two others by 1.In the second test one should increase all skills to maximum.
Input3 5 10 1 51 3 1
Output122 5 2
2 seconds
256 megabytes
['binary search', 'brute force', 'dp', 'greedy', 'sortings', 'two pointers', '*1900']
A. Peter and Snow Blowertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPeter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of ​​the region that will be cleared from snow. Help him.InputThe first line of the input contains three integersΒ β€” the number of vertices of the polygon n (), and coordinates of point P.Each of the next n lines contains two integersΒ β€” coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line.All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.OutputPrint a single real value numberΒ β€” the area of the region that will be cleared. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .ExamplesInput3 0 00 1-1 21 2Output12.566370614359172464Input4 1 -10 01 22 01 1Output21.991148575128551812NoteIn the first sample snow will be removed from that area:
Input3 0 00 1-1 21 2
Output12.566370614359172464
2 seconds
256 megabytes
['binary search', 'geometry', 'ternary search', '*1900']
F. Simba on the Circletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a circular array with n elements. The elements are numbered from some element with values from 1 to n in clockwise order. The i-th cell contains the value ai. The robot Simba is in cell s.Each moment of time the robot is in some of the n cells (at the begin he is in s). In one turn the robot can write out the number written in current cell or move to the adjacent cell in clockwise or counterclockwise direction. To write out the number from the cell Simba doesn't spend any time, but to move to adjacent cell Simba spends one unit of time.Simba wants to write the number from each cell one time, so the numbers will be written in a non decreasing order. Find the least number of time units to write out all numbers.InputThe first line contains two integers n and s (1 ≀ s ≀ n ≀ 2000) β€” the number of cells in the circular array and the starting position of Simba.The second line contains n integers ai ( - 109 ≀ ai ≀ 109) β€” the number written in the i-th cell. The numbers are given for cells in order from 1 to n. Some of numbers ai can be equal.OutputIn the first line print the number t β€” the least number of time units.Each of the next n lines should contain the direction of robot movement and the number of cells to move in that direction. After that movement the robot writes out the number from the cell in which it turns out. The direction and the number of cells should be printed in the form of +x in case of clockwise movement and -x in case of counterclockwise movement to x cells (0 ≀ x ≀ n - 1).Note that the sum of absolute values of x should be equal to t.ExamplesInput9 10 1 2 2 2 1 0 1 1Output12+0-3-1+2+1+2+1+1+1Input8 10 1 0 1 0 1 0 1Output13+0+2+2+2-1+2+2+2Input8 11 2 3 4 5 6 7 8Output7+0+1+1+1+1+1+1+1Input8 10 0 0 0 0 0 0 0Output7+0+1+1+1+1+1+1+1
Input9 10 1 2 2 2 1 0 1 1
Output12+0-3-1+2+1+2+1+1+1
1 second
256 megabytes
['dp', '*2600']
E. Square Root of Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1].This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them.InputThe first line contains integer n (1 ≀ n ≀ 106) β€” the number of elements in permutation p.The second line contains n distinct integers p1, p2, ..., pn (1 ≀ pi ≀ n) β€” the elements of permutation p.OutputIf there is no permutation q such that q2 = p print the number "-1".If the answer exists print it. The only line should contain n different integers qi (1 ≀ qi ≀ n) β€” the elements of the permutation q. If there are several solutions print any of them.ExamplesInput42 1 4 3Output3 4 2 1Input42 1 3 4Output-1Input52 3 4 5 1Output4 5 1 2 3
Input42 1 4 3
Output3 4 2 1
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'dfs and similar', 'graphs', 'math', '*2200']
D. The Union of k-Segmentstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.InputThe first line contains two integers n and k (1 ≀ k ≀ n ≀ 106) β€” the number of segments and the value of k.The next n lines contain two integers li, ri ( - 109 ≀ li ≀ ri ≀ 109) each β€” the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.OutputFirst line contains integer m β€” the smallest number of segments.Next m lines contain two integers aj, bj (aj ≀ bj) β€” the ends of j-th segment in the answer. The segments should be listed in the order from left to right.ExamplesInput3 20 5-3 23 8Output20 23 5Input3 20 5-3 33 8Output10 5
Input3 20 5-3 23 8
Output20 23 5
4 seconds
256 megabytes
['greedy', 'sortings', '*1800']
C. Replace To Make Regular Bracket Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.InputThe only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.OutputIf it's impossible to get RBS from s print Impossible.Otherwise print the least number of replaces needed to get RBS from s.ExamplesInput[<}){}Output2Input{()}[]Output0Input]]OutputImpossible
Input[<}){}
Output2
1 second
256 megabytes
['data structures', 'expression parsing', 'math', '*1400']
B. HDD is Outdated Technologytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 ≀ fi ≀ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.InputThe first line contains a positive integer n (1 ≀ n ≀ 2Β·105) β€” the number of fragments.The second line contains n different integers fi (1 ≀ fi ≀ n) β€” the number of the fragment written in the i-th sector.OutputPrint the only integer β€” the number of time units needed to read the file.ExamplesInput33 1 2Output3Input51 3 5 4 2Output10NoteIn the second example the head moves in the following way: 1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units 2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units 3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units 4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4 + 3 + 2 + 1 = 10.
Input33 1 2
Output3
1 second
256 megabytes
['implementation', 'math', '*1200']
A. The Text Splittingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).InputThe first line contains three positive integers n, p, q (1 ≀ p, q ≀ n ≀ 100).The second line contains the string s consists of lowercase and uppercase latin letters and digits.OutputIf it's impossible to split the string s to the strings of length p and q print the only number "-1".Otherwise in the first line print integer k β€” the number of strings in partition of s.Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s β€” from left to right.If there are several solutions print any of them.ExamplesInput5 2 3HelloOutput2HelloInput10 9 5CodeforcesOutput2CodeforcesInput6 4 5PrivetOutput-1Input8 1 1abacabacOutput8abacabac
Input5 2 3Hello
Output2Hello
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*1300']
H. New Year and Forgotten Treetime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected undirected graph with n - 1 edges, where n denotes the number of vertices. Vertices are numbered 1 through n.Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in the next year. Limak was responsible for remembering that tree.It would be hard to remember a whole tree. Limak decided to describe it in his notebook instead. He took a pen and wrote n - 1 lines, each with two integersΒ β€” indices of two vertices connected by an edge.Now, the New Year is just around the corner and Limak is asked to reconstruct that tree. Of course, there is a problem. He was a very little bear a year ago, and he didn't know digits and the alphabet, so he just replaced each digit with a question markΒ β€” the only character he knew. That means, for any vertex index in his notes he knows only the number of digits in it. At least he knows there were no leading zeroes.Limak doesn't want to disappoint everyone. Please, take his notes and reconstruct a New Year tree. Find any tree matching Limak's records and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1" (without the quotes).InputThe first line contains a single integer n (2 ≀ n ≀ 200 000)Β β€” the number of vertices.Each of the next n - 1 lines contains two space-separated non-empty strings, both consisting of questions marks only. No string has more characters than the number of digits in n.OutputIf there is no tree matching Limak's records, print the only line with "-1" (without the quotes).Otherwise, describe any tree matching Limak's notes. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. You can print edges in any order.ExamplesInput12? ?? ?? ?? ???? ??? ??? ??? ?? ?? ?? ?Output3 11 69 12 101 78 11 41 105 110 1112 1Input12?? ??? ?? ?? ???? ??? ??? ??? ?? ??? ??? ?Output-1
Input12? ?? ?? ?? ???? ??? ??? ??? ?? ?? ?? ?
Output3 11 69 12 101 78 11 41 105 110 1112 1
7 seconds
256 megabytes
['constructive algorithms', 'flows', 'graphs', '*3200']
G. New Year and Caketime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. According to some old traditions, his bear family prepared a New Year cake. And Limak likes cakes.As you may know, a New Year cake is a strictly convex polygon with n vertices.Parents won't allow Limak to eat more than half of a cake because he would get sick. After some thinking they decided to cut a cake along one of nΒ·(n - 3) / 2 diagonals. Then Limak will get a non-greater piece.Limak understands rules but he won't be happy if the second piece happens to be much bigger. Limak's disappointment will be equal to the difference between pieces' areas, multiplied by two. It can be proved that it will be integer for the given constraints.There are nΒ·(n - 3) / 2 possible scenarios. Consider them all and find the sum of values of Limak's disappointment, modulo 109 + 7.InputThe first line of the input contains a single integer n (4 ≀ n ≀ 500 000)Β β€” the number of vertices in the polygon denoting the cake.Each of the next n lines contains two integers xi and yi (|xi|, |yi| ≀ 109)Β β€” coordinates of the i-th point.It's guaranteed that all points are distinct, polygon is strictly convex and points are given in the clockwise order.OutputPrint the sum of values of Limak's disappointment over all possible scenarios modulo 109 + 7.ExamplesInput52 42 75 75 43 -2Output90Input4-1000000000 -50000000 12345671 1-5 -100000000Output525185196Input8-10 0-6 60 106 610 06 -60 -10-6 -6Output5216NoteIn the first sample possible values of Limak's disappointment are 0, 18, 18, 24, 30.
Input52 42 75 75 43 -2
Output90
2 seconds
256 megabytes
['geometry', 'two pointers', '*2900']
F. New Year and Cleaningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with h rows and w columns. Each cell is an empty square.He is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot.A cleaning robot has a built-in pattern of n moves, defined by a string of the length n. A single move (character) moves a robot to one of four adjacent cells. Each character is one of the following four: 'U' (up), 'D' (down), 'L' (left), 'R' (right). One move takes one minute.A cleaning robot must be placed and started in some cell. Then it repeats its pattern of moves till it hits a wall (one of four borders of a house). After hitting a wall it can be placed and used again.Limak isn't sure if placing a cleaning robot in one cell will be enough. Thus, he is going to start it wΒ·h times, one time in each cell. Maybe some cells will be cleaned more than once but who cares?Limak asks you one question. How much time will it take to clean a house? Find and print the number of minutes modulo 109 + 7. It's also possible that a cleaning robot will never stopΒ β€” then print "-1" (without the quotes) instead.Placing and starting a robot takes no time, however, you must count a move when robot hits a wall. Take a look into samples for further clarification.InputThe first line contains three integers n, h and w (1 ≀ n, h, w ≀ 500 000)Β β€” the length of the pattern, the number of rows and the number of columns, respectively.The second line contains a string of length nΒ β€” the pattern of n moves. Each character is one of uppercase letters 'U', 'D', 'L' or 'R'.OutputPrint one line with the answer.If a cleaning robot will never stop, print "-1" (without the quotes). Otherwise, print the number of minutes it will take to clean a house modulo 109 + 7.ExamplesInput1 10 2ROutput30Input3 4 6RULOutput134Input4 1 500000RLRLOutput-1NoteIn the first sample house is a grid with 10 rows and 2 columns. Starting a robot anywhere in the second column will result in only one move (thus, one minute of cleaning) in which robot will hit a wallΒ β€” he tried to go right but there is no third column. Starting a robot anywhere in the first column will result in two moves. The total number of minutes is 10Β·1 + 10Β·2 = 30.In the second sample a started robot will try to move "RULRULRULR..." For example, for the leftmost cell in the second row robot will make 5 moves before it stops because of hitting an upper wall.
Input1 10 2R
Output30
2 seconds
256 megabytes
['binary search', 'implementation', '*2500']
E. New Year and Three Musketeerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDo you know the story about the three musketeers? Anyway, you must help them now.Richelimakieu is a cardinal in the city of Bearis. He found three brave warriors and called them the three musketeers. Athos has strength a, Borthos strength b, and Caramis has strength c.The year 2015 is almost over and there are still n criminals to be defeated. The i-th criminal has strength ti. It's hard to defeat strong criminalsΒ β€” maybe musketeers will have to fight together to achieve it.Richelimakieu will coordinate musketeers' actions. In each hour each musketeer can either do nothing or be assigned to one criminal. Two or three musketeers can be assigned to the same criminal and then their strengths are summed up. A criminal can be defeated in exactly one hour (also if two or three musketeers fight him). Richelimakieu can't allow the situation where a criminal has strength bigger than the sum of strengths of musketeers fighting himΒ β€” a criminal would win then!In other words, there are three ways to defeat a criminal. A musketeer of the strength x in one hour can defeat a criminal of the strength not greater than x. So, for example Athos in one hour can defeat criminal i only if ti ≀ a. Two musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of strengths of these two musketeers. So, for example Athos and Caramis in one hour can defeat criminal i only if ti ≀ a + c. Note that the third remaining musketeer can either do nothing or fight some other criminal. Similarly, all three musketeers can fight together and in one hour defeat a criminal of the strength not greater than the sum of musketeers' strengths, i.e. ti ≀ a + b + c. Richelimakieu doesn't want musketeers to fight during the New Year's Eve. Thus, he must coordinate their actions in order to minimize the number of hours till all criminals will be defeated.Find the minimum number of hours to defeat all criminals. If musketeers can't defeat them all then print "-1" (without the quotes) instead.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of criminals.The second line contains three integers a, b and c (1 ≀ a, b, c ≀ 108)Β β€” strengths of musketeers.The third line contains n integers t1, t2, ..., tn (1 ≀ ti ≀ 108)Β β€” strengths of criminals.OutputPrint one line with the answer.If it's impossible to defeat all criminals, print "-1" (without the quotes). Otherwise, print the minimum number of hours the three musketeers will spend on defeating all criminals.ExamplesInput510 20 301 1 1 1 50Output2Input510 20 301 1 1 1 51Output3Input730 20 1034 19 50 33 88 15 20Output-1Input610 5 1010 9 5 25 20 5Output3NoteIn the first sample Athos has strength 10, Borthos 20, and Caramis 30. They can defeat all criminals in two hours: Borthos and Caramis should together fight a criminal with strength 50. In the same hour Athos can fight one of four criminals with strength 1. There are three criminals left, each with strength 1. Each musketeer can fight one criminal in the second hour. In the second sample all three musketeers must together fight a criminal with strength 51. It takes one hour. In the second hour they can fight separately, each with one criminal. In the third hour one criminal is left and any of musketeers can fight him.
Input510 20 301 1 1 1 50
Output2
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*2400']
D. New Year and Ancient Prophecytime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLimak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.Limak assumes three things: Years are listed in the strictly increasing order; Every year is a positive integer number; There are no leading zeros. Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 5000)Β β€” the number of digits.The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.OutputPrint the number of ways to correctly split the given sequence modulo 109 + 7.ExamplesInput6123434Output8Input820152016Output4NoteIn the first sample there are 8 ways to split the sequence: "123434" = "123434" (maybe the given sequence is just one big number) "123434" = "1" + "23434" "123434" = "12" + "3434" "123434" = "123" + "434" "123434" = "1" + "23" + "434" "123434" = "1" + "2" + "3434" "123434" = "1" + "2" + "3" + "434" "123434" = "1" + "2" + "3" + "4" + "34" Note that we don't count a split "123434" = "12" + "34" + "34" because numbers have to be strictly increasing.In the second sample there are 4 ways: "20152016" = "20152016" "20152016" = "20" + "152016" "20152016" = "201" + "52016" "20152016" = "2015" + "2016"
Input6123434
Output8
2.5 seconds
512 megabytes
['dp', 'hashing', 'strings', '*2000']
C. New Year and Dominotime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThey say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so.Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Rows are numbered 1 through h from top to bottom. Columns are numbered 1 through w from left to right.Also, Limak has a single domino. He wants to put it somewhere in a grid. A domino will occupy exactly two adjacent cells, located either in one row or in one column. Both adjacent cells must be empty and must be inside a grid.Limak needs more fun and thus he is going to consider some queries. In each query he chooses some rectangle and wonders, how many way are there to put a single domino inside of the chosen rectangle?InputThe first line of the input contains two integers h and w (1 ≀ h, w ≀ 500) – the number of rows and the number of columns, respectively.The next h lines describe a grid. Each line contains a string of the length w. Each character is either '.' or '#'Β β€” denoting an empty or forbidden cell, respectively.The next line contains a single integer q (1 ≀ q ≀ 100 000)Β β€” the number of queries.Each of the next q lines contains four integers r1i, c1i, r2i, c2i (1 ≀ r1i ≀ r2i ≀ h, 1 ≀ c1i ≀ c2i ≀ w)Β β€” the i-th query. Numbers r1i and c1i denote the row and the column (respectively) of the upper left cell of the rectangle. Numbers r2i and c2i denote the row and the column (respectively) of the bottom right cell of the rectangle.OutputPrint q integers, i-th should be equal to the number of ways to put a single domino inside the i-th rectangle.ExamplesInput5 8....#..#.#......##.#....##..#.##........41 1 2 34 1 4 11 2 4 52 5 5 8Output401015Input7 39........................................###..###..#..###.....###..###..#..###....#..#.#..#..#.........#..#.#..#..#....###..#.#..#..###.....###..#.#..#..###..#....#.#..#....#.....#....#.#..#..#.#..###..###..#..###.....###..###..#..###........................................61 1 3 202 10 6 302 10 7 302 2 7 71 7 7 71 8 7 8Output53891202302NoteA red frame below corresponds to the first query of the first sample. A domino can be placed in 4 possible ways.
Input5 8....#..#.#......##.#....##..#.##........41 1 2 34 1 4 11 2 4 52 5 5 8
Output401015
3 seconds
256 megabytes
['dp', 'implementation', '*1500']
B. New Year and Old Propertytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe year 2015 is almost over.Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary systemΒ β€” 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?Assume that all positive integers are always written without leading zeros.InputThe only line of the input contains two integers a and b (1 ≀ a ≀ b ≀ 1018)Β β€” the first year and the last year in Limak's interval respectively.OutputPrint one integer – the number of years Limak will count in his chosen interval.ExamplesInput5 10Output2Input2015 2015Output1Input100 105Output0Input72057594000000000 72057595000000000Output26NoteIn the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and 1010 = 10102. Two of them (1012 and 1102) have the described property.
Input5 10
Output2
2 seconds
256 megabytes
['bitmasks', 'brute force', 'implementation', '*1300']
A. New Year and Daystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.Limak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.Limak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. He can save one candy either on some fixed day of the week or on some fixed day of the month.Limak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.InputThe only line of the input is in one of the following two formats: "x of week" where x (1 ≀ x ≀ 7) denotes the day of the week. The 1-st day is Monday and the 7-th one is Sunday. "x of month" where x (1 ≀ x ≀ 31) denotes the day of the month. OutputPrint one integerΒ β€” the number of candies Limak will save in the year 2016.ExamplesInput4 of weekOutput52Input30 of monthOutput11NotePolar bears use the Gregorian calendar. It is the most common calendar and you likely use it too. You can read about it on Wikipedia if you want to – https://en.wikipedia.org/wiki/Gregorian_calendar. The week starts with Monday.In the first sample Limak wants to save one candy on each Thursday (the 4-th day of the week). There are 52 Thursdays in the 2016. Thus, he will save 52 candies in total.In the second sample Limak wants to save one candy on the 30-th day of each month. There is the 30-th day in exactly 11 months in the 2016Β β€” all months but February. It means that Limak will save 11 candies in total.
Input4 of week
Output52
2 seconds
256 megabytes
['implementation', '*900']
E. Alphabet Permutationstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n, consisting of first k lowercase English letters.We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string "acbacbacbacb" is a 4-repeat of the string "acb".Let's say that string a contains string b as a subsequence, if string b can be obtained from a by erasing some symbols.Let p be a string that represents some permutation of the first k lowercase English letters. We define function d(p) as the smallest integer such that a d(p)-repeat of the string p contains string s as a subsequence.There are m operations of one of two types that can be applied to string s: Replace all characters at positions from li to ri by a character ci. For the given p, that is a permutation of first k lowercase English letters, find the value of function d(p). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function d(p) for all operations of the second type.InputThe first line contains three positive integers n, m and k (1 ≀ n ≀ 200 000, 1 ≀ m ≀ 20000, 1 ≀ k ≀ 10)Β β€” the length of the string s, the number of operations and the size of the alphabet respectively. The second line contains the string s itself.Each of the following lines m contains a description of some operation: Operation of the first type starts with 1 followed by a triple li, ri and ci, that denotes replacement of all characters at positions from li to ri by character ci (1 ≀ li ≀ ri ≀ n, ci is one of the first k lowercase English letters). Operation of the second type starts with 2 followed by a permutation of the first k lowercase English letters.OutputFor each query of the second type the value of function d(p).ExamplesInput7 4 3abacaba1 3 5 b2 abc1 4 4 c2 cbaOutput65NoteAfter the first operation the string s will be abbbbba.In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc.After the third operation the string s will be abbcbba.In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA.Uppercase letters means the occurrences of symbols from the string s.
Input7 4 3abacaba1 3 5 b2 abc1 4 4 c2 cba
Output65
1 second
512 megabytes
['data structures', 'strings', '*2500']
D. Vika and Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 100 000)Β β€” the number of segments drawn by Vika.Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 ≀ x1, y1, x2, y2 ≀ 109)Β β€” the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.OutputPrint the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.ExamplesInput30 1 2 11 4 1 20 3 2 3Output8Input4-2 -1 2 -12 1 -2 1-1 -2 -1 21 2 1 -2Output16NoteIn the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).
Input30 1 2 11 4 1 20 3 2 3
Output8
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'geometry', 'two pointers', '*2300']
C. Harmony Analysistime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or  - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?InputThe only line of the input contains a single integer k (0 ≀ k ≀ 9).OutputPrint 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to  - 1, and must be equal to ' + ' if it's equal to  + 1. It's guaranteed that the answer always exists.If there are many correct answers, print any.ExamplesInput2Output++**+*+*+++++**+NoteConsider all scalar products in example: Vectors 1 and 2: ( + 1)Β·( + 1) + ( + 1)Β·( - 1) + ( - 1)Β·( + 1) + ( - 1)Β·( - 1) = 0 Vectors 1 and 3: ( + 1)Β·( + 1) + ( + 1)Β·( + 1) + ( - 1)Β·( + 1) + ( - 1)Β·( + 1) = 0 Vectors 1 and 4: ( + 1)Β·( + 1) + ( + 1)Β·( - 1) + ( - 1)Β·( - 1) + ( - 1)Β·( + 1) = 0 Vectors 2 and 3: ( + 1)Β·( + 1) + ( - 1)Β·( + 1) + ( + 1)Β·( + 1) + ( - 1)Β·( + 1) = 0 Vectors 2 and 4: ( + 1)Β·( + 1) + ( - 1)Β·( - 1) + ( + 1)Β·( - 1) + ( - 1)Β·( + 1) = 0 Vectors 3 and 4: ( + 1)Β·( + 1) + ( + 1)Β·( - 1) + ( + 1)Β·( - 1) + ( + 1)Β·( + 1) = 0
Input2
Output++**+*+*+++++**+
3 seconds
256 megabytes
['constructive algorithms', '*1800']
B. Vika and Squarestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.InputThe first line of the input contains a single integer n (1 ≀ n ≀ 200 000)Β β€” the number of jars with colors Vika has.The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≀ ai ≀ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.OutputThe only line of the output should contain a single integerΒ β€” the maximum number of squares that Vika can paint if she follows the rules described above.ExamplesInput52 4 2 3 3Output12Input35 5 5Output15Input610 10 10 1 10 10Output11NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.
Input52 4 2 3 3
Output12
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1300']
A. Pasha and Sticktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n. Pasha likes rectangles but hates squares, so he wonders, how many ways are there to split a stick into four parts so that it's possible to form a rectangle using these parts, but is impossible to form a square.Your task is to help Pasha and count the number of such ways. Two ways to cut the stick are considered distinct if there exists some integer x, such that the number of parts of length x in the first way differ from the number of parts of length x in the second way.InputThe first line of the input contains a positive integer n (1 ≀ n ≀ 2Β·109) β€” the length of Pasha's stick.OutputThe output should contain a single integerΒ β€” the number of ways to split Pasha's stick into four parts of positive integer length so that it's possible to make a rectangle by connecting the ends of these parts, but is impossible to form a square. ExamplesInput6Output1Input20Output4NoteThere is only one way to divide the stick in the first sample {1, 1, 2, 2}.Four ways to divide the stick in the second sample are {1, 1, 9, 9}, {2, 2, 8, 8}, {3, 3, 7, 7} and {4, 4, 6, 6}. Note that {5, 5, 5, 5} doesn't work.
Input6
Output1
1 second
256 megabytes
['combinatorics', 'math', '*1000']
F. Frogs and mosquitoestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n frogs sitting on the coordinate axis Ox. For each frog two values xi, ti are known β€” the position and the initial length of the tongue of the i-th frog (it is guaranteed that all positions xi are different). m mosquitoes one by one are landing to the coordinate axis. For each mosquito two values are known pj β€” the coordinate of the position where the j-th mosquito lands and bj β€” the size of the j-th mosquito. Frogs and mosquitoes are represented as points on the coordinate axis.The frog can eat mosquito if mosquito is in the same position with the frog or to the right, and the distance between them is not greater than the length of the tongue of the frog.If at some moment several frogs can eat a mosquito the leftmost frog will eat it (with minimal xi). After eating a mosquito the length of the tongue of a frog increases with the value of the size of eaten mosquito. It's possible that after it the frog will be able to eat some other mosquitoes (the frog should eat them in this case).For each frog print two values β€” the number of eaten mosquitoes and the length of the tongue after landing all mosquitoes and after eating all possible mosquitoes by frogs.Each mosquito is landing to the coordinate axis only after frogs eat all possible mosquitoes landed before. Mosquitoes are given in order of their landing to the coordinate axis.InputFirst line contains two integers n, m (1 ≀ n, m ≀ 2Β·105) β€” the number of frogs and mosquitoes.Each of the next n lines contains two integers xi, ti (0 ≀ xi, ti ≀ 109) β€” the position and the initial length of the tongue of the i-th frog. It is guaranteed that all xi are different.Next m lines contain two integers each pj, bj (0 ≀ pj, bj ≀ 109) β€” the position and the size of the j-th mosquito.OutputPrint n lines. The i-th line should contain two integer values ci, li β€” the number of mosquitoes eaten by the i-th frog and the length of the tongue of the i-th frog.ExamplesInput4 610 215 06 10 1110 101 16 015 1014 10012 2Output3 1141 101 11 2Input1 210 220 212 1Output1 3
Input4 610 215 06 10 1110 101 16 015 1014 10012 2
Output3 1141 101 11 2
2 seconds
512 megabytes
['data structures', 'greedy', '*2500']
E. Minimum spanning tree for each edgetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConnected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.InputFirst line contains two integers n and m (1 ≀ n ≀ 2Β·105, n - 1 ≀ m ≀ 2Β·105) β€” the number of vertices and edges in graph.Each of the next m lines contains three integers ui, vi, wi (1 ≀ ui, vi ≀ n, ui ≠ vi, 1 ≀ wi ≀ 109) β€” the endpoints of the i-th edge and its weight.OutputPrint m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge.The edges are numbered from 1 to m in order of their appearing in input.ExamplesInput5 71 2 31 3 11 4 52 3 22 5 33 4 24 5 4Output98118889
Input5 71 2 31 3 11 4 52 3 22 5 33 4 24 5 4
Output98118889
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'trees', '*2100']
D. Gadgets for dollars and poundstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.InputFirst line contains four integers n, m, k, s (1 ≀ n ≀ 2Β·105, 1 ≀ k ≀ m ≀ 2Β·105, 1 ≀ s ≀ 109) β€” number of days, total number and required number of gadgets, number of burles Nura has.Second line contains n integers ai (1 ≀ ai ≀ 106) β€” the cost of one dollar in burles on i-th day.Third line contains n integers bi (1 ≀ bi ≀ 106) β€” the cost of one pound in burles on i-th day.Each of the next m lines contains two integers ti, ci (1 ≀ ti ≀ 2, 1 ≀ ci ≀ 106) β€” type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.OutputIf Nura can't buy k gadgets print the only line with the number -1.Otherwise the first line should contain integer d β€” the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di β€” the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n.In case there are multiple possible solutions, print any of them.ExamplesInput5 4 2 21 2 3 2 13 2 1 2 31 12 11 22 2Output31 12 3Input4 3 2 20069 70 71 72104 105 106 1071 12 21 2Output-1Input4 3 1 1000000000900000 910000 940000 990000990000 999000 999900 9999901 876542 765431 65432Output-1
Input5 4 2 21 2 3 2 13 2 1 2 31 12 11 22 2
Output31 12 3
2 seconds
256 megabytes
['binary search', 'greedy', 'two pointers', '*2000']
C. Load Balancingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.InputThe first line contains positive number n (1 ≀ n ≀ 105) β€” the number of the servers. The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≀ mi ≀ 2Β·104), where mi is the number of tasks assigned to the i-th server.OutputPrint the minimum number of seconds required to balance the load.ExamplesInput21 6Output2Input710 11 10 11 10 11 11Output0Input51 2 3 4 5Output3NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is: move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5); then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4); then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.
Input21 6
Output2
2 seconds
256 megabytes
['implementation', 'math', '*1500']
B. The Best Gifttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEmily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.InputThe first line contains two positive integers n and m (2 ≀ n ≀ 2Β·105, 2 ≀ m ≀ 10) β€” the number of books in the bookstore and the number of genres.The second line contains a sequence a1, a2, ..., an, where ai (1 ≀ ai ≀ m) equals the genre of the i-th book.It is guaranteed that for each genre there is at least one book of that genre.OutputPrint the only integer β€” the number of ways in which Jack can choose books.It is guaranteed that the answer doesn't exceed the value 2Β·109.ExamplesInput4 32 1 3 1Output5Input7 44 2 3 1 2 4 3Output18NoteThe answer to the first test sample equals 5 as Sasha can choose: the first and second books, the first and third books, the first and fourth books, the second and third books, the third and fourth books.
Input4 32 1 3 1
Output5
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1100']
A. USB Flash Drivestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.InputThe first line contains positive integer n (1 ≀ n ≀ 100) β€” the number of USB flash drives.The second line contains positive integer m (1 ≀ m ≀ 105) β€” the size of Sean's file.Each of the next n lines contains positive integer ai (1 ≀ ai ≀ 1000) β€” the sizes of USB flash drives in megabytes.It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.OutputPrint the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.ExamplesInput35213Output2Input36232Output3Input25510Output1NoteIn the first example Sean needs only two USB flash drives β€” the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive β€” the first or the second.
Input35213
Output2
2 seconds
256 megabytes
['greedy', 'implementation', 'sortings', '*800']
B. Hamming Distance Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGenos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.InputThe first line of the input contains binary string a (1 ≀ |a| ≀ 200 000).The second line of the input contains binary string b (|a| ≀ |b| ≀ 200 000).Both strings are guaranteed to consist of characters '0' and '1' only.OutputPrint a single integerΒ β€” the sum of Hamming distances between a and all contiguous substrings of b of length |a|.ExamplesInput0100111Output3Input00110110Output2NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.
Input0100111
Output3
2 seconds
256 megabytes
['combinatorics', 'strings', '*1500']
A. Saitama Destroys Hoteltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSaitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special β€” it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.InputThe first line of input contains two integers n and s (1 ≀ n ≀ 100, 1 ≀ s ≀ 1000)Β β€” the number of passengers and the number of the top floor respectively.The next n lines each contain two space-separated integers fi and ti (1 ≀ fi ≀ s, 1 ≀ ti ≀ 1000)Β β€” the floor and the time of arrival in seconds for the passenger number i.OutputPrint a single integerΒ β€” the minimum amount of time in seconds needed to bring all the passengers to floor 0.ExamplesInput3 72 13 85 2Output11Input5 102 773 338 219 1210 64Output79NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.
Input3 72 13 85 2
Output11
1 second
256 megabytes
['implementation', 'math', '*1000']