problem_statement
stringlengths 147
8.53k
| input
stringlengths 1
771
| output
stringlengths 1
592
⌀ | time_limit
stringclasses 32
values | memory_limit
stringclasses 21
values | tags
stringlengths 6
168
|
---|---|---|---|---|---|
A. Rowtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a row with n chairs. We call a seating of people "maximal" if the two following conditions hold: There are no neighbors adjacent to anyone seated. It's impossible to seat one more person without violating the first rule. The seating is given as a string consisting of zeros and ones (0 means that the corresponding seat is empty, 1 — occupied). The goal is to determine whether this seating is "maximal".Note that the first and last seats are not adjacent (if n \ne 2).InputThe first line contains a single integer n (1 \leq n \leq 1000) — the number of chairs.The next line contains a string of n characters, each of them is either zero or one, describing the seating.OutputOutput "Yes" (without quotation marks) if the seating is "maximal". Otherwise print "No".You are allowed to print letters in whatever case you'd like (uppercase or lowercase).ExamplesInput3101OutputYesInput41011OutputNoInput510001OutputNoNoteIn sample case one the given seating is maximal.In sample case two the person at chair three has a neighbour to the right.In sample case three it is possible to seat yet another person into chair three. | Input3101 | OutputYes | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', '*1200'] |
H. K Pathstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree of n vertices. You are to select k (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty.Compute the number of ways to select k paths modulo 998244353.The paths are enumerated, in other words, two ways are considered distinct if there are such i (1 \leq i \leq k) and an edge that the i-th path contains the edge in one way and does not contain it in the other.InputThe first line contains two integers n and k (1 \leq n, k \leq 10^{5}) — the number of vertices in the tree and the desired number of paths.The next n - 1 lines describe edges of the tree. Each line contains two integers a and b (1 \le a, b \le n, a \ne b) — the endpoints of an edge. It is guaranteed that the given edges form a tree.OutputPrint the number of ways to select k enumerated not necessarily distinct simple paths in such a way that for each edge either it is not contained in any path, or it is contained in exactly one path, or it is contained in all k paths, and the intersection of all paths is non-empty. As the answer can be large, print it modulo 998244353.ExamplesInput3 21 22 3Output7Input5 14 12 34 52 1Output10Input29 291 21 31 41 55 65 75 88 98 108 1111 1211 1311 1414 1514 1614 1717 1817 1917 2020 2120 2220 2323 2423 2523 2626 2726 2826 29Output125580756NoteIn the first example the following ways are valid: ((1,2), (1,2)), ((1,2), (1,3)), ((1,3), (1,2)), ((1,3), (1,3)), ((1,3), (2,3)), ((2,3), (1,3)), ((2,3), (2,3)). In the second example k=1, so all n \cdot (n - 1) / 2 = 5 \cdot 4 / 2 = 10 paths are valid.In the third example, the answer is \geq 998244353, so it was taken modulo 998244353, don't forget it! | Input3 21 22 3 | Output7 | 4 seconds | 256 megabytes | ['combinatorics', 'data structures', 'dp', 'fft', 'math', '*3100'] |
G. Magic multisetstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the School of Magic in Dirtpolis a lot of interesting objects are studied on Computer Science lessons.Consider, for example, the magic multiset. If you try to add an integer to it that is already presented in the multiset, each element in the multiset duplicates. For example, if you try to add the integer 2 to the multiset \{1, 2, 3, 3\}, you will get \{1, 1, 2, 2, 3, 3, 3, 3\}. If you try to add an integer that is not presented in the multiset, it is simply added to it. For example, if you try to add the integer 4 to the multiset \{1, 2, 3, 3\}, you will get \{1, 2, 3, 3, 4\}.Also consider an array of n initially empty magic multisets, enumerated from 1 to n.You are to answer q queries of the form "add an integer x to all multisets with indices l, l + 1, \ldots, r" and "compute the sum of sizes of multisets with indices l, l + 1, \ldots, r". The answers for the second type queries can be large, so print the answers modulo 998244353.InputThe first line contains two integers n and q (1 \leq n, q \leq 2 \cdot 10^{5}) — the number of magic multisets in the array and the number of queries, respectively.The next q lines describe queries, one per line. Each line starts with an integer t (1 \leq t \leq 2) — the type of the query. If t equals 1, it is followed by three integers l, r, x (1 \leq l \leq r \leq n, 1 \leq x \leq n) meaning that you should add x to all multisets with indices from l to r inclusive. If t equals 2, it is followed by two integers l, r (1 \leq l \leq r \leq n) meaning that you should compute the sum of sizes of all multisets with indices from l to r inclusive.OutputFor each query of the second type print the sum of sizes of multisets on the given segment.The answers can be large, so print them modulo 998244353.ExamplesInput4 41 1 2 11 1 2 21 1 4 12 1 4Output10Input3 71 1 1 31 1 1 31 1 1 21 1 1 12 1 11 1 1 22 1 1Output48NoteIn the first example after the first two queries the multisets are equal to [\{1, 2\},\{1, 2\},\{\},\{\}], after the third query they are equal to [\{1, 1, 2, 2\},\{1, 1, 2, 2\},\{1\},\{1\}].In the second example the first multiset evolves as follows: \{\} \to \{3\} \to \{3, 3\} \to \{2, 3, 3\} \to \{1, 2, 3, 3\} \to \{1, 1, 2, 2, 3, 3, 3, 3\}. | Input4 41 1 2 11 1 2 21 1 4 12 1 4 | Output10 | 4 seconds | 256 megabytes | ['data structures', '*2500'] |
F. Round Marriagetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's marriage season in Ringland!Ringland has a form of a circle's boundary of length L. There are n bridegrooms and n brides, and bridegrooms decided to marry brides.Of course, each bridegroom should choose exactly one bride, and each bride should be chosen by exactly one bridegroom.All objects in Ringland are located on the boundary of the circle, including the capital, bridegrooms' castles and brides' palaces. The castle of the i-th bridegroom is located at the distance a_i from the capital in clockwise direction, and the palace of the i-th bride is located at the distance b_i from the capital in clockwise direction.Let's define the inconvenience of a marriage the maximum distance that some bride should walk along the circle from her palace to her bridegroom's castle in the shortest direction (in clockwise or counter-clockwise direction).Help the bridegrooms of Ringland to choose brides in such a way that the inconvenience of the marriage is the smallest possible.InputThe first line contains two integers n and L (1 \leq n \leq 2 \cdot 10^{5}, 1 \leq L \leq 10^{9}) — the number of bridegrooms and brides and the length of Ringland.The next line contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i < L) — the distances from the capital to the castles of bridegrooms in clockwise direction.The next line contains n integers b_1, b_2, \ldots, b_n (0 \leq b_i < L) — the distances from the capital to the palaces of brides in clockwise direction.OutputIn the only line print the smallest possible inconvenience of the wedding, where the inconvenience is the largest distance traveled by a bride.ExamplesInput2 40 12 3Output1Input10 1003 14 15 92 65 35 89 79 32 382 71 82 81 82 84 5 90 45 23Output27NoteIn the first example the first bridegroom should marry the second bride, the second bridegroom should marry the first bride. This way, the second bride should walk the distance of 1, and the first bride should also walk the same distance. Thus, the inconvenience is equal to 1.In the second example let p_i be the bride the i-th bridegroom will marry. One of optimal p is the following: (6,8,1,4,5,10,3,2,7,9). | Input2 40 12 3 | Output1 | 3 seconds | 256 megabytes | ['binary search', 'graph matchings', 'greedy', '*2500'] |
E. Addition on Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGrisha come to a contest and faced the following problem.You are given an array of size n, initially consisting of zeros. The elements of the array are enumerated from 1 to n. You perform q operations on the array. The i-th operation is described with three integers l_i, r_i and x_i (1 \leq l_i \leq r_i \leq n, 1 \leq x_i \leq n) and means that you should add x_i to each of the elements with indices l_i, l_i + 1, \ldots, r_i. After all operations you should find the maximum in the array.Grisha is clever, so he solved the problem quickly.However something went wrong inside his head and now he thinks of the following question: "consider we applied some subset of the operations to the array. What are the possible values of the maximum in the array?"Help Grisha, find all integers y between 1 and n such that if you apply some subset (possibly empty) of the operations, then the maximum in the array becomes equal to y.InputThe first line contains two integers n and q (1 \leq n, q \leq 10^{4}) — the length of the array and the number of queries in the initial problem.The following q lines contain queries, one per line. The i-th of these lines contains three integers l_i, r_i and x_i (1 \leq l_i \leq r_i \leq n, 1 \leq x_i \leq n), denoting a query of adding x_i to the segment from l_i-th to r_i-th elements of the array, inclusive.OutputIn the first line print the only integer k, denoting the number of integers from 1 to n, inclusive, that can be equal to the maximum in the array after applying some subset (possibly empty) of the given operations.In the next line print these k integers from 1 to n — the possible values of the maximum. Print these integers in increasing order.ExamplesInput4 31 3 12 4 23 4 4Output41 2 3 4 Input7 21 5 13 7 2Output31 2 3 Input10 31 1 21 1 31 1 6Output62 3 5 6 8 9 NoteConsider the first example. If you consider the subset only of the first query, the maximum is equal to 1. If you take only the second query, the maximum equals to 2. If you take the first two queries, the maximum becomes 3. If you take only the fourth query, the maximum becomes 4. If you take the fourth query and something more, the maximum becomes greater that n, so you shouldn't print it.In the second example you can take the first query to obtain 1. You can take only the second query to obtain 2. You can take all queries to obtain 3.In the third example you can obtain the following maximums: You can achieve the maximim of 2 by using queries: (1). You can achieve the maximim of 3 by using queries: (2). You can achieve the maximim of 5 by using queries: (1, 2). You can achieve the maximim of 6 by using queries: (3). You can achieve the maximim of 8 by using queries: (1, 3). You can achieve the maximim of 9 by using queries: (2, 3). | Input4 31 3 12 4 23 4 4 | Output41 2 3 4 | 2 seconds | 256 megabytes | ['bitmasks', 'data structures', 'divide and conquer', 'dp', '*2200'] |
D. Bookshelvestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly k bookshelves. He decided that the beauty of the k shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on k shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.InputThe first line contains two integers n and k (1 \leq k \leq n \leq 50) — the number of books and the number of shelves in the new office.The second line contains n integers a_1, a_2, \ldots a_n, (0 < a_i < 2^{50}) — the prices of the books in the order they stand on the old shelf.OutputPrint the maximum possible beauty of k shelves in the new office.ExamplesInput10 49 14 28 1 7 13 15 29 2 31Output24Input7 33 14 15 92 65 35 89Output64NoteIn the first example you can split the books as follows:(9 + 14 + 28 + 1 + 7) \& (13 + 15) \& (29 + 2) \& (31) = 24.In the second example you can split the books as follows:(3 + 14 + 15 + 92) \& (65) \& (35 + 89) = 64. | Input10 49 14 28 1 7 13 15 29 2 31 | Output24 | 1 second | 256 megabytes | ['bitmasks', 'dp', 'greedy', '*1900'] |
C. Useful Decompositiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRamesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.InputThe first line contains a single integer n (2 \leq n \leq 10^{5}) the number of nodes in the tree.Each of the next n - 1 lines contains two integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) — the edges of the tree. It is guaranteed that the given edges form a tree.OutputIf there are no decompositions, print the only line containing "No".Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition m. Each of the next m lines should contain two integers u_i, v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i) denoting that one of the paths in the decomposition is the simple path between nodes u_i and v_i. Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order.If there are multiple decompositions, print any.ExamplesInput41 22 33 4OutputYes11 4Input61 22 33 42 53 6OutputNoInput51 21 31 41 5OutputYes41 21 31 41 5NoteThe tree from the first example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.The tree from the second example is shown on the picture below: We can show that there are no valid decompositions of this tree.The tree from the third example is shown on the picture below: The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions. | Input41 22 33 4 | OutputYes11 4 | 1 second | 256 megabytes | ['implementation', 'trees', '*1400'] |
B. Businessmen Problemstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies.In order to avoid this representatives of both companies decided to make an agreement on the sets the companies should present. The sets should be chosen in the way that maximizes the total income of the companies.All elements are enumerated with integers. The ChemForces company has discovered n distinct chemical elements with indices a_1, a_2, \ldots, a_n, and will get an income of x_i Berland rubles if the i-th element from this list is in the set of this company.The TopChemist company discovered m distinct chemical elements with indices b_1, b_2, \ldots, b_m, and it will get an income of y_j Berland rubles for including the j-th element from this list to its set.In other words, the first company can present any subset of elements from \{a_1, a_2, \ldots, a_n\} (possibly empty subset), the second company can present any subset of elements from \{b_1, b_2, \ldots, b_m\} (possibly empty subset). There shouldn't be equal elements in the subsets.Help the representatives select the sets in such a way that no element is presented in both sets and the total income is the maximum possible.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of elements discovered by ChemForces.The i-th of the next n lines contains two integers a_i and x_i (1 \leq a_i \leq 10^9, 1 \leq x_i \leq 10^9) — the index of the i-th element and the income of its usage on the exhibition. It is guaranteed that all a_i are distinct.The next line contains a single integer m (1 \leq m \leq 10^5) — the number of chemicals invented by TopChemist.The j-th of the next m lines contains two integers b_j and y_j, (1 \leq b_j \leq 10^9, 1 \leq y_j \leq 10^9) — the index of the j-th element and the income of its usage on the exhibition. It is guaranteed that all b_j are distinct.OutputPrint the maximum total income you can obtain by choosing the sets for both companies in such a way that no element is presented in both sets.ExamplesInput31 27 23 1041 42 43 44 4Output24Input11000000000 239314 1592 6535 89Output408NoteIn the first example ChemForces can choose the set (3, 7), while TopChemist can choose (1, 2, 4). This way the total income is (10 + 2) + (4 + 4 + 4) = 24.In the second example ChemForces can choose the only element 10^9, while TopChemist can choose (14, 92, 35). This way the total income is (239) + (15 + 65 + 89) = 408. | Input31 27 23 1041 42 43 44 4 | Output24 | 2 seconds | 256 megabytes | ['sortings', '*1000'] |
A. Antipalindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.A substring s[l \ldots r] (1 \leq l \leq r \leq |s|) of a string s = s_{1}s_{2} \ldots s_{|s|} is the string s_{l}s_{l + 1} \ldots s_{r}.Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word s is changed into its longest substring that is not a palindrome. If all the substrings of s are palindromes, she skips the word at all.Some time ago Ann read the word s. What is the word she changed it into?InputThe first line contains a non-empty string s with length at most 50 characters, containing lowercase English letters only.OutputIf there is such a substring in s that is not a palindrome, print the maximum length of such a substring. Otherwise print 0.Note that there can be multiple longest substrings that are not palindromes, but their length is unique.ExamplesInputmewOutput3InputwuffuwOutput5InputqqqqqqqqOutput0Note"mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is 3.The string "uffuw" is one of the longest non-palindrome substrings (of length 5) of the string "wuffuw", so the answer for the second example is 5.All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is 0. | Inputmew | Output3 | 1 second | 256 megabytes | ['brute force', 'implementation', 'strings', '*900'] |
F. Cactus to Treetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a special connected undirected graph where each vertex belongs to at most one simple cycle.Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance.InputThe first line of input contains two integers n and m (1 \leq n \leq 5\cdot 10^5), the number of nodes and the number of edges, respectively.Each of the following m lines contains two integers u and v (1 \leq u,v \leq n, u \ne v), and represents an edge connecting the two nodes u and v. Each pair of nodes is connected by at most one edge.It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle.OutputPrint n space-separated integers, the i-th integer represents the maximum distance between node i and a leaf if the removed edges were chosen in a way that minimizes this distance.ExamplesInput9 107 29 21 63 14 34 77 69 85 85 9Output5 3 5 4 5 4 3 5 4Input4 41 22 33 44 1Output2 2 2 2NoteIn the first sample, a possible way to minimize the maximum distance from vertex 1 is by removing the marked edges in the following image: Note that to minimize the answer for different nodes, you can remove different edges. | Input9 107 29 21 63 14 34 77 69 85 85 9 | Output5 3 5 4 5 4 3 5 4 | 4 seconds | 256 megabytes | ['dp', 'graphs', 'trees', '*2900'] |
E. The Number Gamestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equal to 2^i.This year, the president decided to reduce the costs. He wants to remove k contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts. The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.Which contestants should the president remove?InputThe first line of input contains two integers n and k (1 \leq k < n \leq 10^6) — the number of districts in Panel, and the number of contestants the president wishes to remove, respectively.The next n-1 lines each contains two integers a and b (1 \leq a, b \leq n, a \ne b), that describe a road that connects two different districts a and b in the nation. It is guaranteed that there is exactly one path between every two districts.OutputPrint k space-separated integers: the numbers of the districts of which the contestants should be removed, in increasing order of district number.ExamplesInput6 32 12 64 25 62 3Output1 3 4Input8 42 62 77 81 23 12 47 5Output1 3 4 5NoteIn the first sample, the maximum possible total number of fans is 2^2 + 2^5 + 2^6 = 100. We can achieve it by removing the contestants of the districts 1, 3, and 4. | Input6 32 12 64 25 62 3 | Output1 3 4 | 3 seconds | 256 megabytes | ['data structures', 'greedy', 'trees', '*2200'] |
D. Perfect Groupstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive).InputThe first line of input contains a single integer n (1 \leq n \leq 5000), the size of the array.The second line contains n integers a_1,a_2,\dots,a_n (-10^8 \leq a_i \leq 10^8), the values of the array.OutputOutput n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k.ExamplesInput25 5Output3 0Input55 -4 2 1 8Output5 5 3 2 0Input10Output1 | Input25 5 | Output3 0 | 1 second | 256 megabytes | ['dp', 'math', 'number theory', '*2100'] |
C. Posterizedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputProfessor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the i-th integer represents the color of the i-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than k, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing k to the right. To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.InputThe first line of input contains two integers n and k (1 \leq n \leq 10^5, 1 \leq k \leq 256), the number of pixels in the image, and the maximum size of a group, respectively.The second line contains n integers p_1, p_2, \dots, p_n (0 \leq p_i \leq 255), where p_i is the color of the i-th pixel.OutputPrint n space-separated integers; the lexicographically smallest possible array that represents the image after applying the Posterization filter.ExamplesInput4 32 14 3 4Output0 12 3 3Input5 20 2 1 255 254Output0 1 1 254 254NoteOne possible way to group colors and assign keys for the first sample:Color 2 belongs to the group [0,2], with group key 0.Color 14 belongs to the group [12,14], with group key 12.Colors 3 and 4 belong to group [3, 5], with group key 3.Other groups won't affect the result so they are not listed here. | Input4 32 14 3 4 | Output0 12 3 3 | 1 second | 256 megabytes | ['games', 'greedy', '*1700'] |
B. Marlintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe city of Fishtopia can be imagined as a grid of 4 rows and an odd number of columns. It has two main villages; the first is located at the top-left cell (1,1), people who stay there love fishing at the Tuna pond at the bottom-right cell (4, n). The second village is located at (4, 1) and its people love the Salmon pond at (1, n).The mayor of Fishtopia wants to place k hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?InputThe first line of input contain two integers, n and k (3 \leq n \leq 99, 0 \leq k \leq 2\times(n-2)), n is odd, the width of the city, and the number of hotels to be placed, respectively.OutputPrint "YES", if it is possible to place all the hotels in a way that satisfies the problem statement, otherwise print "NO".If it is possible, print an extra 4 lines that describe the city, each line should have n characters, each of which is "#" if that cell has a hotel on it, or "." if not.ExamplesInput7 2OutputYES........#......#............Input5 3OutputYES......###........... | Input7 2 | OutputYES........#......#............ | 1 second | 256 megabytes | ['constructive algorithms', '*1600'] |
A. Links and Pearlstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one. You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times as you like, but you can't throw away any parts.Can you make the number of links between every two adjacent pearls equal? Two pearls are considered to be adjacent if there is no other pearl between them.Note that the final necklace should remain as one circular part of the same length as the initial necklace.InputThe only line of input contains a string s (3 \leq |s| \leq 100), representing the necklace, where a dash '-' represents a link and the lowercase English letter 'o' represents a pearl.OutputPrint "YES" if the links and pearls can be rejoined such that the number of links between adjacent pearls is equal. Otherwise print "NO".You can print each letter in any case (upper or lower).ExamplesInput-o-o--OutputYESInput-o---OutputYESInput-o---o-OutputNOInputoooOutputYES | Input-o-o-- | OutputYES | 1 second | 256 megabytes | ['implementation', 'math', '*900'] |
E. Kuro and Topological Paritytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuro has recently won the "Most intelligent cat ever" contest. The three friends then decided to go to Katie's home to celebrate Kuro's winning. After a big meal, they took a small break then started playing games.Kuro challenged Katie to create a game with only a white paper, a pencil, a pair of scissors and a lot of arrows (you can assume that the number of arrows is infinite). Immediately, Katie came up with the game called Topological Parity.The paper is divided into n pieces enumerated from 1 to n. Shiro has painted some pieces with some color. Specifically, the i-th piece has color c_{i} where c_{i} = 0 defines black color, c_{i} = 1 defines white color and c_{i} = -1 means that the piece hasn't been colored yet.The rules of the game is simple. Players must put some arrows between some pairs of different pieces in such a way that for each arrow, the number in the piece it starts from is less than the number of the piece it ends at. Also, two different pieces can only be connected by at most one arrow. After that the players must choose the color (0 or 1) for each of the unpainted pieces. The score of a valid way of putting the arrows and coloring pieces is defined as the number of paths of pieces of alternating colors. For example, [1 \to 0 \to 1 \to 0], [0 \to 1 \to 0 \to 1], [1], [0] are valid paths and will be counted. You can only travel from piece x to piece y if and only if there is an arrow from x to y.But Kuro is not fun yet. He loves parity. Let's call his favorite parity p where p = 0 stands for "even" and p = 1 stands for "odd". He wants to put the arrows and choose colors in such a way that the score has the parity of p.It seems like there will be so many ways which satisfy Kuro. He wants to count the number of them but this could be a very large number. Let's help him with his problem, but print it modulo 10^{9} + 7.InputThe first line contains two integers n and p (1 \leq n \leq 50, 0 \leq p \leq 1) — the number of pieces and Kuro's wanted parity.The second line contains n integers c_{1}, c_{2}, ..., c_{n} (-1 \leq c_{i} \leq 1) — the colors of the pieces.OutputPrint a single integer — the number of ways to put the arrows and choose colors so the number of valid paths of alternating colors has the parity of p.ExamplesInput3 1-1 0 1Output6Input2 11 0Output1Input1 1-1Output2NoteIn the first example, there are 6 ways to color the pieces and add the arrows, as are shown in the figure below. The scores are 3, 3, 5 for the first row and 5, 3, 3 for the second row, both from left to right. | Input3 1-1 0 1 | Output6 | 1 second | 256 megabytes | ['dp', '*2400'] |
D. Kuro and GCD and XOR and SUMtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputKuro is currently playing an educational game about numbers. The game focuses on the greatest common divisor (GCD), the XOR value, and the sum of two numbers. Kuro loves the game so much that he solves levels by levels day by day.Sadly, he's going on a vacation for a day, and he isn't able to continue his solving streak on his own. As Katie is a reliable person, Kuro kindly asked her to come to his house on this day to play the game for him.Initally, there is an empty array a. The game consists of q tasks of two types. The first type asks Katie to add a number u_i to a. The second type asks Katie to find a number v existing in a such that k_i \mid GCD(x_i, v), x_i + v \leq s_i, and x_i \oplus v is maximized, where \oplus denotes the bitwise XOR operation, GCD(c, d) denotes the greatest common divisor of integers c and d, and y \mid x means x is divisible by y, or report -1 if no such numbers are found.Since you are a programmer, Katie needs you to automatically and accurately perform the tasks in the game to satisfy her dear friend Kuro. Let's help her!InputThe first line contains one integer q (2 \leq q \leq 10^{5}) — the number of tasks the game wants you to perform.q lines follow, each line begins with an integer t_i — the type of the task: If t_i = 1, an integer u_i follow (1 \leq u_i \leq 10^{5}) — you have to add u_i to the array a. If t_i = 2, three integers x_i, k_i, and s_i follow (1 \leq x_i, k_i, s_i \leq 10^{5}) — you must find a number v existing in the array a such that k_i \mid GCD(x_i, v), x_i + v \leq s_i, and x_i \oplus v is maximized, where \oplus denotes the XOR operation, or report -1 if no such numbers are found. It is guaranteed that the type of the first task is type 1, and there exists at least one task of type 2.OutputFor each task of type 2, output on one line the desired number v, or -1 if no such numbers are found.ExamplesInput51 11 22 1 1 32 1 1 22 1 1 1Output21-1Input101 92 9 9 222 3 3 181 252 9 9 202 25 25 141 202 26 26 31 142 20 20 9Output999-1-1-1NoteIn the first example, there are 5 tasks: The first task requires you to add 1 into a. a is now \left\{1\right\}. The second task requires you to add 2 into a. a is now \left\{1, 2\right\}. The third task asks you a question with x = 1, k = 1 and s = 3. Taking both 1 and 2 as v satisfies 1 \mid GCD(1, v) and 1 + v \leq 3. Because 2 \oplus 1 = 3 > 1 \oplus 1 = 0, 2 is the answer to this task. The fourth task asks you a question with x = 1, k = 1 and s = 2. Only v = 1 satisfies 1 \mid GCD(1, v) and 1 + v \leq 2, so 1 is the answer to this task. The fifth task asks you a question with x = 1, k = 1 and s = 1. There are no elements in a that satisfy the conditions, so we report -1 as the answer to this task. | Input51 11 22 1 1 32 1 1 22 1 1 1 | Output21-1 | 2 seconds | 512 megabytes | ['binary search', 'bitmasks', 'brute force', 'data structures', 'dp', 'dsu', 'greedy', 'math', 'number theory', 'strings', 'trees', '*2200'] |
C. Kuro and Walking Routetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuro is living in a country called Uberland, consisting of n towns, numbered from 1 to n, and n - 1 bidirectional roads connecting these towns. It is possible to reach each town from any other. Each road connects two towns a and b. Kuro loves walking and he is planning to take a walking marathon, in which he will choose a pair of towns (u, v) (u \neq v) and walk from u using the shortest path to v (note that (u, v) is considered to be different from (v, u)).Oddly, there are 2 special towns in Uberland named Flowrisa (denoted with the index x) and Beetopia (denoted with the index y). Flowrisa is a town where there are many strong-scent flowers, and Beetopia is another town where many bees live. In particular, Kuro will avoid any pair of towns (u, v) if on the path from u to v, he reaches Beetopia after he reached Flowrisa, since the bees will be attracted with the flower smell on Kuro’s body and sting him.Kuro wants to know how many pair of city (u, v) he can take as his route. Since he’s not really bright, he asked you to help him with this problem.InputThe first line contains three integers n, x and y (1 \leq n \leq 3 \cdot 10^5, 1 \leq x, y \leq n, x \ne y) - the number of towns, index of the town Flowrisa and index of the town Beetopia, respectively.n - 1 lines follow, each line contains two integers a and b (1 \leq a, b \leq n, a \ne b), describes a road connecting two towns a and b.It is guaranteed that from each town, we can reach every other town in the city using the given roads. That is, the given map of towns and roads is a tree.OutputA single integer resembles the number of pair of towns (u, v) that Kuro can use as his walking route.ExamplesInput3 1 31 22 3Output5Input3 1 31 21 3Output4NoteOn the first example, Kuro can choose these pairs: (1, 2): his route would be 1 \rightarrow 2, (2, 3): his route would be 2 \rightarrow 3, (3, 2): his route would be 3 \rightarrow 2, (2, 1): his route would be 2 \rightarrow 1, (3, 1): his route would be 3 \rightarrow 2 \rightarrow 1. Kuro can't choose pair (1, 3) since his walking route would be 1 \rightarrow 2 \rightarrow 3, in which Kuro visits town 1 (Flowrisa) and then visits town 3 (Beetopia), which is not allowed (note that pair (3, 1) is still allowed because although Kuro visited Flowrisa and Beetopia, he did not visit them in that order).On the second example, Kuro can choose the following pairs: (1, 2): his route would be 1 \rightarrow 2, (2, 1): his route would be 2 \rightarrow 1, (3, 2): his route would be 3 \rightarrow 1 \rightarrow 2, (3, 1): his route would be 3 \rightarrow 1. | Input3 1 31 22 3 | Output5 | 2 seconds | 256 megabytes | ['dfs and similar', 'trees', '*1600'] |
B. Treasure Hunttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of 7 because its subribbon a appears 7 times, and the ribbon abcdabc has the beauty of 2 because its subribbon abc appears twice.The rules are simple. The game will have n turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after n turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?InputThe first line contains an integer n (0 \leq n \leq 10^{9}) — the number of turns.Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than 10^{5} uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.OutputPrint the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".ExamplesInput3KurooShiroKatieOutputKuroInput7treasurehuntthreefriendshiCodeforcesOutputShiroInput1abcabccbabacababcaOutputKatieInput15foPaErcvJmZaxowpbtmkuOlaHREOutputDrawNoteIn the first example, after 3 turns, Kuro can change his ribbon into ooooo, which has the beauty of 5, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most 4, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is 9 and the number of turn is 15, everyone can change their ribbons in some way to reach the maximal beauty of 9 by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw. | Input3KurooShiroKatie | OutputKuro | 1 second | 256 megabytes | ['greedy', '*1800'] |
A. Pizza, Pizza, Pizza!!!time limit per test1 secondmemory limit per test128 megabytesinputstandard inputoutputstandard outputKatie, Kuro and Shiro are best friends. They have known each other since kindergarten. That's why they often share everything with each other and work together on some very hard problems.Today is Shiro's birthday. She really loves pizza so she wants to invite her friends to the pizza restaurant near her house to celebrate her birthday, including her best friends Katie and Kuro.She has ordered a very big round pizza, in order to serve her many friends. Exactly n of Shiro's friends are here. That's why she has to divide the pizza into n + 1 slices (Shiro also needs to eat). She wants the slices to be exactly the same size and shape. If not, some of her friends will get mad and go home early, and the party will be over.Shiro is now hungry. She wants to cut the pizza with minimum of straight cuts. A cut is a straight segment, it might have ends inside or outside the pizza. But she is too lazy to pick up the calculator.As usual, she will ask Katie and Kuro for help. But they haven't come yet. Could you help Shiro with this problem?InputA single line contains one non-negative integer n (0 \le n \leq 10^{18}) — the number of Shiro's friends. The circular pizza has to be sliced into n + 1 pieces.OutputA single integer — the number of straight cuts Shiro needs.ExamplesInput3Output2Input4Output5NoteTo cut the round pizza into quarters one has to make two cuts through the center with angle 90^{\circ} between them.To cut the round pizza into five equal parts one has to make five cuts. | Input3 | Output2 | 1 second | 128 megabytes | ['math', '*1000'] |
G. Petya's Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya studies at university. The current academic year finishes with n special days. Petya needs to pass m exams in those special days. The special days in this problem are numbered from 1 to n.There are three values about each exam: s_i — the day, when questions for the i-th exam will be published, d_i — the day of the i-th exam (s_i < d_i), c_i — number of days Petya needs to prepare for the i-th exam. For the i-th exam Petya should prepare in days between s_i and d_i-1, inclusive. There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the i-th exam in day j, then s_i \le j < d_i.It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.InputThe first line contains two integers n and m (2 \le n \le 100, 1 \le m \le n) — the number of days and the number of exams.Each of the following m lines contains three integers s_i, d_i, c_i (1 \le s_i < d_i \le n, 1 \le c_i \le n) — the day, when questions for the i-th exam will be given, the day of the i-th exam, number of days Petya needs to prepare for the i-th exam. Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.OutputIf Petya can not prepare and pass all the exams, print -1. In case of positive answer, print n integers, where the j-th number is: (m + 1), if the j-th day is a day of some exam (recall that in each day no more than one exam is conducted), zero, if in the j-th day Petya will have a rest, i (1 \le i \le m), if Petya will prepare for the i-th exam in the day j (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).Assume that the exams are numbered in order of appearing in the input, starting from 1.If there are multiple schedules, print any of them.ExamplesInput5 21 3 11 5 1Output1 2 3 0 3 Input3 21 3 11 2 1Output-1Input10 34 7 21 10 38 9 1Output2 2 2 1 1 0 4 3 4 4 NoteIn the first example Petya can, for example, prepare for exam 1 in the first day, prepare for exam 2 in the second day, pass exam 1 in the third day, relax in the fourth day, and pass exam 2 in the fifth day. So, he can prepare and pass all exams.In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | Input5 21 3 11 5 1 | Output1 2 3 0 3 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1700'] |
F. Mentorstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn BerSoft n programmers work, the programmer i is characterized by a skill r_i.A programmer a can be a mentor of a programmer b if and only if the skill of the programmer a is strictly greater than the skill of the programmer b (r_a > r_b) and programmers a and b are not in a quarrel.You are given the skills of each programmers and a list of k pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer i, find the number of programmers, for which the programmer i can be a mentor.InputThe first line contains two integers n and k (2 \le n \le 2 \cdot 10^5, 0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2})) — total number of programmers and number of pairs of programmers which are in a quarrel.The second line contains a sequence of integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^{9}), where r_i equals to the skill of the i-th programmer.Each of the following k lines contains two distinct integers x, y (1 \le x, y \le n, x \ne y) — pair of programmers in a quarrel. The pairs are unordered, it means that if x is in a quarrel with y then y is in a quarrel with x. Guaranteed, that for each pair (x, y) there are no other pairs (x, y) and (y, x) in the input.OutputPrint n integers, the i-th number should be equal to the number of programmers, for which the i-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.ExamplesInput4 210 4 10 151 24 3Output0 0 1 2 Input10 45 4 1 5 4 3 7 1 2 54 62 110 83 5Output5 4 0 5 3 3 9 0 2 5 NoteIn the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel. | Input4 210 4 10 151 24 3 | Output0 0 1 2 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'implementation', '*1500'] |
E. Bus Video Systemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the system records the number y-x. So the system records show how number of passengers changed.The test run was made for single bus and n bus stops. Thus, the system recorded the sequence of integers a_1, a_2, \dots, a_n (exactly one number for each bus stop), where a_i is the record for the bus stop i. The bus stops are numbered from 1 to n in chronological order.Determine the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to w (that is, at any time in the bus there should be from 0 to w passengers inclusive).InputThe first line contains two integers n and w (1 \le n \le 1\,000, 1 \le w \le 10^{9}) — the number of bus stops and the capacity of the bus.The second line contains a sequence a_1, a_2, \dots, a_n (-10^{6} \le a_i \le 10^{6}), where a_i equals to the number, which has been recorded by the video system after the i-th bus stop.OutputPrint the number of possible ways how many people could be in the bus before the first bus stop, if the bus has a capacity equals to w. If the situation is contradictory (i.e. for any initial number of passengers there will be a contradiction), print 0.ExamplesInput3 52 1 -3Output3Input2 4-1 1Output4Input4 102 4 1 2Output2NoteIn the first example initially in the bus could be 0, 1 or 2 passengers.In the second example initially in the bus could be 1, 2, 3 or 4 passengers.In the third example initially in the bus could be 0 or 1 passenger. | Input3 52 1 -3 | Output3 | 1 second | 256 megabytes | ['combinatorics', 'math', '*1400'] |
D. Almost Arithmetic Progressiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp likes arithmetic progressions. A sequence [a_1, a_2, \dots, a_n] is called an arithmetic progression if for each i (1 \le i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are not.It follows from the definition that any sequence of length one or two is an arithmetic progression.Polycarp found some sequence of positive integers [b_1, b_2, \dots, b_n]. He agrees to change each element by at most one. In the other words, for each element there are exactly three options: an element can be decreased by 1, an element can be increased by 1, an element can be left unchanged.Determine a minimum possible number of elements in b which can be changed (by exactly one), so that the sequence b becomes an arithmetic progression, or report that it is impossible.It is possible that the resulting sequence contains element equals 0.InputThe first line contains a single integer n (1 \le n \le 100\,000) — the number of elements in b.The second line contains a sequence b_1, b_2, \dots, b_n (1 \le b_i \le 10^{9}).OutputIf it is impossible to make an arithmetic progression with described operations, print -1. In the other case, print non-negative integer — the minimum number of elements to change to make the given sequence becomes an arithmetic progression. The only allowed operation is to add/to subtract one from an element (can't use operation twice to the same position).ExamplesInput424 21 14 10Output3Input2500 500Output0Input314 5 1Output-1Input51 3 6 9 12Output1NoteIn the first example Polycarp should increase the first number on 1, decrease the second number on 1, increase the third number on 1, and the fourth number should left unchanged. So, after Polycarp changed three elements by one, his sequence became equals to [25, 20, 15, 10], which is an arithmetic progression.In the second example Polycarp should not change anything, because his sequence is an arithmetic progression.In the third example it is impossible to make an arithmetic progression.In the fourth example Polycarp should change only the first element, he should decrease it on one. After that his sequence will looks like [0, 3, 6, 9, 12], which is an arithmetic progression. | Input424 21 14 10 | Output3 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*1500'] |
C. Letterstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all n dormitories is written on an envelope. In this case, assume that all the rooms are numbered from 1 to a_1 + a_2 + \dots + a_n and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case n=2, a_1=3 and a_2=5 an envelope can have any integer from 1 to 8 written on it. If the number 7 is written on an envelope, it means that the letter should be delivered to the room number 4 of the second dormitory.For each of m letters by the room number among all n dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.InputThe first line contains two integers n and m (1 \le n, m \le 2 \cdot 10^{5}) — the number of dormitories and the number of letters.The second line contains a sequence a_1, a_2, \dots, a_n (1 \le a_i \le 10^{10}), where a_i equals to the number of rooms in the i-th dormitory. The third line contains a sequence b_1, b_2, \dots, b_m (1 \le b_j \le a_1 + a_2 + \dots + a_n), where b_j equals to the room number (among all rooms of all dormitories) for the j-th letter. All b_j are given in increasing order.OutputPrint m lines. For each letter print two integers f and k — the dormitory number f (1 \le f \le n) and the room number k in this dormitory (1 \le k \le a_f) to deliver the letter.ExamplesInput3 610 15 121 9 12 23 26 37Output1 11 92 22 133 13 12Input2 35 100000000005 6 9999999999Output1 52 12 9999999994NoteIn the first example letters should be delivered in the following order: the first letter in room 1 of the first dormitory the second letter in room 9 of the first dormitory the third letter in room 2 of the second dormitory the fourth letter in room 13 of the second dormitory the fifth letter in room 1 of the third dormitory the sixth letter in room 12 of the third dormitory | Input3 610 15 121 9 12 23 26 37 | Output1 11 92 22 133 13 12 | 4 seconds | 256 megabytes | ['binary search', 'implementation', 'two pointers', '*1000'] |
B. File Nametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the social network topic. In this case, the file is not sent and an error message is displayed.Determine the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. Print 0 if the file name does not initially contain a forbidden substring "xxx".You can delete characters in arbitrary positions (not necessarily consecutive). If you delete a character, then the length of a string is reduced by 1. For example, if you delete the character in the position 2 from the string "exxxii", then the resulting string is "exxii".InputThe first line contains integer n (3 \le n \le 100) — the length of the file name.The second line contains a string of length n consisting of lowercase Latin letters only — the file name.OutputPrint the minimum number of characters to remove from the file name so after that the name does not contain "xxx" as a substring. If initially the file name dost not contain a forbidden substring "xxx", print 0.ExamplesInput6xxxiiiOutput1Input5xxoxxOutput0Input10xxxxxxxxxxOutput8NoteIn the first example Polycarp tried to send a file with name contains number 33, written in Roman numerals. But he can not just send the file, because it name contains three letters "x" in a row. To send the file he needs to remove any one of this letters. | Input6xxxiii | Output1 | 1 second | 256 megabytes | ['greedy', 'strings', '*800'] |
A. Remove Duplicatestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has an array a consisting of n integers. He wants to remove duplicate (equal) elements.Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed.InputThe first line contains a single integer n (1 \le n \le 50) — the number of elements in Petya's array.The following line contains a sequence a_1, a_2, \dots, a_n (1 \le a_i \le 1\,000) — the Petya's array.OutputIn the first line print integer x — the number of elements which will be left in Petya's array after he removed the duplicates.In the second line print x integers separated with a space — Petya's array after he removed the duplicates. For each unique element only the rightmost entry should be left.ExamplesInput61 5 5 1 6 1Output35 6 1 Input52 4 2 4 4Output22 4 Input56 6 6 6 6Output16 NoteIn the first example you should remove two integers 1, which are in the positions 1 and 4. Also you should remove the integer 5, which is in the position 2.In the second example you should remove integer 2, which is in the position 1, and two integers 4, which are in the positions 2 and 4.In the third example you should remove four integers 6, which are in the positions 1, 2, 3 and 4. | Input61 5 5 1 6 1 | Output35 6 1 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Consecutive Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array of length n.You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x, x + 1, \dots, x + k - 1] for some value x and length k.Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order. For example, for the array [5, 3, 1, 2, 4] the following arrays are subsequences: [3], [5, 3, 1, 2, 4], [5, 1, 4], but the array [1, 3] is not.InputThe first line of the input containing integer number n (1 \le n \le 2 \cdot 10^5) — the length of the array. The second line of the input containing n integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the array itself.OutputOn the first line print k — the maximum length of the subsequence of the given array that forms an increasing sequence of consecutive integers.On the second line print the sequence of the indices of the any maximum length subsequence of the given array that forms an increasing sequence of consecutive integers.ExamplesInput73 3 4 7 5 6 8Output42 3 5 6 Input61 3 5 2 4 6Output21 4 Input410 9 8 7Output11 Input96 7 8 3 4 5 9 10 11Output61 2 3 7 8 9 NoteAll valid answers for the first example (as sequences of indices): [1, 3, 5, 6] [2, 3, 5, 6] All valid answers for the second example: [1, 4] [2, 5] [3, 6] All valid answers for the third example: [1] [2] [3] [4] All valid answers for the fourth example: [1, 2, 3, 7, 8, 9] | Input73 3 4 7 5 6 8 | Output42 3 5 6 | 2 seconds | 256 megabytes | ['dp', '*1700'] |
E. Cyclic Componentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles.Here are some definitions of graph theory.An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices. All edges are bidirectional (i.e. if a vertex a is connected with a vertex b, a vertex b is also connected with a vertex a). An edge can't connect vertex with itself, there is at most one edge between a pair of vertices.Two vertices u and v belong to the same connected component if and only if there is at least one path along edges connecting u and v.A connected component is a cycle if and only if its vertices can be reordered in such a way that: the first vertex is connected with the second vertex by an edge, the second vertex is connected with the third vertex by an edge, ... the last vertex is connected with the first vertex by an edge, all the described edges of a cycle are distinct. A cycle doesn't contain any other edges except described above. By definition any cycle contains three or more vertices. There are 6 connected components, 2 of them are cycles: [7, 10, 16] and [5, 11, 9, 15]. InputThe first line contains two integer numbers n and m (1 \le n \le 2 \cdot 10^5, 0 \le m \le 2 \cdot 10^5) — number of vertices and edges.The following m lines contains edges: edge i is given as a pair of vertices v_i, u_i (1 \le v_i, u_i \le n, u_i \ne v_i). There is no multiple edges in the given graph, i.e. for each pair (v_i, u_i) there no other pairs (v_i, u_i) and (u_i, v_i) in the list of edges.OutputPrint one integer — the number of connected components which are also cycles.ExamplesInput5 41 23 45 43 5Output1Input17 151 81 125 1111 99 1515 54 133 134 310 167 1016 714 314 417 6Output2NoteIn the first example only component [3, 4, 5] is also a cycle.The illustration above corresponds to the second example. | Input5 41 23 45 43 5 | Output1 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', '*1500'] |
D. Divide by three, multiply by twotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp likes to play with numbers. He takes some integer number x, writes it down on the board, and then performs with it n - 1 operations of the two kinds: divide the number x by 3 (x must be divisible by 3); multiply the number x by 2. After each operation, Polycarp writes down the result on the board and replaces x by the result. So there will be n numbers on the board after all.You are given a sequence of length n — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.InputThe first line of the input contatins an integer number n (2 \le n \le 100) — the number of the elements in the sequence. The second line of the input contains n integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 3 \cdot 10^{18}) — rearranged (reordered) sequence that Polycarp can wrote down on the board.OutputPrint n integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board.It is guaranteed that the answer exists.ExamplesInput64 8 6 3 12 9Output9 3 6 12 4 8 Input442 28 84 126Output126 42 84 28 Input21000000000000000000 3000000000000000000Output3000000000000000000 1000000000000000000 NoteIn the first example the given sequence can be rearranged in the following way: [9, 3, 6, 12, 4, 8]. It can match possible Polycarp's game which started with x = 9. | Input64 8 6 3 12 9 | Output9 3 6 12 4 8 | 1 second | 256 megabytes | ['dfs and similar', 'math', 'sortings', '*1400'] |
C. Less or Equaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 \le x \le 10^9) such that exactly k elements of given sequence are less than or equal to x.Note that the sequence can contain equal elements.If there is no such x, print "-1" (without quotes).InputThe first line of the input contains integer numbers n and k (1 \le n \le 2 \cdot 10^5, 0 \le k \le n). The second line of the input contains n integer numbers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the sequence itself.OutputPrint any integer number x from range [1; 10^9] such that exactly k elements of given sequence is less or equal to x.If there is no such x, print "-1" (without quotes).ExamplesInput7 43 7 5 1 10 3 20Output6Input7 23 7 5 1 10 3 20Output-1NoteIn the first example 5 is also a valid answer because the elements with indices [1, 3, 4, 6] is less than or equal to 5 and obviously less than or equal to 6.In the second example you cannot choose any number that only 2 elements of the given sequence will be less than or equal to this number because 3 elements of the given sequence will be also less than or equal to this number. | Input7 43 7 5 1 10 3 20 | Output6 | 2 seconds | 256 megabytes | ['sortings', '*1200'] |
B. Two-gramtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string s = "BBAABBBA" the answer is two-gram "BB", which contained in s three times. In other words, find any most frequent two-gram.Note that occurrences of the two-gram can overlap with each other.InputThe first line of the input contains integer number n (2 \le n \le 100) — the length of string s. The second line of the input contains the string s consisting of n capital Latin letters.OutputPrint the only line containing exactly two capital Latin letters — any two-gram contained in the given string s as a substring (i.e. two consecutive characters of the string) maximal number of times.ExamplesInput7ABACABAOutputABInput5ZZZAAOutputZZNoteIn the first example "BA" is also valid answer.In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times. | Input7ABACABA | OutputAB | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
A. Wrong Subtractiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: if the last digit of the number is non-zero, she decreases the number by one; if the last digit of the number is zero, she divides the number by 10 (i.e. removes the last digit). You are given an integer number n. Tanya will subtract one from it k times. Your task is to print the result after all k subtractions.It is guaranteed that the result will be positive integer number.InputThe first line of the input contains two integer numbers n and k (2 \le n \le 10^9, 1 \le k \le 50) — the number from which Tanya will subtract and the number of subtractions correspondingly.OutputPrint one integer number — the result of the decreasing n by one k times.It is guaranteed that the result will be positive integer number. ExamplesInput512 4Output50Input1000000000 9Output1NoteThe first example corresponds to the following sequence: 512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50. | Input512 4 | Output50 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Minimal k-coveringtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph G = (U, V, E), U is the set of vertices of the first part, V is the set of vertices of the second part and E is the set of edges. There might be multiple edges.Let's call some subset of its edges k-covering iff the graph has each of its vertices incident to at least k edges. Minimal k-covering is such a k-covering that the size of the subset is minimal possible.Your task is to find minimal k-covering for each , where minDegree is the minimal degree of any vertex in graph G.InputThe first line contains three integers n1, n2 and m (1 ≤ n1, n2 ≤ 2000, 0 ≤ m ≤ 2000) — the number of vertices in the first part, the number of vertices in the second part and the number of edges, respectively.The i-th of the next m lines contain two integers ui and vi (1 ≤ ui ≤ n1, 1 ≤ vi ≤ n2) — the description of the i-th edge, ui is the index of the vertex in the first part and vi is the index of the vertex in the second part.OutputFor each print the subset of edges (minimal k-covering) in separate line.The first integer cntk of the k-th line is the number of edges in minimal k-covering of the graph. Then cntk integers follow — original indices of the edges which belong to the minimal k-covering, these indices should be pairwise distinct. Edges are numbered 1 through m in order they are given in the input.ExamplesInput3 3 71 22 31 33 23 32 12 1Output0 3 3 7 4 6 1 3 6 7 4 5 Input1 1 51 11 11 11 11 1Output0 1 5 2 4 5 3 3 4 5 4 2 3 4 5 5 1 2 3 4 5 | Input3 3 71 22 31 33 23 32 12 1 | Output0 3 3 7 4 6 1 3 6 7 4 5 | 1.5 seconds | 256 megabytes | ['flows', 'graphs', '*2500'] |
E. Well played!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently Max has got himself into popular CCG "BrainStone". As "BrainStone" is a pretty intellectual game, Max has to solve numerous hard problems during the gameplay. Here is one of them:Max owns n creatures, i-th of them can be described with two numbers — its health hpi and its damage dmgi. Max also has two types of spells in stock: Doubles health of the creature (hpi := hpi·2); Assigns value of health of the creature to its damage (dmgi := hpi). Spell of first type can be used no more than a times in total, of the second type — no more than b times in total. Spell can be used on a certain creature multiple times. Spells can be used in arbitrary order. It isn't necessary to use all the spells.Max is really busy preparing for his final exams, so he asks you to determine what is the maximal total damage of all creatures he can achieve if he uses spells in most optimal way.InputThe first line contains three integers n, a, b (1 ≤ n ≤ 2·105, 0 ≤ a ≤ 20, 0 ≤ b ≤ 2·105) — the number of creatures, spells of the first type and spells of the second type, respectively.The i-th of the next n lines contain two number hpi and dmgi (1 ≤ hpi, dmgi ≤ 109) — description of the i-th creature.OutputPrint single integer — maximum total damage creatures can deal.ExamplesInput2 1 110 156 1Output27Input3 0 310 87 115 2Output26NoteIn the first example Max should use the spell of the first type on the second creature, then the spell of the second type on the same creature. Then total damage will be equal to 15 + 6·2 = 27.In the second example Max should use the spell of the second type on the first creature, then the spell of the second type on the third creature. Total damage will be equal to 10 + 11 + 5 = 26. | Input2 1 110 156 1 | Output27 | 1 second | 256 megabytes | ['greedy', 'sortings', '*2100'] |
D. Degree Settime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence of n positive integers d1, d2, ..., dn (d1 < d2 < ... < dn). Your task is to construct an undirected graph such that: there are exactly dn + 1 vertices; there are no self-loops; there are no multiple edges; there are no more than 106 edges; its degree set is equal to d. Vertices should be numbered 1 through (dn + 1).Degree sequence is an array a with length equal to the number of vertices in a graph such that ai is the number of vertices adjacent to i-th vertex.Degree set is a sorted in increasing order sequence of all distinct values from the degree sequence.It is guaranteed that there exists such a graph that all the conditions hold, and it contains no more than 106 edges.Print the resulting graph.InputThe first line contains one integer n (1 ≤ n ≤ 300) — the size of the degree set.The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 1000, d1 < d2 < ... < dn) — the degree set.OutputIn the first line print one integer m (1 ≤ m ≤ 106) — the number of edges in the resulting graph. It is guaranteed that there exists such a graph that all the conditions hold and it contains no more than 106 edges.Each of the next m lines should contain two integers vi and ui (1 ≤ vi, ui ≤ dn + 1) — the description of the i-th edge.ExamplesInput32 3 4Output83 14 24 52 55 13 22 15 3Input31 2 3Output41 21 31 42 3 | Input32 3 4 | Output83 14 24 52 55 13 22 15 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'implementation', '*2500'] |
C. Nested Segmentstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.InputThe first line contains one integer n (1 ≤ n ≤ 3·105) — the number of segments.Each of the next n lines contains two integers li and ri (1 ≤ li ≤ ri ≤ 109) — the i-th segment.OutputPrint two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.ExamplesInput51 102 93 92 32 9Output2 1Input31 52 66 20Output-1 -1NoteIn the first example the following pairs are considered correct: (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders; (3, 2), (4, 2), (3, 5), (4, 5) — touch one border; (5, 2), (2, 5) — match exactly. | Input51 102 93 92 32 9 | Output2 1 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1500'] |
B. Lara Croft and the New Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of n rows and m columns. Cell (x, y) is the cell in the x-th row in the y-th column. Lara can move between the neighbouring by side cells in all four directions.Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1, 1), that is top left corner of the matrix. Then she goes down all the way to cell (n, 1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. n and m given are such that she always end up in cell (1, 2).Lara has already moved to a neighbouring cell k times. Can you determine her current position?InputThe only line contains three integers n, m and k (2 ≤ n, m ≤ 109, n is always even, 0 ≤ k < n·m). Note that k doesn't fit into 32-bit integer type!OutputPrint the cell (the row and the column where the cell is situated) where Lara ends up after she moves k times.ExamplesInput4 3 0Output1 1Input4 3 11Output1 2Input4 3 7Output3 2NoteHere is her path on matrix 4 by 3: | Input4 3 0 | Output1 1 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1300'] |
A. Minimum Binary Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputString can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".You are given a correct string s.You can perform two different operations on this string: swap any pair of adjacent characters (for example, "101" "110"); replace "11" with "1" (for example, "110" "10"). Let val(s) be such a number that s is its binary representation.Correct string a is less than some other correct string b iff val(a) < val(b).Your task is to find the minimum correct string that you can obtain from the given one using the operations described above. You can use these operations any number of times in any order (or even use no operations at all).InputThe first line contains integer number n (1 ≤ n ≤ 100) — the length of string s.The second line contains the string s consisting of characters "0" and "1". It is guaranteed that the string s is correct.OutputPrint one string — the minimum correct string that you can obtain from the given one.ExamplesInput41001Output100Input11Output1NoteIn the first example you can obtain the answer by the following sequence of operations: "1001" "1010" "1100" "100".In the second example you can't obtain smaller answer no matter what operations you use. | Input41001 | Output100 | 1 second | 256 megabytes | ['implementation', '*800'] |
E. Hag's Khashbatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHag is a very talented person. He has always had an artist inside him but his father forced him to study mechanical engineering.Yesterday he spent all of his time cutting a giant piece of wood trying to make it look like a goose. Anyway, his dad found out that he was doing arts rather than studying mechanics and other boring subjects. He confronted Hag with the fact that he is a spoiled son that does not care about his future, and if he continues to do arts he will cut his 25 Lira monthly allowance.Hag is trying to prove to his dad that the wooden piece is a project for mechanics subject. He also told his dad that the wooden piece is a strictly convex polygon with n vertices.Hag brought two pins and pinned the polygon with them in the 1-st and 2-nd vertices to the wall. His dad has q queries to Hag of two types. 1 f t: pull a pin from the vertex f, wait for the wooden polygon to rotate under the gravity force (if it will rotate) and stabilize. And then put the pin in vertex t. 2 v: answer what are the coordinates of the vertex v. Please help Hag to answer his father's queries.You can assume that the wood that forms the polygon has uniform density and the polygon has a positive thickness, same in all points. After every query of the 1-st type Hag's dad tries to move the polygon a bit and watches it stabilize again.InputThe first line contains two integers n and q (3\leq n \leq 10\,000, 1 \leq q \leq 200000) — the number of vertices in the polygon and the number of queries.The next n lines describe the wooden polygon, the i-th line contains two integers x_i and y_i (|x_i|, |y_i|\leq 10^8) — the coordinates of the i-th vertex of the polygon. It is guaranteed that polygon is strictly convex and the vertices are given in the counter-clockwise order and all vertices are distinct.The next q lines describe the queries, one per line. Each query starts with its type 1 or 2. Each query of the first type continues with two integers f and t (1 \le f, t \le n) — the vertex the pin is taken from, and the vertex the pin is put to and the polygon finishes rotating. It is guaranteed that the vertex f contains a pin. Each query of the second type continues with a single integer v (1 \le v \le n) — the vertex the coordinates of which Hag should tell his father.It is guaranteed that there is at least one query of the second type.OutputThe output should contain the answer to each query of second type — two numbers in a separate line. Your answer is considered correct, if its absolute or relative error does not exceed 10^{-4}.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}ExamplesInput3 40 02 02 21 1 22 12 22 3Output3.4142135624 -1.41421356242.0000000000 0.00000000000.5857864376 -1.4142135624Input3 2-1 10 01 11 1 22 1Output1.0000000000 -1.0000000000NoteIn the first test note the initial and the final state of the wooden polygon. Red Triangle is the initial state and the green one is the triangle after rotation around (2,0).In the second sample note that the polygon rotates 180 degrees counter-clockwise or clockwise direction (it does not matter), because Hag's father makes sure that the polygon is stable and his son does not trick him. | Input3 40 02 02 21 1 22 12 22 3 | Output3.4142135624 -1.41421356242.0000000000 0.00000000000.5857864376 -1.4142135624 | 3 seconds | 256 megabytes | ['geometry', '*2600'] |
D. Ghoststime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGhosts live in harmony and peace, they travel the space without any purpose other than scare whoever stands in their way.There are n ghosts in the universe, they move in the OXY plane, each one of them has its own velocity that does not change in time: \overrightarrow{V} = V_{x}\overrightarrow{i} + V_{y}\overrightarrow{j} where V_{x} is its speed on the x-axis and V_{y} is on the y-axis.A ghost i has experience value EX_i, which represent how many ghosts tried to scare him in his past. Two ghosts scare each other if they were in the same cartesian point at a moment of time.As the ghosts move with constant speed, after some moment of time there will be no further scaring (what a relief!) and the experience of ghost kind GX = \sum_{i=1}^{n} EX_i will never increase.Tameem is a red giant, he took a picture of the cartesian plane at a certain moment of time T, and magically all the ghosts were aligned on a line of the form y = a \cdot x + b. You have to compute what will be the experience index of the ghost kind GX in the indefinite future, this is your task for today.Note that when Tameem took the picture, GX may already be greater than 0, because many ghosts may have scared one another at any moment between [-\infty, T].InputThe first line contains three integers n, a and b (1 \leq n \leq 200000, 1 \leq |a| \leq 10^9, 0 \le |b| \le 10^9) — the number of ghosts in the universe and the parameters of the straight line.Each of the next n lines contains three integers x_i, V_{xi}, V_{yi} (-10^9 \leq x_i \leq 10^9, -10^9 \leq V_{x i}, V_{y i} \leq 10^9), where x_i is the current x-coordinate of the i-th ghost (and y_i = a \cdot x_i + b).It is guaranteed that no two ghosts share the same initial position, in other words, it is guaranteed that for all (i,j) x_i \neq x_j for i \ne j.OutputOutput one line: experience index of the ghost kind GX in the indefinite future.ExamplesInput4 1 11 -1 -12 1 13 1 14 -1 -1Output8Input3 1 0-1 1 00 0 -11 -1 -2Output6Input3 1 00 0 01 0 02 0 0Output0NoteThere are four collisions (1,2,T-0.5), (1,3,T-1), (2,4,T+1), (3,4,T+0.5), where (u,v,t) means a collision happened between ghosts u and v at moment t. At each collision, each ghost gained one experience point, this means that GX = 4 \cdot 2 = 8.In the second test, all points will collide when t = T + 1. The red arrow represents the 1-st ghost velocity, orange represents the 2-nd ghost velocity, and blue represents the 3-rd ghost velocity. | Input4 1 11 -1 -12 1 13 1 14 -1 -1 | Output8 | 2 seconds | 256 megabytes | ['geometry', 'math', '*2000'] |
C. Valhalla Siegetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIvar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has n warriors, he places them on a straight line in front of the main gate, in a way that the i-th warrior stands right after (i-1)-th warrior. The first warrior leads the attack.Each attacker can take up to a_i arrows before he falls to the ground, where a_i is the i-th warrior's strength.Lagertha orders her warriors to shoot k_i arrows during the i-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute t, they will all be standing to fight at the end of minute t.The battle will last for q minutes, after each minute you should tell Ivar what is the number of his standing warriors.InputThe first line contains two integers n and q (1 \le n, q \leq 200\,000) — the number of warriors and the number of minutes in the battle.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) that represent the warriors' strengths.The third line contains q integers k_1, k_2, \ldots, k_q (1 \leq k_i \leq 10^{14}), the i-th of them represents Lagertha's order at the i-th minute: k_i arrows will attack the warriors.OutputOutput q lines, the i-th of them is the number of standing warriors after the i-th minute.ExamplesInput5 51 2 1 2 13 10 1 1 1Output35443Input4 41 2 3 49 1 10 6Output1441NoteIn the first example: after the 1-st minute, the 1-st and 2-nd warriors die. after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive. after the 3-rd minute, the 1-st warrior dies. after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1. after the 5-th minute, the 2-nd warrior dies. | Input5 51 2 1 2 13 10 1 1 1 | Output35443 | 2 seconds | 256 megabytes | ['binary search', '*1400'] |
B. Mancalatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.InputThe only line contains 14 integers a_1, a_2, \ldots, a_{14} (0 \leq a_i \leq 10^9) — the number of stones in each hole.It is guaranteed that for any i (1\leq i \leq 14) a_i is either zero or odd, and there is at least one stone in the board.OutputOutput one integer, the maximum possible score after one move.ExamplesInput0 1 1 0 0 0 0 0 0 7 0 0 0 0Output4Input5 1 1 1 1 0 0 0 0 0 0 0 0 0Output8NoteIn the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4. | Input0 1 1 0 0 0 0 0 0 7 0 0 0 0 | Output4 | 1 second | 256 megabytes | ['brute force', 'implementation', '*1100'] |
A. Aramic scripttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Aramic language words can only represent objects.Words in Aramic have special properties: A word is a root if it does not contain the same letter more than once. A root and all its permutations represent the same object. The root x of a word y is the word that contains all letters that appear in y in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?InputThe first line contains one integer n (1 \leq n \leq 10^3) — the number of words in the script.The second line contains n words s_1, s_2, \ldots, s_n — the script itself. The length of each string does not exceed 10^3.It is guaranteed that all characters of the strings are small latin letters.OutputOutput one integer — the number of different objects mentioned in the given ancient Aramic script.ExamplesInput5a aa aaa ab abbOutput2Input3amer arem mreaOutput1NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer". | Input5a aa aaa ab abb | Output2 | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
B. Watering Systemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady wants to water his only flower. Unfortunately, he has a very poor watering system that was designed for n flowers and so it looks like a pipe with n holes. Arkady can only use the water that flows from the first hole.Arkady can block some of the holes, and then pour A liters of water into the pipe. After that, the water will flow out from the non-blocked holes proportionally to their sizes s_1, s_2, \ldots, s_n. In other words, if the sum of sizes of non-blocked holes is S, and the i-th hole is not blocked, \frac{s_i \cdot A}{S} liters of water will flow out of it.What is the minimum number of holes Arkady should block to make at least B liters of water flow out of the first hole?InputThe first line contains three integers n, A, B (1 \le n \le 100\,000, 1 \le B \le A \le 10^4) — the number of holes, the volume of water Arkady will pour into the system, and the volume he wants to get out of the first hole.The second line contains n integers s_1, s_2, \ldots, s_n (1 \le s_i \le 10^4) — the sizes of the holes.OutputPrint a single integer — the number of holes Arkady should block.ExamplesInput4 10 32 2 2 2Output1Input4 80 203 2 1 4Output0Input5 10 101000 1 1 1 1Output4NoteIn the first example Arkady should block at least one hole. After that, \frac{10 \cdot 2}{6} \approx 3.333 liters of water will flow out of the first hole, and that suits Arkady.In the second example even without blocking any hole, \frac{80 \cdot 3}{10} = 24 liters will flow out of the first hole, that is not less than 20.In the third example Arkady has to block all holes except the first to make all water flow out of the first hole. | Input4 10 32 2 2 2 | Output1 | 1 second | 256 megabytes | ['math', 'sortings', '*1000'] |
A. Mind the Gaptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThese days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute.He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least s minutes from both sides.Find the earliest time when Arkady can insert the takeoff.InputThe first line of input contains two integers n and s (1 \le n \le 100, 1 \le s \le 60) — the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff.Each of next n lines contains two integers h and m (0 \le h \le 23, 0 \le m \le 59) — the time, in hours and minutes, when a plane will land, starting from current moment (i. e. the current time is 0 0). These times are given in increasing order.OutputPrint two integers h and m — the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff.ExamplesInput6 600 01 203 215 019 3023 40Output6 1Input16 500 301 203 04 306 107 509 3011 1012 5014 3016 1017 5019 3021 1022 5023 59Output24 50Input3 170 301 012 0Output0 0NoteIn the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute.In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than 24 hours to insert the takeoff.In the third example Arkady can insert the takeoff even between the first landing. | Input6 600 01 203 215 019 3023 40 | Output6 1 | 1 second | 256 megabytes | ['implementation', '*1100'] |
E. Short Codetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady's code contains n variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.A string a is a prefix of a string b if you can delete some (possibly none) characters from the end of b and obtain a.Please find this minimum possible total length of new names.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of variables.The next n lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than 10^5. The variable names are distinct.OutputPrint a single integer — the minimum possible total length of new variable names.ExamplesInput3codeforcescodehorsescodeOutput6Input5abbaabbabaaaacadaOutput11Input3telegramdigitalresistanceOutput3NoteIn the first example one of the best options is to shorten the names in the given order as "cod", "co", "c".In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names. | Input3codeforcescodehorsescode | Output6 | 1 second | 256 megabytes | ['data structures', 'dp', 'greedy', 'strings', 'trees', '*2200'] |
D. Single-use Stonestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them.The stones are located at integer distances from the banks. There are a_i stones at the distance of i units from the bank the frogs are currently at. Each stone can only be used once by one frog, after that it drowns in the water.What is the maximum number of frogs that can cross the river, given that then can only jump on the stones?InputThe first line contains two integers w and l (1 \le l < w \le 10^5) — the width of the river and the maximum length of a frog's jump.The second line contains w - 1 integers a_1, a_2, \ldots, a_{w-1} (0 \le a_i \le 10^4), where a_i is the number of stones at the distance i from the bank the frogs are currently at.OutputPrint a single integer — the maximum number of frogs that can cross the river.ExamplesInput10 50 0 1 0 2 0 0 1 0Output3Input10 31 1 1 1 2 1 1 1 1Output3NoteIn the first sample two frogs can use the different stones at the distance 5, and one frog can use the stones at the distances 3 and then 8.In the second sample although there are two stones at the distance 5, that does not help. The three paths are: 0 \to 3 \to 6 \to 9 \to 10, 0 \to 2 \to 5 \to 8 \to 10, 0 \to 1 \to 4 \to 7 \to 10. | Input10 50 0 1 0 2 0 0 1 0 | Output3 | 1 second | 256 megabytes | ['binary search', 'flows', 'greedy', 'two pointers', '*1900'] |
C. Greedy Arkadytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputk people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away.The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second person, the next x candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by x) will be thrown away.Arkady can't choose x greater than M as it is considered greedy. Also, he can't choose such a small x that some person will receive candies more than D times, as it is considered a slow splitting.Please find what is the maximum number of candies Arkady can receive by choosing some valid x.InputThe only line contains four integers n, k, M and D (2 \le n \le 10^{18}, 2 \le k \le n, 1 \le M \le n, 1 \le D \le \min{(n, 1000)}, M \cdot D \cdot k \ge n) — the number of candies, the number of people, the maximum number of candies given to a person at once, the maximum number of times a person can receive candies.OutputPrint a single integer — the maximum possible number of candies Arkady can give to himself.Note that it is always possible to choose some valid x.ExamplesInput20 4 5 2Output8Input30 9 4 1Output4NoteIn the first example Arkady should choose x = 4. He will give 4 candies to himself, 4 candies to the second person, 4 candies to the third person, then 4 candies to the fourth person and then again 4 candies to himself. No person is given candies more than 2 times, and Arkady receives 8 candies in total.Note that if Arkady chooses x = 5, he will receive only 5 candies, and if he chooses x = 3, he will receive only 3 + 3 = 6 candies as well as the second person, the third and the fourth persons will receive 3 candies, and 2 candies will be thrown away. He can't choose x = 1 nor x = 2 because in these cases he will receive candies more than 2 times.In the second example Arkady has to choose x = 4, because any smaller value leads to him receiving candies more than 1 time. | Input20 4 5 2 | Output8 | 1 second | 256 megabytes | ['math', '*2000'] |
B. Battleshiptime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady is playing Battleship. The rules of this game aren't really important.There is a field of n \times n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.InputThe first line contains two integers n and k (1 \le k \le n \le 100) — the size of the field and the size of the ship.The next n lines contain the field. Each line contains n characters, each of which is either '#' (denotes a definitely empty cell) or '.' (denotes a cell that can belong to the ship).OutputOutput two integers — the row and the column of a cell that belongs to the maximum possible number of different locations of the ship.If there are multiple answers, output any of them. In particular, if no ship can be placed on the field, you can output any cell.ExamplesInput4 3#..##.#......###Output3 2Input10 4#....##....#...#......#..#..#....#.#.....#..##.#.......#...#...#.##....#...#.#.......#..#....#.#...#Output6 1Input19 6##..............####......#####.....##.....#########.........###########.......#############.....###############...#################..#################..#################..#################.#####....##....########............#######............########...####...####.#####..####..#####...###........###......###########.............##........#.................#Output1 8NoteThe picture below shows the three possible locations of the ship that contain the cell (3, 2) in the first sample. | Input4 3#..##.#......### | Output3 2 | 1.5 seconds | 256 megabytes | ['implementation', '*1300'] |
A. Paper Airplanestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo make a paper airplane, one has to use a rectangular piece of paper. From a sheet of standard size you can make s airplanes.A group of k people decided to make n airplanes each. They are going to buy several packs of paper, each of them containing p sheets, and then distribute the sheets between the people. Each person should have enough sheets to make n airplanes. How many packs should they buy?InputThe only line contains four integers k, n, s, p (1 \le k, n, s, p \le 10^4) — the number of people, the number of airplanes each should make, the number of airplanes that can be made using one sheet and the number of sheets in one pack, respectively.OutputPrint a single integer — the minimum number of packs they should buy.ExamplesInput5 3 2 3Output4Input5 3 100 1Output5NoteIn the first sample they have to buy 4 packs of paper: there will be 12 sheets in total, and giving 2 sheets to each person is enough to suit everyone's needs.In the second sample they have to buy a pack for each person as they can't share sheets. | Input5 3 2 3 | Output4 | 1 second | 256 megabytes | ['math', '*800'] |
B. Messagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.InputThe first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000).The second string contains n integers ti (1 ≤ ti ≤ T).OutputOutput one integer — the answer to the problem.ExamplesInput4 5 5 3 51 5 5 4Output20Input5 3 1 1 32 2 2 1 1Output15Input5 5 3 4 51 2 3 4 5Output35NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 = - 5 points. This is 35 in total. | Input4 5 5 3 51 5 5 4 | Output20 | 1 second | 256 megabytes | ['math', '*1300'] |
A. Splitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a split of n as a nonincreasing sequence of positive integers, the sum of which is n. For example, the following sequences are splits of 8: [4, 4], [3, 3, 2], [2, 2, 1, 1, 1, 1], [5, 2, 1].The following sequences aren't splits of 8: [1, 7], [5, 4], [11, -3], [1, 1, 4, 1, 1].The weight of a split is the number of elements in the split that are equal to the first element. For example, the weight of the split [1, 1, 1, 1, 1] is 5, the weight of the split [5, 5, 3, 3, 3] is 2 and the weight of the split [9] equals 1.For a given n, find out the number of different weights of its splits.InputThe first line contains one integer n (1 \leq n \leq 10^9).OutputOutput one integer — the answer to the problem.ExamplesInput7Output4Input8Output5Input9Output5NoteIn the first sample, there are following possible weights of splits of 7:Weight 1: [\textbf 7] Weight 2: [\textbf 3, \textbf 3, 1] Weight 3: [\textbf 2, \textbf 2, \textbf 2, 1] Weight 7: [\textbf 1, \textbf 1, \textbf 1, \textbf 1, \textbf 1, \textbf 1, \textbf 1] | Input7 | Output4 | 1 second | 256 megabytes | ['math', '*800'] |
E. Circles of Waitingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA chip was placed on a field with coordinate system onto point (0, 0).Every second the chip moves randomly. If the chip is currently at a point (x, y), after a second it moves to the point (x - 1, y) with probability p1, to the point (x, y - 1) with probability p2, to the point (x + 1, y) with probability p3 and to the point (x, y + 1) with probability p4. It's guaranteed that p1 + p2 + p3 + p4 = 1. The moves are independent.Find out the expected time after which chip will move away from origin at a distance greater than R (i.e. will be satisfied).InputFirst line contains five integers R, a1, a2, a3 and a4 (0 ≤ R ≤ 50, 1 ≤ a1, a2, a3, a4 ≤ 1000).Probabilities pi can be calculated using formula .OutputIt can be shown that answer for this problem is always a rational number of form , where .Print P·Q - 1 modulo 109 + 7. ExamplesInput0 1 1 1 1Output1Input1 1 1 1 1Output666666674Input1 1 2 1 2Output538461545NoteIn the first example initially the chip is located at a distance 0 from origin. In one second chip will move to distance 1 is some direction, so distance to origin will become 1.Answers to the second and the third tests: and . | Input0 1 1 1 1 | Output1 | 2 seconds | 256 megabytes | ['math', '*3100'] |
D. Frequency of Stringtime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s. You should answer n queries. The i-th query consists of integer k_i and string m_i. The answer for this query is the minimum length of such a string t that t is a substring of s and m_i has at least k_i occurrences as a substring in t.A substring of a string is a continuous segment of characters of the string.It is guaranteed that for any two queries the strings m_i from these queries are different. InputThe first line contains string s (1 \leq \left | s \right | \leq 10^{5}).The second line contains an integer n (1 \leq n \leq 10^5).Each of next n lines contains an integer k_i (1 \leq k_i \leq |s|) and a non-empty string m_i — parameters of the query with number i, in this order.All strings in input consists of lowercase English letters. Sum of length of all strings in input doesn't exceed 10^5. All m_i are distinct.OutputFor each query output the answer for it in a separate line.If a string m_{i} occurs in s less that k_{i} times, output -1.ExamplesInputaaaaa53 a3 aa2 aaa3 aaaa1 aaaaaOutput344-15Inputabbb74 b1 ab3 bb1 abb2 bbb1 a2 abbbOutput-12-13-11-1 | Inputaaaaa53 a3 aa2 aaa3 aaaa1 aaaaa | Output344-15 | 1.5 seconds | 512 megabytes | ['hashing', 'string suffix structures', 'strings', '*2500'] |
C. Cutting Rectangletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA rectangle with sides A and B is cut into rectangles with cuts parallel to its sides. For example, if p horizontal and q vertical cuts were made, (p + 1) \cdot (q + 1) rectangles were left after the cutting. After the cutting, rectangles were of n different types. Two rectangles are different if at least one side of one rectangle isn't equal to the corresponding side of the other. Note that the rectangle can't be rotated, this means that rectangles a \times b and b \times a are considered different if a \neq b.For each type of rectangles, lengths of the sides of rectangles are given along with the amount of the rectangles of this type that were left after cutting the initial rectangle.Calculate the amount of pairs (A; B) such as the given rectangles could be created by cutting the rectangle with sides of lengths A and B. Note that pairs (A; B) and (B; A) are considered different when A \neq B.InputThe first line consists of a single integer n (1 \leq n \leq 2 \cdot 10^{5}) — amount of different types of rectangles left after cutting the initial rectangle.The next n lines each consist of three integers w_{i}, h_{i}, c_{i} (1 \leq w_{i}, h_{i}, c_{i} \leq 10^{12}) — the lengths of the sides of the rectangles of this type and the amount of the rectangles of this type.It is guaranteed that the rectangles of the different types are different.OutputOutput one integer — the answer to the problem.ExamplesInput11 1 9Output3Input22 3 202 4 40Output6Input21 2 52 3 5Output0NoteIn the first sample there are three suitable pairs: (1; 9), (3; 3) and (9; 1).In the second sample case there are 6 suitable pairs: (2; 220), (4; 110), (8; 55), (10; 44), (20; 22) and (40; 11).Here the sample of cut for (20; 22). The third sample has no suitable pairs. | Input11 1 9 | Output3 | 2 seconds | 256 megabytes | ['brute force', 'math', 'number theory', '*2600'] |
B. Destruction of a Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree (a graph with n vertices and n - 1 edges in which it's possible to reach any vertex from any other vertex using only its edges).A vertex can be destroyed if this vertex has even degree. If you destroy a vertex, all edges connected to it are also deleted.Destroy all vertices in the given tree or determine that it is impossible.InputThe first line contains integer n (1 ≤ n ≤ 2·105) — number of vertices in a tree.The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ n). If pi ≠ 0 there is an edge between vertices i and pi. It is guaranteed that the given graph is a tree.OutputIf it's possible to destroy all vertices, print "YES" (without quotes), otherwise print "NO" (without quotes).If it's possible to destroy all vertices, in the next n lines print the indices of the vertices in order you destroy them. If there are multiple correct answers, print any.ExamplesInput50 1 2 1 2OutputYES12354Input40 1 2 3OutputNONoteIn the first example at first you have to remove the vertex with index 1 (after that, the edges (1, 2) and (1, 4) are removed), then the vertex with index 2 (and edges (2, 3) and (2, 5) are removed). After that there are no edges in the tree, so you can remove remaining vertices in any order. | Input50 1 2 1 2 | OutputYES12354 | 1 second | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*2000'] |
A. Alternating Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers a and b. Moreover, you are given a sequence s_0, s_1, \dots, s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k \leq i \leq n it's satisfied that s_{i} = s_{i - k}.Find out the non-negative remainder of division of \sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i} by 10^{9} + 9.Note that the modulo is unusual!InputThe first line contains four integers n, a, b and k (1 \leq n \leq 10^{9}, 1 \leq a, b \leq 10^{9}, 1 \leq k \leq 10^{5}).The second line contains a sequence of length k consisting of characters '+' and '-'. If the i-th character (0-indexed) is '+', then s_{i} = 1, otherwise s_{i} = -1.Note that only the first k members of the sequence are given, the rest can be obtained using the periodicity property.OutputOutput a single integer — value of given expression modulo 10^{9} + 9.ExamplesInput2 2 3 3+-+Output7Input4 1 5 1-Output999999228NoteIn the first example:(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = 2^{2} 3^{0} - 2^{1} 3^{1} + 2^{0} 3^{2} = 7In the second example:(\sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i}) = -1^{4} 5^{0} - 1^{3} 5^{1} - 1^{2} 5^{2} - 1^{1} 5^{3} - 1^{0} 5^{4} = -781 \equiv 999999228 \pmod{10^{9} + 9}. | Input2 2 3 3+-+ | Output7 | 1 second | 256 megabytes | ['math', 'number theory', '*1800'] |
G. Visible Black Areastime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has a polygon consisting of n vertices. All sides of the Petya's polygon are parallel to the coordinate axes, and each two adjacent sides of the Petya's polygon are perpendicular. It is guaranteed that the polygon is simple, that is, it doesn't have self-intersections and self-touches. All internal area of the polygon (borders are not included) was painted in black color by Petya.Also, Petya has a rectangular window, defined by its coordinates, through which he looks at the polygon. A rectangular window can not be moved. The sides of the rectangular window are parallel to the coordinate axes. Blue color represents the border of a polygon, red color is the Petya's window. The answer in this case is 2. Determine the number of black connected areas of Petya's polygon, which can be seen through the rectangular window.InputThe first line contain four integers x_1, y_1, x_2, y_2 (x_1 < x_2, y_2 < y_1) — the coordinates of top-left and bottom-right corners of the rectangular window. The second line contains a single integer n (4 \le n \le 15\,000) — the number of vertices in Petya's polygon.Each of the following n lines contains two integers — the coordinates of vertices of the Petya's polygon in counterclockwise order. Guaranteed, that the given polygon satisfies the conditions described in the statement.All coordinates of the rectangular window and all coordinates of the vertices of the polygon are non-negative and do not exceed 15\,000.OutputPrint the number of black connected areas of Petya's polygon, which can be seen through the rectangular window.ExampleInput5 7 16 3160 018 018 616 616 110 110 47 47 22 22 612 612 1210 1210 80 8Output2NoteThe example corresponds to the picture above. | Input5 7 16 3160 018 018 616 616 110 110 47 47 22 22 612 612 1210 1210 80 8 | Output2 | 1 second | 256 megabytes | ['data structures', 'dsu', 'geometry', 'trees', '*2800'] |
F. Simple Cycles Edgestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph, consisting of n vertices and m edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself).A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle.Determine the edges, which belong to exactly on one simple cycle.InputThe first line contain two integers n and m (1 \le n \le 100\,000, 0 \le m \le \min(n \cdot (n - 1) / 2, 100\,000)) — the number of vertices and the number of edges.Each of the following m lines contain two integers u and v (1 \le u, v \le n, u \neq v) — the description of the edges.OutputIn the first line print the number of edges, which belong to exactly one simple cycle.In the second line print the indices of edges, which belong to exactly one simple cycle, in increasing order. The edges are numbered from one in the same order as they are given in the input.ExamplesInput3 31 22 33 1Output31 2 3 Input6 72 33 44 21 21 55 66 1Output61 2 3 5 6 7 Input5 61 22 32 44 32 55 3Output0 | Input3 31 22 33 1 | Output31 2 3 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'trees', '*2400'] |
E. Byteland, Berland and Disputed Citiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe cities of Byteland and Berland are located on the axis Ox. In addition, on this axis there are also disputed cities, which belong to each of the countries in their opinion. Thus, on the line Ox there are three types of cities: the cities of Byteland, the cities of Berland, disputed cities. Recently, the project BNET has been launched — a computer network of a new generation. Now the task of the both countries is to connect the cities so that the network of this country is connected.The countries agreed to connect the pairs of cities with BNET cables in such a way that: If you look at the only cities of Byteland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables, If you look at the only cities of Berland and the disputed cities, then in the resulting set of cities, any city should be reachable from any other one by one or more cables. Thus, it is necessary to choose a set of pairs of cities to connect by cables in such a way that both conditions are satisfied simultaneously. Cables allow bi-directional data transfer. Each cable connects exactly two distinct cities.The cost of laying a cable from one city to another is equal to the distance between them. Find the minimum total cost of laying a set of cables so that two subsets of cities (Byteland and disputed cities, Berland and disputed cities) are connected.Each city is a point on the line Ox. It is technically possible to connect the cities a and b with a cable so that the city c (a < c < b) is not connected to this cable, where a, b and c are simultaneously coordinates of the cities a, b and c.InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^{5}) — the number of cities.The following n lines contains an integer x_i and the letter c_i (-10^{9} \le x_i \le 10^{9}) — the coordinate of the city and its type. If the city belongs to Byteland, c_i equals to 'B'. If the city belongs to Berland, c_i equals to «R». If the city is disputed, c_i equals to 'P'. All cities have distinct coordinates. Guaranteed, that the cities are given in the increasing order of their coordinates.OutputPrint the minimal total length of such set of cables, that if we delete all Berland cities (c_i='R'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables. Similarly, if we delete all Byteland cities (c_i='B'), it will be possible to find a way from any remaining city to any other remaining city, moving only by cables.ExamplesInput4-5 R0 P3 P7 BOutput12Input510 R14 B16 B21 R32 ROutput24NoteIn the first example, you should connect the first city with the second, the second with the third, and the third with the fourth. The total length of the cables will be 5 + 3 + 4 = 12.In the second example there are no disputed cities, so you need to connect all the neighboring cities of Byteland and all the neighboring cities of Berland. The cities of Berland have coordinates 10, 21, 32, so to connect them you need two cables of length 11 and 11. The cities of Byteland have coordinates 14 and 16, so to connect them you need one cable of length 2. Thus, the total length of all cables is 11 + 11 + 2 = 24. | Input4-5 R0 P3 P7 B | Output12 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*2200'] |
D. Merge Equalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers. While there are at least two equal elements, we will perform the following operation. We choose the smallest value x that occurs in the array 2 or more times. Take the first two occurrences of x in this array (the two leftmost occurrences). Remove the left of these two occurrences, and the right one is replaced by the sum of this two values (that is, 2 \cdot x).Determine how the array will look after described operations are performed.For example, consider the given array looks like [3, 4, 1, 2, 2, 1, 1]. It will be changed in the following way: [3, 4, 1, 2, 2, 1, 1]~\rightarrow~[3, 4, 2, 2, 2, 1]~\rightarrow~[3, 4, 4, 2, 1]~\rightarrow~[3, 8, 2, 1].If the given array is look like [1, 1, 3, 1, 1] it will be changed in the following way: [1, 1, 3, 1, 1]~\rightarrow~[2, 3, 1, 1]~\rightarrow~[2, 3, 2]~\rightarrow~[3, 4].InputThe first line contains a single integer n (2 \le n \le 150\,000) — the number of elements in the array.The second line contains a sequence from n elements a_1, a_2, \dots, a_n (1 \le a_i \le 10^{9}) — the elements of the array.OutputIn the first line print an integer k — the number of elements in the array after all the performed operations. In the second line print k integers — the elements of the array after all the performed operations.ExamplesInput73 4 1 2 2 1 1Output43 8 2 1 Input51 1 3 1 1Output23 4 Input510 40 20 50 30Output510 40 20 50 30 NoteThe first two examples were considered in the statement.In the third example all integers in the given array are distinct, so it will not change. | Input73 4 1 2 2 1 1 | Output43 8 2 1 | 2 seconds | 256 megabytes | ['data structures', 'implementation', '*1600'] |
C. Make a Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.Determine the minimum number of operations that you need to consistently apply to the given integer n to make from it the square of some positive integer or report that it is impossible.An integer x is the square of some positive integer if and only if x=y^2 for some positive integer y.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^{9}). The number is given without leading zeroes.OutputIf it is impossible to make the square of some positive integer from n, print -1. In the other case, print the minimal number of operations required to do it.ExamplesInput8314Output2Input625Output0Input333Output-1NoteIn the first example we should delete from 8314 the digits 3 and 4. After that 8314 become equals to 81, which is the square of the integer 9.In the second example the given 625 is the square of the integer 25, so you should not delete anything. In the third example it is impossible to make the square from 333, so the answer is -1. | Input8314 | Output2 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*1400'] |
B. Students in Railway Carriagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of a student-programmers and b student-athletes. Determine the largest number of students from all a+b students, which you can put in the railway carriage so that: no student-programmer is sitting next to the student-programmer; and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).InputThe first line contain three integers n, a and b (1 \le n \le 2\cdot10^{5}, 0 \le a, b \le 2\cdot10^{5}, a + b > 0) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes.The second line contains a string with length n, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.OutputPrint the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.ExamplesInput5 1 1*...*Output2Input6 2 3*...*.Output4Input11 3 10.*....**.*.Output7Input3 2 3***Output0NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete. | Input5 1 1*...* | Output2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'implementation', '*1300'] |
A. Equatortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has created his own training plan to prepare for the programming contests. He will train for n days, all days are numbered from 1 to n, beginning from the first.On the i-th day Polycarp will necessarily solve a_i problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.InputThe first line contains a single integer n (1 \le n \le 200\,000) — the number of days to prepare for the programming contests.The second line contains a sequence a_1, a_2, \dots, a_n (1 \le a_i \le 10\,000), where a_i equals to the number of problems, which Polycarp will solve on the i-th day.OutputPrint the index of the day when Polycarp will celebrate the equator.ExamplesInput41 3 2 1Output2Input62 2 2 2 2 2Output3NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve 4 out of 7 scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve 6 out of 12 scheduled problems on six days of the training. | Input41 3 2 1 | Output2 | 2 seconds | 256 megabytes | ['implementation', '*1300'] |
G. Partitionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of n elements indexed from 1 to n. The weight of i-th element is wi. The weight of some subset of a given set is denoted as . The weight of some partition R of a given set into k subsets is (recall that a partition of a given set is a set of its subsets such that every element of the given set belongs to exactly one subset in partition).Calculate the sum of weights of all partitions of a given set into exactly k non-empty subsets, and print it modulo 109 + 7. Two partitions are considered different iff there exist two elements x and y such that they belong to the same set in one of the partitions, and to different sets in another partition.InputThe first line contains two integers n and k (1 ≤ k ≤ n ≤ 2·105) — the number of elements and the number of subsets in each partition, respectively.The second line contains n integers wi (1 ≤ wi ≤ 109)— weights of elements of the set.OutputPrint one integer — the sum of weights of all partitions of a given set into k non-empty subsets, taken modulo 109 + 7.ExamplesInput4 22 3 2 3Output160Input5 21 2 3 4 5Output645NotePossible partitions in the first sample: {{1, 2, 3}, {4}}, W(R) = 3·(w1 + w2 + w3) + 1·w4 = 24; {{1, 2, 4}, {3}}, W(R) = 26; {{1, 3, 4}, {2}}, W(R) = 24; {{1, 2}, {3, 4}}, W(R) = 2·(w1 + w2) + 2·(w3 + w4) = 20; {{1, 3}, {2, 4}}, W(R) = 20; {{1, 4}, {2, 3}}, W(R) = 20; {{1}, {2, 3, 4}}, W(R) = 26; Possible partitions in the second sample: {{1, 2, 3, 4}, {5}}, W(R) = 45; {{1, 2, 3, 5}, {4}}, W(R) = 48; {{1, 2, 4, 5}, {3}}, W(R) = 51; {{1, 3, 4, 5}, {2}}, W(R) = 54; {{2, 3, 4, 5}, {1}}, W(R) = 57; {{1, 2, 3}, {4, 5}}, W(R) = 36; {{1, 2, 4}, {3, 5}}, W(R) = 37; {{1, 2, 5}, {3, 4}}, W(R) = 38; {{1, 3, 4}, {2, 5}}, W(R) = 38; {{1, 3, 5}, {2, 4}}, W(R) = 39; {{1, 4, 5}, {2, 3}}, W(R) = 40; {{2, 3, 4}, {1, 5}}, W(R) = 39; {{2, 3, 5}, {1, 4}}, W(R) = 40; {{2, 4, 5}, {1, 3}}, W(R) = 41; {{3, 4, 5}, {1, 2}}, W(R) = 42. | Input4 22 3 2 3 | Output160 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'number theory', '*2700'] |
F. k-substringstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters.Let's denote k-substring of s as a string subsk = sksk + 1..sn + 1 - k. Obviously, subs1 = s, and there are exactly such substrings.Let's call some string t an odd proper suprefix of a string T iff the following conditions are met: |T| > |t|; |t| is an odd number; t is simultaneously a prefix and a suffix of T.For evey k-substring () of s you have to calculate the maximum length of its odd proper suprefix.InputThe first line contains one integer n (2 ≤ n ≤ 106) — the length s.The second line contains the string s consisting of n lowercase Latin letters.OutputPrint integers. i-th of them should be equal to maximum length of an odd proper suprefix of i-substring of s (or - 1, if there is no such string that is an odd proper suprefix of i-substring).ExamplesInput15bcabcabcabcabcaOutput9 7 5 3 1 -1 -1 -1Input24abaaabaaaabaaabaaaabaaabOutput15 13 11 9 7 5 3 1 1 -1 -1 1Input19cabcabbcabcabbcabcaOutput5 3 1 -1 -1 1 1 -1 -1 -1NoteThe answer for first sample test is folowing: 1-substring: bcabcabcabcabca 2-substring: cabcabcabcabc 3-substring: abcabcabcab 4-substring: bcabcabca 5-substring: cabcabc 6-substring: abcab 7-substring: bca 8-substring: c | Input15bcabcabcabcabca | Output9 7 5 3 1 -1 -1 -1 | 4 seconds | 256 megabytes | ['binary search', 'hashing', 'string suffix structures', '*2700'] |
E. Tufuramatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!InputThe first line contains one integer n (1 ≤ n ≤ 2·105) — the number of seasons.The second line contains n integers separated by space a1, a2, ..., an (1 ≤ ai ≤ 109) — number of episodes in each season.OutputPrint one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.ExamplesInput51 2 3 4 5Output0Input38 12 7Output3Input33 2 1Output2NotePossible pairs in the second example: x = 1, y = 2 (season 1 episode 2 season 2 episode 1); x = 2, y = 3 (season 2 episode 3 season 3 episode 2); x = 1, y = 3 (season 1 episode 3 season 3 episode 1). In the third example: x = 1, y = 2 (season 1 episode 2 season 2 episode 1); x = 1, y = 3 (season 1 episode 3 season 3 episode 1). | Input51 2 3 4 5 | Output0 | 2 seconds | 256 megabytes | ['data structures', '*1900'] |
D. Pair Of Linestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?InputThe first line contains one integer n (1 ≤ n ≤ 105) — the number of points you are given.Then n lines follow, each line containing two integers xi and yi (|xi|, |yi| ≤ 109)— coordinates of i-th point. All n points are distinct.OutputIf it is possible to draw two straight lines in such a way that each of given points belongs to at least one of these lines, print YES. Otherwise, print NO.ExamplesInput50 00 11 11 -12 2OutputYESInput50 01 02 11 12 3OutputNONoteIn the first example it is possible to draw two lines, the one containing the points 1, 3 and 5, and another one containing two remaining points. | Input50 00 11 11 -12 2 | OutputYES | 2 seconds | 256 megabytes | ['geometry', '*2000'] |
C. Chessboardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMagnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.InputThe first line contains odd integer n (1 ≤ n ≤ 100) — the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line.OutputPrint one number — minimum number of squares Magnus should recolor to be able to obtain a valid chessboard.ExamplesInput10010Output1Input3101010101101000101010101011010101010Output2 | Input10010 | Output1 | 1 second | 256 megabytes | ['bitmasks', 'brute force', 'implementation', '*1400'] |
B. Lecture Sleeptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.InputThe first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 105) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.The second line of the input contains n integer numbers a1, a2, ... an (1 ≤ ai ≤ 104) — the number of theorems lecturer tells during the i-th minute.The third line of the input contains n integer numbers t1, t2, ... tn (0 ≤ ti ≤ 1) — type of Mishka's behavior at the i-th minute of the lecture.OutputPrint only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.ExampleInput6 31 3 5 2 5 41 1 0 1 0 0Output16NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16. | Input6 31 3 5 2 5 41 1 0 1 0 0 | Output16 | 1 second | 256 megabytes | ['data structures', 'dp', 'implementation', 'two pointers', '*1200'] |
A. Tetristime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a following process. There is a platform with n columns. 1 \times 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the n columns have at least one square in them, the bottom row is being removed. You will receive 1 point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.InputThe first line of input contain 2 integer numbers n and m (1 \le n, m \le 1000) — the length of the platform and the number of the squares.The next line contain m integer numbers c_1, c_2, \dots, c_m (1 \le c_i \le n) — column in which i-th square will appear.OutputPrint one integer — the amount of points you will receive.ExampleInput3 91 1 2 2 2 3 1 2 3Output2NoteIn the sample case the answer will be equal to 2 because after the appearing of 6-th square will be removed one row (counts of the squares on the platform will look like [2~ 3~ 1], and after removing one row will be [1~ 2~ 0]).After the appearing of 9-th square counts will be [2~ 3~ 1], and after removing one row it will look like [1~ 2~ 0].So the answer will be equal to 2. | Input3 91 1 2 2 2 3 1 2 3 | Output2 | 1 second | 256 megabytes | ['implementation', '*900'] |
H. Santa's Gifttime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSanta has an infinite number of candies for each of m flavours. You are given a rooted tree with n vertices. The root of the tree is the vertex 1. Each vertex contains exactly one candy. The i-th vertex has a candy of flavour f_i.Sometimes Santa fears that candies of flavour k have melted. He chooses any vertex x randomly and sends the subtree of x to the Bakers for a replacement. In a replacement, all the candies with flavour k are replaced with a new candy of the same flavour. The candies which are not of flavour k are left unchanged. After the replacement, the tree is restored.The actual cost of replacing one candy of flavour k is c_k (given for each k). The Baker keeps the price fixed in order to make calculation simple. Every time when a subtree comes for a replacement, the Baker charges C, no matter which subtree it is and which flavour it is.Suppose that for a given flavour k the probability that Santa chooses a vertex for replacement is same for all the vertices. You need to find out the expected value of error in calculating the cost of replacement of flavour k. The error in calculating the cost is defined as follows. Error\ E(k) =\ (Actual Cost\ –\ Price\ charged\ by\ the\ Bakers) ^ 2.Note that the actual cost is the cost of replacement of one candy of the flavour k multiplied by the number of candies in the subtree.Also, sometimes Santa may wish to replace a candy at vertex x with a candy of some flavour from his pocket.You need to handle two types of operations: Change the flavour of the candy at vertex x to w. Calculate the expected value of error in calculating the cost of replacement for a given flavour k. InputThe first line of the input contains four integers n (2 \leqslant n \leqslant 5 \cdot 10^4), m, q, C (1 \leqslant m, q \leqslant 5 \cdot 10^4, 0 \leqslant C \leqslant 10^6) — the number of nodes, total number of different flavours of candies, the number of queries and the price charged by the Bakers for replacement, respectively.The second line contains n integers f_1, f_2, \dots, f_n (1 \leqslant f_i \leqslant m), where f_i is the initial flavour of the candy in the i-th node.The third line contains n - 1 integers p_2, p_3, \dots, p_n (1 \leqslant p_i \leqslant n), where p_i is the parent of the i-th node.The next line contains m integers c_1, c_2, \dots c_m (1 \leqslant c_i \leqslant 10^2), where c_i is the cost of replacing one candy of flavour i.The next q lines describe the queries. Each line starts with an integer t (1 \leqslant t \leqslant 2) — the type of the query.If t = 1, then the line describes a query of the first type. Two integers x and w follow (1 \leqslant x \leqslant n, 1 \leqslant w \leqslant m), it means that Santa replaces the candy at vertex x with flavour w.Otherwise, if t = 2, the line describes a query of the second type and an integer k (1 \leqslant k \leqslant m) follows, it means that you should print the expected value of the error in calculating the cost of replacement for a given flavour k.The vertices are indexed from 1 to n. Vertex 1 is the root.OutputOutput the answer to each query of the second type in a separate line.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. The checker program considers your answer correct if and only if \frac{|a-b|}{max(1,b)}\leqslant 10^{-6}.ExampleInput3 5 5 73 1 41 173 1 48 85 892 12 31 2 32 12 3Output2920.333333333333593.00000000000049.0000000000003217.000000000000NoteFor 1-st query, the error in calculating the cost of replacement for flavour 1 if vertex 1, 2 or 3 is chosen are 66^2, 66^2 and (-7)^2 respectively. Since the probability of choosing any vertex is same, therefore the expected value of error is \frac{66^2+66^2+(-7)^2}{3}.Similarly, for 2-nd query the expected value of error is \frac{41^2+(-7)^2+(-7)^2}{3}.After 3-rd query, the flavour at vertex 2 changes from 1 to 3.For 4-th query, the expected value of error is \frac{(-7)^2+(-7)^2+(-7)^2}{3}.Similarly, for 5-th query, the expected value of error is \frac{89^2+41^2+(-7)^2}{3}. | Input3 5 5 73 1 41 173 1 48 85 892 12 31 2 32 12 3 | Output2920.333333333333593.00000000000049.0000000000003217.000000000000 | 4 seconds | 512 megabytes | ['data structures', 'trees', '*3100'] |
G. Bandit Bluestime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJapate, while traveling through the forest of Mala, saw N bags of gold lying in a row. Each bag has some distinct weight of gold between 1 to N. Japate can carry only one bag of gold with him, so he uses the following strategy to choose a bag.Initially, he starts with an empty bag (zero weight). He considers the bags in some order. If the current bag has a higher weight than the bag in his hand, he picks the current bag.Japate put the bags in some order. Japate realizes that he will pick A bags, if he starts picking bags from the front, and will pick B bags, if he starts picking bags from the back. By picking we mean replacing the bag in his hand with the current one.Now he wonders how many permutations of bags are possible, in which he picks A bags from the front and B bags from back using the above strategy.Since the answer can be very large, output it modulo 998244353.InputThe only line of input contains three space separated integers N (1 ≤ N ≤ 105), A and B (0 ≤ A, B ≤ N).OutputOutput a single integer — the number of valid permutations modulo 998244353.ExamplesInput1 1 1Output1Input2 1 1Output0Input2 2 1Output1Input5 2 2Output22NoteIn sample case 1, the only possible permutation is [1]In sample cases 2 and 3, only two permutations of size 2 are possible:{[1, 2], [2, 1]}. The values of a and b for first permutation is 2 and 1, and for the second permutation these values are 1 and 2. In sample case 4, out of 120 permutations of [1, 2, 3, 4, 5] possible, only 22 satisfy the given constraints of a and b. | Input1 1 1 | Output1 | 3.5 seconds | 256 megabytes | ['combinatorics', 'dp', 'fft', 'math', '*2900'] |
F. Pathwalkstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph with n nodes and m edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value.Please note that the edges picked don't have to be consecutive in the input.InputThe first line contains two integers n and m (1 ≤ n ≤ 100000,1 ≤ m ≤ 100000) — the number of vertices and edges in the graph, respectively. m lines follows. The i-th of these lines contains three space separated integers ai, bi and wi (1 ≤ ai, bi ≤ n, 0 ≤ wi ≤ 100000), denoting an edge from vertex ai to vertex bi having weight wiOutputPrint one integer in a single line — the maximum number of edges in the path.ExamplesInput3 33 1 31 2 12 3 2Output2Input5 51 3 23 2 33 4 55 4 04 5 8Output3NoteThe answer for the first sample input is 2: . Note that you cannot traverse because edge appears earlier in the input than the other two edges and hence cannot be picked/traversed after either of the other two edges.In the second sample, it's optimal to pick 1-st, 3-rd and 5-th edges to get the optimal answer: . | Input3 33 1 31 2 12 3 2 | Output2 | 1 second | 256 megabytes | ['data structures', 'dp', 'graphs', '*2100'] |
E. Alternating Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a tree with n nodes numbered from 1 to n. Each node i has an associated value V_i.If the simple path from u_1 to u_m consists of m nodes namely u_1 \rightarrow u_2 \rightarrow u_3 \rightarrow \dots u_{m-1} \rightarrow u_{m}, then its alternating function A(u_{1},u_{m}) is defined as A(u_{1},u_{m}) = \sum\limits_{i=1}^{m} (-1)^{i+1} \cdot V_{u_{i}}. A path can also have 0 edges, i.e. u_{1}=u_{m}.Compute the sum of alternating functions of all unique simple paths. Note that the paths are directed: two paths are considered different if the starting vertices differ or the ending vertices differ. The answer may be large so compute it modulo 10^{9}+7. InputThe first line contains an integer n (2 \leq n \leq 2\cdot10^{5} ) — the number of vertices in the tree.The second line contains n space-separated integers V_1, V_2, \ldots, V_n (-10^9\leq V_i \leq 10^9) — values of the nodes.The next n-1 lines each contain two space-separated integers u and v (1\leq u, v\leq n, u \neq v) denoting an edge between vertices u and v. It is guaranteed that the given graph is a tree.OutputPrint the total sum of alternating functions of all unique simple paths modulo 10^{9}+7. ExamplesInput4-4 1 5 -21 21 31 4Output40Input8-2 6 -4 -4 -9 -3 -7 238 22 31 46 57 64 75 8Output4NoteConsider the first example.A simple path from node 1 to node 2: 1 \rightarrow 2 has alternating function equal to A(1,2) = 1 \cdot (-4)+(-1) \cdot 1 = -5.A simple path from node 1 to node 3: 1 \rightarrow 3 has alternating function equal to A(1,3) = 1 \cdot (-4)+(-1) \cdot 5 = -9.A simple path from node 2 to node 4: 2 \rightarrow 1 \rightarrow 4 has alternating function A(2,4) = 1 \cdot (1)+(-1) \cdot (-4)+1 \cdot (-2) = 3.A simple path from node 1 to node 1 has a single node 1, so A(1,1) = 1 \cdot (-4) = -4.Similarly, A(2, 1) = 5, A(3, 1) = 9, A(4, 2) = 3, A(1, 4) = -2, A(4, 1) = 2, A(2, 2) = 1, A(3, 3) = 5, A(4, 4) = -2, A(3, 4) = 7, A(4, 3) = 7, A(2, 3) = 10, A(3, 2) = 10. So the answer is (-5) + (-9) + 3 + (-4) + 5 + 9 + 3 + (-2) + 2 + 1 + 5 + (-2) + 7 + 7 + 10 + 10 = 40.Similarly A(1,4)=-2, A(2,2)=1, A(2,1)=5, A(2,3)=10, A(3,3)=5, A(3,1)=9, A(3,2)=10, A(3,4)=7, A(4,4)=-2, A(4,1)=2, A(4,2)=3 , A(4,3)=7 which sums upto 40. | Input4-4 1 5 -21 21 31 4 | Output40 | 2 seconds | 256 megabytes | ['combinatorics', 'dfs and similar', 'divide and conquer', 'dp', 'probabilities', 'trees', '*2300'] |
D. Full Binary Tree Queriestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a full binary tree having infinite levels.Each node has an initial value. If a node has value x, then its left child has value 2·x and its right child has value 2·x + 1. The value of the root is 1. You need to answer Q queries. There are 3 types of queries: Cyclically shift the values of all nodes on the same level as node with value X by K units. (The values/nodes of any other level are not affected). Cyclically shift the nodes on the same level as node with value X by K units. (The subtrees of these nodes will move along with them). Print the value of every node encountered on the simple path from the node with value X to the root.Positive K implies right cyclic shift and negative K implies left cyclic shift. It is guaranteed that atleast one type 3 query is present.InputThe first line contains a single integer Q (1 ≤ Q ≤ 105).Then Q queries follow, one per line: Queries of type 1 and 2 have the following format: T X K (1 ≤ T ≤ 2; 1 ≤ X ≤ 1018; 0 ≤ |K| ≤ 1018), where T is type of the query. Queries of type 3 have the following format: 3 X (1 ≤ X ≤ 1018).OutputFor each query of type 3, print the values of all nodes encountered in descending order.ExamplesInput53 121 2 13 122 4 -13 8Output12 6 3 1 12 6 2 1 8 4 2 1 Input53 141 5 -33 141 3 13 14Output14 7 3 1 14 6 3 1 14 6 2 1 NoteFollowing are the images of the first 4 levels of the tree in the first test case:Original: After query 1 2 1: After query 2 4 -1: | Input53 121 2 13 122 4 -13 8 | Output12 6 3 1 12 6 2 1 8 4 2 1 | 4 seconds | 256 megabytes | ['brute force', 'implementation', 'trees', '*2100'] |
C. Subsequence Countingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPikachu had an array with him. He wrote down all the non-empty subsequences of the array on paper. Note that an array of size n has 2n - 1 non-empty subsequences in it. Pikachu being mischievous as he always is, removed all the subsequences in which Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ dPikachu was finally left with X subsequences. However, he lost the initial array he had, and now is in serious trouble. He still remembers the numbers X and d. He now wants you to construct any such array which will satisfy the above conditions. All the numbers in the final array should be positive integers less than 1018. Note the number of elements in the output array should not be more than 104. If no answer is possible, print - 1.InputThe only line of input consists of two space separated integers X and d (1 ≤ X, d ≤ 109).OutputOutput should consist of two lines.First line should contain a single integer n (1 ≤ n ≤ 10 000)— the number of integers in the final array.Second line should consist of n space separated integers — a1, a2, ... , an (1 ≤ ai < 1018).If there is no answer, print a single integer -1. If there are multiple answers, print any of them.ExamplesInput10 5Output65 50 7 15 6 100Input4 2Output410 100 1000 10000NoteIn the output of the first example case, the remaining subsequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 5 are [5], [5, 7], [5, 6], [5, 7, 6], [50], [7], [7, 6], [15], [6], [100]. There are 10 of them. Hence, the array [5, 50, 7, 15, 6, 100] is valid.Similarly, in the output of the second example case, the remaining sub-sequences after removing those with Maximum_element_of_the_subsequence - Minimum_element_of_subsequence ≥ 2 are [10], [100], [1000], [10000]. There are 4 of them. Hence, the array [10, 100, 1000, 10000] is valid. | Input10 5 | Output65 50 7 15 6 100 | 1 second | 256 megabytes | ['bitmasks', 'constructive algorithms', 'greedy', 'implementation', '*1700'] |
B. Minimize the errortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.InputThe first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2 (0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively.Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A.Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.OutputOutput a single integer — the minimum possible value of after doing exactly k1 operations on array A and exactly k2 operations on array B.ExamplesInput2 0 01 22 3Output2Input2 1 01 22 2Output0Input2 5 73 414 4Output1NoteIn the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2. In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.In the third sample case, we can increase the first element of A to 8, using the all of the 5 moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7 available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1. | Input2 0 01 22 3 | Output2 | 1 second | 256 megabytes | ['data structures', 'greedy', 'sortings', '*1500'] |
A. Check the stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.B now gives this string to C and he appends some number of letters 'c' to the end of the string. However, since C is a good friend of A and B, the number of letters 'c' he appends is equal to the number of 'a' or to the number of 'b' in the string. It is also possible that the number of letters 'c' equals both to the number of letters 'a' and to the number of letters 'b' at the same time.You have a string in your hands, and you want to check if it is possible to obtain the string in this way or not. If it is possible to obtain the string, print "YES", otherwise print "NO" (without the quotes).InputThe first and only line consists of a string S ( 1 \le |S| \le 5\,000 ). It is guaranteed that the string will only consist of the lowercase English letters 'a', 'b', 'c'.OutputPrint "YES" or "NO", according to the condition.ExamplesInputaaabcccOutputYESInputbbaccOutputNOInputaabcOutputYESNoteConsider first example: the number of 'c' is equal to the number of 'a'. Consider second example: although the number of 'c' is equal to the number of the 'b', the order is not correct.Consider third example: the number of 'c' is equal to the number of 'b'. | Inputaaabccc | OutputYES | 1 second | 256 megabytes | ['implementation', '*1200'] |
F. Mahmoud and Ehab and yet another xor tasktime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputEhab has an array a of n integers. He likes the bitwise-xor operation and he likes to bother Mahmoud so he came up with a problem. He gave Mahmoud q queries. In each of them, he gave Mahmoud 2 integers l and x, and asked him to find the number of subsequences of the first l elements of the array such that their bitwise-xor sum is x. Can you help Mahmoud answer the queries?A subsequence can contain elements that are not neighboring.InputThe first line contains integers n and q (1 ≤ n, q ≤ 105), the number of elements in the array and the number of queries.The next line contains n integers a1, a2, ..., an (0 ≤ ai < 220), the elements of the array.The next q lines, each contains integers l and x (1 ≤ l ≤ n, 0 ≤ x < 220), representing the queries.OutputFor each query, output its answer modulo 109 + 7 in a newline.ExamplesInput5 50 1 2 3 44 32 03 75 75 8Output42040Input3 21 1 13 12 0Output42NoteThe bitwise-xor sum of the empty set is 0 and the bitwise-xor sum of a set containing one element is that element itself. | Input5 50 1 2 3 44 32 03 75 75 8 | Output42040 | 1 second | 512 megabytes | ['bitmasks', 'dp', 'math', 'matrices', '*2400'] |
E. Mahmoud and Ehab and the xor-MSTtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab is interested in the bitwise-xor operation and the special graphs. Mahmoud gave him a problem that combines both. He has a complete graph consisting of n vertices numbered from 0 to n - 1. For all 0 ≤ u < v < n, vertex u and vertex v are connected with an undirected edge that has weight (where is the bitwise-xor operation). Can you find the weight of the minimum spanning tree of that graph?You can read about complete graphs in https://en.wikipedia.org/wiki/Complete_graphYou can read about the minimum spanning tree in https://en.wikipedia.org/wiki/Minimum_spanning_treeThe weight of the minimum spanning tree is the sum of the weights on the edges included in it.InputThe only line contains an integer n (2 ≤ n ≤ 1012), the number of vertices in the graph.OutputThe only line contains an integer x, the weight of the graph's minimum spanning tree.ExampleInput4Output4NoteIn the first sample: The weight of the minimum spanning tree is 1+2+1=4. | Input4 | Output4 | 2 seconds | 256 megabytes | ['bitmasks', 'dp', 'graphs', 'implementation', 'math', '*1900'] |
D. Mahmoud and Ehab and another array construction tasktime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that: b is lexicographically greater than or equal to a. bi ≥ 2. b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest common divisor of w and z. Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?An array x is lexicographically greater than an array y if there exists an index i such than xi > yi and xj = yj for all 1 ≤ j < i. An array x is equal to an array y if xi = yi for all 1 ≤ i ≤ n.InputThe first line contains an integer n (1 ≤ n ≤ 105), the number of elements in a and b.The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 105), the elements of a.OutputOutput n space-separated integers, the i-th of them representing bi.ExamplesInput52 3 5 4 13Output2 3 5 7 11 Input310 3 7Output10 3 7 NoteNote that in the second sample, the array is already pairwise coprime so we printed it. | Input52 3 5 4 13 | Output2 3 5 7 11 | 3 seconds | 256 megabytes | ['constructive algorithms', 'greedy', 'math', 'number theory', '*1900'] |
C. Mahmoud and Ehab and the wrong algorithmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm: Root the tree at node 1. Count the number of nodes at an even depth. Let it be evenCnt. Count the number of nodes at an odd depth. Let it be oddCnt. The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.InputThe only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.OutputThe output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only.If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict.If there are multiple answers, you can print any of them.ExamplesInput2Output-11 2Input8Output1 21 32 42 53 64 74 81 21 32 42 52 63 76 8NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this: In the second tree, the algorithm will find an answer with 3 nodes which is correct: | Input2 | Output-11 2 | 2 seconds | 256 megabytes | ['constructive algorithms', 'trees', '*1500'] |
B. Mahmoud and Ehab and the messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.InputThe first line of input contains integers n, k and m (1 ≤ k ≤ n ≤ 105, 1 ≤ m ≤ 105) — the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively.The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct.The third line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) where ai is the cost of sending the i-th word.The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≤ x ≤ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group.The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words.OutputThe only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning.ExamplesInput5 4 4i loser am the second100 1 1 5 101 11 32 2 51 4i am the secondOutput107Input5 4 4i loser am the second100 20 1 5 101 11 32 2 51 4i am the secondOutput116NoteIn the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107.In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116. | Input5 4 4i loser am the second100 1 1 5 101 11 32 2 51 4i am the second | Output107 | 2 seconds | 256 megabytes | ['dsu', 'greedy', 'implementation', '*1200'] |
A. Mahmoud and Ehab and the even-odd gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: 1 ≤ a ≤ n. If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has to be odd. If the current player can't choose any number satisfying the conditions, he loses. Can you determine the winner if they both play optimally?InputThe only line contains an integer n (1 ≤ n ≤ 109), the number at the beginning of the game.OutputOutput "Mahmoud" (without quotes) if Mahmoud wins and "Ehab" (without quotes) otherwise.ExamplesInput1OutputEhabInput2OutputMahmoudNoteIn the first sample, Mahmoud can't choose any integer a initially because there is no positive even integer less than or equal to 1 so Ehab wins.In the second sample, Mahmoud has to choose a = 2 and subtract it from n. It's Ehab's turn and n = 0. There is no positive odd integer less than or equal to 0 so Mahmoud wins. | Input1 | OutputEhab | 1 second | 256 megabytes | ['games', 'math', '*800'] |
F3. Lightsabers (hard)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere used to be unrest in the Galactic Senate. Several thousand solar systems had declared their intentions to leave the Republic. But fear not! Master Heidi was able to successfully select the Jedi Knights that have restored peace in the galaxy. However, she knows that evil never sleeps and a time may come when she will need to pick another group of Jedi Knights. She wants to be sure she has enough options to do so.There are n Jedi Knights, each of them with a lightsaber of one of m colors. Given a number k, compute the number of differently colored collections of k lightsabers that some k Jedi Knights might have. Jedi Knights with lightsabers of the same color are indistinguishable (it's not the person, it's the lightsaber color that matters!), and their order does not matter; that is, we consider two collections of Jedi Knights to be different if and only if their vectors of counts of lightsabers of each color (like what you were given in the easy and the medium versions) are different. We count all subsets, not only contiguous subsegments of the input sequence. Output the answer modulo 1009.InputThe first line of the input contains n (1 ≤ n ≤ 2·105), m (1 ≤ m ≤ n) and k (1 ≤ k ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of subsequent Jedi Knights.OutputOutput one number: the number of differently colored collections of k lightsabers modulo 1009.ExampleInput4 3 21 2 3 2Output4 | Input4 3 21 2 3 2 | Output4 | 4 seconds | 256 megabytes | ['fft', '*2600'] |
F2. Lightsabers (medium)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color.However, since the last time, she has learned that it is not always possible to select such an interval. Therefore, she decided to ask some Jedi Knights to go on an indefinite unpaid vacation leave near certain pits on Tatooine, if you know what I mean. Help Heidi decide what is the minimum number of Jedi Knights that need to be let go before she is able to select the desired interval from the subsequence of remaining knights.InputThe first line of the input contains n (1 ≤ n ≤ 2·105) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k1, k2, ..., km (with ) – the desired counts of Jedi Knights with lightsabers of each color from 1 to m.OutputOutput one number: the minimum number of Jedi Knights that need to be removed from the sequence so that, in what remains, there is an interval with the prescribed counts of lightsaber colors. If this is not possible, output - 1.ExampleInput8 33 3 1 2 2 1 1 33 1 1Output1 | Input8 33 3 1 2 2 1 1 33 1 1 | Output1 | 1 second | 256 megabytes | ['binary search', 'two pointers', '*1800'] |
F1. Lightsabers (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission. Heidi has n Jedi Knights standing in front of her, each one with a lightsaber of one of m possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly k1 knights with lightsabers of the first color, k2 knights with lightsabers of the second color, ..., km knights with lightsabers of the m-th color. Help her find out if this is possible.InputThe first line of the input contains n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ n). The second line contains n integers in the range {1, 2, ..., m} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains m integers k1, k2, ..., km (with ) – the desired counts of lightsabers of each color from 1 to m.OutputOutput YES if an interval with prescribed color counts exists, or output NO if there is none.ExampleInput5 21 1 2 2 11 2OutputYES | Input5 21 1 2 2 11 2 | OutputYES | 1 second | 256 megabytes | ['implementation', '*1500'] |
E3. Guard Duty (hard)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Heidi knows that she can assign Rebel spaceships to bases (recall the easy subtask), she is asking you: how exactly to do this? Now, given positions of N spaceships and N bases on a plane, your task is to connect spaceships and bases with line segments so that: The segments do not intersect. Such a connection forms a perfect matching. InputThe first line contains an integer N (1 ≤ n ≤ 10000). For 1 ≤ i ≤ N, the i + 1-th line contains two integers xi and yi (|xi|, |yi| ≤ 10000) denoting the coordinates of the i-th spaceship. The following N lines have the same format, denoting the position of bases. It is guaranteed that no two points coincide and no three points are on the same line.OutputThe output should have N lines. The i-th line should contain an integer pi, the index of the base to which the i-th spaceship is connected. The sequence p1, ..., pN should form a permutation of 1, ..., N.It is guaranteed that a solution exists. If there are multiple solutions, you can output any one of them.ExampleInput46 65 12 44 05 41 22 13 5Output4123 | Input46 65 12 44 05 41 22 13 5 | Output4123 | 5 seconds | 256 megabytes | ['geometry', '*2700'] |
E2. Guard Duty (medium)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPrincess Heidi decided to give orders to all her K Rebel ship commanders in person. Unfortunately, she is currently travelling through hyperspace, and will leave it only at N specific moments t1, t2, ..., tN. The meetings with commanders must therefore start and stop at those times. Namely, each commander will board her ship at some time ti and disembark at some later time tj. Of course, Heidi needs to meet with all commanders, and no two meetings can be held during the same time. Two commanders cannot even meet at the beginnings/endings of the hyperspace jumps, because too many ships in one position could give out their coordinates to the enemy. Your task is to find minimum time that Princess Heidi has to spend on meetings, with her schedule satisfying the conditions above. InputThe first line contains two integers K, N (2 ≤ 2K ≤ N ≤ 500000, K ≤ 5000). The second line contains N distinct integers t1, t2, ..., tN (1 ≤ ti ≤ 109) representing the times when Heidi leaves hyperspace.OutputOutput only one integer: the minimum time spent on meetings. ExamplesInput2 51 4 6 7 12Output4Input3 66 3 4 2 5 1Output3Input4 1215 7 4 19 3 30 14 1 5 23 17 25Output6NoteIn the first example, there are five valid schedules: [1, 4], [6, 7] with total time 4, [1, 4], [6, 12] with total time 9, [1, 4], [7, 12] with total time 8, [1, 6], [7, 12] with total time 10, and [4, 6], [7, 12] with total time 7. So the answer is 4.In the second example, there is only 1 valid schedule: [1, 2], [3, 4], [5, 6].For the third example, one possible schedule with total time 6 is: [1, 3], [4, 5], [14, 15], [23, 25]. | Input2 51 4 6 7 12 | Output4 | 3 seconds | 256 megabytes | ['binary search', 'dp', 'greedy', 'sortings', '*2200'] |
E1. Guard Duty (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Rebel fleet is afraid that the Empire might want to strike back again. Princess Heidi needs to know if it is possible to assign R Rebel spaceships to guard B bases so that every base has exactly one guardian and each spaceship has exactly one assigned base (in other words, the assignment is a perfect matching). Since she knows how reckless her pilots are, she wants to be sure that any two (straight) paths – from a base to its assigned spaceship – do not intersect in the galaxy plane (that is, in 2D), and so there is no risk of collision.InputThe first line contains two space-separated integers R, B(1 ≤ R, B ≤ 10). For 1 ≤ i ≤ R, the i + 1-th line contains two space-separated integers xi and yi (|xi|, |yi| ≤ 10000) denoting the coordinates of the i-th Rebel spaceship. The following B lines have the same format, denoting the position of bases. It is guaranteed that no two points coincide and that no three points are on the same line.OutputIf it is possible to connect Rebel spaceships and bases so as satisfy the constraint, output Yes, otherwise output No (without quote).ExamplesInput3 30 02 03 1-2 10 32 2OutputYesInput2 11 02 23 1OutputNoNoteFor the first example, one possible way is to connect the Rebels and bases in order.For the second example, there is no perfect matching between Rebels and bases. | Input3 30 02 03 1-2 10 32 2 | OutputYes | 1 second | 256 megabytes | ['brute force', 'geometry', 'greedy', 'math', '*1600'] |
D2. Hyperspace Jump (hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is now 125 years later, but humanity is still on the run from a humanoid-cyborg race determined to destroy it. Or perhaps we are getting some stories mixed up here... In any case, the fleet is now smaller. However, in a recent upgrade, all the navigation systems have been outfitted with higher-dimensional, linear-algebraic jump processors.Now, in order to make a jump, a ship's captain needs to specify a subspace of the d-dimensional space in which the events are taking place. She does so by providing a generating set of vectors for that subspace.Princess Heidi has received such a set from the captain of each of m ships. Again, she would like to group up those ships whose hyperspace jump subspaces are equal. To do so, she wants to assign a group number between 1 and m to each of the ships, so that two ships have the same group number if and only if their corresponding subspaces are equal (even though they might be given using different sets of vectors).Help Heidi!InputThe first line of the input contains two space-separated integers m and d (2 ≤ m ≤ 30 000, 1 ≤ d ≤ 5) – the number of ships and the dimension of the full underlying vector space, respectively. Next, the m subspaces are described, one after another. The i-th subspace, which corresponds to the i-th ship, is described as follows:The first line contains one integer ki (1 ≤ ki ≤ d). Then ki lines follow, the j-th of them describing the j-th vector sent by the i-th ship. Each of the j lines consists of d space-separated integers aj, j = 1, ..., d, that describe the vector ; it holds that |aj| ≤ 250. The i-th subspace is the linear span of these ki vectors.OutputOutput m space-separated integers g1, ..., gm, where denotes the group number assigned to the i-th ship. That is, for any 1 ≤ i < j ≤ m, the following should hold: gi = gj if and only if the i-th and the j-th subspaces are equal. In addition, the sequence (g1, g2, ..., gm) should be lexicographically minimal among all sequences with that property.ExampleInput8 215 010 110 120 60 120 11 02-5 -54 321 10 121 01 0Output1 2 2 2 3 3 3 1 NoteIn the sample testcase, the first and the last subspace are equal, subspaces 2 to 4 are equal, and subspaces 5 to 7 are equal.Recall that two subspaces, one given as the span of vectors and another given as the span of vectors , are equal if each vector vi can be written as a linear combination of vectors w1, ..., wk (that is, there exist coefficients such that vi = α1w1 + ... + αkwk) and, similarly, each vector wi can be written as a linear combination of vectors v1, ..., vn.Recall that a sequence (g1, g2, ..., gm) is lexicographically smaller than a sequence (h1, h2, ..., hm) if there exists an index i, 1 ≤ i ≤ m, such that gi < hi and gj = hj for all j < i. | Input8 215 010 110 120 60 120 11 02-5 -54 321 10 121 01 0 | Output1 2 2 2 3 3 3 1 | 3 seconds | 256 megabytes | ['*2700'] |
D1. Hyperspace Jump (easy)time limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Rebel fleet is on the run. It consists of m ships currently gathered around a single planet. Just a few seconds ago, the vastly more powerful Empire fleet has appeared in the same solar system, and the Rebels will need to escape into hyperspace. In order to spread the fleet, the captain of each ship has independently come up with the coordinate to which that ship will jump. In the obsolete navigation system used by the Rebels, this coordinate is given as the value of an arithmetic expression of the form .To plan the future of the resistance movement, Princess Heidi needs to know, for each ship, how many ships are going to end up at the same coordinate after the jump. You are her only hope!InputThe first line of the input contains a single integer m (1 ≤ m ≤ 200 000) – the number of ships. The next m lines describe one jump coordinate each, given as an arithmetic expression. An expression has the form (a+b)/c. Namely, it consists of: an opening parenthesis (, a positive integer a of up to two decimal digits, a plus sign +, a positive integer b of up to two decimal digits, a closing parenthesis ), a slash /, and a positive integer c of up to two decimal digits.OutputPrint a single line consisting of m space-separated integers. The i-th integer should be equal to the number of ships whose coordinate is equal to that of the i-th ship (including the i-th ship itself).ExampleInput4(99+98)/97(26+4)/10(12+33)/15(5+1)/7Output1 2 2 1 NoteIn the sample testcase, the second and the third ship will both end up at the coordinate 3.Note that this problem has only two versions – easy and hard. | Input4(99+98)/97(26+4)/10(12+33)/15(5+1)/7 | Output1 2 2 1 | 5 seconds | 256 megabytes | ['expression parsing', 'math', '*1400'] |
C3. Encryption (hard)time limit per test2.2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputHeidi is now just one code away from breaking the encryption of the Death Star plans. The screen that should be presenting her with the description of the next code looks almost like the previous one, though who would have thought that the evil Empire engineers would fill this small screen with several million digits! It is just ridiculous to think that anyone would read them all...Heidi is once again given a sequence A and two integers k and p. She needs to find out what the encryption key S is.Let X be a sequence of integers, and p a positive integer. We define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given integers k and p. Her goal is to split A into k parts such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. No two parts overlap. The total sum S of the scores of those parts is minimized (not maximized!). Output the sum S, which is the encryption code.InputThe first line of the input contains three space-separated integers N, k and p (k ≤ N ≤ 500 000, 2 ≤ k ≤ 100, 2 ≤ p ≤ 100) – the number of elements in A, the number of parts A should be split into, and the modulo for computing scores, respectively.The second line contains N space-separated integers that are the elements of A. Each integer is from the interval [1, 1 000 000].OutputOutput the number S as described in the problem statement.ExamplesInput4 3 103 4 7 2Output6Input10 5 1216 3 24 13 9 8 7 5 12 12Output13NoteIn the first example, if the input sequence is split as (3), (4, 7), (2), the total score would be . It is easy to see that this score is the smallest possible.In the second example, one possible way to obtain score 13 is to make the following split: (16, 3), (24), (13), (9, 8), (7, 5, 12, 12). | Input4 3 103 4 7 2 | Output6 | 2.2 seconds | 512 megabytes | ['data structures', 'dp', '*2500'] |
C2. Encryption (medium)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputHeidi has now broken the first level of encryption of the Death Star plans, and is staring at the screen presenting her with the description of the next code she has to enter. It looks surprisingly similar to the first one – seems like the Empire engineers were quite lazy...Heidi is once again given a sequence A, but now she is also given two integers k and p. She needs to find out what the encryption key S is.Let X be a sequence of integers, and p a positive integer. We define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given integers k and p. Her goal is to split A into k part such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. No two parts overlap. The total sum S of the scores of those parts is maximized. Output the sum S – the encryption code.InputThe first line of the input contains three space-separated integer N, k and p (k ≤ N ≤ 20 000, 2 ≤ k ≤ 50, 2 ≤ p ≤ 100) – the number of elements in A, the number of parts A should be split into, and the modulo for computing scores, respectively.The second line contains N space-separated integers that are the elements of A. Each integer is from the interval [1, 1 000 000].OutputOutput the number S as described in the problem statement.ExamplesInput4 3 103 4 7 2Output16Input10 5 1216 3 24 13 9 8 7 5 12 12Output37NoteIn the first example, if the input sequence is split as (3, 4), (7), (2), the total score would be . It is easy to see that this score is maximum.In the second example, one possible way to obtain score 37 is to make the following split: (16, 3, 24), (13, 9), (8), (7), (5, 12, 12). | Input4 3 103 4 7 2 | Output16 | 3 seconds | 512 megabytes | ['dp', '*2000'] |
C1. Encryption (easy)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.Heidi is presented with a screen that shows her a sequence of integers A and a positive integer p. She knows that the encryption code is a single number S, which is defined as follows:Define the score of X to be the sum of the elements of X modulo p.Heidi is given a sequence A that consists of N integers, and also given an integer p. She needs to split A into 2 parts such that: Each part contains at least 1 element of A, and each part consists of contiguous elements of A. The two parts do not overlap. The total sum S of the scores of those two parts is maximized. This is the encryption code. Output the sum S, which is the encryption code.InputThe first line of the input contains two space-separated integer N and p (2 ≤ N ≤ 100 000, 2 ≤ p ≤ 10 000) – the number of elements in A, and the modulo for computing scores, respectively.The second line contains N space-separated integers which are the elements of A. Each integer is from the interval [1, 1 000 000].OutputOutput the number S as described in the problem statement.ExamplesInput4 103 4 7 2Output16Input10 1216 3 24 13 9 8 7 5 12 12Output13NoteIn the first example, the score is maximized if the input sequence is split into two parts as (3, 4), (7, 2). It gives the total score of .In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is . | Input4 103 4 7 2 | Output16 | 1 second | 256 megabytes | ['brute force', '*1200'] |
B2. Maximum Control (medium)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.InputThe first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.OutputOn a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.ExamplesInput31 22 3Output1 3 3 Input41 23 24 2Output1 3 4 4 NoteConsider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets. | Input31 22 3 | Output1 3 3 | 3 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'graphs', 'greedy', 'trees', '*2200'] |
B1. Maximum Control (easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.How much work is there left to be done: that is, how many remote planets are there?InputThe first line of the input contains an integer N (2 ≤ N ≤ 1000) – the number of planets in the galaxy.The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.OutputA single integer denoting the number of remote planets.ExamplesInput54 14 21 31 5Output3Input41 24 31 4Output2NoteIn the first example, only planets 2, 3 and 5 are connected by a single tunnel.In the second example, the remote planets are 2 and 3.Note that this problem has only two versions – easy and medium. | Input54 14 21 31 5 | Output3 | 2 seconds | 256 megabytes | ['implementation', '*1000'] |
A2. Death Stars (medium)time limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the solar system that contains the Death Star. However, this time the Empire has hidden the Death Star very well, and Heidi needs to find a place that appears on both maps in order to detect the Death Star.The first map is an N × M grid, each cell of which shows some type of cosmic object that is present in the corresponding quadrant of space. The second map is an M × N grid. Heidi needs to align those two maps in such a way that they overlap over some M × M section in which all cosmic objects are identical. Help Heidi by identifying where such an M × M section lies within both maps.InputThe first line of the input contains two space-separated integers N and M (1 ≤ N ≤ 2000, 1 ≤ M ≤ 200, M ≤ N). The next N lines each contain M lower-case Latin characters (a-z), denoting the first map. Different characters correspond to different cosmic object types. The next M lines each contain N characters, describing the second map in the same format. OutputThe only line of the output should contain two space-separated integers i and j, denoting that the section of size M × M in the first map that starts at the i-th row is equal to the section of the second map that starts at the j-th column. Rows and columns are numbered starting from 1.If there are several possible ways to align the maps, Heidi will be satisfied with any of those. It is guaranteed that a solution exists.ExampleInput10 5somerandomnoisemaytheforcebewithyouhctwoagainnoisesomermaythandomeforcnoiseebewiagainthyounoisehctwoOutput4 6NoteThe 5-by-5 grid for the first test case looks like this: maytheforcebewithyouhctwo | Input10 5somerandomnoisemaytheforcebewithyouhctwoagainnoisesomermaythandomeforcnoiseebewiagainthyounoisehctwo | Output4 6 | 2.5 seconds | 256 megabytes | ['hashing', 'strings', '*2000'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.