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
|
---|---|---|---|---|---|
E. Numbers Exchangetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEugeny has n cards, each of them has exactly one integer written on it. Eugeny wants to exchange some cards with Nikolay so that the number of even integers on his cards would equal the number of odd integers, and that all these numbers would be distinct. Nikolay has m cards, distinct numbers from 1 to m are written on them, one per card. It means that Nikolay has exactly one card with number 1, exactly one card with number 2 and so on. A single exchange is a process in which Eugeny gives one card to Nikolay and takes another one from those Nikolay has. Your task is to find the minimum number of card exchanges and determine which cards Eugeny should exchange.InputThe first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 109) — the number of cards Eugeny has and the number of cards Nikolay has. It is guaranteed that n is even.The second line contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the numbers on Eugeny's cards.OutputIf there is no answer, print -1.Otherwise, in the first line print the minimum number of exchanges. In the second line print n integers — Eugeny's cards after all the exchanges with Nikolay. The order of cards should coincide with the card's order in the input data. If the i-th card wasn't exchanged then the i-th number should coincide with the number from the input data. Otherwise, it is considered that this card was exchanged, and the i-th number should be equal to the number on the card it was exchanged to.If there are multiple answers, it is allowed to print any of them.ExamplesInput6 25 6 7 9 4 5Output15 6 7 9 4 2 Input8 67 7 7 7 8 8 8 8Output67 2 4 6 8 1 3 5 Input4 14 2 1 10Output-1 | Input6 25 6 7 9 4 5 | Output15 6 7 9 4 2 | 1 second | 256 megabytes | ['greedy', 'implementation', 'math', '*1900'] |
D. Green and Black Teatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInnokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.InputThe first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.OutputIf it is impossible to drink n cups of tea, print "NO" (without quotes).Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black.If there are multiple answers, print any of them.ExamplesInput5 1 3 2OutputGBGBGInput7 2 2 5OutputBBGBGBBInput4 3 4 0OutputNO | Input5 1 3 2 | OutputGBGBG | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1500'] |
C. Tramtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe tram in Berland goes along a straight line from the point 0 to the point s and back, passing 1 meter per t1 seconds in both directions. It means that the tram is always in the state of uniform rectilinear motion, instantly turning around at points x = 0 and x = s.Igor is at the point x1. He should reach the point x2. Igor passes 1 meter per t2 seconds. Your task is to determine the minimum time Igor needs to get from the point x1 to the point x2, if it is known where the tram is and in what direction it goes at the moment Igor comes to the point x1.Igor can enter the tram unlimited number of times at any moment when his and the tram's positions coincide. It is not obligatory that points in which Igor enter and exit the tram are integers. Assume that any boarding and unboarding happens instantly. Igor can move arbitrary along the line (but not faster than 1 meter per t2 seconds). He can also stand at some point for some time.InputThe first line contains three integers s, x1 and x2 (2 ≤ s ≤ 1000, 0 ≤ x1, x2 ≤ s, x1 ≠ x2) — the maximum coordinate of the point to which the tram goes, the point Igor is at, and the point he should come to.The second line contains two integers t1 and t2 (1 ≤ t1, t2 ≤ 1000) — the time in seconds in which the tram passes 1 meter and the time in seconds in which Igor passes 1 meter.The third line contains two integers p and d (1 ≤ p ≤ s - 1, d is either 1 or ) — the position of the tram in the moment Igor came to the point x1 and the direction of the tram at this moment. If , the tram goes in the direction from the point s to the point 0. If d = 1, the tram goes in the direction from the point 0 to the point s.OutputPrint the minimum time in seconds which Igor needs to get from the point x1 to the point x2.ExamplesInput4 2 43 41 1Output8Input5 4 01 23 1Output7NoteIn the first example it is profitable for Igor to go by foot and not to wait the tram. Thus, he has to pass 2 meters and it takes 8 seconds in total, because he passes 1 meter per 4 seconds. In the second example Igor can, for example, go towards the point x2 and get to the point 1 in 6 seconds (because he has to pass 3 meters, but he passes 1 meters per 2 seconds). At that moment the tram will be at the point 1, so Igor can enter the tram and pass 1 meter in 1 second. Thus, Igor will reach the point x2 in 7 seconds in total. | Input4 2 43 41 1 | Output8 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', 'math', '*1600'] |
B. Decodingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it. InputThe first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word.The second line contains the string s of length n consisting of lowercase English letters — the encoding.OutputPrint the word that Polycarp encoded.ExamplesInput5logvaOutputvolgaInput2noOutputnoInput4abbaOutputbabaNoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba. | Input5logva | Outputvolga | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
A. Compotetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has a lemons, b apples and c pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1: 2: 4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — lemons, apples and pears — should be put in the compote as whole fruits.Your task is to determine the maximum total number of lemons, apples and pears from which Nikolay can cook the compote. It is possible that Nikolay can't use any fruits, in this case print 0. InputThe first line contains the positive integer a (1 ≤ a ≤ 1000) — the number of lemons Nikolay has. The second line contains the positive integer b (1 ≤ b ≤ 1000) — the number of apples Nikolay has. The third line contains the positive integer c (1 ≤ c ≤ 1000) — the number of pears Nikolay has.OutputPrint the maximum total number of lemons, apples and pears from which Nikolay can cook the compote.ExamplesInput257Output7Input4713Output21Input232Output0NoteIn the first example Nikolay can use 1 lemon, 2 apples and 4 pears, so the answer is 1 + 2 + 4 = 7.In the second example Nikolay can use 3 lemons, 6 apples and 12 pears, so the answer is 3 + 6 + 12 = 21.In the third example Nikolay don't have enough pears to cook any compote, so the answer is 0. | Input257 | Output7 | 1 second | 256 megabytes | ['implementation', 'math', '*800'] |
B. Hongcow Solves A Puzzletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.InputThe first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece.The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space.It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.OutputOutput "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.ExamplesInput2 3XXXXXXOutputYESInput2 2.XXXOutputNOInput5 5.......X.................OutputYESNoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................ | Input2 3XXXXXX | OutputYES | 2 seconds | 256 megabytes | ['implementation', '*1400'] |
A. Hongcow Learns the Cyclic Shifttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.InputThe first line of input will be a single string s (1 ≤ |s| ≤ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'–'z').OutputOutput a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.ExamplesInputabcdOutput4InputbbbOutput1InputyzyzOutput2NoteFor the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy". | Inputabcd | Output4 | 2 seconds | 256 megabytes | ['implementation', 'strings', '*900'] |
E. Hongcow Masters the Cyclic Shifttime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHongcow's teacher heard that Hongcow had learned about the cyclic shift, and decided to set the following problem for him.You are given a list of n strings s1, s2, ..., sn contained in the list A.A list X of strings is called stable if the following condition holds.First, a message is defined as a concatenation of some elements of the list X. You can use an arbitrary element as many times as you want, and you may concatenate these elements in any arbitrary order. Let SX denote the set of of all messages you can construct from the list. Of course, this set has infinite size if your list is nonempty.Call a single message good if the following conditions hold: Suppose the message is the concatenation of k strings w1, w2, ..., wk, where each wi is an element of X. Consider the |w1| + |w2| + ... + |wk| cyclic shifts of the string. Let m be the number of these cyclic shifts of the string that are elements of SX. A message is good if and only if m is exactly equal to k. The list X is called stable if and only if every element of SX is good.Let f(L) be 1 if L is a stable list, and 0 otherwise.Find the sum of f(L) where L is a nonempty contiguous sublist of A (there are contiguous sublists in total).InputThe first line of input will contain a single integer n (1 ≤ n ≤ 30), denoting the number of strings in the list.The next n lines will each contain a string si ().OutputPrint a single integer, the number of nonempty contiguous sublists that are stable.ExamplesInput4aabbbbaOutput7Input5hheellllooOutput0Input6aababbbababcOutput13NoteFor the first sample, there are 10 sublists to consider. Sublists ["a", "ab", "b"], ["ab", "b", "bba"], and ["a", "ab", "b", "bba"] are not stable. The other seven sublists are stable.For example, X = ["a", "ab", "b"] is not stable, since the message "ab" + "ab" = "abab" has four cyclic shifts ["abab", "baba", "abab", "baba"], which are all elements of SX. | Input4aabbbba | Output7 | 5 seconds | 256 megabytes | ['strings', 'two pointers', '*3200'] |
D. Hongcow Draws a Circletime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHongcow really likes the color red. Hongcow doesn't like the color blue.Hongcow is standing in an infinite field where there are n red points and m blue points.Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside.Compute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print - 1. Otherwise, your answer will be accepted if it has relative or absolute error at most 10 - 4.InputThe first line of the input will contain two integers n, m (1 ≤ n, m ≤ 1, 000).The next n lines will contain two integers xi, yi (1 ≤ xi, yi ≤ 104). This denotes the coordinates of a red point.The next m lines will contain two integers xi, yi (1 ≤ xi, yi ≤ 104). This denotes the coordinates of a blue point.No two points will have the same coordinates.OutputPrint - 1 if the circle can have arbitrary size. Otherwise, print a floating point number representing the largest radius circle that satisfies the conditions. 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 52 33 41 11 44 24 72 5Output3.5355338827Input1 63 31 55 42 13 44 21 3Output1.5811388195Input2 22 23 31 14 4Output-1NoteThis is a picture of the first sample This is a picture of the second sample | Input2 52 33 41 11 44 24 72 5 | Output3.5355338827 | 6 seconds | 256 megabytes | ['geometry', '*3200'] |
C. Hongcow Buys a Deck of Cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Hongcow goes to the store and sees a brand new deck of n special cards. Each individual card is either red or blue. He decides he wants to buy them immediately. To do this, he needs to play a game with the owner of the store.This game takes some number of turns to complete. On a turn, Hongcow may do one of two things: Collect tokens. Hongcow collects 1 red token and 1 blue token by choosing this option (thus, 2 tokens in total per one operation). Buy a card. Hongcow chooses some card and spends tokens to purchase it as specified below. The i-th card requires ri red resources and bi blue resources. Suppose Hongcow currently has A red cards and B blue cards. Then, the i-th card will require Hongcow to spend max(ri - A, 0) red tokens, and max(bi - B, 0) blue tokens. Note, only tokens disappear, but the cards stay with Hongcow forever. Each card can be bought only once.Given a description of the cards and their costs determine the minimum number of turns Hongcow needs to purchase all cards.InputThe first line of input will contain a single integer n (1 ≤ n ≤ 16).The next n lines of input will contain three tokens ci, ri and bi. ci will be 'R' or 'B', denoting the color of the card as red or blue. ri will be an integer denoting the amount of red resources required to obtain the card, and bi will be an integer denoting the amount of blue resources required to obtain the card (0 ≤ ri, bi ≤ 107).OutputOutput a single integer, denoting the minimum number of turns needed to acquire all the cards.ExamplesInput3R 0 1B 1 0R 1 1Output4Input3R 3 0R 2 0R 1 0Output6NoteFor the first sample, Hongcow's four moves are as follows: Collect tokens Buy card 1 Buy card 2 Buy card 3 Note, at the fourth step, Hongcow is able to buy card 3 because Hongcow already has one red and one blue card, so we don't need to collect tokens.For the second sample, one optimal strategy is as follows: Collect tokens Collect tokens Buy card 2 Collect tokens Buy card 3 Buy card 1 At the fifth step, even though Hongcow has a red token, Hongcow doesn't actually need to spend it, since Hongcow has a red card already. | Input3R 0 1B 1 0R 1 1 | Output4 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'dp', '*2400'] |
B. Hongcow's Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. In the interaction section below you will see the information about flushing the output.In this problem, you will be playing a game with Hongcow. How lucky of you!Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and columns are labeled from 1 to n.The matrix entries are between 0 and 109. In addition, Mi, i = 0 for all valid i. Your task is to find the minimum value along each row, excluding diagonal elements. Formally, for each i, you must find .To do this, you can ask Hongcow some questions.A question consists of giving Hongcow a subset of distinct indices {w1, w2, ..., wk}, with 1 ≤ k ≤ n. Hongcow will respond with n integers. The i-th integer will contain the minimum value of min1 ≤ j ≤ kMi, wj.You may only ask Hongcow at most 20 questions — he thinks you only need that many questions answered.When you are ready to answer, print out a single integer - 1 on its own line, then n integers on the next line. The i-th integer should be the minimum value in the i-th row of the matrix, excluding the i-th element. Do not forget to flush the final answer as well. Printing the answer does not count as asking a question.You will get Wrong Answer verdict if Your question or answers are not in the format described in this statement. You ask strictly more than 20 questions. Your question contains duplicate indices. The value of k in your question does not lie in the range from 1 to n, inclusive. Your final answer is not correct. You will get Idleness Limit Exceeded if you don't print anything or if you forget to flush the output, including for the final answer (more info about flushing output below).InputThe first line of input will contain a single integer n (2 ≤ n ≤ 1, 000).OutputTo print the final answer, print out the string -1 on its own line. Then, the next line should contain n integers. The i-th integer should be the minimum value of the i-th row of the matrix, excluding elements on the diagonal. Do not forget to flush your answer!InteractionTo ask a question, print out a single integer k on its own line, denoting the size of your subset. Then, the next line should contain k integers w1, w2, ... wk. Note, you must flush your output to get a response.Hongcow will respond by printing out a line with n integers. The i-th integer in this line represents the minimum value of Mi, wj where j is between 1 and k.You may only ask a question at most 20 times, otherwise, you will get Wrong Answer.To flush you can use (just after printing an integer and end-of-line): fflush(stdout) in C++; System.out.flush() in Java; stdout.flush() in Python; flush(output) in Pascal; See the documentation for other languages. Hacking To hack someone, use the following format nM_{1,1} M_{1,2} ... M_{1,n}M_{2,1} M_{2,2} ... M_{2,n}...M_{n,1} M_{n,2} ... M_{n,n}Of course, contestant programs will not be able to see this input.ExamplesInput30 0 02 7 00 0 43 0 80 5 4Output31 2 31321 21211-12 5 4Input20 00 0Output1211-10 0NoteIn the first sample, Hongcow has the hidden matrix [ [0, 3, 2], [5, 0, 7], [4, 8 ,0],]Here is a more readable version demonstrating the interaction. The column on the left represents Hongcow, while the column on the right represents the contestant. 3 3 1 2 30 0 0 1 32 7 0 2 1 20 0 4 1 23 0 8 1 10 5 4 -1 2 5 4For the second sample, it is possible for off-diagonal elements of the matrix to be zero. | Input30 0 02 7 00 0 43 0 80 5 4 | Output31 2 31321 21211-12 5 4 | 3 seconds | 256 megabytes | ['bitmasks', 'divide and conquer', 'interactive', '*1900'] |
A. Hongcow Builds A Nationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.InputThe first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government. The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.It is guaranteed that the graph described by the input is stable.OutputOutput a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.ExamplesInput4 1 21 31 2Output2Input3 3 121 21 32 3Output0NoteFor the first sample test, the graph looks like this: Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this: We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple. | Input4 1 21 31 2 | Output2 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', '*1500'] |
E. Vladik and cardstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVladik was bored on his way home and decided to play the following game. He took n cards and put them in a row in front of himself. Every card has a positive integer number not exceeding 8 written on it. He decided to find the longest subsequence of cards which satisfies the following conditions: the number of occurrences of each number from 1 to 8 in the subsequence doesn't differ by more then 1 from the number of occurrences of any other number. Formally, if there are ck cards with number k on them in the subsequence, than for all pairs of integers the condition |ci - cj| ≤ 1 must hold. if there is at least one card with number x on it in the subsequence, then all cards with number x in this subsequence must form a continuous segment in it (but not necessarily a continuous segment in the original sequence). For example, the subsequence [1, 1, 2, 2] satisfies this condition while the subsequence [1, 2, 2, 1] doesn't. Note that [1, 1, 2, 2] doesn't satisfy the first condition. Please help Vladik to find the length of the longest subsequence that satisfies both conditions.InputThe first line contains single integer n (1 ≤ n ≤ 1000) — the number of cards in Vladik's sequence.The second line contains the sequence of n positive integers not exceeding 8 — the description of Vladik's sequence.OutputPrint single integer — the length of the longest subsequence of Vladik's sequence that satisfies both conditions.ExamplesInput31 1 1Output1Input88 7 6 5 4 3 2 1Output8Input241 8 1 2 8 2 3 8 3 4 8 4 5 8 5 6 8 6 7 8 7 8 8 8Output17NoteIn the first sample all the numbers written on the cards are equal, so you can't take more than one card, otherwise you'll violate the first condition. | Input31 1 1 | Output1 | 2 seconds | 256 megabytes | ['binary search', 'bitmasks', 'brute force', 'dp', '*2200'] |
D. Chloe and pleasant prizestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGenerous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible.InputThe first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of gifts.The next line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the pleasantness of the gifts.The next (n - 1) lines contain two numbers each. The i-th of these lines contains integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the description of the tree's edges. It means that gifts with numbers ui and vi are connected to each other with a rope. The gifts' ids in the description of the ropes can be given in arbirtary order: vi hangs on ui or ui hangs on vi. It is guaranteed that all the gifts hang on the first gift, possibly with a sequence of ropes and another gifts.OutputIf it is possible for Chloe and Vladik to choose prizes without fighting, print single integer — the maximum possible sum of pleasantness they can get together.Otherwise print Impossible.ExamplesInput80 5 -1 4 3 2 6 51 22 42 51 33 66 76 8Output25Input41 -5 1 11 21 42 3Output2Input1-1OutputImpossible | Input80 5 -1 4 3 2 6 51 22 42 51 33 66 76 8 | Output25 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'trees', '*1800'] |
C. Vladik and fractionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.InputThe single line contains single integer n (1 ≤ n ≤ 104).OutputIf the answer exists, print 3 distinct numbers x, y and z (1 ≤ x, y, z ≤ 109, x ≠ y, x ≠ z, y ≠ z). Otherwise print -1.If there are multiple answers, print any of them.ExamplesInput3Output2 7 42Input7Output7 8 56 | Input3 | Output2 7 42 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'math', 'number theory', '*1500'] |
B. Chloe and the sequence time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputChloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (n - 1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1, 2, 1] after the first step, the sequence [1, 2, 1, 3, 1, 2, 1] after the second step.The task is to find the value of the element with index k (the elements are numbered from 1) in the obtained sequence, i. e. after (n - 1) steps.Please help Chloe to solve the problem!InputThe only line contains two integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n - 1).OutputPrint single integer — the integer at the k-th position in the obtained sequence.ExamplesInput3 2Output2Input4 8Output4NoteIn the first sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1]. The number on the second position is 2.In the second sample the obtained sequence is [1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1]. The number on the eighth position is 4. | Input3 2 | Output2 | 1 second | 256 megabytes | ['binary search', 'bitmasks', 'constructive algorithms', 'implementation', '*1200'] |
A. Vladik and flightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.InputThe first line contains three integers n, a, and b (1 ≤ n ≤ 105, 1 ≤ a, b ≤ n) — the number of airports, the id of the airport from which Vladik starts his route and the id of the airport which he has to reach. The second line contains a string with length n, which consists only of characters 0 and 1. If the i-th character in this string is 0, then i-th airport belongs to first company, otherwise it belongs to the second.OutputPrint single integer — the minimum cost Vladik has to pay to get to the olympiad.ExamplesInput4 1 41010Output1Input5 5 210110Output0NoteIn the first example Vladik can fly to the airport 2 at first and pay |1 - 2| = 1 (because the airports belong to different companies), and then fly from the airport 2 to the airport 4 for free (because the airports belong to the same company). So the cost of the whole flight is equal to 1. It's impossible to get to the olympiad for free, so the answer is equal to 1. In the second example Vladik can fly directly from the airport 5 to the airport 2, because they belong to the same company. | Input4 1 41010 | Output1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1200'] |
B. Arpa’s obvious problem and Mehrdad’s terrible solutiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where is bitwise xor operation (see notes for explanation). Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.InputFirst line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x.Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.OutputPrint a single integer: the answer to the problem.ExamplesInput2 31 2Output1Input6 15 1 2 3 4 1Output2NoteIn the first sample there is only one pair of i = 1 and j = 2. so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR. | Input2 31 2 | Output1 | 1 second | 256 megabytes | ['brute force', 'math', 'number theory', '*1500'] |
A. Arpa’s hard exam and Mehrdad’s naive cheattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere exists an island called Arpa’s land, some beautiful girls live there, as ugly ones do.Mehrdad wants to become minister of Arpa’s land. Arpa has prepared an exam. Exam has only one question, given n, print the last digit of 1378n. Mehrdad has become quite confused and wants you to help him. Please help, although it's a naive cheat.InputThe single line of input contains one integer n (0 ≤ n ≤ 109).OutputPrint single integer — the last digit of 1378n.ExamplesInput1Output8Input2Output4NoteIn the first example, last digit of 13781 = 1378 is 8.In the second example, last digit of 13782 = 1378·1378 = 1898884 is 4. | Input1 | Output8 | 1 second | 256 megabytes | ['implementation', 'math', 'number theory', '*1000'] |
E. Arpa’s abnormal DNA and Mehrdad’s deep interesttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll of us know that girls in Arpa’s land are... ok, you’ve got the idea :DAnyone knows that Arpa isn't a normal man, he is ... well, sorry, I can't explain it more. Mehrdad is interested about the reason, so he asked Sipa, one of the best biology scientists in Arpa's land, for help. Sipa has a DNA editor. Sipa put Arpa under the DNA editor. DNA editor showed Arpa's DNA as a string S consisting of n lowercase English letters. Also Sipa has another DNA T consisting of lowercase English letters that belongs to a normal man.Now there are (n + 1) options to change Arpa's DNA, numbered from 0 to n. i-th of them is to put T between i-th and (i + 1)-th characters of S (0 ≤ i ≤ n). If i = 0, T will be put before S, and if i = n, it will be put after S.Mehrdad wants to choose the most interesting option for Arpa's DNA among these n + 1 options. DNA A is more interesting than B if A is lexicographically smaller than B. Mehrdad asked Sipa q questions: Given integers l, r, k, x, y, what is the most interesting option if we only consider such options i that l ≤ i ≤ r and ? If there are several most interesting options, Mehrdad wants to know one with the smallest number i.Since Sipa is a biology scientist but not a programmer, you should help him.InputThe first line contains strings S, T and integer q (1 ≤ |S|, |T|, q ≤ 105) — Arpa's DNA, the DNA of a normal man, and the number of Mehrdad's questions. The strings S and T consist only of small English letters.Next q lines describe the Mehrdad's questions. Each of these lines contain five integers l, r, k, x, y (0 ≤ l ≤ r ≤ n, 1 ≤ k ≤ n, 0 ≤ x ≤ y < k).OutputPrint q integers. The j-th of them should be the number i of the most interesting option among those that satisfy the conditions of the j-th question. If there is no option i satisfying the conditions in some question, print -1.ExamplesInputabc d 40 3 2 0 00 3 1 0 01 2 1 0 00 1 3 2 2Output2 3 2 -1 Inputabbbbbbaaa baababaaab 101 2 1 0 02 7 8 4 72 3 9 2 83 4 6 1 10 8 5 2 42 8 10 4 77 10 1 0 01 4 6 0 20 9 8 0 64 8 5 0 1Output1 4 2 -1 2 4 10 1 1 5 NoteExplanation of first sample case:In the first question Sipa has two options: dabc (i = 0) and abdc (i = 2). The latter (abcd) is better than abdc, so answer is 2.In the last question there is no i such that 0 ≤ i ≤ 1 and . | Inputabc d 40 3 2 0 00 3 1 0 01 2 1 0 00 1 3 2 2 | Output2 3 2 -1 | 2 seconds | 256 megabytes | ['data structures', 'string suffix structures', '*3400'] |
D. Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh pathstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJust in case somebody missed it: we have wonderful girls in Arpa’s land.Arpa has a rooted tree (connected acyclic graph) consisting of n vertices. The vertices are numbered 1 through n, the vertex 1 is the root. There is a letter written on each edge of this tree. Mehrdad is a fan of Dokhtar-kosh things. He call a string Dokhtar-kosh, if we can shuffle the characters in string such that it becomes palindrome. He asks Arpa, for each vertex v, what is the length of the longest simple path in subtree of v that form a Dokhtar-kosh string.InputThe first line contains integer n (1 ≤ n ≤ 5·105) — the number of vertices in the tree.(n - 1) lines follow, the i-th of them contain an integer pi + 1 and a letter ci + 1 (1 ≤ pi + 1 ≤ i, ci + 1 is lowercase English letter, between a and v, inclusively), that mean that there is an edge between nodes pi + 1 and i + 1 and there is a letter ci + 1 written on this edge.OutputPrint n integers. The i-th of them should be the length of the longest simple path in subtree of the i-th vertex that form a Dokhtar-kosh string.ExamplesInput41 s2 a3 sOutput3 1 1 0 Input51 a2 h1 a4 hOutput4 1 0 1 0 | Input41 s2 a3 s | Output3 1 1 0 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'trees', '*2900'] |
C. Arpa’s overnight party and Mehrdad’s silent enteringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNote that girls in Arpa’s land are really attractive.Arpa loves overnight parties. In the middle of one of these parties Mehrdad suddenly appeared. He saw n pairs of friends sitting around a table. i-th pair consisted of a boy, sitting on the ai-th chair, and his girlfriend, sitting on the bi-th chair. The chairs were numbered 1 through 2n in clockwise direction. There was exactly one person sitting on each chair. There were two types of food: Kooft and Zahre-mar. Now Mehrdad wonders, was there any way to serve food for the guests such that: Each person had exactly one type of food, No boy had the same type of food as his girlfriend, Among any three guests sitting on consecutive chairs, there was two of them who had different type of food. Note that chairs 2n and 1 are considered consecutive. Find the answer for the Mehrdad question. If it was possible, find some arrangement of food types that satisfies the conditions.InputThe first line contains an integer n (1 ≤ n ≤ 105) — the number of pairs of guests.The i-th of the next n lines contains a pair of integers ai and bi (1 ≤ ai, bi ≤ 2n) — the number of chair on which the boy in the i-th pair was sitting and the number of chair on which his girlfriend was sitting. It's guaranteed that there was exactly one person sitting on each chair. OutputIf there is no solution, print -1.Otherwise print n lines, the i-th of them should contain two integers which represent the type of food for the i-th pair. The first integer in the line is the type of food the boy had, and the second integer is the type of food the girl had. If someone had Kooft, print 1, otherwise print 2.If there are multiple solutions, print any of them.ExampleInput31 42 53 6Output1 22 11 2 | Input31 42 53 6 | Output1 22 11 2 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'graphs', '*2600'] |
B. Arpa's weak amphitheater and Mehrdad's valuable Hosestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJust to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y. Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.InputThe first line contains integers n, m and w (1 ≤ n ≤ 1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited.The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses.The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses.The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.OutputPrint the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.ExamplesInput3 1 53 2 52 4 21 2Output6Input4 2 112 4 6 66 4 2 11 22 3Output7NoteIn the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7. | Input3 1 53 2 52 4 21 2 | Output6 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'dsu', '*1600'] |
A. Arpa's loud Owf and Mehrdad's evil plantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you have noticed, there are lovely girls in Arpa’s land.People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi. Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are as follows.The game consists of rounds. Assume person x wants to start a round, he calls crushx and says: "Oww...wwf" (the letter w is repeated t times) and cuts off the phone immediately. If t > 1 then crushx calls crushcrushx and says: "Oww...wwf" (the letter w is repeated t - 1 times) and cuts off the phone immediately. The round continues until some person receives an "Owf" (t = 1). This person is called the Joon-Joon of the round. There can't be two rounds at the same time.Mehrdad has an evil plan to make the game more funny, he wants to find smallest t (t ≥ 1) such that for each person x, if x starts some round and y becomes the Joon-Joon of the round, then by starting from y, x would become the Joon-Joon of the round. Find such t for Mehrdad if it's possible.Some strange fact in Arpa's land is that someone can be himself's crush (i.e. crushi = i).InputThe first line of input contains integer n (1 ≤ n ≤ 100) — the number of people in Arpa's land.The second line contains n integers, i-th of them is crushi (1 ≤ crushi ≤ n) — the number of i-th person's crush.OutputIf there is no t satisfying the condition, print -1. Otherwise print such smallest t.ExamplesInput42 3 1 4Output3Input44 4 4 4Output-1Input42 1 4 3Output1NoteIn the first sample suppose t = 3. If the first person starts some round:The first person calls the second person and says "Owwwf", then the second person calls the third person and says "Owwf", then the third person calls the first person and says "Owf", so the first person becomes Joon-Joon of the round. So the condition is satisfied if x is 1.The process is similar for the second and the third person.If the fourth person starts some round:The fourth person calls himself and says "Owwwf", then he calls himself again and says "Owwf", then he calls himself for another time and says "Owf", so the fourth person becomes Joon-Joon of the round. So the condition is satisfied when x is 4.In the last example if the first person starts a round, then the second person becomes the Joon-Joon, and vice versa. | Input42 3 1 4 | Output3 | 1 second | 256 megabytes | ['dfs and similar', 'math', '*1600'] |
B. Alyona and flowerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1, - 2, 1, 3, - 4. Suppose the mother suggested subarrays (1, - 2), (3, - 4), (1, 3), (1, - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then: the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays, the second flower adds ( - 2)·1 = - 2, because he is in one of chosen subarrays, the third flower adds 1·2 = 2, because he is in two of chosen subarrays, the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays, the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother.The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100).The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri].Each subarray can encounter more than once.OutputPrint single integer — the maximum possible value added to the Alyona's happiness.ExamplesInput5 41 -2 1 3 -41 24 53 41 4Output7Input4 31 2 3 41 32 41 1Output16Input2 2-1 -21 11 2Output0NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays. | Input5 41 -2 1 3 -41 24 53 41 4 | Output7 | 2 seconds | 256 megabytes | ['constructive algorithms', '*1200'] |
A. Alyona and copybookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Alyona is in a shop to buy some copybooks for school. She study four subjects so she wants to have equal number of copybooks for each of the subjects. There are three types of copybook's packs in the shop: it is possible to buy one copybook for a rubles, a pack of two copybooks for b rubles, and a pack of three copybooks for c rubles. Alyona already has n copybooks.What is the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4? There are infinitely many packs of any type in the shop. Alyona can buy packs of different type in the same purchase.InputThe only line contains 4 integers n, a, b, c (1 ≤ n, a, b, c ≤ 109).OutputPrint the minimum amount of rubles she should pay to buy such number of copybooks k that n + k is divisible by 4.ExamplesInput1 1 3 4Output3Input6 2 1 1Output1Input4 4 4 4Output0Input999999999 1000000000 1000000000 1000000000Output1000000000NoteIn the first example Alyona can buy 3 packs of 1 copybook for 3a = 3 rubles in total. After that she will have 4 copybooks which she can split between the subjects equally. In the second example Alyuna can buy a pack of 2 copybooks for b = 1 ruble. She will have 8 copybooks in total.In the third example Alyona can split the copybooks she already has between the 4 subject equally, so she doesn't need to buy anything.In the fourth example Alyona should buy one pack of one copybook. | Input1 1 3 4 | Output3 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1300'] |
E. Gosha is huntingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has a Poke Balls and b Ultra Balls. There are n Pokemons. They are numbered 1 through n. Gosha knows that if he throws a Poke Ball at the i-th Pokemon he catches it with probability pi. If he throws an Ultra Ball at the i-th Pokemon he catches it with probability ui. He can throw at most one Ball of each type at any Pokemon.The hunting proceeds as follows: at first, Gosha chooses no more than a Pokemons at which he will throw Poke Balls and no more than b Pokemons at which he will throw Ultra Balls. After that, he throws the chosen Balls at the chosen Pokemons. If he throws both Ultra Ball and Poke Ball at some Pokemon, he is caught if and only if he is caught by any of these Balls. The outcome of a throw doesn't depend on the other throws.Gosha would like to know what is the expected number of the Pokemons he catches if he acts in an optimal way. In other words, he would like to know the maximum possible expected number of Pokemons can catch.InputThe first line contains three integers n, a and b (2 ≤ n ≤ 2000, 0 ≤ a, b ≤ n) — the number of Pokemons, the number of Poke Balls and the number of Ultra Balls.The second line contains n real values p1, p2, ..., pn (0 ≤ pi ≤ 1), where pi is the probability of catching the i-th Pokemon if Gosha throws a Poke Ball to it.The third line contains n real values u1, u2, ..., un (0 ≤ ui ≤ 1), where ui is the probability of catching the i-th Pokemon if Gosha throws an Ultra Ball to it.All the probabilities are given with exactly three digits after the decimal separator.OutputPrint the maximum possible expected number of Pokemons Gosha can catch. The answer is considered correct if it's absolute or relative error doesn't exceed 10 - 4.ExamplesInput3 2 21.000 0.000 0.5000.000 1.000 0.500Output2.75Input4 1 30.100 0.500 0.500 0.6000.100 0.500 0.900 0.400Output2.16Input3 2 00.412 0.198 0.5990.612 0.987 0.443Output1.011 | Input3 2 21.000 0.000 0.5000.000 1.000 0.500 | Output2.75 | 5 seconds | 256 megabytes | ['brute force', 'data structures', 'dp', 'flows', 'math', 'probabilities', 'sortings', '*3000'] |
D. Recover a functional graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFunctional graph is a directed graph in which all vertices have outdegree equal to 1. Loops are allowed.Some vertices of a functional graph lay on a cycle. From the others we can come to a cycle by making a finite number of steps along the edges (we consider only finite functional graphs in this problem).Let's compute two values for each vertex. precyclei is the amount of edges we should pass to get to a vertex which is a part of some cycle (zero, if i itself lies on a cycle), cyclei is the length of the cycle we get to.You are given the information about these values for some functional graph. For each vertex you know the values precyclei and cyclei, however, instead of some values there can be the question mark. It means that these values are unknown.Build any functional graph that suits the description or determine that there is no such graph.InputThe first line contains single integer n (1 ≤ n ≤ 300) — the number of vertices in the graph.Each of the next n lines contain two integers — precyclei (0 ≤ precyclei ≤ n - 1) and cyclei (1 ≤ cyclei ≤ n). There could be question marks instead of some of these values.OutputIn case there is no solution, print -1.Otherwise, print n integers. i-th of them is the number of vertex to which the edge form the i-th vertex go.The vertices should be in the same order as they go in input data.If there are multiple solutions, print any of them.ExamplesInput30 30 3? ?Output2 3 1 Input53 2? ?? ?? ?? ?Output5 3 2 2 4 Input8? 3? ?0 20 20 30 30 33 3Output5 1 4 3 6 7 5 2 Input1? ?Output1 Input60 30 30 30 30 30 3Output2 3 1 5 6 4 Input21 11 1Output-1 | Input30 30 3? ? | Output2 3 1 | 2 seconds | 256 megabytes | ['graph matchings', '*3400'] |
C. Alyona and towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlyona has built n towers by putting small cubes some on the top of others. Each cube has size 1 × 1 × 1. A tower is a non-zero amount of cubes standing on the top of each other. The towers are next to each other, forming a row.Sometimes Alyona chooses some segment towers, and put on the top of each tower several cubes. Formally, Alyouna chooses some segment of towers from li to ri and adds di cubes on the top of them.Let the sequence a1, a2, ..., an be the heights of the towers from left to right. Let's call as a segment of towers al, al + 1, ..., ar a hill if the following condition holds: there is integer k (l ≤ k ≤ r) such that al < al + 1 < al + 2 < ... < ak > ak + 1 > ak + 2 > ... > ar.After each addition of di cubes on the top of the towers from li to ri, Alyona wants to know the maximum width among all hills. The width of a hill is the number of towers in it.InputThe first line contain single integer n (1 ≤ n ≤ 3·105) — the number of towers.The second line contain n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the number of cubes in each tower. The third line contain single integer m (1 ≤ m ≤ 3·105) — the number of additions.The next m lines contain 3 integers each. The i-th of these lines contains integers li, ri and di (1 ≤ l ≤ r ≤ n, 1 ≤ di ≤ 109), that mean that Alyona puts di cubes on the tio of each of the towers from li to ri.OutputPrint m lines. In i-th line print the maximum width of the hills after the i-th addition.ExampleInput55 5 5 5 531 3 22 2 14 4 1Output245NoteThe first sample is as follows:After addition of 2 cubes on the top of each towers from the first to the third, the number of cubes in the towers become equal to [7, 7, 7, 5, 5]. The hill with maximum width is [7, 5], thus the maximum width is 2.After addition of 1 cube on the second tower, the number of cubes in the towers become equal to [7, 8, 7, 5, 5]. The hill with maximum width is now [7, 8, 7, 5], thus the maximum width is 4.After addition of 1 cube on the fourth tower, the number of cubes in the towers become equal to [7, 8, 7, 6, 5]. The hill with maximum width is now [7, 8, 7, 6, 5], thus the maximum width is 5. | Input55 5 5 5 531 3 22 2 14 4 1 | Output245 | 2 seconds | 256 megabytes | ['data structures', '*2500'] |
B. Alyona and a treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.InputThe first line contains single integer n (1 ≤ n ≤ 2·105).The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices.The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).It is guaranteed that the given graph is a tree.OutputPrint n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.ExamplesInput52 5 1 4 61 71 13 53 6Output1 0 1 0 0Input59 7 8 6 51 12 13 14 1Output4 3 2 1 0NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5). | Input52 5 1 4 61 71 13 53 6 | Output1 0 1 0 0 | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dfs and similar', 'graphs', 'trees', '*1900'] |
A. Alyona and mextime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 105).The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].OutputIn the first line print single integer — the maximum possible minimum mex.In the second line print n integers — the array a. All the elements in a should be between 0 and 109.It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109.If there are multiple solutions, print any of them.ExamplesInput5 31 32 54 5Output21 0 2 1 0Input4 21 42 4Output35 2 0 1NoteThe first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2. | Input5 31 32 54 5 | Output21 0 2 1 0 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1700'] |
F. Dirty platestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter one of celebrations there is a stack of dirty plates in Nikita's kitchen. Nikita has to wash them and put into a dryer. In dryer, the plates should be also placed in a stack also, and the plates sizes should increase down up. The sizes of all plates are distinct.Nikita has no so much free space, specifically, he has a place for only one more stack of plates. Therefore, he can perform only such two operations: Take any number of plates from 1 to a from the top of the dirty stack, wash them and put them to the intermediate stack. Take any number of plates from 1 to b from the top of the intermediate stack and put them to the stack in the dryer. Note that after performing each of the operations, the plates are put in the same order as they were before the operation.You are given the sizes of the plates s1, s2, ..., sn in the down up order in the dirty stack, and integers a and b. All the sizes are distinct. Write a program that determines whether or not Nikita can put the plates in increasing down up order in the dryer. If he is able to do so, the program should find some sequence of operations (not necessary optimal) to achieve it.InputThe first line contains three integers n, a and b (1 ≤ n ≤ 2000, 1 ≤ a, b ≤ n). The second line contains integers s1, s2, ..., sn (1 ≤ si ≤ n) — the sizes of the plates in down up order. All the sizes are distinct.OutputIn the first line print "YES" if there is a solution. In this case, in the second line print integer k — the number of operations. Then in k lines print the operations, one per line. Each operation is described by two integers tj and cj, where tj = 1, if the operation is to wash the top cj places from the dirty stack and put them onto the intermediate stack, and tj = 2, if the operation is to move th top cj plates from the intermediate stack to the dryer. In case there is no solution, print single line "NO".If there are multiple solutions, print any of them. Note that it is not necessary to minimize the number of operations.ExamplesInput6 2 32 3 6 4 1 5OutputYES81 21 12 11 21 12 12 12 3Input7 7 71 2 3 4 5 6 7OutputYES21 72 7Input7 1 11 2 3 4 5 6 7OutputYES141 11 11 11 11 11 11 12 12 12 12 12 12 12 1Input4 2 23 2 1 4OutputNONoteIn the first example the initial order of plates was 2, 3, 6, 4, 1, 5. Here is how the stacks look like after each of the operations: [1 2]: Dirty stack: 6, 4, 1, 5. Intermediary stack: 2, 3. The dryer is empty. [1 1]: Dirty stack: 4, 1, 5. Intermediary stack: 6, 2, 3. The dryer is empty. [2 1]: Dirty stack: 4, 1, 5. Intermediary stack: 2, 3. Dryer stack: 6. [1 2]: Dirty stack: 5. Intermediary stack: 4, 1, 2, 3. Dryer stack: 6. [1 1]: There are no dirty plates. Intermediary stack: 5, 4, 1, 2, 3. Dryer stack: 6. [2 1]: There are no dirty plates. Intermediary stack: 4, 1, 2, 3. Dryer stack: 5, 6. [2 1]: There are no dirty plates. Intermediary stack: 1, 2, 3. Dryer stack: 4, 5, 6. [2 3]: All the plates are in the dryer: 1, 2, 3, 4, 5, 6. In the second example it is possible to wash all the plates in one operation, and then move them all to the dryer.This is not possible in the third example, because it is not permitted to move more than one plate at the same time. It is possible to wash plates one by one so that they are placed onto the intermediary stack in the reverse order, and then move plates one by one to the dryer. The final order is correct. | Input6 2 32 3 6 4 1 5 | OutputYES81 21 12 11 21 12 12 12 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*3300'] |
E. Tanya is 5!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya is now five so all her friends gathered together to celebrate her birthday. There are n children on the celebration, including Tanya.The celebration is close to its end, and the last planned attraction is gaming machines. There are m machines in the hall, they are numbered 1 through m. Each of the children has a list of machines he wants to play on. Moreover, for each of the machines he knows the exact time he wants to play on it. For every machine, no more than one child can play on this machine at the same time.It is evening already, so every adult wants to go home. To speed up the process, you can additionally rent second copies of each of the machines. To rent the second copy of the j-th machine, you have to pay pj burles. After you rent a machine, you can use it for as long as you want.How long it will take to make every child play according to his plan, if you have a budget of b burles for renting additional machines? There is only one copy of each machine, so it's impossible to rent a third machine of the same type.The children can interrupt the game in any moment and continue it later. If the i-th child wants to play on the j-th machine, it is allowed after you rent the copy of the j-th machine that this child would play some part of the time on the j-th machine and some part of the time on its copy (each of these parts could be empty). The interruptions and changes take no time and can be performed in any integer moment of time. Of course, a child can't play on more than one machine at the same time.Remember, that it is not needed to save money (no one saves money at the expense of children happiness!), it is needed to minimize the latest moment of time some child ends his game.InputThe first line contains three integers n, m and b (1 ≤ n ≤ 40, 1 ≤ m ≤ 10, 0 ≤ b ≤ 106) — the number of children, the number of gaming machines and the budget for renting additional machines.The second line contains m integers p1, p2, ..., pm (1 ≤ pj ≤ 106), where pj is the rent price for the second copy of the j-th machine.n lines follow, i-th of them describes the wishes of the i-th child. The line starts with an integer ki (0 ≤ ki ≤ m) — the number of machines, the i-th child wants to play on. Then there are ki pairs in the line, the y-th of them is xiy, tiy. It means that, the i-th child wants to play tiy (1 ≤ tiy ≤ 2500) minutes on the xiy-th (1 ≤ xiy ≤ m) machine. In each of these n lines the values xiy are distinct.OutputIn the first line print the minimum time in which all the children can finish their games.In the second line print a string of length m consisting of zeros and ones. The j-th character is '1', if the copy of j-th machine should be rated, and '0' otherwise.In the third line print integer g (0 ≤ g ≤ 106) — the total number of time segments of continuous playing for all of the children. Then in g lines print the segments as four integers i, j, s, d, meaning that the i-th child was playing on the j-th machine or its copy from the time moment s (s ≥ 0) for d minutes (d ≥ 1). You can print these lines in arbitrary order.If there are multiple answers, print any of them.ExamplesInput2 2 1003 72 1 3 2 12 1 3 2 1Output41081 1 0 12 2 0 11 1 1 12 1 1 12 1 2 11 1 2 11 2 3 12 1 3 1Input3 2 1511 72 2 10 1 51 2 202 1 4 2 3Output2001172 2 0 42 2 4 11 1 5 22 2 5 21 2 7 52 2 7 52 2 12 11 2 12 13 1 13 42 2 13 41 2 13 41 1 17 23 2 17 22 2 17 21 1 19 12 2 19 13 2 19 1 | Input2 2 1003 72 1 3 2 12 1 3 2 1 | Output41081 1 0 12 2 0 11 1 1 12 1 1 12 1 2 11 1 2 11 2 3 12 1 3 1 | 2 seconds | 256 megabytes | ['graph matchings', 'graphs', 'greedy', 'schedules', '*3300'] |
E. Chess Championshiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOstap is preparing to play chess again and this time he is about to prepare. Thus, he was closely monitoring one recent chess tournament. There were m players participating and each pair of players played exactly one game. The victory gives 2 points, draw — 1 points, lose — 0 points.Ostap is lazy, so he never tries to remember the outcome of each game. Instead, he computes the total number of points earned by each of the players (the sum of his points in all games which he took part in), sort these value in non-ascending order and then remembers first n integers in this list.Now the Great Strategist Ostap wonders whether he remembers everything correct. He considers that he is correct if there exists at least one tournament results table such that it will produce the given integers. That means, if we count the sum of points for each player, sort them and take first n elements, the result will coincide with what Ostap remembers. Can you check if such table exists?InputThe first line of the input contains two integers m and n (1 ≤ n ≤ m ≤ 3000) — the number of participants of the tournament and the number of top results Ostap remembers.The second line contains n integers, provided in non-ascending order — the number of points earned by top participants as Ostap remembers them. It's guaranteed that this integers are non-negative and do not exceed 2·m.OutputIf there is no tournament such that Ostap can obtain the given set of integers using the procedure described in the statement, then print "no" in the only line of the output. Otherwise, the first line of the output should contain the word "yes". Next m lines should provide the description of any valid tournament. Each of these lines must contain m characters 'X', 'W', 'D' and 'L'. Character 'X' should always be located on the main diagonal (and only there), that is on the i-th position of the i-th string. Character 'W' on the j-th position of the i-th string means that the i-th player won the game against the j-th. In the same way character 'L' means loose and 'D' means draw.The table you print must be consistent and the points earned by best n participants should match the memory of Ostap. If there are many possible answers, print any of them.ExamplesInput5 58 6 4 2 0OutputyesXWWWWLXWWWLLXWWLLLXWLLLLXInput5 19Outputno | Input5 58 6 4 2 0 | OutputyesXWWWWLXWWWLLXWWLLLXWLLLLX | 2 seconds | 256 megabytes | ['constructive algorithms', 'flows', 'greedy', 'math', '*2900'] |
D. Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOstap Bender is worried that people started to forget that he is the Great Combinator. Now he wants to show them his skills in combinatorics. Now he studies the permutations of length n. He has a list of m valid pairs, pair ai and bi means that he is allowed to place integers bi at position ai.He knows that the number of permutations that use only valid pairs is odd. Now, for each pair he wants to find out, will the number of valid permutations be odd if he removes this pair (and only it) from the list.InputThe first line contains two integers n and m (1 ≤ n ≤ 2000, n ≤ m ≤ min(n2, 500 000)) — the number of elements in the permutation. Then follow m lines, each containing some valid pair (ai, bi) (1 ≤ ai, bi ≤ n). It's guaranteed that no pair occurs in the input twice and that the total number of valid permutations (i.e. using only allowed pairs position-elements) is odd.OutputPrint m lines, one line for each valid pair. The i-th line should contain "YES" if after Ostap removes the i-th pair (and only it) the remaining number of valid permutations is odd. Otherwise, print «NO».ExamplesInput2 31 11 22 2OutputNOYESNOInput3 31 12 23 3OutputNONONOInput3 73 33 11 31 12 21 22 1OutputYESNONONOYESNONO | Input2 31 11 22 2 | OutputNOYESNO | 2 seconds | 256 megabytes | ['math', 'matrices', '*2800'] |
E. Ostap and Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOstap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.InputThe first line of the input contains two integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ min(20, n - 1)) — the number of vertices in Ostap's tree and the maximum allowed distance to the nearest black vertex. Don't miss the unusual constraint for k.Each of the next n - 1 lines contain two integers ui and vi (1 ≤ ui, vi ≤ n) — indices of vertices, connected by the i-th edge. It's guaranteed that given graph is a tree.OutputPrint one integer — the remainder of division of the number of ways to paint the tree by 1 000 000 007 (109 + 7).ExamplesInput2 01 2Output1Input2 11 2Output3Input4 11 22 33 4Output9Input7 21 22 31 44 51 66 7Output91NoteIn the first sample, Ostap has to paint both vertices black.In the second sample, it is enough to paint only one of two vertices, thus the answer is 3: Ostap can paint only vertex 1, only vertex 2, vertices 1 and 2 both.In the third sample, the valid ways to paint vertices are: {1, 3}, {1, 4}, {2, 3}, {2, 4}, {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, {1, 2, 3, 4}. | Input2 01 2 | Output1 | 2 seconds | 256 megabytes | ['dp', 'trees', '*2500'] |
D. Taxestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he needs to pay 5 and if n = 2 he pays only 1 burle.As mr. Funt is a very opportunistic person he wants to cheat a bit. In particular, he wants to split the initial n in several parts n1 + n2 + ... + nk = n (here k is arbitrary, even k = 1 is allowed) and pay the taxes for each part separately. He can't make some part equal to 1 because it will reveal him. So, the condition ni ≥ 2 should hold for all i from 1 to k.Ostap Bender wonders, how many money Funt has to pay (i.e. minimal) if he chooses and optimal way to split n in parts.InputThe first line of the input contains a single integer n (2 ≤ n ≤ 2·109) — the total year income of mr. Funt.OutputPrint one integer — minimum possible number of burles that mr. Funt has to pay as a tax.ExamplesInput4Output2Input27Output3 | Input4 | Output2 | 2 seconds | 256 megabytes | ['math', 'number theory', '*1600'] |
C. Tennis Championshiptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFamous Brazil city Rio de Janeiro holds a tennis tournament and Ostap Bender doesn't want to miss this event. There will be n players participating, and the tournament will follow knockout rules from the very first game. That means, that if someone loses a game he leaves the tournament immediately.Organizers are still arranging tournament grid (i.e. the order games will happen and who is going to play with whom) but they have already fixed one rule: two players can play against each other only if the number of games one of them has already played differs by no more than one from the number of games the other one has already played. Of course, both players had to win all their games in order to continue participating in the tournament.Tournament hasn't started yet so the audience is a bit bored. Ostap decided to find out what is the maximum number of games the winner of the tournament can take part in (assuming the rule above is used). However, it is unlikely he can deal with this problem without your help.InputThe only line of the input contains a single integer n (2 ≤ n ≤ 1018) — the number of players to participate in the tournament.OutputPrint the maximum number of games in which the winner of the tournament can take part.ExamplesInput2Output1Input3Output2Input4Output2Input10Output4NoteIn all samples we consider that player number 1 is the winner.In the first sample, there would be only one game so the answer is 1.In the second sample, player 1 can consequently beat players 2 and 3. In the third sample, player 1 can't play with each other player as after he plays with players 2 and 3 he can't play against player 4, as he has 0 games played, while player 1 already played 2. Thus, the answer is 2 and to achieve we make pairs (1, 2) and (3, 4) and then clash the winners. | Input2 | Output1 | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'greedy', 'math', '*1600'] |
B. Urbanizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLocal authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.InputThe first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.OutputPrint one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. 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 .ExamplesInput2 1 11 5Output6.00000000Input4 2 11 4 2 3Output6.50000000NoteIn the first sample, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5 | Input2 1 11 5 | Output6.00000000 | 2 seconds | 256 megabytes | ['greedy', 'number theory', 'sortings', '*1100'] |
A. Ostap and Grasshoppertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the way to Rio de Janeiro Ostap kills time playing with a grasshopper he took with him in a special box. Ostap builds a line of length n such that some cells of this line are empty and some contain obstacles. Then, he places his grasshopper to one of the empty cells and a small insect in another empty cell. The grasshopper wants to eat the insect.Ostap knows that grasshopper is able to jump to any empty cell that is exactly k cells away from the current (to the left or to the right). Note that it doesn't matter whether intermediate cells are empty or not as the grasshopper makes a jump over them. For example, if k = 1 the grasshopper can jump to a neighboring cell only, and if k = 2 the grasshopper can jump over a single cell.Your goal is to determine whether there is a sequence of jumps such that grasshopper will get from his initial position to the cell with an insect.InputThe first line of the input contains two integers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1) — the number of cells in the line and the length of one grasshopper's jump.The second line contains a string of length n consisting of characters '.', '#', 'G' and 'T'. Character '.' means that the corresponding cell is empty, character '#' means that the corresponding cell contains an obstacle and grasshopper can't jump there. Character 'G' means that the grasshopper starts at this position and, finally, 'T' means that the target insect is located at this cell. It's guaranteed that characters 'G' and 'T' appear in this line exactly once.OutputIf there exists a sequence of jumps (each jump of length k), such that the grasshopper can get from his initial position to the cell with the insect, print "YES" (without quotes) in the only line of the input. Otherwise, print "NO" (without quotes).ExamplesInput5 2#G#T#OutputYESInput6 1T....GOutputYESInput7 3T..#..GOutputNOInput6 2..GT..OutputNONoteIn the first sample, the grasshopper can make one jump to the right in order to get from cell 2 to cell 4.In the second sample, the grasshopper is only able to jump to neighboring cells but the way to the insect is free — he can get there by jumping left 5 times.In the third sample, the grasshopper can't make a single jump.In the fourth sample, the grasshopper can only jump to the cells with odd indices, thus he won't be able to reach the insect. | Input5 2#G#T# | OutputYES | 2 seconds | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Anton and Schooltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton goes to school, his favorite lessons are arraystudying. He usually solves all the tasks pretty fast, but this time the teacher gave him a complicated one: given two arrays b and c of length n, find array a, such that:where a and b means bitwise AND, while a or b means bitwise OR.Usually Anton is good in arraystudying, but this problem is too hard, so Anton asks you to help.InputThe first line of the input contains a single integers n (1 ≤ n ≤ 200 000) — the size of arrays b and c.The second line contains n integers bi (0 ≤ bi ≤ 109) — elements of the array b.Third line contains n integers ci (0 ≤ ci ≤ 109) — elements of the array c.OutputIf there is no solution, print - 1.Otherwise, the only line of the output should contain n non-negative integers ai — elements of the array a. If there are multiple possible solutions, you may print any of them.ExamplesInput46 8 4 416 22 10 10Output3 5 1 1 Input58 25 14 7 1619 6 9 4 25Output-1 | Input46 8 4 416 22 10 10 | Output3 5 1 1 | 2 seconds | 256 megabytes | ['bitmasks', 'constructive algorithms', 'implementation', 'math', '*2500'] |
E. Anton and Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree and apply operation paint(3) to get the following: Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree.The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black.Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.OutputPrint one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.ExamplesInput110 0 0 1 1 0 1 0 0 1 11 21 32 42 55 65 73 83 93 109 11Output2Input40 0 0 01 22 33 4Output0NoteIn the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0. | Input110 0 0 1 1 0 1 0 0 1 11 21 32 42 55 65 73 83 93 109 11 | Output2 | 3 seconds | 256 megabytes | ['dfs and similar', 'dp', 'trees', '*2100'] |
D. Anton and Chesstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead.The first task he faced is to check whether the king is in check. Anton doesn't know how to implement this so he asks you to help.Consider that an infinite chess board contains one white king and the number of black pieces. There are only rooks, bishops and queens, as the other pieces are not supported yet. The white king is said to be in check if at least one black piece can reach the cell with the king in one move. Help Anton and write the program that for the given position determines whether the white king is in check.Remainder, on how do chess pieces move: Bishop moves any number of cells diagonally, but it can't "leap" over the occupied cells. Rook moves any number of cells horizontally or vertically, but it also can't "leap" over the occupied cells. Queen is able to move any number of cells horizontally, vertically or diagonally, but it also can't "leap". InputThe first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of black pieces.The second line contains two integers x0 and y0 ( - 109 ≤ x0, y0 ≤ 109) — coordinates of the white king.Then follow n lines, each of them contains a character and two integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — type of the i-th piece and its position. Character 'B' stands for the bishop, 'R' for the rook and 'Q' for the queen. It's guaranteed that no two pieces occupy the same position.OutputThe only line of the output should contains "YES" (without quotes) if the white king is in check and "NO" (without quotes) otherwise.ExamplesInput24 2R 1 1B 1 5OutputYESInput24 2R 3 3B 1 5OutputNONotePicture for the first sample: White king is in check, because the black bishop can reach the cell with the white king in one move. The answer is "YES".Picture for the second sample: Here bishop can't reach the cell with the white king, because his path is blocked by the rook, and the bishop cant "leap" over it. Rook can't reach the white king, because it can't move diagonally. Hence, the king is not in check and the answer is "NO". | Input24 2R 1 1B 1 5 | OutputYES | 4 seconds | 256 megabytes | ['implementation', '*1700'] |
C. Anton and Making Potionstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions. Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x. Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.InputThe first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·109, 1 ≤ m, k ≤ 2·105) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type.The second line of the input contains two integers x and s (2 ≤ x ≤ 2·109, 1 ≤ s ≤ 2·109) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use.The third line contains m integers ai (1 ≤ ai < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used.The fourth line contains m integers bi (1 ≤ bi ≤ 2·109) — the number of manapoints to use the i-th spell of the first type.There are k integers ci (1 ≤ ci ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci ≤ cj if i < j.The sixth line contains k integers di (1 ≤ di ≤ 2·109) — the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di ≤ dj if i < j.OutputPrint one integer — the minimum time one has to spent in order to prepare n potions.ExamplesInput20 3 210 992 4 320 10 404 1510 80Output20Input20 3 210 992 4 3200 100 4004 15100 800Output200NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20·10 = 200. | Input20 3 210 992 4 320 10 404 1510 80 | Output20 | 4 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', 'two pointers', '*1600'] |
B. Anton and Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Anton found a box with digits in his room. There are k2 digits 2, k3 digits 3, k5 digits 5 and k6 digits 6.Anton's favorite integers are 32 and 256. He decided to compose this integers from digits he has. He wants to make the sum of these integers as large as possible. Help him solve this task!Each digit can be used no more than once, i.e. the composed integers should contain no more than k2 digits 2, k3 digits 3 and so on. Of course, unused digits are not counted in the sum.InputThe only line of the input contains four integers k2, k3, k5 and k6 — the number of digits 2, 3, 5 and 6 respectively (0 ≤ k2, k3, k5, k6 ≤ 5·106).OutputPrint one integer — maximum possible sum of Anton's favorite integers that can be composed using digits from the box.ExamplesInput5 1 3 4Output800Input1 1 1 1Output256NoteIn the first sample, there are five digits 2, one digit 3, three digits 5 and four digits 6. Anton can compose three integers 256 and one integer 32 to achieve the value 256 + 256 + 256 + 32 = 800. Note, that there is one unused integer 2 and one unused integer 6. They are not counted in the answer.In the second sample, the optimal answer is to create on integer 256, thus the answer is 256. | Input5 1 3 4 | Output800 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*800'] |
A. Anton and Daniktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played.The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.OutputIf Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output.If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output.If Anton and Danik won the same number of games, print "Friendship" (without quotes).ExamplesInput6ADAAAAOutputAntonInput7DDDAADAOutputDanikInput6DADADAOutputFriendshipNoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship". | Input6ADAAAA | OutputAnton | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Drivers Dissatisfactiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn one kingdom there are n cities and m two-way roads. Each road connects a pair of cities, and for each road we know the level of drivers dissatisfaction — the value wi.For each road we know the value ci — how many lamziks we should spend to reduce the level of dissatisfaction with this road by one. Thus, to reduce the dissatisfaction with the i-th road by k, we should spend k·ci lamziks. And it is allowed for the dissatisfaction to become zero or even negative.In accordance with the king's order, we need to choose n - 1 roads and make them the main roads. An important condition must hold: it should be possible to travel from any city to any other by the main roads.The road ministry has a budget of S lamziks for the reform. The ministry is going to spend this budget for repair of some roads (to reduce the dissatisfaction with them), and then to choose the n - 1 main roads.Help to spend the budget in such a way and then to choose the main roads so that the total dissatisfaction with the main roads will be as small as possible. The dissatisfaction with some roads can become negative. It is not necessary to spend whole budget S.It is guaranteed that it is possible to travel from any city to any other using existing roads. Each road in the kingdom is a two-way road.InputThe first line contains two integers n and m (2 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of cities and the number of roads in the kingdom, respectively.The second line contains m integers w1, w2, ..., wm (1 ≤ wi ≤ 109), where wi is the drivers dissatisfaction with the i-th road.The third line contains m integers c1, c2, ..., cm (1 ≤ ci ≤ 109), where ci is the cost (in lamziks) of reducing the dissatisfaction with the i-th road by one.The next m lines contain the description of the roads. The i-th of this lines contain a pair of integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) which mean that the i-th road connects cities ai and bi. All roads are two-way oriented so it is possible to move by the i-th road from ai to bi, and vice versa. It is allowed that a pair of cities is connected by more than one road. The last line contains one integer S (0 ≤ S ≤ 109) — the number of lamziks which we can spend for reforms. OutputIn the first line print K — the minimum possible total dissatisfaction with main roads.In each of the next n - 1 lines print two integers x, vx, which mean that the road x is among main roads and the road x, after the reform, has the level of dissatisfaction vx.Consider that roads are numbered from 1 to m in the order as they are given in the input data. The edges can be printed in arbitrary order. If there are several answers, print any of them. ExamplesInput6 91 3 1 1 3 1 2 2 24 1 4 2 2 5 3 1 61 21 32 32 42 53 53 64 55 67Output01 13 16 17 28 -5Input3 39 5 17 7 22 13 13 22Output53 02 5 | Input6 91 3 1 1 3 1 2 2 24 1 4 2 2 5 3 1 61 21 32 32 42 53 53 64 55 67 | Output01 13 16 17 28 -5 | 4 seconds | 256 megabytes | ['data structures', 'dsu', 'graphs', 'trees', '*2200'] |
E. Sleep in Classtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe academic year has just begun, but lessons and olympiads have already occupied all the free time. It is not a surprise that today Olga fell asleep on the Literature. She had a dream in which she was on a stairs. The stairs consists of n steps. The steps are numbered from bottom to top, it means that the lowest step has number 1, and the highest step has number n. Above each of them there is a pointer with the direction (up or down) Olga should move from this step. As soon as Olga goes to the next step, the direction of the pointer (above the step she leaves) changes. It means that the direction "up" changes to "down", the direction "down" — to the direction "up".Olga always moves to the next step in the direction which is shown on the pointer above the step. If Olga moves beyond the stairs, she will fall and wake up. Moving beyond the stairs is a moving down from the first step or moving up from the last one (it means the n-th) step. In one second Olga moves one step up or down according to the direction of the pointer which is located above the step on which Olga had been at the beginning of the second. For each step find the duration of the dream if Olga was at this step at the beginning of the dream.Olga's fall also takes one second, so if she was on the first step and went down, she would wake up in the next second.InputThe first line contains single integer n (1 ≤ n ≤ 106) — the number of steps on the stairs.The second line contains a string s with the length n — it denotes the initial direction of pointers on the stairs. The i-th character of string s denotes the direction of the pointer above i-th step, and is either 'U' (it means that this pointer is directed up), or 'D' (it means this pointed is directed down).The pointers are given in order from bottom to top.OutputPrint n numbers, the i-th of which is equal either to the duration of Olga's dream or to - 1 if Olga never goes beyond the stairs, if in the beginning of sleep she was on the i-th step.ExamplesInput3UUDOutput5 6 3 Input10UUDUDUUDDUOutput5 12 23 34 36 27 18 11 6 1 | Input3UUD | Output5 6 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'data structures', 'math', 'two pointers', '*2400'] |
D. Kostya the Sculptortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere. Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are ai, bi and ci. He can take no more than two stones and present them to Kostya. If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way. Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.InputThe first line contains the integer n (1 ≤ n ≤ 105).n lines follow, in the i-th of which there are three integers ai, bi and ci (1 ≤ ai, bi, ci ≤ 109) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.OutputIn the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data.You can print the stones in arbitrary order. If there are several answers print any of them. ExamplesInput65 5 53 2 41 4 12 1 33 2 43 3 4Output11Input710 7 85 10 34 2 65 5 510 2 84 2 17 7 7Output21 5NoteIn the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5 Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5 It is most profitable to take only the first stone. | Input65 5 53 2 41 4 12 1 33 2 43 3 4 | Output11 | 3 seconds | 256 megabytes | ['data structures', 'hashing', '*1600'] |
C. Epidemic in Monstropolistime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere was an epidemic in Monstropolis and all monsters became sick. To recover, all monsters lined up in queue for an appointment to the only doctor in the city.Soon, monsters became hungry and began to eat each other. One monster can eat other monster if its weight is strictly greater than the weight of the monster being eaten, and they stand in the queue next to each other. Monsters eat each other instantly. There are no monsters which are being eaten at the same moment. After the monster A eats the monster B, the weight of the monster A increases by the weight of the eaten monster B. In result of such eating the length of the queue decreases by one, all monsters after the eaten one step forward so that there is no empty places in the queue again. A monster can eat several monsters one after another. Initially there were n monsters in the queue, the i-th of which had weight ai.For example, if weights are [1, 2, 2, 2, 1, 2] (in order of queue, monsters are numbered from 1 to 6 from left to right) then some of the options are: the first monster can't eat the second monster because a1 = 1 is not greater than a2 = 2; the second monster can't eat the third monster because a2 = 2 is not greater than a3 = 2; the second monster can't eat the fifth monster because they are not neighbors; the second monster can eat the first monster, the queue will be transformed to [3, 2, 2, 1, 2]. After some time, someone said a good joke and all monsters recovered. At that moment there were k (k ≤ n) monsters in the queue, the j-th of which had weight bj. Both sequences (a and b) contain the weights of the monsters in the order from the first to the last.You are required to provide one of the possible orders of eating monsters which led to the current queue, or to determine that this could not happen. Assume that the doctor didn't make any appointments while monsters were eating each other.InputThe first line contains single integer n (1 ≤ n ≤ 500) — the number of monsters in the initial queue.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial weights of the monsters.The third line contains single integer k (1 ≤ k ≤ n) — the number of monsters in the queue after the joke. The fourth line contains k integers b1, b2, ..., bk (1 ≤ bj ≤ 5·108) — the weights of the monsters after the joke. Monsters are listed in the order from the beginning of the queue to the end.OutputIn case if no actions could lead to the final queue, print "NO" (without quotes) in the only line. Otherwise print "YES" (without quotes) in the first line. In the next n - k lines print actions in the chronological order. In each line print x — the index number of the monster in the current queue which eats and, separated by space, the symbol 'L' if the monster which stays the x-th in the queue eats the monster in front of him, or 'R' if the monster which stays the x-th in the queue eats the monster behind him. After each eating the queue is enumerated again. When one monster eats another the queue decreases. If there are several answers, print any of them.ExamplesInput61 2 2 2 1 225 5OutputYES2 L1 R4 L3 LInput51 2 3 4 5115OutputYES5 L4 L3 L2 LInput51 1 1 3 332 1 6OutputNONoteIn the first example, initially there were n = 6 monsters, their weights are [1, 2, 2, 2, 1, 2] (in order of queue from the first monster to the last monster). The final queue should be [5, 5]. The following sequence of eatings leads to the final queue: the second monster eats the monster to the left (i.e. the first monster), queue becomes [3, 2, 2, 1, 2]; the first monster (note, it was the second on the previous step) eats the monster to the right (i.e. the second monster), queue becomes [5, 2, 1, 2]; the fourth monster eats the mosnter to the left (i.e. the third monster), queue becomes [5, 2, 3]; the finally, the third monster eats the monster to the left (i.e. the second monster), queue becomes [5, 5]. Note that for each step the output contains numbers of the monsters in their current order in the queue. | Input61 2 2 2 1 225 5 | OutputYES2 L1 R4 L3 L | 1 second | 256 megabytes | ['constructive algorithms', 'dp', 'greedy', 'two pointers', '*1800'] |
B. Paradetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVery soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.InputThe first line contains single integer n (1 ≤ n ≤ 105) — the number of columns. The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.OutputPrint single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached.Consider that columns are numbered from 1 to n in the order they are given in the input data.If there are several answers, print any of them.ExamplesInput35 68 910 3Output3Input26 55 6Output1Input65 91 34 84 523 5412 32Output0NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9. | Input35 68 910 3 | Output3 | 1 second | 256 megabytes | ['math', '*1100'] |
A. Grasshopper And the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, the Grasshopper was jumping on the lawn and found a piece of paper with a string. Grasshopper became interested what is the minimum jump ability he should have in order to be able to reach the far end of the string, jumping only on vowels of the English alphabet. Jump ability is the maximum possible length of his jump. Formally, consider that at the begginning the Grasshopper is located directly in front of the leftmost character of the string. His goal is to reach the position right after the rightmost character of the string. In one jump the Grasshopper could jump to the right any distance from 1 to the value of his jump ability. The picture corresponds to the first example. The following letters are vowels: 'A', 'E', 'I', 'O', 'U' and 'Y'.InputThe first line contains non-empty string consisting of capital English letters. It is guaranteed that the length of the string does not exceed 100. OutputPrint single integer a — the minimum jump ability of the Grasshopper (in the number of symbols) that is needed to overcome the given string, jumping only on vowels.ExamplesInputABABBBACFEYUKOTTOutput4InputAAAOutput1 | InputABABBBACFEYUKOTT | Output4 | 1 second | 256 megabytes | ['implementation', '*1000'] |
F. Tourist Reformtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland is a tourist country! At least, it can become such — the government of Berland is confident about this. There are n cities in Berland, some pairs of which are connected by two-ways roads. Each road connects two different cities. In Berland there are no roads which connect the same pair of cities. It is possible to get from any city to any other city using given two-ways roads. According to the reform each road will become one-way. It will be oriented to one of two directions.To maximize the tourist attraction of Berland, after the reform for each city i the value ri will be calculated. It will equal to the number of cities x for which there is an oriented path from the city i to the city x. In other words, ri will equal the number of cities which can be reached from the city i by roads. The government is sure that tourist's attention will be focused on the minimum value of ri.Help the government of Berland make the reform to maximize the minimum of ri.InputThe first line contains two integers n, m (2 ≤ n ≤ 400 000, 1 ≤ m ≤ 400 000) — the number of cities and the number of roads. The next m lines describe roads in Berland: the j-th of them contains two integers uj and vj (1 ≤ uj, vj ≤ n, uj ≠ vj), where uj and vj are the numbers of cities which are connected by the j-th road.The cities are numbered from 1 to n. It is guaranteed that it is possible to get from any city to any other by following two-ways roads. In Berland there are no roads which connect the same pair of cities. OutputIn the first line print single integer — the maximum possible value min1 ≤ i ≤ n{ri} after the orientation of roads. The next m lines must contain the description of roads after the orientation: the j-th of them must contain two integers uj, vj, it means that the j-th road will be directed from the city uj to the city vj. Print roads in the same order as they are given in the input data. ExampleInput7 94 32 67 14 17 33 57 46 52 5Output44 36 27 11 43 75 37 45 62 5 | Input7 94 32 67 14 17 33 57 46 52 5 | Output44 36 27 11 43 75 37 45 62 5 | 4 seconds | 256 megabytes | ['dfs and similar', 'graphs', '*2300'] |
E. Socketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe ICM ACPC World Finals is coming! Unfortunately, the organizers of the competition were so busy preparing tasks that totally missed an important technical point — the organization of electricity supplement for all the participants workstations.There are n computers for participants, the i-th of which has power equal to positive integer pi. At the same time there are m sockets available, the j-th of which has power euqal to positive integer sj. It is possible to connect the i-th computer to the j-th socket if and only if their powers are the same: pi = sj. It is allowed to connect no more than one computer to one socket. Thus, if the powers of all computers and sockets are distinct, then no computer can be connected to any of the sockets. In order to fix the situation professor Puch Williams urgently ordered a wagon of adapters — power splitters. Each adapter has one plug and one socket with a voltage divider between them. After plugging an adapter to a socket with power x, the power on the adapter's socket becomes equal to , it means that it is equal to the socket's power divided by two with rounding up, for example and .Each adapter can be used only once. It is possible to connect several adapters in a chain plugging the first to a socket. For example, if two adapters are plugged one after enother to a socket with power 10, it becomes possible to connect one computer with power 3 to this socket.The organizers should install adapters so that it will be possible to supply with electricity the maximum number of computers c at the same time. If there are several possible connection configurations, they want to find the one that uses the minimum number of adapters u to connect c computers.Help organizers calculate the maximum number of connected computers c and the minimum number of adapters u needed for this.The wagon of adapters contains enough of them to do the task. It is guaranteed that it's possible to connect at least one computer.InputThe first line contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of computers and the number of sockets.The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 109) — the powers of the computers. The third line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 109) — the power of the sockets. OutputIn the first line print two numbers c and u — the maximum number of computers which can at the same time be connected to electricity and the minimum number of adapters needed to connect c computers.In the second line print m integers a1, a2, ..., am (0 ≤ ai ≤ 109), where ai equals the number of adapters orginizers need to plug into the i-th socket. The sum of all ai should be equal to u.In third line print n integers b1, b2, ..., bn (0 ≤ bi ≤ m), where the bj-th equals the number of the socket which the j-th computer should be connected to. bj = 0 means that the j-th computer should not be connected to any socket. All bj that are different from 0 should be distinct. The power of the j-th computer should be equal to the power of the socket bj after plugging in abj adapters. The number of non-zero bj should be equal to c.If there are multiple answers, print any of them.ExamplesInput2 21 12 2Output2 21 11 2Input2 12 10099Output1 661 0 | Input2 21 12 2 | Output2 21 11 2 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*2100'] |
D. Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number ai — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during ai days for the exam number i. He can mix the order of preparation for exams in any way.Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time. InputThe first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of days in the exam period and the number of subjects. The second line contains n integers d1, d2, ..., dn (0 ≤ di ≤ m), where di is the number of subject, the exam of which can be passed on the day number i. If di equals 0, it is not allowed to pass any exams on the day number i. The third line contains m positive integers a1, a2, ..., am (1 ≤ ai ≤ 105), where ai is the number of days that are needed to prepare before passing the exam on the subject i.OutputPrint one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.ExamplesInput7 20 1 0 2 1 0 22 1Output5Input10 30 0 1 2 3 0 2 0 1 21 1 4Output9Input5 11 1 1 1 15Output-1NoteIn the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it. | Input7 20 1 0 2 1 0 22 1 | Output5 | 1 second | 256 megabytes | ['binary search', 'greedy', 'sortings', '*1700'] |
C. Sanatoriumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasiliy spent his vacation in a sanatorium, came back and found that he completely forgot details of his vacation! Every day there was a breakfast, a dinner and a supper in a dining room of the sanatorium (of course, in this order). The only thing that Vasiliy has now is a card from the dining room contaning notes how many times he had a breakfast, a dinner and a supper (thus, the card contains three integers). Vasiliy could sometimes have missed some meal, for example, he could have had a breakfast and a supper, but a dinner, or, probably, at some days he haven't been at the dining room at all.Vasiliy doesn't remember what was the time of the day when he arrived to sanatorium (before breakfast, before dinner, before supper or after supper), and the time when he left it (before breakfast, before dinner, before supper or after supper). So he considers any of these options. After Vasiliy arrived to the sanatorium, he was there all the time until he left. Please note, that it's possible that Vasiliy left the sanatorium on the same day he arrived.According to the notes in the card, help Vasiliy determine the minimum number of meals in the dining room that he could have missed. We shouldn't count as missed meals on the arrival day before Vasiliy's arrival and meals on the departure day after he left.InputThe only line contains three integers b, d and s (0 ≤ b, d, s ≤ 1018, b + d + s ≥ 1) — the number of breakfasts, dinners and suppers which Vasiliy had during his vacation in the sanatorium. OutputPrint single integer — the minimum possible number of meals which Vasiliy could have missed during his vacation. ExamplesInput3 2 1Output1Input1 0 0Output0Input1 1 1Output0Input1000000000000000000 0 1000000000000000000Output999999999999999999NoteIn the first sample, Vasiliy could have missed one supper, for example, in case he have arrived before breakfast, have been in the sanatorium for two days (including the day of arrival) and then have left after breakfast on the third day. In the second sample, Vasiliy could have arrived before breakfast, have had it, and immediately have left the sanatorium, not missing any meal.In the third sample, Vasiliy could have been in the sanatorium for one day, not missing any meal. | Input3 2 1 | Output1 | 1 second | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'implementation', 'math', '*1200'] |
B. Cormen — The Best Friend Of a Mantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.InputThe first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days. The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned. OutputIn the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days. In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them. ExamplesInput3 52 0 1Output42 3 2Input3 10 0 0Output10 1 0Input4 62 4 3 5Output02 4 3 5 | Input3 52 0 1 | Output42 3 2 | 1 second | 256 megabytes | ['dp', 'greedy', '*1000'] |
A. Buy a Shoveltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ≤ 9).What is the minimum number of shovels Polycarp has to buy so that he can pay for the purchase without any change? It is obvious that he can pay for 10 shovels without any change (by paying the requied amount of 10-burle coins and not using the coin of r burles). But perhaps he can buy fewer shovels and pay without any change. Note that Polycarp should buy at least one shovel.InputThe single line of input contains two integers k and r (1 ≤ k ≤ 1000, 1 ≤ r ≤ 9) — the price of one shovel and the denomination of the coin in Polycarp's pocket that is different from "10-burle coins". Remember that he has an unlimited number of coins in the denomination of 10, that is, Polycarp has enough money to buy any number of shovels.OutputPrint the required minimum number of shovels Polycarp has to buy so that he can pay for them without any change. ExamplesInput117 3Output9Input237 7Output1Input15 2Output2NoteIn the first example Polycarp can buy 9 shovels and pay 9·117 = 1053 burles. Indeed, he can pay this sum by using 10-burle coins and one 3-burle coin. He can't buy fewer shovels without any change.In the second example it is enough for Polycarp to buy one shovel.In the third example Polycarp should buy two shovels and pay 2·15 = 30 burles. It is obvious that he can pay this sum without any change. | Input117 3 | Output9 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'math', '*800'] |
F. Video Cardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.There are n video cards in the shop, the power of the i-th video card is equal to integer value ai. As Vlad wants to be sure the new game will work he wants to buy not one, but several video cards and unite their powers using the cutting-edge technology. To use this technology one of the cards is chosen as the leading one and other video cards are attached to it as secondary. For this new technology to work it's required that the power of each of the secondary video cards is divisible by the power of the leading video card. In order to achieve that the power of any secondary video card can be reduced to any integer value less or equal than the current power. However, the power of the leading video card should remain unchanged, i.e. it can't be reduced.Vlad has an infinite amount of money so he can buy any set of video cards. Help him determine which video cards he should buy such that after picking the leading video card and may be reducing some powers of others to make them work together he will get the maximum total value of video power.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of video cards in the shop.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 200 000) — powers of video cards.OutputThe only line of the output should contain one integer value — the maximum possible total power of video cards working together.ExamplesInput43 2 15 9Output27Input48 2 2 7Output18NoteIn the first sample, it would be optimal to buy video cards with powers 3, 15 and 9. The video card with power 3 should be chosen as the leading one and all other video cards will be compatible with it. Thus, the total power would be 3 + 15 + 9 = 27. If he buys all the video cards and pick the one with the power 2 as the leading, the powers of all other video cards should be reduced by 1, thus the total power would be 2 + 2 + 14 + 8 = 26, that is less than 27. Please note, that it's not allowed to reduce the power of the leading video card, i.e. one can't get the total power 3 + 1 + 15 + 9 = 28.In the second sample, the optimal answer is to buy all video cards and pick the one with the power 2 as the leading. The video card with the power 7 needs it power to be reduced down to 6. The total power would be 8 + 2 + 2 + 6 = 18. | Input43 2 15 9 | Output27 | 1 second | 256 megabytes | ['brute force', 'data structures', 'implementation', 'math', 'number theory', '*1900'] |
E. Funny Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. InputThe first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall.The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right.OutputPrint one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally.ExamplesInput32 4 8Output14Input41 -7 -2 3Output-3NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Input32 4 8 | Output14 | 1 second | 256 megabytes | ['dp', 'games', '*2200'] |
D. 80-th Level Archeologytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArcheologists have found a secret pass in the dungeon of one of the pyramids of Cycleland. To enter the treasury they have to open an unusual lock on the door. The lock consists of n words, each consisting of some hieroglyphs. The wall near the lock has a round switch. Each rotation of this switch changes the hieroglyphs according to some rules. The instruction nearby says that the door will open only if words written on the lock would be sorted in lexicographical order (the definition of lexicographical comparison in given in notes section).The rule that changes hieroglyphs is the following. One clockwise rotation of the round switch replaces each hieroglyph with the next hieroglyph in alphabet, i.e. hieroglyph x (1 ≤ x ≤ c - 1) is replaced with hieroglyph (x + 1), and hieroglyph c is replaced with hieroglyph 1.Help archeologist determine, how many clockwise rotations they should perform in order to open the door, or determine that this is impossible, i.e. no cyclic shift of the alphabet will make the sequence of words sorted lexicographically.InputThe first line of the input contains two integers n and c (2 ≤ n ≤ 500 000, 1 ≤ c ≤ 106) — the number of words, written on the lock, and the number of different hieroglyphs.Each of the following n lines contains the description of one word. The i-th of these lines starts with integer li (1 ≤ li ≤ 500 000), that denotes the length of the i-th word, followed by li integers wi, 1, wi, 2, ..., wi, li (1 ≤ wi, j ≤ c) — the indices of hieroglyphs that make up the i-th word. Hieroglyph with index 1 is the smallest in the alphabet and with index c — the biggest.It's guaranteed, that the total length of all words doesn't exceed 106.OutputIf it is possible to open the door by rotating the round switch, print integer x (0 ≤ x ≤ c - 1) that defines the required number of clockwise rotations. If there are several valid x, print any of them.If it is impossible to open the door by this method, print - 1.ExamplesInput4 32 3 21 13 2 3 14 2 3 1 2Output1Input2 52 4 22 4 2Output0Input4 41 21 31 41 2Output-1NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold: at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character in the first position where they differ; if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.In the first sample, after the round switch is rotated 1 position clockwise the words look as follows:1 323 1 23 1 2 3In the second sample, words are already sorted in lexicographical order.In the last sample, one can check that no shift of the alphabet will work. | Input4 32 3 21 13 2 3 14 2 3 1 2 | Output1 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'greedy', 'sortings', '*2200'] |
C. Sockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clothes to wear on each of the days she will be absent. Arseniy's family is a bit weird so all the clothes is enumerated. For example, each of Arseniy's n socks is assigned a unique integer from 1 to n. Thus, the only thing his mother had to do was to write down two integers li and ri for each of the days — the indices of socks to wear on the day i (obviously, li stands for the left foot and ri for the right). Each sock is painted in one of k colors.When mother already left Arseniy noticed that according to instruction he would wear the socks of different colors on some days. Of course, that is a terrible mistake cause by a rush. Arseniy is a smart boy, and, by some magical coincidence, he posses k jars with the paint — one for each of k colors.Arseniy wants to repaint some of the socks in such a way, that for each of m days he can follow the mother's instructions and wear the socks of the same color. As he is going to be very busy these days he will have no time to change the colors of any socks so he has to finalize the colors now.The new computer game Bota-3 was just realised and Arseniy can't wait to play it. What is the minimum number of socks that need their color to be changed in order to make it possible to follow mother's instructions and wear the socks of the same color during each of m days.InputThe first line of input contains three integers n, m and k (2 ≤ n ≤ 200 000, 0 ≤ m ≤ 200 000, 1 ≤ k ≤ 200 000) — the number of socks, the number of days and the number of available colors respectively.The second line contain n integers c1, c2, ..., cn (1 ≤ ci ≤ k) — current colors of Arseniy's socks.Each of the following m lines contains two integers li and ri (1 ≤ li, ri ≤ n, li ≠ ri) — indices of socks which Arseniy should wear during the i-th day.OutputPrint one integer — the minimum number of socks that should have their colors changed in order to be able to obey the instructions and not make people laugh from watching the socks of different colors.ExamplesInput3 2 31 2 31 22 3Output2Input3 2 21 1 21 22 1Output0NoteIn the first sample, Arseniy can repaint the first and the third socks to the second color.In the second sample, there is no need to change any colors. | Input3 2 31 2 31 22 3 | Output2 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'greedy', '*1600'] |
B. Coupons and Discountstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.InputThe first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions.The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.OutputIf there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).ExamplesInput41 2 1 2OutputYESInput31 0 1OutputNONoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days. | Input41 2 1 2 | OutputYES | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1100'] |
A. Night at the Museumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGrigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture: After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.InputThe only line of input contains the name of some exhibit — the non-empty string consisting of no more than 100 characters. It's guaranteed that the string consists of only lowercase English letters.OutputPrint one integer — the minimum number of rotations of the wheel, required to print the name given in the input.ExamplesInputzeusOutput18InputmapOutput35InputaresOutput34Note To print the string from the first sample it would be optimal to perform the following sequence of rotations: from 'a' to 'z' (1 rotation counterclockwise), from 'z' to 'e' (5 clockwise rotations), from 'e' to 'u' (10 rotations counterclockwise), from 'u' to 's' (2 counterclockwise rotations). In total, 1 + 5 + 10 + 2 = 18 rotations are required. | Inputzeus | Output18 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
L. Expression Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA simplified arithmetic expression (SAE) is an arithmetic expression defined by the following grammar: <SAE> ::= <Number> | <SAE>+<SAE> | <SAE>*<SAE> | (<SAE>) <Number> ::= <Digit> | <Digit><Number> <Digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 In other words it's a correct arithmetic expression that is allowed to contain brackets, numbers (possibly with leading zeros), multiplications and additions. For example expressions "(0+01)", "0" and "1*(0)" are simplified arithmetic expressions, but expressions "2-1", "+1" and "1+2)" are not.Given a string s1s2...s|s| that represents a SAE; si denotes the i-th character of the string which can be either a digit ('0'-'9'), a plus sign ('+'), a multiplication sign ('*'), an opening round bracket '(' or a closing round bracket ')'.A part slsl + 1...sr of this string is called a sub-expression if and only if it is a SAE.You task is to answer m queries, each of which is a pair of integers li, ri (1 ≤ li ≤ ri ≤ |s|). For each query determine whether the corresponding part of the given string is a sub-expression and in case it's a sub-expression calculate its value modulo 1000000007 (109 + 7). The values should be calculated using standard operator priorities.InputThe first line of the input contains non-empty string s (1 ≤ |s| ≤ 4·105) which represents a correct SAE. Each character of the string can be one of the following characters: '*', '+', '(', ')' or a digit ('0'-'9'). The expression might contain extra-huge numbers.The second line contains an integer m (1 ≤ m ≤ 4·105) which is the number of queries. Each of the next m lines contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ |s|) — the i-th query.OutputThe i-th number of output should be the answer for the i-th query. If the i-th query corresponds to a valid sub-expression output the value of the sub-expression modulo 1000000007 (109 + 7). Otherwise output -1 as an answer for the query. Print numbers on separate lines.ExamplesInput((1+2)*3+101*2)68 141 62 1011 145 54 5Output205-11022-1Input(01)11 4Output1 | Input((1+2)*3+101*2)68 141 62 1011 145 54 5 | Output205-11022-1 | 4 seconds | 512 megabytes | ['data structures', '*3200'] |
K. Roads Orientation Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerland consists of n cities and m bidirectional roads connecting pairs of cities. There is no road connecting a city to itself, and between any pair of cities there is no more than one road. It is possible to reach any city from any other moving along roads.Currently Mr. President is in the city s and his destination is the city t. He plans to move along roads from s to t (s ≠ t).That's why Ministry of Fools and Roads has difficult days. The minister is afraid that Mr. President could get into a traffic jam or get lost. Who knows what else can happen!To be sure that everything goes as planned, the minister decided to temporarily make all roads one-way. So each road will be oriented in one of two possible directions. The following conditions must be satisfied: There should be no cycles along roads after orientation. The city s should be the only such city that all its roads are oriented out (i.e. there are no ingoing roads to the city s and the city s is the only such city). The city t should be the only such city that all its roads are oriented in (i.e. there are no outgoing roads from the city t and the city t is the only such city). Help the minister solve his problem. Write a program to find any such orientation of all roads or report that no solution exists.InputEach test in this problem contains one or more test cases to solve. The first line of the input contains positive number T — the number of cases to solve.Each case starts with a line containing four integers n, m, s and t (2 ≤ n ≤ 4·105, 1 ≤ m ≤ 106, 1 ≤ s, t ≤ n, s ≠ t) — the number of cities, the number of roads and indices of departure and destination cities. The cities are numbered from 1 to n.The following m lines contain roads, one road per line. Each road is given as two integer numbers xj, yj (1 ≤ xj, yj ≤ n, xj ≠ yj), which means that the j-th road connects cities xj and yj. There is at most one road between any pair of cities. It is possible to reach any city from any other moving along roads.The sum of values n over all cases in a test doesn't exceed 4·105. The sum of values m over all cases in a test doesn't exceed 106.OutputFor each case print "Yes" if the answer exists. In the following m lines print roads in the required directions. You can print roads in arbitrary order. If there are multiple answers, print any of them.Print the only line "No" if there is no answer for a case.ExampleInput24 4 1 21 22 33 44 13 2 1 33 12 3OutputYes1 23 24 31 4No | Input24 4 1 21 22 33 44 13 2 1 33 12 3 | OutputYes1 23 24 31 4No | 5 seconds | 512 megabytes | ['graphs', '*3200'] |
J. Bottlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputNick has n bottles of soda left after his birthday. Each bottle is described by two values: remaining amount of soda ai and bottle volume bi (ai ≤ bi).Nick has decided to pour all remaining soda into minimal number of bottles, moreover he has to do it as soon as possible. Nick spends x seconds to pour x units of soda from one bottle to another.Nick asks you to help him to determine k — the minimal number of bottles to store all remaining soda and t — the minimal time to pour soda into k bottles. A bottle can't store more soda than its volume. All remaining soda should be saved.InputThe first line contains positive integer n (1 ≤ n ≤ 100) — the number of bottles.The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the amount of soda remaining in the i-th bottle.The third line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the volume of the i-th bottle.It is guaranteed that ai ≤ bi for any i.OutputThe only line should contain two integers k and t, where k is the minimal number of bottles that can store all the soda and t is the minimal time to pour the soda into k bottles.ExamplesInput43 3 4 34 7 6 5Output2 6Input21 1100 100Output1 1Input510 30 5 6 2410 41 7 8 24Output3 11NoteIn the first example Nick can pour soda from the first bottle to the second bottle. It will take 3 seconds. After it the second bottle will contain 3 + 3 = 6 units of soda. Then he can pour soda from the fourth bottle to the second bottle and to the third bottle: one unit to the second and two units to the third. It will take 1 + 2 = 3 seconds. So, all the soda will be in two bottles and he will spend 3 + 3 = 6 seconds to do it. | Input43 3 4 34 7 6 5 | Output2 6 | 2 seconds | 512 megabytes | ['dp', '*1900'] |
I. Olympiad in Programming and Sportstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n students at Berland State University. Every student has two skills, each measured as a number: ai — the programming skill and bi — the sports skill.It is announced that an Olympiad in programming and sports will be held soon. That's why Berland State University should choose two teams: one to take part in the programming track and one to take part in the sports track.There should be exactly p students in the programming team and exactly s students in the sports team. A student can't be a member of both teams.The university management considers that the strength of the university on the Olympiad is equal to the sum of two values: the programming team strength and the sports team strength. The strength of a team is the sum of skills of its members in the corresponding area, so the strength of the programming team is the sum of all ai and the strength of the sports team is the sum of all bi over corresponding team members.Help Berland State University to compose two teams to maximize the total strength of the university on the Olympiad.InputThe first line contains three positive integer numbers n, p and s (2 ≤ n ≤ 3000, p + s ≤ n) — the number of students, the size of the programming team and the size of the sports team.The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 3000), where ai is the programming skill of the i-th student.The third line contains n positive integers b1, b2, ..., bn (1 ≤ bi ≤ 3000), where bi is the sports skill of the i-th student.OutputIn the first line, print the the maximum strength of the university on the Olympiad. In the second line, print p numbers — the members of the programming team. In the third line, print s numbers — the members of the sports team.The students are numbered from 1 to n as they are given in the input. All numbers printed in the second and in the third lines should be distinct and can be printed in arbitrary order.If there are multiple solutions, print any of them.ExamplesInput5 2 21 3 4 5 25 3 2 1 4Output183 4 1 5 Input4 2 210 8 8 310 7 9 4Output311 2 3 4 Input5 3 15 2 5 1 76 3 1 6 3Output231 3 5 4 | Input5 2 21 3 4 5 25 3 2 1 4 | Output183 4 1 5 | 2 seconds | 512 megabytes | ['dp', 'flows', 'graphs', 'greedy', '*2000'] |
H. Delete Themtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp is a beginner programmer. He is studying how to use a command line.Polycarp faced the following problem. There are n files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the pattern and all other files shouldn't match the pattern.Polycarp doesn't know about an asterisk '*', the only special character he knows is a question mark '?' which matches any single character. All other characters in the pattern match themselves only.Formally, a pattern matches a filename if and only if they have equal lengths and all characters in the corresponding positions are equal except when the character in the pattern is '?', in which case the corresponding filename character does not matter.For example, the filename pattern "a?ba?": matches filenames "aabaa", "abba.", "a.ba9" and "a.ba."; does not match filenames "aaba", "abaab", "aabaaa" and "aabaa.". Help Polycarp find a pattern which matches files to be deleted and only them or report if there is no such pattern.InputThe first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 100) — the total number of files and the number of files to be deleted.The following n lines contain filenames, single filename per line. All filenames are non-empty strings containing only lowercase English letters, digits and dots ('.'). The length of each filename doesn't exceed 100. It is guaranteed that all filenames are distinct.The last line of the input contains m distinct integer numbers in ascending order a1, a2, ..., am (1 ≤ ai ≤ n) — indices of files to be deleted. All files are indexed from 1 to n in order of their appearance in the input.OutputIf the required pattern exists, print "Yes" in the first line of the output. The second line should contain the required pattern. If there are multiple solutions, print any of them.If the required pattern doesn't exist, print the only line containing "No".ExamplesInput3 2abaccd1 2OutputYesa?Input5 3testtezttest..esttes.1 4 5OutputYes?es?Input4 4abcdd1 2 3 4OutputNoInput6 3.svn.git..........1 2 3OutputYes.??? | Input3 2abaccd1 2 | OutputYesa? | 2 seconds | 512 megabytes | ['constructive algorithms', 'implementation', '*1300'] |
G. Car Repair Shoptime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time.Polycarp is good at marketing, so he has already collected n requests from clients. The requests are numbered from 1 to n in order they came.The i-th request is characterized by two values: si — the day when a client wants to start the repair of his car, di — duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on.Polycarp is making schedule by processing requests in the order from the first to the n-th request. He schedules the i-th request as follows: If the car repair shop is idle for di days starting from si (si, si + 1, ..., si + di - 1), then these days are used to repair a car of the i-th client. Otherwise, Polycarp finds the first day x (from 1 and further) that there are di subsequent days when no repair is scheduled starting from x. In other words he chooses the smallest positive x that all days x, x + 1, ..., x + di - 1 are not scheduled for repair of any car. So, the car of the i-th client will be repaired in the range [x, x + di - 1]. It is possible that the day x when repair is scheduled to start will be less than si. Given n requests, you are asked to help Polycarp schedule all of them according to the rules above.InputThe first line contains integer n (1 ≤ n ≤ 200) — the number of requests from clients.The following n lines contain requests, one request per line. The i-th request is given as the pair of integers si, di (1 ≤ si ≤ 109, 1 ≤ di ≤ 5·106), where si is the preferred time to start repairing the i-th car, di is the number of days to repair the i-th car.The requests should be processed in the order they are given in the input.OutputPrint n lines. The i-th line should contain two integers — the start day to repair the i-th car and the finish day to repair the i-th car.ExamplesInput39 27 32 4Output9 101 34 7Input41000000000 10000001000000000 1000000100000000 10000001000000000 1000000Output1000000000 10009999991 1000000100000000 1009999991000001 2000000 | Input39 27 32 4 | Output9 101 34 7 | 2 seconds | 512 megabytes | ['implementation', '*1600'] |
F. Ber Patiotime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp is a regular customer at the restaurant "Ber Patio". He likes having lunches there."Ber Patio" has special discount program for regular customers. A customer can collect bonuses and partially cover expenses in the restaurant.Let's assume a customer currently has b bonuses and she has to pay r burles for a lunch. In this case the customer can use bonuses (1 bonus = 1 burle) to reduce the payment. She can cover at most half of the payment using bonuses. However, 1 bonus will be added to the customer's bonus balance per each 10 burles she paid.Formally: a customer can choose any number x of bonuses to use ()), the customer's bonus balance is reduced by x, the customer pays r - x burles, the customer's bonus balance is increased by ⌊(r - x) / 10⌋ (i.e. integer division rounded down is used). Initially, there are b bonuses on Polycarp's account. Polycarp is going to have a lunch in "Ber Patio" for the next n days. He estimated the values a1, a2, ..., an, where ai is the number of burles in a receipt for the i-th day. The sum over all receipts doesn't exceed 105 burles.Write a program to find the minimum number of burles Polycarp has to spend and an optimal strategy to use bonuses.InputThe first line contains two integer numbers n and b (1 ≤ n ≤ 5000, 0 ≤ b ≤ 105) — number of days and initial number of bonuses Polycarp has.The second line contains the integer sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai is the amount of burles in the i-th day's receipt.It is guaranteed that the sum of all receipts does not exceed 105 burles.OutputOn the first line, print the expected minimal number of burles to pay for all n receipts.On the second line, print the sequence of integer numbers b1, b2, ..., bn, where bi is the number of bonuses to use on the i-th day. If there are multiple solutions, print any of them.ExamplesInput3 2112 75 52Output1102 5 22 Input3 3958 64 33Output10728 4 16 | Input3 2112 75 52 | Output1102 5 22 | 3 seconds | 512 megabytes | ['*3100'] |
E. Award Ceremonytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAll-Berland programming contest comes to an end. In total, n teams participated in it. Like in ACM-ICPC, current results stopped refreshing one hour before the contest ends. So at the Award Ceremony, results are partially known. For each team the value ai is given — the number of points the i-th team has earned before the last hour of the contest. Besides that, the Jury has evaluated all submissions sent during the last hour and knows values di — the number of points earned by the i-th team during the last hour (these values can be negative, which means that a team can lose points).Before the contest, each team got unique id from 1 to n. According to the contest rules, a team with more points takes a higher place. If two or more teams have equal number of points, the team with lower id will take the higher place. So no two teams can share the same place.The Award Ceremony proceeds in the following way. At the beginning of the ceremony, a large screen shows the results for the time moment "one hour before the end", which means that the i-th team has ai points. Then the Jury unfreezes results of the teams one by one in some order. When result of the j-th team is unfrozen, its score changes from aj to aj + dj. At this time the table of results is modified and the place of the team can change. The unfreezing of the j-th team is followed by the applause from the audience with duration of |xj - yj| seconds, where xj is the place of the j-th team before unfreezing and yj is the place right after the unfreezing. For example, if the team does not change the place, there is no applause from the audience. As you can see, during the Award Ceremony, each team will be unfrozen exactly once.Your task is to find such an order to unfreeze all the teams that the total duration of applause is maximum possible.InputThe first line of the input file contains a single integer n (1 ≤ n ≤ 100) — the number of teams.Each of the next n lines contains two integers ai and di (1 ≤ ai ≤ 100, - 100 ≤ di ≤ 100) — the number of points the i-th team has earned before the last hour of the contest and the number of points earned by this team during the last hour. It is possible that after unfreezing a team will have a negative score.OutputPrint the only integer — maximal total applause duration in seconds if the Jury can choose any order of the teams to unfreeze.ExamplesInput417 -1452 -51 526 0Output4Input54 53 25 -36 -24 3Output14NoteIn the first example the initial standings are: Team 2, 52 points Team 1, 17 points Team 4, 6 points Team 3, 1 point Here any order of unfreezing the teams leads to 4 seconds of applause in total. For example, let's unfreeze teams in their order from the Team 1 to the Team 4.After the Team 1 became unfrozen the standings are: Team 2, 52 points Team 4, 6 points Team 1, 3 points Team 3, 1 point So there is 1 second of applause, because the difference between old and new places |2 - 3| = 1.After the Team 2 became unfrozen the standings are: Team 2, 47 points Team 4, 6 points Team 1, 3 points Team 3, 1 point The place of the Team 2 has not changed, so no applause during unfreezing.After the Team 3 became unfrozen the standings are: Team 3, 53 point Team 2, 47 points Team 4, 6 points Team 1, 3 points The place of the Team 3 has changed from 4 to 1, so the duration of applause is |4 - 1| = 3.The unfreezing of the Team 4 has not changed any place because d4 = 0.Therefore, the total duration of applause is 1 + 0 + 3 + 0 = 4 seconds. | Input417 -1452 -51 526 0 | Output4 | 2 seconds | 512 megabytes | ['greedy', 'implementation', '*2200'] |
D. Running Over The Bridgestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPolycarp is playing a game called "Running Over The Bridges". In this game he has to run over n bridges from the left to the right. Bridges are arranged one after the other, so the i-th bridge begins where the (i - 1)-th bridge ends.You have the following data about bridges: li and ti — the length of the i-th bridge and the maximum allowed time which Polycarp can spend running over the i-th bridge. Thus, if Polycarp is in the beginning of the bridge i at the time T then he has to leave it at the time T + ti or earlier. It is allowed to reach the right end of a bridge exactly at the time T + ti.Polycarp can run from the left side to the right one with speed 0.5, so he will run over a bridge with length s in time 2·s. Besides, he has several magical drinks. If he uses one drink, his speed increases twice (i.e. to value 1) for r seconds. All magical drinks are identical. Please note that Polycarp can use a drink only at integer moments of time, and he drinks it instantly and completely. Additionally, if Polycarp uses a drink at the moment T he can use the next drink not earlier than at the moment T + r.What is the minimal number of drinks Polycarp has to use to run over all n bridges? If this number is not greater than 105, then you have to find out the moments of time when Polycarp has to use each magical drink.InputThe first line contains two integers n and r (1 ≤ n ≤ 2·105, 1 ≤ r ≤ 1012) — the number of bridges and the duration of the effect of a magical drink.The second line contains a sequence of integers l1, l2, ..., ln (1 ≤ li ≤ 5·106), where li is equal to the length of the i-th bridge.The third line contains a sequence of integers t1, t2, ..., tn (1 ≤ ti ≤ 107), where ti is equal to the maximum allowed time which Polycarp can spend running over the i-th bridge.OutputThe first line of the output should contain k — the minimal number of drinks which Polycarp has to use, or -1 if there is no solution.If the solution exists and the value of k is not greater than 105 then output k integers on the next line — moments of time from beginning of the game when Polycarp has to use drinks. Print the moments of time in chronological order. If there are several solutions, you can output any of them.ExamplesInput1 3710Output20 3Input3 33 3 33 3 2Output-1Input3 1000005 5 55 7 8Output10 Input4 10001 2 3 410 9 10 9Output0NoteIn the first case, there is only one bridge and it is clear that Polycarp cannot run over it without magical drinks. So, if he will use one magical drink on start (moment of time 0), and the second one — three seconds later (moment of time 3), he will be able to reach the end of the bridge in time. Please note, in this case there are several possible answers to the problem. For example, Polycarp can use the first drink at the moment of time 4 and the second one — at the moment of time 7.In the second case, Polycarp cannot run over all bridges even if he will use magical drinks. So, answer in this case is -1.In the fourth case, Polycarp can run over all bridges without magical drinks. | Input1 3710 | Output20 3 | 2 seconds | 512 megabytes | ['greedy', 'implementation', 'math', '*2200'] |
C. Bulmarttime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA new trade empire is rising in Berland. Bulmart, an emerging trade giant, decided to dominate the market of ... shovels! And now almost every city in Berland has a Bulmart store, and some cities even have several of them! The only problem is, at the moment sales are ... let's say a little below estimates. Some people even say that shovels retail market is too small for such a big company to make a profit. But the company management believes in the future of that market and seeks new ways to increase income. There are n cities in Berland connected with m bi-directional roads. All roads have equal lengths. It can happen that it is impossible to reach a city from another city using only roads. There is no road which connects a city to itself. Any pair of cities can be connected by at most one road.There are w Bulmart stores in Berland. Each of them is described by three numbers: ci — the number of city where the i-th store is located (a city can have no stores at all or have several of them), ki — the number of shovels in the i-th store, pi — the price of a single shovel in the i-th store (in burles). The latest idea of the Bulmart management is to create a program which will help customers get shovels as fast as possible for affordable budget. Formally, the program has to find the minimum amount of time needed to deliver rj shovels to the customer in the city gj for the total cost of no more than aj burles. The delivery time between any two adjacent cities is equal to 1. If shovels are delivered from several cities, the delivery time is equal to the arrival time of the last package. The delivery itself is free of charge.The program needs to find answers to q such queries. Each query has to be processed independently from others, i.e. a query does not change number of shovels in stores for the next queries.InputThe first line contains two integers n, m (1 ≤ n ≤ 5000, 0 ≤ m ≤ min(5000, n·(n - 1) / 2)). Each of the next m lines contains two integers xe and ye, meaning that the e-th road connects cities xe and ye (1 ≤ xe, ye ≤ n).The next line contains a single integer w (1 ≤ w ≤ 5000) — the total number of Bulmart stores in Berland. Each of the next w lines contains three integers describing the i-th store: ci, ki, pi (1 ≤ ci ≤ n, 1 ≤ ki, pi ≤ 2·105).The next line contains a single integer q (1 ≤ q ≤ 1000) — the number of queries. Each of the next q lines contains three integers describing the j-th query: gj, rj and aj (1 ≤ gj ≤ n, 1 ≤ rj, aj ≤ 109)OutputOutput q lines. On the j-th line, print an answer for the j-th query — the minimum amount of time needed to deliver rj shovels to the customer in city gj spending no more than aj burles. Print -1 if there is no solution for the j-th query.ExampleInput6 44 25 41 23 224 1 23 2 361 2 62 3 73 1 24 3 85 2 56 1 10Output2-1223-1 | Input6 44 25 41 23 224 1 23 2 361 2 62 3 73 1 24 3 85 2 56 1 10 | Output2-1223-1 | 1.5 seconds | 512 megabytes | ['binary search', 'dfs and similar', '*2100'] |
B. Minimum and Maximumtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use function fflush(stdout), in Java — System.out.flush(), in Pascal — flush(output) and in Python — sys.stdout.flush().In this problem, you need to find maximal and minimal elements of an array. What could be simpler?You can imagine that the jury has an array, and initially you know the only number n — array's length.Array's elements are numbered from 1 to n. You are allowed to compare two elements of the array by using their indices i and j. There are three possible responses to this query: '<' (if ai is less than aj), '=' (if ai is equal to aj) and finally '>' (if ai is greater than aj).It's known that it's always possible to find both maximal and minimal elements of the array by using no more than comparisons, where ⌈ x⌉ is the result of rounding x up.Write the program that will find positions of the minimum and the maximum in the jury's array of length n, by using no more than f(n) comparisons.InteractionEach test for this problem will contain one or more arrays. You have to find positions of minimal and maximal elements for each of these arrays. The first line of the input contains integer T (1 ≤ T ≤ 1000) — number of arrays in the test.Thus, at the beginning, you program should read number T, and then it should solve the problem for T jury's arrays one by one.Then input for each array goes. Firstly, your program has to read the number n (1 ≤ n ≤ 50) — the length of the array. It will be provided in the next line of the input.Further, your program can perform comparisons or report that the answer is found. To perform a comparison, you have to output string of the following pattern «? i j» (i and j must be integer numbers from 1 to n) — the indices of the elements to compare in the current query. To report the indices of minimal and maximal elements of the hidden array, your program have to output a line in the form «! i j» (i and j must be integer numbers from 1 to n), where i is an index of the minimal element of array, and j is an index of the maximal element of the array. If there are several possible answers to the problem, you can output any of them. There are several possible responses for a comparison: '<' — if ai is less than aj, '=' — if ai is equal to aj, '>' — if ai is greater than aj. For an array of length n your program can make at most comparisons. Note that the operation of reporting an answer («! i j» ) is not included into the value of f(n).After the answer is reported, your program has to solve the problem for the next array or it should terminate if all T arrays are processed.ExampleInput22 > 3 = = Output ? 1 2 ! 2 1 ? 3 1 ? 2 1 ! 2 3 | Input22 > 3 = = | Output ? 1 2 ! 2 1 ? 3 1 ? 2 1 ! 2 3 | 4 seconds | 512 megabytes | ['constructive algorithms', 'interactive', '*1800'] |
A. Toda 2time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA group of n friends enjoys playing popular video game Toda 2. There is a rating system describing skill level of each player, initially the rating of the i-th friend is ri.The friends decided to take part in the championship as a team. But they should have equal ratings to be allowed to compose a single team consisting of all n friends. So the friends are faced with the problem: how to make all their ratings equal.One way to change ratings is to willingly lose in some matches. Friends can form a party consisting of two to five (but not more than n) friends and play a match in the game. When the party loses, the rating of each of its members decreases by 1. A rating can't become negative, so ri = 0 doesn't change after losing.The friends can take part in multiple matches, each time making a party from any subset of friends (but remember about constraints on party size: from 2 to 5 members).The friends want to make their ratings equal but as high as possible.Help the friends develop a strategy of losing the matches so that all their ratings become equal and the resulting rating is maximum possible.InputThe first line contains a single integer n (2 ≤ n ≤ 100) — the number of friends.The second line contains n non-negative integers r1, r2, ..., rn (0 ≤ ri ≤ 100), where ri is the initial rating of the i-th friend.OutputIn the first line, print a single integer R — the final rating of each of the friends.In the second line, print integer t — the number of matches the friends have to play. Each of the following t lines should contain n characters '0' or '1', where the j-th character of the i-th line is equal to: '0', if friend j should not play in match i, '1', if friend j should play in match i. Each line should contain between two and five characters '1', inclusive.The value t should not exceed 104, it is guaranteed that such solution exists. Remember that you shouldn't minimize the value t, but you should maximize R. If there are multiple solutions, print any of them.ExamplesInput54 5 1 7 4Output180101000011010101001000011110000001111000Input21 2Output021111Input31 1 1Output10 | Input54 5 1 7 4 | Output180101000011010101001000011110000001111000 | 2 seconds | 512 megabytes | ['greedy', 'implementation', '*1800'] |
F. Financiers Gametime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis problem has unusual memory constraint.At evening, Igor and Zhenya the financiers became boring, so they decided to play a game. They prepared n papers with the income of some company for some time periods. Note that the income can be positive, zero or negative.Igor and Zhenya placed the papers in a row and decided to take turns making moves. Igor will take the papers from the left side, Zhenya will take the papers from the right side. Igor goes first and takes 1 or 2 (on his choice) papers from the left. Then, on each turn a player can take k or k + 1 papers from his side if the opponent took exactly k papers in the previous turn. Players can't skip moves. The game ends when there are no papers left, or when some of the players can't make a move.Your task is to determine the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it.InputThe first line contains single positive integer n (1 ≤ n ≤ 4000) — the number of papers.The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105), where ai is the income on the i-th paper from the left.OutputPrint the difference between the sum of incomes on the papers Igor took and the sum of incomes on the papers Zhenya took, assuming both players play optimally. Igor wants to maximize the difference, Zhenya wants to minimize it.ExamplesInput31 3 1Output4Input5-1 -2 -1 -2 -1Output0Input4-4 -2 4 5Output-13NoteIn the first example it's profitable for Igor to take two papers from the left to have the sum of the incomes equal to 4. Then Zhenya wouldn't be able to make a move since there would be only one paper, and he would be able to take only 2 or 3.. | Input31 3 1 | Output4 | 2 seconds | 512 megabytes | ['dp', '*2500'] |
E. Subordinatestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n workers in a company, each of them has a unique id from 1 to n. Exaclty one of them is a chief, his id is s. Each worker except the chief has exactly one immediate superior.There was a request to each of the workers to tell how how many superiors (not only immediate). Worker's superiors are his immediate superior, the immediate superior of the his immediate superior, and so on. For example, if there are three workers in the company, from which the first is the chief, the second worker's immediate superior is the first, the third worker's immediate superior is the second, then the third worker has two superiors, one of them is immediate and one not immediate. The chief is a superior to all the workers except himself.Some of the workers were in a hurry and made a mistake. You are to find the minimum number of workers that could make a mistake.InputThe first line contains two positive integers n and s (1 ≤ n ≤ 2·105, 1 ≤ s ≤ n) — the number of workers and the id of the chief.The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n - 1), where ai is the number of superiors (not only immediate) the worker with id i reported about.OutputPrint the minimum number of workers that could make a mistake.ExamplesInput3 22 0 2Output1Input5 31 0 0 4 1Output2NoteIn the first example it is possible that only the first worker made a mistake. Then: the immediate superior of the first worker is the second worker, the immediate superior of the third worker is the first worker, the second worker is the chief. | Input3 22 0 2 | Output1 | 1 second | 256 megabytes | ['constructive algorithms', 'data structures', 'graphs', 'greedy', 'sortings', '*1900'] |
D. Sea Battletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGalya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.InputThe first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made.The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string. OutputIn the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.In the second line print the cells Galya should shoot at.Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left.If there are multiple answers, you can print any of them.ExamplesInput5 1 2 100100Output24 2Input13 3 2 31000000010001Output27 11NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part. | Input5 1 2 100100 | Output24 2 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', 'math', '*1700'] |
C. Road to Cinematime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.InputThe first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts. Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity.The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.OutputPrint the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.ExamplesInput3 1 8 1010 85 711 93Output10Input2 2 10 1810 420 65 3Output20NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel. | Input3 1 8 1010 85 711 93 | Output10 | 1 second | 256 megabytes | ['binary search', 'greedy', 'sortings', '*1700'] |
B. Spotlightstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the four directions (if you look at the stage from above) — left, right, up or down. Thus, the spotlight's position is a cell it is placed to and a direction it shines.A position is good if two conditions hold: there is no actor in the cell the spotlight is placed to; there is at least one actor in the direction the spotlight projects. Count the number of good positions for placing the spotlight. Two positions of spotlight are considered to be different if the location cells or projection direction differ.InputThe first line contains two positive integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in the plan.The next n lines contain m integers, 0 or 1 each — the description of the plan. Integer 1, means there will be an actor in the corresponding cell, while 0 means the cell will remain empty. It is guaranteed that there is at least one actor in the plan.OutputPrint one integer — the number of good positions for placing the spotlight.ExamplesInput2 40 1 0 01 0 1 0Output9Input4 40 0 0 01 0 0 10 1 1 00 1 0 0Output20NoteIn the first example the following positions are good: the (1, 1) cell and right direction; the (1, 1) cell and down direction; the (1, 3) cell and left direction; the (1, 3) cell and down direction; the (1, 4) cell and left direction; the (2, 2) cell and left direction; the (2, 2) cell and up direction; the (2, 2) and right direction; the (2, 4) cell and left direction. Therefore, there are 9 good positions in this example. | Input2 40 1 0 01 0 1 0 | Output9 | 1 second | 256 megabytes | ['dp', 'implementation', '*1200'] |
A. Interview with Olegtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has interviewed Oleg and has written the interview down without punctuation marks and spaces to save time. Thus, the interview is now a string s consisting of n lowercase English letters.There is a filler word ogo in Oleg's speech. All words that can be obtained from ogo by adding go several times to the end of it are also considered to be fillers. For example, the words ogo, ogogo, ogogogo are fillers, but the words go, og, ogog, ogogog and oggo are not fillers.The fillers have maximal size, for example, for ogogoo speech we can't consider ogo a filler and goo as a normal phrase. We should consider ogogo as a filler here.To print the interview, Polycarp has to replace each of the fillers with three asterisks. Note that a filler word is replaced with exactly three asterisks regardless of its length.Polycarp has dealt with this problem in no time. Can you do the same? The clock is ticking!InputThe first line contains a positive integer n (1 ≤ n ≤ 100) — the length of the interview.The second line contains the string s of length n, consisting of lowercase English letters.OutputPrint the interview text after the replacement of each of the fillers with "***". It is allowed for the substring "***" to have several consecutive occurences.ExamplesInput7aogogobOutputa***bInput13ogogmgogogogoOutput***gmg***Input9ogoogoogoOutput*********NoteThe first sample contains one filler word ogogo, so the interview for printing is "a***b".The second sample contains two fillers ogo and ogogogo. Thus, the interview is transformed to "***gmg***". | Input7aogogob | Outputa***b | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
F. Polycarp's problemstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses "the current coordinator's mood q = bi".For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.InputThe first line of input contains two integers n and m (1 ≤ n ≤ 750, 1 ≤ m ≤ 200 000) — the number of problems in the problemset and the number of guesses about the current coordinator's mood.The second line of input contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the qualities of the problems in order of increasing difficulty.The third line of input contains m integers b1, b2, ..., bm (0 ≤ bi ≤ 1015) — the guesses of the current coordinator's mood q.OutputPrint m lines, in i-th line print single integer — the answer to the problem with q = bi.ExampleInput6 38 -5 -4 1 -7 40 7 3Output201 | Input6 38 -5 -4 1 -7 40 7 3 | Output201 | 2 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', '*2300'] |
E. Games on a CDtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSeveral years ago Tolya had n computer games and at some point of time he decided to burn them to CD. After that he wrote down the names of the games one after another in a circle on the CD in clockwise order. The names were distinct, the length of each name was equal to k. The names didn't overlap.Thus, there is a cyclic string of length n·k written on the CD.Several years have passed and now Tolya can't remember which games he burned to his CD. He knows that there were g popular games that days. All of the games he burned were among these g games, and no game was burned more than once.You have to restore any valid list of games Tolya could burn to the CD several years ago.InputThe first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 105) — the amount of games Tolya burned to the CD, and the length of each of the names.The second line of the input contains one string consisting of lowercase English letters — the string Tolya wrote on the CD, split in arbitrary place. The length of the string is n·k. It is guaranteed that the length is not greater than 106.The third line of the input contains one positive integer g (n ≤ g ≤ 105) — the amount of popular games that could be written on the CD. It is guaranteed that the total length of names of all popular games is not greater than 2·106.Each of the next g lines contains a single string — the name of some popular game. Each name consists of lowercase English letters and has length k. It is guaranteed that the names are distinct.OutputIf there is no answer, print "NO" (without quotes).Otherwise, print two lines. In the first line print "YES" (without quotes). In the second line, print n integers — the games which names were written on the CD. You should print games in the order they could have been written on the CD, it means, in clockwise order. You can print games starting from any position. Remember, that no game was burned to the CD more than once. If there are several possible answers, print any of them.ExamplesInput3 1abc4bacdOutputYES2 1 3 Input4 2aabbccdd4ddabbccdOutputNO | Input3 1abc4bacd | OutputYES2 1 3 | 4 seconds | 512 megabytes | ['data structures', 'hashing', 'string suffix structures', 'strings', '*2300'] |
D. T-shirts Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size: the size he wanted, if he specified one size; any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.InputThe first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000.The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants.The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.OutputIf it is not possible to present a t-shirt to each participant, print «NO» (without quotes).Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input.If there are multiple solutions, print any of them.ExamplesInput0 1 0 1 1 03XLS,MXL,XXLOutputYESXLMXXLInput1 1 2 0 1 15SMS,MXXL,XXXLXL,XXLOutputNO | Input0 1 0 1 1 03XLS,MXL,XXL | OutputYESXLMXXL | 1 second | 256 megabytes | ['constructive algorithms', 'flows', 'greedy', '*1800'] |
C. Guess the Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. You should use flush operation after each printed line. For example, in C++ you should use fflush(stdout), in Java you should use System.out.flush(), and in Pascal — flush(output).In this problem you should guess an array a which is unknown for you. The only information you have initially is the length n of the array a.The only allowed action is to ask the sum of two elements by their indices. Formally, you can print two indices i and j (the indices should be distinct). Then your program should read the response: the single integer equals to ai + aj.It is easy to prove that it is always possible to guess the array using at most n requests.Write a program that will guess the array a by making at most n requests.InteractionIn each test your program should guess a single array.The input starts with a line containing integer n (3 ≤ n ≤ 5000) — the length of the array. Your program should read it at first.After that your program should print to the standard output the requests about the sum of two elements or inform that the array is guessed. In case your program is making a request to ask the sum of two elements, it should print line in the format "? i j" (i and j are distinct integers between 1 and n), where i and j are indices in the array a. In case your program informs that the array is guessed, it should print line in the format "! a1 a2 ... an" (it is guaranteed that all ai are positive integers not exceeding 105), where ai is the i-th element of the array a. The response on a request is a single integer equal to ai + aj, printed on a separate line.Your program can do at most n requests. Note that the final line «! a1 a2 ... an» is not counted as a request.Do not forget about flush operation after each printed line.After you program prints the guessed array, it should terminate normally.ExampleInput5 9 7 9 11 6 Output ? 1 5 ? 2 3 ? 4 1 ? 5 2 ? 3 4 ! 4 6 1 5 5NoteThe format of a test to make a hack is: The first line contains an integer number n (3 ≤ n ≤ 5000) — the length of the array. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array to guess. | Input5 9 7 9 11 6 | Output ? 1 5 ? 2 3 ? 4 1 ? 5 2 ? 3 4 ! 4 6 1 5 5 | 1 second | 256 megabytes | ['constructive algorithms', 'interactive', 'math', '*1400'] |
B. Bill Total Valuetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and pricei (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero).Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.For example: "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid. Write a program that will find the total price of all purchases in the given bill.InputThe only line of the input contains a non-empty string s with length not greater than 1000 — the content of the bill.It is guaranteed that the bill meets the format described above. It is guaranteed that each price in the bill is not less than one cent and not greater than 106 dollars.OutputPrint the total price exactly in the same format as prices given in the input.ExamplesInputchipsy48.32televizor12.390Output12.438.32Inputa1b2c3.38Output6.38Inputaa0.01t0.03Output0.04 | Inputchipsy48.32televizor12.390 | Output12.438.32 | 1 second | 256 megabytes | ['expression parsing', 'implementation', 'strings', '*1600'] |
A. Transformation: from A to Btime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasily has a number a, which he wants to turn into a number b. For this purpose, he can do two types of operations: multiply the current number by 2 (that is, replace the number x by 2·x); append the digit 1 to the right of current number (that is, replace the number x by 10·x + 1). You need to help Vasily to transform the number a into the number b using only the operations described above, or find that it is impossible.Note that in this task you are not required to minimize the number of operations. It suffices to find any way to transform a into b.InputThe first line contains two positive integers a and b (1 ≤ a < b ≤ 109) — the number which Vasily has and the number he wants to have.OutputIf there is no way to get b from a, print "NO" (without quotes).Otherwise print three lines. On the first line print "YES" (without quotes). The second line should contain single integer k — the length of the transformation sequence. On the third line print the sequence of transformations x1, x2, ..., xk, where: x1 should be equal to a, xk should be equal to b, xi should be obtained from xi - 1 using any of two described operations (1 < i ≤ k). If there are multiple answers, print any of them.ExamplesInput2 162OutputYES52 4 8 81 162 Input4 42OutputNOInput100 40021OutputYES5100 200 2001 4002 40021 | Input2 162 | OutputYES52 4 8 81 162 | 1 second | 256 megabytes | ['brute force', 'dfs and similar', 'math', '*1000'] |
G. Messages on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are well-known for sending messages to each other. This time you have a rooted tree with Bob standing in the root node and copies of Alice standing in each of the other vertices. The root node has number 0, the rest are numbered 1 through n.At some moments of time some copies of Alice want to send a message to Bob and receive an answer. We will call this copy the initiator. The process of sending a message contains several steps: The initiator sends the message to the person standing in the parent node and begins waiting for the answer. When some copy of Alice receives a message from some of her children nodes, she sends the message to the person standing in the parent node and begins waiting for the answer. When Bob receives a message from some of his child nodes, he immediately sends the answer to the child node where the message came from. When some copy of Alice (except for initiator) receives an answer she is waiting for, she immediately sends it to the child vertex where the message came from. When the initiator receives the answer she is waiting for, she doesn't send it to anybody. There is a special case: a copy of Alice can't wait for two answers at the same time, so if some copy of Alice receives a message from her child node while she already waits for some answer, she rejects the message and sends a message saying this back to the child node where the message came from. Then the copy of Alice in the child vertex processes this answer as if it was from Bob. The process of sending a message to a parent node or to a child node is instant but a receiver (a parent or a child) gets a message after 1 second. If some copy of Alice receives several messages from child nodes at the same moment while she isn't waiting for an answer, she processes the message from the initiator with the smallest number and rejects all the rest. If some copy of Alice receives messages from children nodes and also receives the answer she is waiting for at the same instant, then Alice first processes the answer, then immediately continue as normal with the incoming messages.You are given the moments of time when some copy of Alice becomes the initiator and sends a message to Bob. For each message, find the moment of time when the answer (either from Bob or some copy of Alice) will be received by the initiator.You can assume that if Alice wants to send a message (i.e. become the initiator) while waiting for some answer, she immediately rejects the message and receives an answer from herself in no time.InputThe first line of input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the number of nodes with Alices and the number of messages.Second line contains n integers p1, p2, ..., pn (0 ≤ pi < i). The integer pi is the number of the parent node of node i.The next m lines describe the messages. The i-th of them contains two integers xi and ti (1 ≤ xi ≤ n, 1 ≤ ti ≤ 109) — the number of the vertex of the initiator of the i-th message and the time of the initiation (in seconds). The messages are given in order of increasing initiation time (i.e. ti + 1 ≥ ti holds for 1 ≤ i < m). The pairs (xi, ti) are distinct.OutputPrint m integers — the i-th of them is the moment of time when the answer for the i-th message will be received by the initiator.ExamplesInput6 30 1 2 3 2 54 66 95 11Output14 13 11 Input3 20 1 12 13 1Output5 3 Input8 30 1 1 2 3 3 4 56 18 24 5Output7 6 11 NoteIn the first example the first message is initiated at the moment 6, reaches Bob at the moment 10, and the answer reaches the initiator at the moment 14. The second message reaches vertex 2 at the moment 11. At this moment the copy of Alice in this vertex is still waiting for the answer for the first message, so she rejects the second message. The answer reaches the initiator at the moment 13. The third message is not sent at all, because at the moment 11 Alice in vertex 5 is waiting for the answer for the second message.In the second example the first message reaches Bob, the second is rejected by Alice in vertex 1. This is because the message with smaller initiator number has the priority.In the third example the first and the third messages reach Bob, while the second message is rejected by Alice in vertex 3. | Input6 30 1 2 3 2 54 66 95 11 | Output14 13 11 | 2 seconds | 256 megabytes | ['*3300'] |
F. Family Photostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y.InputThe first line of input contains a single integer n (1 ≤ n ≤ 100 000) — the number of two-photo stacks. Then follow n lines, each describing one of the stacks. A stack is described by four space-separated non-negative integers a1, b1, a2 and b2, each not exceeding 109. a1 and b1 describe the top photo in the stack, while a2 and b2 describe the bottom photo in the stack.OutputOutput a single integer: the difference between Alice's and Bonnie's happiness if both play optimally.ExamplesInput212 3 4 71 15 9 1Output1Input25 4 8 84 12 14 0Output4Input10 10 0 10Output-10 | Input212 3 4 71 15 9 1 | Output1 | 2 seconds | 256 megabytes | ['games', 'greedy', '*2900'] |
E. Too Much Moneytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlfred wants to buy a toy moose that costs c dollars. The store doesn’t give change, so he must give the store exactly c dollars, no more and no less. He has n coins. To make c dollars from his coins, he follows the following algorithm: let S be the set of coins being used. S is initially empty. Alfred repeatedly adds to S the highest-valued coin he has such that the total value of the coins in S after adding the coin doesn’t exceed c. If there is no such coin, and the value of the coins in S is still less than c, he gives up and goes home. Note that Alfred never removes a coin from S after adding it.As a programmer, you might be aware that Alfred’s algorithm can fail even when there is a set of coins with value exactly c. For example, if Alfred has one coin worth $3, one coin worth $4, and two coins worth $5, and the moose costs $12, then Alfred will add both of the $5 coins to S and then give up, since adding any other coin would cause the value of the coins in S to exceed $12. Of course, Alfred could instead combine one $3 coin, one $4 coin, and one $5 coin to reach the total.Bob tried to convince Alfred that his algorithm was flawed, but Alfred didn’t believe him. Now Bob wants to give Alfred some coins (in addition to those that Alfred already has) such that Alfred’s algorithm fails. Bob can give Alfred any number of coins of any denomination (subject to the constraint that each coin must be worth a positive integer number of dollars). There can be multiple coins of a single denomination. He would like to minimize the total value of the coins he gives Alfred. Please find this minimum value. If there is no solution, print "Greed is good". You can assume that the answer, if it exists, is positive. In other words, Alfred's algorithm will work if Bob doesn't give him any coins.InputThe first line contains c (1 ≤ c ≤ 200 000) — the price Alfred wants to pay. The second line contains n (1 ≤ n ≤ 200 000) — the number of coins Alfred initially has. Then n lines follow, each containing a single integer x (1 ≤ x ≤ c) representing the value of one of Alfred's coins.OutputIf there is a solution, print the minimum possible total value of the coins in a solution. Otherwise, print "Greed is good" (without quotes).ExamplesInput123534Output5Input508124816373737OutputGreed is goodNoteIn the first sample, Bob should give Alfred a single coin worth $5. This creates the situation described in the problem statement.In the second sample, there is no set of coins that will cause Alfred's algorithm to fail. | Input123534 | Output5 | 2 seconds | 256 megabytes | ['brute force', 'greedy', '*2600'] |
D. Contest Balloonstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne tradition of ACM-ICPC contests is that a team gets a balloon for every solved problem. We assume that the submission time doesn't matter and teams are sorted only by the number of balloons they have. It means that one's place is equal to the number of teams with more balloons, increased by 1. For example, if there are seven teams with more balloons, you get the eight place. Ties are allowed.You should know that it's important to eat before a contest. If the number of balloons of a team is greater than the weight of this team, the team starts to float in the air together with their workstation. They eventually touch the ceiling, what is strictly forbidden by the rules. The team is then disqualified and isn't considered in the standings.A contest has just finished. There are n teams, numbered 1 through n. The i-th team has ti balloons and weight wi. It's guaranteed that ti doesn't exceed wi so nobody floats initially.Limak is a member of the first team. He doesn't like cheating and he would never steal balloons from other teams. Instead, he can give his balloons away to other teams, possibly making them float. Limak can give away zero or more balloons of his team. Obviously, he can't give away more balloons than his team initially has.What is the best place Limak can get?InputThe first line of the standard input contains one integer n (2 ≤ n ≤ 300 000) — the number of teams.The i-th of n following lines contains two integers ti and wi (0 ≤ ti ≤ wi ≤ 1018) — respectively the number of balloons and the weight of the i-th team. Limak is a member of the first team.OutputPrint one integer denoting the best place Limak can get.ExamplesInput820 100032 3740 100045 5016 1616 1614 10002 1000Output3Input74 44 44 44 44 44 45 5Output2Input714000000003 100000000000000000081000000000 880000000005000000000 700000000015000000000 3900000000046000000000 510000000000 10000000000 0Output2NoteIn the first sample, Limak has 20 balloons initially. There are three teams with more balloons (32, 40 and 45 balloons), so Limak has the fourth place initially. One optimal strategy is: Limak gives 6 balloons away to a team with 32 balloons and weight 37, which is just enough to make them fly. Unfortunately, Limak has only 14 balloons now and he would get the fifth place. Limak gives 6 balloons away to a team with 45 balloons. Now they have 51 balloons and weight 50 so they fly and get disqualified. Limak gives 1 balloon to each of two teams with 16 balloons initially. Limak has 20 - 6 - 6 - 1 - 1 = 6 balloons. There are three other teams left and their numbers of balloons are 40, 14 and 2. Limak gets the third place because there are two teams with more balloons. In the second sample, Limak has the second place and he can't improve it.In the third sample, Limak has just enough balloons to get rid of teams 2, 3 and 5 (the teams with 81 000 000 000, 5 000 000 000 and 46 000 000 000 balloons respectively). With zero balloons left, he will get the second place (ex-aequo with team 6 and team 7). | Input820 100032 3740 100045 5016 1616 1614 10002 1000 | Output3 | 3 seconds | 256 megabytes | ['data structures', 'greedy', '*1800'] |
C. Hidden Wordtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet’s define a grid to be a set of tiles with 2 rows and 13 columns. Each tile has an English letter written in it. The letters don't have to be unique: there might be two or more tiles with the same letter written on them. Here is an example of a grid: ABCDEFGHIJKLMNOPQRSTUVWXYZ We say that two tiles are adjacent if they share a side or a corner. In the example grid above, the tile with the letter 'A' is adjacent only to the tiles with letters 'B', 'N', and 'O'. A tile is not adjacent to itself.A sequence of tiles is called a path if each tile in the sequence is adjacent to the tile which follows it (except for the last tile in the sequence, which of course has no successor). In this example, "ABC" is a path, and so is "KXWIHIJK". "MAB" is not a path because 'M' is not adjacent to 'A'. A single tile can be used more than once by a path (though the tile cannot occupy two consecutive places in the path because no tile is adjacent to itself).You’re given a string s which consists of 27 upper-case English letters. Each English letter occurs at least once in s. Find a grid that contains a path whose tiles, viewed in the order that the path visits them, form the string s. If there’s no solution, print "Impossible" (without the quotes).InputThe only line of the input contains the string s, consisting of 27 upper-case English letters. Each English letter occurs at least once in s.OutputOutput two lines, each consisting of 13 upper-case English characters, representing the rows of the grid. If there are multiple solutions, print any of them. If there is no solution print "Impossible".ExamplesInputABCDEFGHIJKLMNOPQRSGTUVWXYZOutputYXWVUTGHIJKLMZABCDEFSRQPONInputBUVTYZFQSNRIWOXXGJLKACPEMDHOutputImpossible | InputABCDEFGHIJKLMNOPQRSGTUVWXYZ | OutputYXWVUTGHIJKLMZABCDEFSRQPON | 2 seconds | 256 megabytes | ['brute force', 'constructive algorithms', 'implementation', 'strings', '*1600'] |
B. Food on the Planetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats 'd', 'e' and 'f' are located to the right. Seats 'a' and 'f' are located near the windows, while seats 'c' and 'd' are located near the aisle. It's lunch time and two flight attendants have just started to serve food. They move from the first rows to the tail, always maintaining a distance of two rows from each other because of the food trolley. Thus, at the beginning the first attendant serves row 1 while the second attendant serves row 3. When both rows are done they move one row forward: the first attendant serves row 2 while the second attendant serves row 4. Then they move three rows forward and the first attendant serves row 5 while the second attendant serves row 7. Then they move one row forward again and so on.Flight attendants work with the same speed: it takes exactly 1 second to serve one passenger and 1 second to move one row forward. Each attendant first serves the passengers on the seats to the right of the aisle and then serves passengers on the seats to the left of the aisle (if one looks in the direction of the cockpit). Moreover, they always serve passengers in order from the window to the aisle. Thus, the first passenger to receive food in each row is located in seat 'f', and the last one — in seat 'c'. Assume that all seats are occupied.Vasya has seat s in row n and wants to know how many seconds will pass before he gets his lunch.InputThe only line of input contains a description of Vasya's seat in the format ns, where n (1 ≤ n ≤ 1018) is the index of the row and s is the seat in this row, denoted as letter from 'a' to 'f'. The index of the row and the seat are not separated by a space.OutputPrint one integer — the number of seconds Vasya has to wait until he gets his lunch.ExamplesInput1fOutput1Input2dOutput10Input4aOutput11Input5eOutput18NoteIn the first sample, the first flight attendant serves Vasya first, so Vasya gets his lunch after 1 second.In the second sample, the flight attendants will spend 6 seconds to serve everyone in the rows 1 and 3, then they will move one row forward in 1 second. As they first serve seats located to the right of the aisle in order from window to aisle, Vasya has to wait 3 more seconds. The total is 6 + 1 + 3 = 10. | Input1f | Output1 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1200'] |
A. Jumping Balltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position i + 1) if the type of this bumper is '>', or one position to the left (to i - 1) if the type of the bumper at position i is '<'. If there is no such position, in other words if i - 1 < 1 or i + 1 > n, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position.InputThe first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper.OutputPrint one integer — the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position.ExamplesInput4<<><Output2Input5>>>>>Output5Input4>><<Output0NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Input4<<>< | Output2 | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
G. Xor-matic Number of the Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph, constisting of n vertices and m edges. Each edge of the graph has some non-negative integer written on it.Let's call a triple (u, v, s) interesting, if 1 ≤ u < v ≤ n and there is a path (possibly non-simple, i.e. it can visit the same vertices and edges multiple times) between vertices u and v such that xor of all numbers written on the edges of this path is equal to s. When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path. It's not hard to prove that there are finite number of such triples.Calculate the sum over modulo 109 + 7 of the values of s over all interesting triples.InputThe first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 0 ≤ m ≤ 200 000) — numbers of vertices and edges in the given graph.The follow m lines contain three integers ui, vi and ti (1 ≤ ui, vi ≤ n, 0 ≤ ti ≤ 1018, ui ≠ vi) — vertices connected by the edge and integer written on it. It is guaranteed that graph doesn't contain self-loops and multiple edges.OutputPrint the single integer, equal to the described sum over modulo 109 + 7.ExamplesInput4 41 2 11 3 22 3 33 4 1Output12Input4 41 2 12 3 23 4 44 1 8Output90Input8 61 2 22 3 12 4 44 5 54 6 37 8 5Output62NoteIn the first example the are 6 interesting triples: (1, 2, 1) (1, 3, 2) (1, 4, 3) (2, 3, 3) (2, 4, 2) (3, 4, 1) The sum is equal to 1 + 2 + 3 + 3 + 2 + 1 = 12.In the second example the are 12 interesting triples: (1, 2, 1) (2, 3, 2) (1, 3, 3) (3, 4, 4) (2, 4, 6) (1, 4, 7) (1, 4, 8) (2, 4, 9) (3, 4, 11) (1, 3, 12) (2, 3, 13) (1, 2, 14) The sum is equal to 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 + 11 + 12 + 13 + 14 = 90. | Input4 41 2 11 3 22 3 33 4 1 | Output12 | 2 seconds | 256 megabytes | ['bitmasks', 'graphs', 'math', 'number theory', 'trees', '*2600'] |
F. Uniformly Branched Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected graph without cycles.Two trees, consisting of n vertices each, are called isomorphic if there exists a permutation p: {1, ..., n} → {1, ..., n} such that the edge (u, v) is present in the first tree if and only if the edge (pu, pv) is present in the second tree.Vertex of the tree is called internal if its degree is greater than or equal to two.Count the number of different non-isomorphic trees, consisting of n vertices, such that the degree of each internal vertex is exactly d. Print the answer over the given prime modulo mod.InputThe single line of the input contains three integers n, d and mod (1 ≤ n ≤ 1000, 2 ≤ d ≤ 10, 108 ≤ mod ≤ 109) — the number of vertices in the tree, the degree of internal vertices and the prime modulo.OutputPrint the number of trees over the modulo mod.ExamplesInput5 2 433416647Output1Input10 3 409693891Output2Input65 4 177545087Output910726 | Input5 2 433416647 | Output1 | 1 second | 256 megabytes | ['combinatorics', 'dp', 'trees', '*2700'] |
E. Goods transportationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities located along the one-way road. Cities are numbered from 1 to n in the direction of the road.The i-th city had produced pi units of goods. No more than si units of goods can be sold in the i-th city.For each pair of cities i and j such that 1 ≤ i < j ≤ n you can no more than once transport no more than c units of goods from the city i to the city j. Note that goods can only be transported from a city with a lesser index to the city with a larger index. You can transport goods between cities in any order.Determine the maximum number of produced goods that can be sold in total in all the cities after a sequence of transportations.InputThe first line of the input contains two integers n and c (1 ≤ n ≤ 10 000, 0 ≤ c ≤ 109) — the number of cities and the maximum amount of goods for a single transportation.The second line contains n integers pi (0 ≤ pi ≤ 109) — the number of units of goods that were produced in each city.The third line of input contains n integers si (0 ≤ si ≤ 109) — the number of units of goods that can be sold in each city.OutputPrint the maximum total number of produced goods that can be sold in all cities after a sequence of transportations.ExamplesInput3 01 2 33 2 1Output4Input5 17 4 2 1 01 2 3 4 5Output12Input4 313 10 7 44 7 10 13Output34 | Input3 01 2 33 2 1 | Output4 | 2 seconds | 256 megabytes | ['dp', 'flows', 'greedy', '*2900'] |
D. Dense Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase English letters, and the integer m.One should choose some symbols from the given string so that any contiguous subsegment of length m has at least one selected symbol. Note that here we choose positions of symbols, not the symbols themselves.Then one uses the chosen symbols to form a new string. All symbols from the chosen position should be used, but we are allowed to rearrange them in any order.Formally, we choose a subsequence of indices 1 ≤ i1 < i2 < ... < it ≤ |s|. The selected sequence must meet the following condition: for every j such that 1 ≤ j ≤ |s| - m + 1, there must be at least one selected index that belongs to the segment [j, j + m - 1], i.e. there should exist a k from 1 to t, such that j ≤ ik ≤ j + m - 1.Then we take any permutation p of the selected indices and form a new string sip1sip2... sipt.Find the lexicographically smallest string, that can be obtained using this procedure.InputThe first line of the input contains a single integer m (1 ≤ m ≤ 100 000).The second line contains the string s consisting of lowercase English letters. It is guaranteed that this string is non-empty and its length doesn't exceed 100 000. It is also guaranteed that the number m doesn't exceed the length of the string s.OutputPrint the single line containing the lexicographically smallest string, that can be obtained using the procedure described above.ExamplesInput3cbabcOutputaInput2abcabOutputaabInput3bcabcbaccbaOutputaaabbNoteIn the first sample, one can choose the subsequence {3} and form a string "a".In the second sample, one can choose the subsequence {1, 2, 4} (symbols on this positions are 'a', 'b' and 'a') and rearrange the chosen symbols to form a string "aab". | Input3cbabc | Outputa | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'strings', '*1900'] |
C. Ray Tracingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are k sensors located in the rectangular room of size n × m meters. The i-th sensor is located at point (xi, yi). All sensors are located at distinct points strictly inside the rectangle. Opposite corners of the room are located at points (0, 0) and (n, m). Walls of the room are parallel to coordinate axes.At the moment 0, from the point (0, 0) the laser ray is released in the direction of point (1, 1). The ray travels with a speed of meters per second. Thus, the ray will reach the point (1, 1) in exactly one second after the start.When the ray meets the wall it's reflected by the rule that the angle of incidence is equal to the angle of reflection. If the ray reaches any of the four corners, it immediately stops.For each sensor you have to determine the first moment of time when the ray will pass through the point where this sensor is located. If the ray will never pass through this point, print - 1 for such sensors.InputThe first line of the input contains three integers n, m and k (2 ≤ n, m ≤ 100 000, 1 ≤ k ≤ 100 000) — lengths of the room's walls and the number of sensors.Each of the following k lines contains two integers xi and yi (1 ≤ xi ≤ n - 1, 1 ≤ yi ≤ m - 1) — coordinates of the sensors. It's guaranteed that no two sensors are located at the same point.OutputPrint k integers. The i-th of them should be equal to the number of seconds when the ray first passes through the point where the i-th sensor is located, or - 1 if this will never happen. ExamplesInput3 3 41 11 22 12 2Output1-1-12Input3 4 61 12 11 22 21 32 3Output1-1-125-1Input7 4 51 32 25 15 34 3Output13295-1NoteIn the first sample, the ray will consequently pass through the points (0, 0), (1, 1), (2, 2), (3, 3). Thus, it will stop at the point (3, 3) after 3 seconds. In the second sample, the ray will consequently pass through the following points: (0, 0), (1, 1), (2, 2), (3, 3), (2, 4), (1, 3), (0, 2), (1, 1), (2, 0), (3, 1), (2, 2), (1, 3), (0, 4). The ray will stop at the point (0, 4) after 12 seconds. It will reflect at the points (3, 3), (2, 4), (0, 2), (2, 0) and (3, 1). | Input3 3 41 11 22 12 2 | Output1-1-12 | 2 seconds | 256 megabytes | ['greedy', 'hashing', 'implementation', 'math', 'number theory', 'sortings', '*1800'] |
Subsets and Splits