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. Sonya and Hotelstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate x_i. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to d. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original n hotels to the new one is equal to d.InputThe first line contains two integers n and d (1\leq n\leq 100, 1\leq d\leq 10^9) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others.The second line contains n different integers in strictly increasing order x_1, x_2, \ldots, x_n (-10^9\leq x_i\leq 10^9) — coordinates of Sonya's hotels.OutputPrint the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to d.ExamplesInput4 3-3 2 9 16Output6Input5 24 8 11 18 19Output5NoteIn the first example, there are 6 possible cities where Sonya can build a hotel. These cities have coordinates -6, 5, 6, 12, 13, and 19.In the second example, there are 5 possible cities where Sonya can build a hotel. These cities have coordinates 2, 6, 13, 16, and 21. | Input4 3-3 2 9 16 | Output6 | 1 second | 256 megabytes | ['implementation', '*900'] |
F. Abbreviationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a text consisting of n space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. w_i is the i-th word of text. All words consist only of lowercase Latin letters.Let's denote a segment of words w[i..j] as a sequence of words w_i, w_{i + 1}, \dots, w_j. Two segments of words w[i_1 .. j_1] and w[i_2 .. j_2] are considered equal if j_1 - i_1 = j_2 - i_2, j_1 \ge i_1, j_2 \ge i_2, and for every t \in [0, j_1 - i_1] w_{i_1 + t} = w_{i_2 + t}. For example, for the text "to be or not to be" the segments w[1..2] and w[5..6] are equal, they correspond to the words "to be".An abbreviation is a replacement of some segments of words with their first uppercase letters. In order to perform an abbreviation, you have to choose at least two non-intersecting equal segments of words, and replace each chosen segment with the string consisting of first letters of the words in the segment (written in uppercase). For example, for the text "a ab a a b ab a a b c" you can replace segments of words w[2..4] and w[6..8] with an abbreviation "AAA" and obtain the text "a AAA b AAA b c", or you can replace segments of words w[2..5] and w[6..9] with an abbreviation "AAAB" and obtain the text "a AAAB AAAB c".What is the minimum length of the text after at most one abbreviation?InputThe first line of the input contains one integer n (1 \le n \le 300) — the number of words in the text.The next line contains n space-separated words of the text w_1, w_2, \dots, w_n. Each word consists only of lowercase Latin letters.It is guaranteed that the length of text does not exceed 10^5.OutputPrint one integer — the minimum length of the text after at most one abbreviation.ExamplesInput6to be or not to beOutput12Input10a ab a a b ab a a b cOutput13Input6aa bb aa aa bb bbOutput11NoteIn the first example you can obtain the text "TB or not TB".In the second example you can obtain the text "a AAAB AAAB c".In the third example you can obtain the text "AB aa AB bb". | Input6to be or not to be | Output12 | 1 second | 256 megabytes | ['dp', 'hashing', 'strings', '*2200'] |
E. Tree Constructingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers n, d and k.Your task is to construct an undirected tree on n vertices with diameter d and degree of each vertex at most k, or say that it is impossible.An undirected tree is a connected undirected graph with n - 1 edges.Diameter of a tree is the maximum length of a simple path (a path in which each vertex appears at most once) between all pairs of vertices of this tree.Degree of a vertex is the number of edges incident to this vertex (i.e. for a vertex u it is the number of edges (u, v) that belong to the tree, where v is any other vertex of a tree).InputThe first line of the input contains three integers n, d and k (1 \le n, d, k \le 4 \cdot 10^5).OutputIf there is no tree satisfying the conditions above, print only one word "NO" (without quotes).Otherwise in the first line print "YES" (without quotes), and then print n - 1 lines describing edges of a tree satisfying the conditions above. Vertices of the tree must be numbered from 1 to n. You can print edges and vertices connected by an edge in any order. If there are multiple answers, print any of them.1ExamplesInput6 3 3OutputYES3 14 11 25 22 6Input6 2 3OutputNOInput10 4 3OutputYES2 92 1010 33 16 108 24 35 66 7Input8 5 3OutputYES2 57 23 73 11 68 74 3 | Input6 3 3 | OutputYES3 14 11 25 22 6 | 4 seconds | 256 megabytes | ['constructive algorithms', 'graphs', '*2100'] |
D. Coins and Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of coins that is necessary to obtain the value b_j using some subset of coins (Polycarp can use only coins he has). If Polycarp can't obtain the value b_j, the answer to the j-th query is -1.The queries are independent (the answer on the query doesn't affect Polycarp's coins).InputThe first line of the input contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of coins and the number of queries.The second line of the input contains n integers a_1, a_2, \dots, a_n — values of coins (1 \le a_i \le 2 \cdot 10^9). It is guaranteed that all a_i are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d).The next q lines contain one integer each. The j-th line contains one integer b_j — the value of the j-th query (1 \le b_j \le 10^9).OutputPrint q integers ans_j. The j-th integer must be equal to the answer on the j-th query. If Polycarp can't obtain the value b_j the answer to the j-th query is -1.ExampleInput5 42 4 8 2 4851410Output1-132 | Input5 42 4 8 2 4851410 | Output1-132 | 2 seconds | 256 megabytes | ['greedy', '*1600'] |
C. Intense Heattime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:Suppose we want to analyze the segment of n consecutive days. We have measured the temperatures during these n days; the temperature during i-th day equals a_i.We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day x to day y, we calculate it as \frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1} (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than k consecutive days. For example, if analyzing the measures [3, 4, 1, 2] and k = 3, we are interested in segments [3, 4, 1], [4, 1, 2] and [3, 4, 1, 2] (we want to find the maximum value of average temperature over these segments).You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?InputThe first line contains two integers n and k (1 \le k \le n \le 5000) — the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 5000) — the temperature measures during given n days.OutputPrint one real number — the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than k consecutive days.Your answer will be considered correct if the following condition holds: |res - res_0| < 10^{-6}, where res is your answer, and res_0 is the answer given by the jury's solution.ExampleInput4 33 4 1 2Output2.666666666666667 | Input4 33 4 1 2 | Output2.666666666666667 | 4 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*1300'] |
B. Binary String Constructingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 \le i < n) such that s_i \ne s_{i + 1}. It is guaranteed that the answer always exists.For example, for the string "01010" there are four indices i such that 1 \le i < n and s_i \ne s_{i + 1} (i = 1, 2, 3, 4). For the string "111001" there are two such indices i (i = 3, 5).Recall that binary string is a non-empty sequence of characters where each character is either 0 or 1.InputThe first line of the input contains three integers a, b and x (1 \le a, b \le 100, 1 \le x < a + b).OutputPrint only one string s, where s is any binary string satisfying conditions described above. It is guaranteed that the answer always exists.ExamplesInput2 2 1Output1100Input3 3 3Output101100Input5 3 6Output01010100NoteAll possible answers for the first example: 1100; 0011. All possible answers for the second example: 110100; 101100; 110010; 100110; 011001; 001101; 010011; 001011. | Input2 2 1 | Output1100 | 1 second | 256 megabytes | ['constructive algorithms', '*1300'] |
A. Polycarp's Pocketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two pockets as follows: [1, 2, 3], [2, 3, 4].Polycarp wants to distribute all the coins with the minimum number of used pockets. Help him to do that.InputThe first line of the input contains one integer n (1 \le n \le 100) — the number of coins.The second line of the input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100) — values of coins.OutputPrint only one integer — the minimum number of pockets Polycarp needs to distribute all the coins so no two coins with the same value are put into the same pocket.ExamplesInput61 2 4 3 3 2Output2Input1100Output1 | Input61 2 4 3 3 2 | Output2 | 1 second | 256 megabytes | ['implementation', '*800'] |
G. Two-Pathstime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighted tree (undirected connected graph with no cycles, loops or multiple edges) with n vertices. The edge \{u_j, v_j\} has weight w_j. Also each vertex i has its own value a_i assigned to it.Let's call a path starting in vertex u and ending in vertex v, where each edge can appear no more than twice (regardless of direction), a 2-path. Vertices can appear in the 2-path multiple times (even start and end vertices).For some 2-path p profit \text{Pr}(p) = \sum\limits_{v \in \text{distinct vertices in } p}{a_v} - \sum\limits_{e \in \text{distinct edges in } p}{k_e \cdot w_e}, where k_e is the number of times edge e appears in p. That is, vertices are counted once, but edges are counted the number of times they appear in p.You are about to answer m queries. Each query is a pair of vertices (qu, qv). For each query find 2-path p from qu to qv with maximal profit \text{Pr}(p).InputThe first line contains two integers n and q (2 \le n \le 3 \cdot 10^5, 1 \le q \le 4 \cdot 10^5) — the number of vertices in the tree and the number of queries.The second line contains n space-separated integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the values of the vertices.Next n - 1 lines contain descriptions of edges: each line contains three space separated integers u_i, v_i and w_i (1 \le u_i, v_i \le n, u_i \neq v_i, 1 \le w_i \le 10^9) — there is edge \{u_i, v_i\} with weight w_i in the tree.Next q lines contain queries (one per line). Each query contains two integers qu_i and qv_i (1 \le qu_i, qv_i \le n) — endpoints of the 2-path you need to find.OutputFor each query print one integer per line — maximal profit \text{Pr}(p) of the some 2-path p with the corresponding endpoints.ExampleInput7 66 5 5 3 2 1 21 2 22 3 22 4 14 5 16 4 27 3 251 14 45 66 43 43 7Output999812-14NoteExplanation of queries: (1, 1) — one of the optimal 2-paths is the following: 1 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1. \text{Pr}(p) = (a_1 + a_2 + a_3 + a_4 + a_5) - (2 \cdot w(1,2) + 2 \cdot w(2,3) + 2 \cdot w(2,4) + 2 \cdot w(4,5)) = 21 - 2 \cdot 12 = 9. (4, 4): 4 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 4. \text{Pr}(p) = (a_1 + a_2 + a_3 + a_4) - 2 \cdot (w(1,2) + w(2,3) + w(2,4)) = 19 - 2 \cdot 10 = 9. (5, 6): 5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4 \rightarrow 6. (6, 4): 6 \rightarrow 4 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 4. (3, 4): 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4. (3, 7): 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 7. | Input7 66 5 5 3 2 1 21 2 22 3 22 4 14 5 16 4 27 3 251 14 45 66 43 43 7 | Output999812-14 | 3.5 seconds | 256 megabytes | ['data structures', 'dp', 'trees', '*2700'] |
F. One Occurrencetime limit per test3 secondsmemory limit per test768 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers, and q queries to it. i-th query is denoted by two integers l_i and r_i. For each query, you have to find any integer that occurs exactly once in the subarray of a from index l_i to index r_i (a subarray is a contiguous subsegment of an array). For example, if a = [1, 1, 2, 3, 2, 4], then for query (l_i = 2, r_i = 6) the subarray we are interested in is [1, 2, 3, 2, 4], and possible answers are 1, 3 and 4; for query (l_i = 1, r_i = 2) the subarray we are interested in is [1, 1], and there is no such element that occurs exactly once.Can you answer all of the queries?InputThe first line contains one integer n (1 \le n \le 5 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 5 \cdot 10^5).The third line contains one integer q (1 \le q \le 5 \cdot 10^5).Then q lines follow, i-th line containing two integers l_i and r_i representing i-th query (1 \le l_i \le r_i \le n).OutputAnswer the queries as follows:If there is no integer such that it occurs in the subarray from index l_i to index r_i exactly once, print 0. Otherwise print any such integer.ExampleInput61 1 2 3 2 422 61 2Output40 | Input61 1 2 3 2 422 61 2 | Output40 | 3 seconds | 768 megabytes | ['data structures', 'divide and conquer', '*2400'] |
E. We Need More Bossestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour friend is developing a computer game. He has already decided how the game world should look like — it should consist of n locations connected by m two-way passages. The passages are designed in such a way that it should be possible to get from any location to any other location.Of course, some passages should be guarded by the monsters (if you just can go everywhere without any difficulties, then it's not fun, right?). Some crucial passages will be guarded by really fearsome monsters, requiring the hero to prepare for battle and designing his own tactics of defeating them (commonly these kinds of monsters are called bosses). And your friend wants you to help him place these bosses.The game will start in location s and end in location t, but these locations are not chosen yet. After choosing these locations, your friend will place a boss in each passage such that it is impossible to get from s to t without using this passage. Your friend wants to place as much bosses as possible (because more challenges means more fun, right?), so he asks you to help him determine the maximum possible number of bosses, considering that any location can be chosen as s or as t.InputThe first line contains two integers n and m (2 \le n \le 3 \cdot 10^5, n - 1 \le m \le 3 \cdot 10^5) — the number of locations and passages, respectively.Then m lines follow, each containing two integers x and y (1 \le x, y \le n, x \ne y) describing the endpoints of one of the passages.It is guaranteed that there is no pair of locations directly connected by two or more passages, and that any location is reachable from any other location.OutputPrint one integer — the maximum number of bosses your friend can place, considering all possible choices for s and t.ExamplesInput5 51 22 33 14 15 2Output2Input4 31 24 33 2Output3 | Input5 51 22 33 14 15 2 | Output2 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'trees', '*2100'] |
D. Yet Another Problem On a Subsequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe sequence of integers a_1, a_2, \dots, a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] — are not.A sequence of integers is called good if it can be divided into a positive number of good arrays. Each good array should be a subsegment of sequence and each element of the sequence should belong to exactly one array. For example, the sequences [2, -3, 0, 1, 4], [1, 2, 3, -3, -9, 4] are good, and the sequences [2, -3, 0, 1], [1, 2, 3, -3 -9, 4, 1] — are not.For a given sequence of numbers, count the number of its subsequences that are good sequences, and print the number of such subsequences modulo 998244353.InputThe first line contains the number n~(1 \le n \le 10^3) — the length of the initial sequence. The following line contains n integers a_1, a_2, \dots, a_n~(-10^9 \le a_i \le 10^9) — the sequence itself.OutputIn the single line output one integer — the number of subsequences of the original sequence that are good sequences, taken modulo 998244353.ExamplesInput32 1 1Output2Input41 1 1 1Output7NoteIn the first test case, two good subsequences — [a_1, a_2, a_3] and [a_2, a_3].In the second test case, seven good subsequences — [a_1, a_2, a_3, a_4], [a_1, a_2], [a_1, a_3], [a_1, a_4], [a_2, a_3], [a_2, a_4] and [a_3, a_4]. | Input32 1 1 | Output2 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', '*1900'] |
C. Covered Points Counttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.Your task is the following: for every k \in [1..n], calculate the number of points with integer coordinates such that the number of segments that cover these points equals k. A segment with endpoints l_i and r_i covers point x if and only if l_i \le x \le r_i.InputThe first line of the input contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of segments.The next n lines contain segments. The i-th line contains a pair of integers l_i, r_i (0 \le l_i \le r_i \le 10^{18}) — the endpoints of the i-th segment.OutputPrint n space separated integers cnt_1, cnt_2, \dots, cnt_n, where cnt_i is equal to the number of points such that the number of segments that cover these points equals to i.ExamplesInput30 31 33 8Output6 2 1 Input31 32 45 7Output5 2 0 NoteThe picture describing the first example:Points with coordinates [0, 4, 5, 6, 7, 8] are covered by one segment, points [1, 2] are covered by two segments and point [3] is covered by three segments.The picture describing the second example:Points [1, 4, 5, 6, 7] are covered by one segment, points [2, 3] are covered by two segments and there are no points covered by three segments. | Input30 31 33 8 | Output6 2 1 | 3 seconds | 256 megabytes | ['data structures', 'implementation', 'sortings', '*1700'] |
B. Light It Uptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment 0 and turn power off at moment M. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array a, where 0 < a_1 < a_2 < \dots < a_{|a|} < M. All a_i must be integers. Of course, preinstalled program is a good program.The lamp follows program a in next manner: at moment 0 turns power and light on. Then at moment a_i the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment 1 and then do nothing, the total time when the lamp is lit will be 1. Finally, at moment M the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program a, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of a, or even at the begining or at the end of a.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from x till moment y, then its lit for y - x units of time. Segments of time when the lamp is lit are summed up.InputFirst line contains two space separated integers n and M (1 \le n \le 10^5, 2 \le M \le 10^9) — the length of program a and the moment when power turns off.Second line contains n space separated integers a_1, a_2, \dots, a_n (0 < a_1 < a_2 < \dots < a_n < M) — initially installed program a.OutputPrint the only integer — maximum possible total time when the lamp is lit.ExamplesInput3 104 6 7Output8Input2 121 10Output9Input2 73 4Output6NoteIn the first example, one of possible optimal solutions is to insert value x = 3 before a_1, so program will be [3, 4, 6, 7] and time of lamp being lit equals (3 - 0) + (6 - 4) + (10 - 7) = 8. Other possible solution is to insert x = 5 in appropriate place.In the second example, there is only one optimal solution: to insert x = 2 between a_1 and a_2. Program will become [1, 2, 10], and answer will be (1 - 0) + (10 - 2) = 9.In the third example, optimal answer is to leave program untouched, so answer will be (3 - 0) + (7 - 4) = 6. | Input3 104 6 7 | Output8 | 1 second | 256 megabytes | ['greedy', '*1500'] |
A. Codehorses T-shirtstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCodehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are n winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.InputThe first line contains one integer n (1 \le n \le 100) — the number of T-shirts.The i-th of the next n lines contains a_i — the size of the i-th T-shirt of the list for the previous year.The i-th of the next n lines contains b_i — the size of the i-th T-shirt of the list for the current year.It is guaranteed that all the sizes in the input are valid. It is also guaranteed that Ksenia can produce list b from the list a.OutputPrint the minimal number of seconds Ksenia is required to spend to change the last year list to the current one. If the lists are already equal, print 0.ExamplesInput3XSXSMXLSXSOutput2Input2XXXLXXLXXLXXXSOutput1Input2MXSXSMOutput0NoteIn the first example Ksenia can replace "M" with "S" and "S" in one of the occurrences of "XS" with "L".In the second example Ksenia should replace "L" in "XXXL" with "S".In the third example lists are equal. | Input3XSXSMXLSXS | Output2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1200'] |
F. Cards and Joytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n players sitting at the card table. Each player has a favorite number. The favorite number of the j-th player is f_j.There are k \cdot n cards on the table. Each card contains a single integer: the i-th card contains number c_i. Also, you are given a sequence h_1, h_2, \dots, h_k. Its meaning will be explained below.The players have to distribute all the cards in such a way that each of them will hold exactly k cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals h_t if the player holds t cards containing his favorite number. If a player gets no cards with his favorite number (i.e., t=0), his joy level is 0.Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence h_1, \dots, h_k is the same for all the players.InputThe first line of input contains two integers n and k (1 \le n \le 500, 1 \le k \le 10) — the number of players and the number of cards each player will get.The second line contains k \cdot n integers c_1, c_2, \dots, c_{k \cdot n} (1 \le c_i \le 10^5) — the numbers written on the cards.The third line contains n integers f_1, f_2, \dots, f_n (1 \le f_j \le 10^5) — the favorite numbers of the players.The fourth line contains k integers h_1, h_2, \dots, h_k (1 \le h_t \le 10^5), where h_t is the joy level of a player if he gets exactly t cards with his favorite number written on them. It is guaranteed that the condition h_{t - 1} < h_t holds for each t \in [2..k].OutputPrint one integer — the maximum possible total joy levels of the players among all possible card distributions.ExamplesInput4 31 3 2 8 5 5 8 2 2 8 5 21 2 2 52 6 7Output21Input3 39 9 9 9 9 9 9 9 91 2 31 2 3Output0NoteIn the first example, one possible optimal card distribution is the following: Player 1 gets cards with numbers [1, 3, 8]; Player 2 gets cards with numbers [2, 2, 8]; Player 3 gets cards with numbers [2, 2, 8]; Player 4 gets cards with numbers [5, 5, 5]. Thus, the answer is 2 + 6 + 6 + 7 = 21.In the second example, no player can get a card with his favorite number. Thus, the answer is 0. | Input4 31 3 2 8 5 5 8 2 2 8 5 21 2 2 52 6 7 | Output21 | 2 seconds | 256 megabytes | ['dp', '*2000'] |
E. Reachability from the Capitaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n cities and m roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?New roads will also be one-way.InputThe first line of input consists of three integers n, m and s (1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n) — the number of cities, the number of roads and the index of the capital. Cities are indexed from 1 to n.The following m lines contain roads: road i is given as a pair of cities u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i). For each pair of cities (u, v), there can be at most one road from u to v. Roads in opposite directions between a pair of cities are allowed (i.e. from u to v and from v to u).OutputPrint one integer — the minimum number of extra roads needed to make all the cities reachable from city s. If all the cities are already reachable from s, print 0.ExamplesInput9 9 11 21 32 31 55 66 11 89 87 1Output3Input5 4 51 22 33 44 1Output1NoteThe first example is illustrated by the following: For example, you can add roads (6, 4), (7, 9), (1, 7) to make all the cities reachable from s = 1.The second example is illustrated by the following: In this example, you can add any one of the roads (5, 1), (5, 2), (5, 3), (5, 4) to make all the cities reachable from s = 5. | Input9 9 11 21 32 31 55 66 11 89 87 1 | Output3 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'greedy', '*2000'] |
D. Equalize the Remainderstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n integers a_1, a_2, \dots, a_n, and a positive integer m. It is guaranteed that m is a divisor of n.In a single move, you can choose any position i between 1 and n and increase a_i by 1.Let's calculate c_r (0 \le r \le m-1) — the number of elements having remainder r when divided by m. In other words, for each remainder, let's find the number of corresponding elements in a with that remainder.Your task is to change the array in such a way that c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}.Find the minimum number of moves to satisfy the above requirement.InputThe first line of input contains two integers n and m (1 \le n \le 2 \cdot 10^5, 1 \le m \le n). It is guaranteed that m is a divisor of n.The second line of input contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9), the elements of the array.OutputIn the first line, print a single integer — the minimum number of moves required to satisfy the following condition: for each remainder from 0 to m - 1, the number of elements of the array having this remainder equals \frac{n}{m}.In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed 10^{18}.ExamplesInput6 33 2 0 6 10 12Output33 2 0 7 10 14 Input4 20 1 2 3Output00 1 2 3 | Input6 33 2 0 6 10 12 | Output33 2 0 7 10 14 | 3 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', '*1900'] |
C. Alphabetic Removalstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k \le n) from the string s. Polycarp uses the following algorithm k times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.Help Polycarp find the resulting string.InputThe first line of input contains two integers n and k (1 \le k \le n \le 4 \cdot 10^5) — the length of the string and the number of letters Polycarp will remove.The second line contains the string s consisting of n lowercase Latin letters.OutputPrint the string that will be obtained from s after Polycarp removes exactly k letters using the above algorithm k times.If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).ExamplesInput15 3cccaabababaccbcOutputcccbbabaccbcInput15 9cccaabababaccbcOutputccccccInput1 1uOutput | Input15 3cccaabababaccbc | Outputcccbbabaccbc | 2 seconds | 256 megabytes | ['implementation', '*1200'] |
B. Reversing Encryptiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string s of length n can be encrypted by the following algorithm: iterate over all divisors of n in decreasing order (i.e. from n to 1), for each divisor d, reverse the substring s[1 \dots d] (i.e. the substring which starts at position 1 and ends at position d). For example, the above algorithm applied to the string s="codeforces" leads to the following changes: "codeforces" \to "secrofedoc" \to "orcesfedoc" \to "rocesfedoc" \to "rocesfedoc" (obviously, the last reverse operation doesn't change the string because d=1).You are given the encrypted string t. Your task is to decrypt this string, i.e., to find a string s such that the above algorithm results in string t. It can be proven that this string s always exists and is unique.InputThe first line of input consists of a single integer n (1 \le n \le 100) — the length of the string t. The second line of input consists of the string t. The length of t is n, and it consists only of lowercase Latin letters.OutputPrint a string s such that the above algorithm results in t.ExamplesInput10rocesfedocOutputcodeforcesInput16plmaetwoxesisihtOutputthisisexampletwoInput1zOutputzNoteThe first example is described in the problem statement. | Input10rocesfedoc | Outputcodeforces | 1 second | 256 megabytes | ['implementation', '*900'] |
A. Mishka and Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k.Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses which end (left or right) he will solve the next problem from. Thus, each problem Mishka solves is either the leftmost or the rightmost problem in the list.Mishka cannot solve a problem with difficulty greater than k. When Mishka solves the problem, it disappears from the list, so the length of the list decreases by 1. Mishka stops when he is unable to solve any problem from any end of the list.How many problems can Mishka solve?InputThe first line of input contains two integers n and k (1 \le n, k \le 100) — the number of problems in the contest and Mishka's problem-solving skill.The second line of input contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the difficulty of the i-th problem. The problems are given in order from the leftmost to the rightmost in the list.OutputPrint one integer — the maximum number of problems Mishka can solve.ExamplesInput8 44 2 3 1 5 1 6 4Output5Input5 23 1 2 1 3Output0Input5 10012 34 55 43 21Output5NoteIn the first example, Mishka can solve problems in the following order: [4, 2, 3, 1, 5, 1, 6, 4] \rightarrow [2, 3, 1, 5, 1, 6, 4] \rightarrow [2, 3, 1, 5, 1, 6] \rightarrow [3, 1, 5, 1, 6] \rightarrow [1, 5, 1, 6] \rightarrow [5, 1, 6], so the number of solved problems will be equal to 5.In the second example, Mishka can't solve any problem because the difficulties of problems from both ends are greater than k.In the third example, Mishka's solving skill is so amazing that he can solve all the problems. | Input8 44 2 3 1 5 1 6 4 | Output5 | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
B. Cuttingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, [4, 1, 2, 3, 4, 5, 4, 4, 5, 5] \to two cuts \to [4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]. On each segment the number of even elements should be equal to the number of odd elements.The cost of the cut between x and y numbers is |x - y| bitcoins. Find the maximum possible number of cuts that can be made while spending no more than B bitcoins.InputFirst line of the input contains an integer n (2 \le n \le 100) and an integer B (1 \le B \le 100) — the number of elements in the sequence and the number of bitcoins you have.Second line contains n integers: a_1, a_2, ..., a_n (1 \le a_i \le 100) — elements of the sequence, which contains the equal number of even and odd numbersOutputPrint the maximum possible number of cuts which can be made while spending no more than B bitcoins.ExamplesInput6 41 2 5 10 15 20Output1Input4 101 3 2 4Output0Input6 1001 2 3 4 5 6Output2NoteIn the first sample the optimal answer is to split sequence between 2 and 5. Price of this cut is equal to 3 bitcoins.In the second sample it is not possible to make even one cut even with unlimited number of bitcoins.In the third sample the sequence should be cut between 2 and 3, and between 4 and 5. The total price of the cuts is 1 + 1 = 2 bitcoins. | Input6 41 2 5 10 15 20 | Output1 | 2 seconds | 256 megabytes | ['dp', 'greedy', 'sortings', '*1200'] |
A. Balloonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold: Do not rip the packets (both Grigory and Andrew should get unbroken packets); Distribute all packets (every packet should be given to someone); Give both Grigory and Andrew at least one packet; To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.InputThe first line of input contains a single integer n (1 \le n \le 10) — the number of packets with balloons.The second line contains n integers: a_1, a_2, \ldots, a_n (1 \le a_i \le 1000) — the number of balloons inside the corresponding packet.OutputIf it's impossible to divide the balloons satisfying the conditions above, print -1.Otherwise, print an integer k — the number of packets to give to Grigory followed by k distinct integers from 1 to n — the indices of those. The order of packets doesn't matter.If there are multiple ways to divide balloons, output any of them.ExamplesInput31 2 1Output21 2Input25 5Output-1Input110Output-1NoteIn the first test Grigory gets 3 balloons in total while Andrey gets 1.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all. | Input31 2 1 | Output21 2 | 1 second | 256 megabytes | ['constructive algorithms', 'implementation', '*1000'] |
E. Good Subsegmentstime limit per test7 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA permutation p of length n is a sequence p_1, p_2, \ldots, p_n consisting of n distinct integers, each of which from 1 to n (1 \leq p_i \leq n) .Let's call the subsegment [l,r] of the permutation good if all numbers from the minimum on it to the maximum on this subsegment occur among the numbers p_l, p_{l+1}, \dots, p_r.For example, good segments of permutation [1, 3, 2, 5, 4] are: [1, 1], [1, 3], [1, 5], [2, 2], [2, 3], [2, 5], [3, 3], [4, 4], [4, 5], [5, 5]. You are given a permutation p_1, p_2, \ldots, p_n.You need to answer q queries of the form: find the number of good subsegments of the given segment of permutation.In other words, to answer one query, you need to calculate the number of good subsegments [x \dots y] for some given segment [l \dots r], such that l \leq x \leq y \leq r.InputThe first line contains a single integer n (1 \leq n \leq 120000) — the number of elements in the permutation.The second line contains n distinct integers p_1, p_2, \ldots, p_n separated by spaces (1 \leq p_i \leq n).The third line contains an integer q (1 \leq q \leq 120000) — number of queries.The following q lines describe queries, each line contains a pair of integers l, r separated by space (1 \leq l \leq r \leq n).OutputPrint a q lines, i-th of them should contain a number of good subsegments of a segment, given in the i-th query.ExampleInput51 3 2 5 4151 11 21 31 41 52 22 32 42 53 33 43 54 44 55 5Output1256101347124131 | Input51 3 2 5 4151 11 21 31 41 52 22 32 42 53 33 43 54 44 55 5 | Output1256101347124131 | 7 seconds | 512 megabytes | ['data structures', '*3000'] |
D. Cycles in producttime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 \times T_2 in a following way.Let V be the set of vertices in T_1 and U be the set of vertices in T_2.Then the set of vertices of graph T_1 \times T_2 is V \times U, that is, a set of ordered pairs of vertices, where the first vertex in pair is from V and the second — from U.Let's draw the following edges: Between (v, u_1) and (v, u_2) there is an undirected edge, if u_1 and u_2 are adjacent in U. Similarly, between (v_1, u) and (v_2, u) there is an undirected edge, if v_1 and v_2 are adjacent in V. Please see the notes section for the pictures of products of trees in the sample tests.Let's examine the graph T_1 \times T_2. How much cycles (not necessarily simple) of length k it contains? Since this number can be very large, print it modulo 998244353.The sequence of vertices w_1, w_2, ..., w_k, where w_i \in V \times U called cycle, if any neighboring vertices are adjacent and w_1 is adjacent to w_k. Cycles that differ only by the cyclic shift or direction of traversal are still considered different.InputFirst line of input contains three integers — n_1, n_2 and k (2 \le n_1, n_2 \le 4000, 2 \le k \le 75) — number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively.Then follow n_1 - 1 lines describing the first tree. Each of this lines contains two integers — v_i, u_i (1 \le v_i, u_i \le n_1), which define edges of the first tree.Then follow n_2 - 1 lines, which describe the second tree in the same format.It is guaranteed, that given graphs are trees.OutputPrint one integer — number of cycles modulo 998244353.ExamplesInput2 2 21 21 2Output8Input2 2 41 21 2Output32Input2 3 41 21 21 3Output70Input4 2 21 21 31 41 2Output20NoteThe following three pictures illustrate graph, which are products of the trees from sample tests.In the first example, the list of cycles of length 2 is as follows: «AB», «BA» «BC», «CB» «AD», «DA» «CD», «DC» | Input2 2 21 21 2 | Output8 | 7 seconds | 256 megabytes | ['combinatorics', 'divide and conquer', 'trees', '*2900'] |
C. Sky Full of Starstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn one of the planets of Solar system, in Atmosphere University, many students are fans of bingo game.It is well known that one month on this planet consists of n^2 days, so calendars, represented as square matrix n by n are extremely popular.Weather conditions are even more unusual. Due to the unique composition of the atmosphere, when interacting with sunlight, every day sky takes one of three colors: blue, green or red.To play the bingo, you need to observe the sky for one month — after each day, its cell is painted with the color of the sky in that day, that is, blue, green or red.At the end of the month, students examine the calendar. If at least one row or column contains only cells of one color, that month is called lucky.Let's call two colorings of calendar different, if at least one cell has different colors in them. It is easy to see that there are 3^{n \cdot n} different colorings. How much of them are lucky? Since this number can be quite large, print it modulo 998244353.InputThe first and only line of input contains a single integer n (1 \le n \le 1000\,000) — the number of rows and columns in the calendar.OutputPrint one number — number of lucky colorings of the calendar modulo 998244353ExamplesInput1Output3Input2Output63Input3Output9933NoteIn the first sample any coloring is lucky, since the only column contains cells of only one color.In the second sample, there are a lot of lucky colorings, in particular, the following colorings are lucky: While these colorings are not lucky: | Input1 | Output3 | 4 seconds | 256 megabytes | ['combinatorics', 'math', '*2500'] |
B. Roman Digitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed.Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as the sum of digits in it.For example, the number XXXV evaluates to 35 and the number IXI — to 12.Pay attention to the difference to the traditional roman system — in our system any sequence of digits is valid, moreover the order of digits doesn't matter, for example IX means 11, not 9.One can notice that this system is ambiguous, and some numbers can be written in many different ways. Your goal is to determine how many distinct integers can be represented by exactly n roman digits I, V, X, L.InputThe only line of the input file contains a single integer n (1 \le n \le 10^9) — the number of roman digits to use.OutputOutput a single integer — the number of distinct integers which can be represented using n roman digits exactly.ExamplesInput1Output4Input2Output10Input10Output244NoteIn the first sample there are exactly 4 integers which can be represented — I, V, X and L.In the second sample it is possible to represent integers 2 (II), 6 (VI), 10 (VV), 11 (XI), 15 (XV), 20 (XX), 51 (IL), 55 (VL), 60 (XL) and 100 (LL). | Input1 | Output4 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'dp', 'greedy', 'math', '*2000'] |
A. Convert to Onestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou've got a string a_1, a_2, \dots, a_n, consisting of zeros and ones.Let's call a sequence of consecutive elements a_i, a_{i + 1}, \ldots, a_j (1\leq i\leq j\leq n) a substring of string a. You can apply the following operations any number of times: Choose some substring of string a (for example, you can choose entire string) and reverse it, paying x coins for it (for example, «0101101» \to «0111001»); Choose some substring of string a (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying y coins for it (for example, «0101101» \to «0110001»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?InputThe first line of input contains integers n, x and y (1 \leq n \leq 300\,000, 0 \leq x, y \leq 10^9) — length of the string, cost of the first operation (substring reverse) and cost of the second operation (inverting all elements of substring).The second line contains the string a of length n, consisting of zeros and ones.OutputPrint a single integer — the minimum total cost of operations you need to spend to get a string consisting only of ones. Print 0, if you do not need to perform any operations.ExamplesInput5 1 1001000Output11Input5 10 101000Output2Input7 2 31111111Output0NoteIn the first sample, at first you need to reverse substring [1 \dots 2], and then you need to invert substring [2 \dots 5]. Then the string was changed as follows:«01000» \to «10000» \to «11111».The total cost of operations is 1 + 10 = 11.In the second sample, at first you need to invert substring [1 \dots 1], and then you need to invert substring [3 \dots 5]. Then the string was changed as follows:«01000» \to «11000» \to «11111».The overall cost is 1 + 1 = 2.In the third example, string already consists only of ones, so the answer is 0. | Input5 1 1001000 | Output11 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*1500'] |
B. World Cuptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen wants to enter a fan zone that occupies a round square and has n entrances.There already is a queue of a_i people in front of the i-th entrance. Each entrance allows one person from its queue to enter the fan zone in one minute.Allen uses the following strategy to enter the fan zone: Initially he stands in the end of the queue in front of the first entrance. Each minute, if he is not allowed into the fan zone during the minute (meaning he is not the first in the queue), he leaves the current queue and stands in the end of the queue of the next entrance (or the first entrance if he leaves the last entrance). Determine the entrance through which Allen will finally enter the fan zone.InputThe first line contains a single integer n (2 \le n \le 10^5) — the number of entrances.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the number of people in queues. These numbers do not include Allen.OutputPrint a single integer — the number of entrance that Allen will use.ExamplesInput42 3 2 0Output3Input210 10Output1Input65 2 6 5 7 4Output6NoteIn the first example the number of people (not including Allen) changes as follows: [\textbf{2}, 3, 2, 0] \to [1, \textbf{2}, 1, 0] \to [0, 1, \textbf{0}, 0]. The number in bold is the queue Alles stands in. We see that he will enter the fan zone through the third entrance.In the second example the number of people (not including Allen) changes as follows: [\textbf{10}, 10] \to [9, \textbf{9}] \to [\textbf{8}, 8] \to [7, \textbf{7}] \to [\textbf{6}, 6] \to \\ [5, \textbf{5}] \to [\textbf{4}, 4] \to [3, \textbf{3}] \to [\textbf{2}, 2] \to [1, \textbf{1}] \to [\textbf{0}, 0].In the third example the number of people (not including Allen) changes as follows: [\textbf{5}, 2, 6, 5, 7, 4] \to [4, \textbf{1}, 5, 4, 6, 3] \to [3, 0, \textbf{4}, 3, 5, 2] \to \\ [2, 0, 3, \textbf{2}, 4, 1] \to [1, 0, 2, 1, \textbf{3}, 0] \to [0, 0, 1, 0, 2, \textbf{0}]. | Input42 3 2 0 | Output3 | 1 second | 256 megabytes | ['binary search', 'math', '*1300'] |
A. Hit the Lotterytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?InputThe first and only line of input contains a single integer n (1 \le n \le 10^9).OutputOutput the minimum number of bills that Allen could receive.ExamplesInput125Output3Input43Output5Input1000000000Output10000000NoteIn the first sample case, Allen can withdraw this with a 100 dollar bill, a 20 dollar bill, and a 5 dollar bill. There is no way for Allen to receive 125 dollars in one or two bills.In the second sample case, Allen can withdraw two 20 dollar bills and three 1 dollar bills.In the third sample case, Allen can withdraw 100000000 (ten million!) 100 dollar bills. | Input125 | Output3 | 1 second | 256 megabytes | ['dp', 'greedy', '*800'] |
F. Cowmpany Cowmpensationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen, having graduated from the MOO Institute of Techcowlogy (MIT), has started a startup! Allen is the president of his startup. He also hires n-1 other employees, each of which is assigned a direct superior. If u is a superior of v and v is a superior of w then also u is a superior of w. Additionally, there are no u and v such that u is the superior of v and v is the superior of u. Allen himself has no superior. Allen is employee number 1, and the others are employee numbers 2 through n.Finally, Allen must assign salaries to each employee in the company including himself. Due to budget constraints, each employee's salary is an integer between 1 and D. Additionally, no employee can make strictly more than his superior.Help Allen find the number of ways to assign salaries. As this number may be large, output it modulo 10^9 + 7.InputThe first line of the input contains two integers n and D (1 \le n \le 3000, 1 \le D \le 10^9).The remaining n-1 lines each contain a single positive integer, where the i-th line contains the integer p_i (1 \le p_i \le i). p_i denotes the direct superior of employee i+1.OutputOutput a single integer: the number of ways to assign salaries modulo 10^9 + 7.ExamplesInput3 211Output5Input3 312Output10Input2 51Output15NoteIn the first sample case, employee 2 and 3 report directly to Allen. The three salaries, in order, can be (1,1,1), (2,1,1), (2,1,2), (2,2,1) or (2,2,2).In the second sample case, employee 2 reports to Allen and employee 3 reports to employee 2. In order, the possible salaries are (1,1,1), (2,1,1), (2,2,1), (2,2,2), (3,1,1), (3,2,1), (3,2,2), (3,3,1), (3,3,2), (3,3,3). | Input3 211 | Output5 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'math', 'trees', '*2700'] |
E. Number Clickertime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen is playing Number Clicker on his phone.He starts with an integer u on the screen. Every second, he can press one of 3 buttons. Turn u \to u+1 \pmod{p}. Turn u \to u+p-1 \pmod{p}. Turn u \to u^{p-2} \pmod{p}. Allen wants to press at most 200 buttons and end up with v on the screen. Help him!InputThe first line of the input contains 3 positive integers: u, v, p (0 \le u, v \le p-1, 3 \le p \le 10^9 + 9). p is guaranteed to be prime.OutputOn the first line, print a single integer \ell, the number of button presses. On the second line, print integers c_1, \dots, c_\ell, the button presses. For 1 \le i \le \ell, 1 \le c_i \le 3.We can show that the answer always exists.ExamplesInput1 3 5Output21 1Input3 2 5Output13NoteIn the first example the integer on the screen changes as 1 \to 2 \to 3.In the second example the integer on the screen changes as 3 \to 2. | Input1 3 5 | Output21 1 | 5 seconds | 256 megabytes | ['divide and conquer', 'graphs', 'meet-in-the-middle', 'number theory', '*2700'] |
D. Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen and Bessie are playing a simple number game. They both know a function f: \{0, 1\}^n \to \mathbb{R}, i. e. the function takes n binary arguments and returns a real value. At the start of the game, the variables x_1, x_2, \dots, x_n are all set to -1. Each round, with equal probability, one of Allen or Bessie gets to make a move. A move consists of picking an i such that x_i = -1 and either setting x_i \to 0 or x_i \to 1.After n rounds all variables are set, and the game value resolves to f(x_1, x_2, \dots, x_n). Allen wants to maximize the game value, and Bessie wants to minimize it.Your goal is to help Allen and Bessie find the expected game value! They will play r+1 times though, so between each game, exactly one value of f changes. In other words, between rounds i and i+1 for 1 \le i \le r, f(z_1, \dots, z_n) \to g_i for some (z_1, \dots, z_n) \in \{0, 1\}^n. You are to find the expected game value in the beginning and after each change.InputThe first line contains two integers n and r (1 \le n \le 18, 0 \le r \le 2^{18}).The next line contains 2^n integers c_0, c_1, \dots, c_{2^n-1} (0 \le c_i \le 10^9), denoting the initial values of f. More specifically, f(x_0, x_1, \dots, x_{n-1}) = c_x, if x = \overline{x_{n-1} \ldots x_0} in binary.Each of the next r lines contains two integers z and g (0 \le z \le 2^n - 1, 0 \le g \le 10^9). If z = \overline{z_{n-1} \dots z_0} in binary, then this means to set f(z_0, \dots, z_{n-1}) \to g.OutputPrint r+1 lines, the i-th of which denotes the value of the game f during the i-th round. Your answer must have absolute or relative error within 10^{-6}.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^{-6}.ExamplesInput2 20 1 2 32 50 4Output1.5000002.2500003.250000Input1 02 3Output2.500000Input2 01 1 1 1Output1.000000NoteConsider the second test case. If Allen goes first, he will set x_1 \to 1, so the final value will be 3. If Bessie goes first, then she will set x_1 \to 0 so the final value will be 2. Thus the answer is 2.5.In the third test case, the game value will always be 1 regardless of Allen and Bessie's play. | Input2 20 1 2 32 50 4 | Output1.5000002.2500003.250000 | 3 seconds | 256 megabytes | ['math', '*2500'] |
C. Leaving the Bartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a vector \vec{v} = (x, y), define |v| = \sqrt{x^2 + y^2}.Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, \cdots, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_i} or -\vec{v_i}. In other words, if his position is currently p = (x, y), he will either move to p + \vec{v_i} or p - \vec{v_i}.Allen doesn't want to wander too far from home (which happens to also be the bar). You need to help him figure out a sequence of moves (a sequence of signs for the vectors) such that his final position p satisfies |p| \le 1.5 \cdot 10^6 so that he can stay safe.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of moves.Each of the following lines contains two space-separated integers x_i and y_i, meaning that \vec{v_i} = (x_i, y_i). We have that |v_i| \le 10^6 for all i.OutputOutput a single line containing n integers c_1, c_2, \cdots, c_n, each of which is either 1 or -1. Your solution is correct if the value of p = \sum_{i = 1}^n c_i \vec{v_i}, satisfies |p| \le 1.5 \cdot 10^6.It can be shown that a solution always exists under the given constraints.ExamplesInput3999999 00 999999999999 0Output1 1 -1 Input1-824590 246031Output1 Input8-67761 603277640586 -39667146147 -122580569609 -2112400 914208131792 309779-850150 -4862935272 721899Output1 1 1 1 1 1 1 -1 | Input3999999 00 999999999999 0 | Output1 1 -1 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'geometry', 'greedy', 'math', 'sortings', '*2300'] |
B. Suit and Tietime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture more aesthetic.Help Allen find the minimum number of swaps of adjacent positions he must perform to make it so that each couple occupies adjacent positions in the line.InputThe first line contains a single integer n (1 \le n \le 100), the number of pairs of people.The second line contains 2n integers a_1, a_2, \dots, a_{2n}. For each i with 1 \le i \le n, i appears exactly twice. If a_j = a_k = i, that means that the j-th and k-th people in the line form a couple.OutputOutput a single integer, representing the minimum number of adjacent swaps needed to line the people up so that each pair occupies adjacent positions.ExamplesInput41 1 2 3 3 2 4 4Output2Input31 1 2 2 3 3Output0Input33 1 2 3 1 2Output3NoteIn the first sample case, we can transform 1 1 2 3 3 2 4 4 \rightarrow 1 1 2 3 2 3 4 4 \rightarrow 1 1 2 2 3 3 4 4 in two steps. Note that the sequence 1 1 2 3 3 2 4 4 \rightarrow 1 1 3 2 3 2 4 4 \rightarrow 1 1 3 3 2 2 4 4 also works in the same number of steps.The second sample case already satisfies the constraints; therefore we need 0 swaps. | Input41 1 2 3 3 2 4 4 | Output2 | 2 seconds | 256 megabytes | ['greedy', 'implementation', 'math', '*1400'] |
A. Teslatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be represented as a rectangle with 4 rows and n (n \le 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k \le 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places. Illustration to the first example. However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space. Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.InputThe first line of the input contains two space-separated integers n and k (1 \le n \le 50, 1 \le k \le 2n), representing the number of columns and the number of cars, respectively.The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.In the first and last line, an integer 1 \le x \le k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).In the second and third line, an integer 1 \le x \le k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.OutputIf there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.ExamplesInput4 51 2 0 41 2 0 45 0 0 30 5 0 3Output61 1 12 1 24 1 43 4 45 3 25 4 2Input1 21212Output-1Input1 21122Output21 1 12 4 1NoteIn the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible. | Input4 51 2 0 41 2 0 45 0 0 30 5 0 3 | Output61 1 12 1 24 1 43 4 45 3 25 4 2 | 3 seconds | 256 megabytes | ['constructive algorithms', 'implementation', '*2100'] |
B. Knights of a Polygonal Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputUnlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no more than k other knights. Also, each knight has some number of coins. After a kill, a knight can pick up all victim's coins.Now each knight ponders: how many coins he can have if only he kills other knights?You should answer this question for each knight.InputThe first line contains two integers n and k (1 \le n \le 10^5, 0 \le k \le \min(n-1,10)) — the number of knights and the number k from the statement.The second line contains n integers p_1, p_2 ,\ldots,p_n (1 \le p_i \le 10^9) — powers of the knights. All p_i are distinct.The third line contains n integers c_1, c_2 ,\ldots,c_n (0 \le c_i \le 10^9) — the number of coins each knight has.OutputPrint n integers — the maximum number of coins each knight can have it only he kills other knights.ExamplesInput4 24 5 9 71 2 11 33Output1 3 46 36 Input5 11 2 3 4 51 2 3 4 5Output1 3 5 7 9 Input1 023Output3 NoteConsider the first example. The first knight is the weakest, so he can't kill anyone. That leaves him with the only coin he initially has. The second knight can kill the first knight and add his coin to his own two. The third knight is the strongest, but he can't kill more than k = 2 other knights. It is optimal to kill the second and the fourth knights: 2+11+33 = 46. The fourth knight should kill the first and the second knights: 33+1+2 = 36. In the second example the first knight can't kill anyone, while all the others should kill the one with the index less by one than their own.In the third example there is only one knight, so he can't kill anyone. | Input4 24 5 9 71 2 11 33 | Output1 3 46 36 | 1 second | 256 megabytes | ['greedy', 'implementation', 'sortings', '*1400'] |
A. Fingerprintstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are locked in a room with a door that has a keypad with 10 keys corresponding to digits from 0 to 9. To escape from the room, you need to enter a correct code. You also have a sequence of digits.Some keys on the keypad have fingerprints. You believe the correct code is the longest not necessarily contiguous subsequence of the sequence you have that only contains digits with fingerprints on the corresponding keys. Find such code.InputThe first line contains two integers n and m (1 \le n, m \le 10) representing the number of digits in the sequence you have and the number of keys on the keypad that have fingerprints.The next line contains n distinct space-separated integers x_1, x_2, \ldots, x_n (0 \le x_i \le 9) representing the sequence.The next line contains m distinct space-separated integers y_1, y_2, \ldots, y_m (0 \le y_i \le 9) — the keys with fingerprints.OutputIn a single line print a space-separated sequence of integers representing the code. If the resulting sequence is empty, both printing nothing and printing a single line break is acceptable.ExamplesInput7 33 5 7 1 6 2 81 2 7Output7 1 2Input4 43 4 1 00 1 7 9Output1 0NoteIn the first example, the only digits with fingerprints are 1, 2 and 7. All three of them appear in the sequence you know, 7 first, then 1 and then 2. Therefore the output is 7 1 2. Note that the order is important, and shall be the same as the order in the original sequence.In the second example digits 0, 1, 7 and 9 have fingerprints, however only 0 and 1 appear in the original sequence. 1 appears earlier, so the output is 1 0. Again, the order is important. | Input7 33 5 7 1 6 2 81 2 7 | Output7 1 2 | 1 second | 256 megabytes | ['implementation', '*800'] |
F. The Moral Dilemmatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHibiki and Dita are in love with each other, but belong to communities that are in a long lasting conflict. Hibiki is deeply concerned with the state of affairs, and wants to figure out if his relationship with Dita is an act of love or an act of treason. Hibiki prepared several binary features his decision will depend on, and built a three layer logical circuit on top of them, each layer consisting of one or more logic gates. Each gate in the circuit is either "or", "and", "nor" (not or) or "nand" (not and). Each gate in the first layer is connected to exactly two features. Each gate in the second layer is connected to exactly two gates in the first layer. The third layer has only one "or" gate, which is connected to all the gates in the second layer (in other words, the entire circuit produces 1 if and only if at least one gate in the second layer produces 1).The problem is, Hibiki knows very well that when the person is in love, his ability to think logically degrades drastically. In particular, it is well known that when a person in love evaluates a logical circuit in his mind, every gate evaluates to a value that is the opposite of what it was supposed to evaluate to. For example, "or" gates return 1 if and only if both inputs are zero, "t{nand}" gates produce 1 if and only if both inputs are one etc.In particular, the "or" gate in the last layer also produces opposite results, and as such if Hibiki is in love, the entire circuit produces 1 if and only if all the gates on the second layer produced 0.Hibiki can’t allow love to affect his decision. He wants to know what is the smallest number of gates that needs to be removed from the second layer so that the output of the circuit for all possible inputs doesn't depend on whether Hibiki is in love or not.InputThe first line contains three integers n, m, k (2 \le n, m \le 50; 1 \le k \le 50) — the number of input features, the number of gates in the first layer, and the number of gates in the second layer correspondingly.The second line contains m pairs of strings separated by spaces describing the first layer. The first string in each pair describes the gate ("and", "or", "nand" or "nor"), and the second string describes the two input features the gate is connected two as a string consisting of exactly n characters, with exactly two characters (that correspond to the input features the gate is connected to) equal to 'x' and the remaining characters equal to ".'.The third line contains k pairs of strings separated by spaces describing the second layer in the same format, where the strings that describe the input parameters have length m and correspond to the gates of the first layer.OutputPrint the number of gates that need to be removed from the second layer so that the output of the remaining circuit doesn't depend on whether Hibiki is in love or not.If no matter how many gates are removed the output of the circuit continues to depend on Hibiki's feelings, print -1.ExamplesInput2 2 2and xx nand xxand xx or xxOutput1Input3 2 2and xx. nor .xxand xx nor xxOutput-1Input4 4 5nor x..x and ..xx and xx.. nand xx..nand ..xx nor ..xx and xx.. nor ..xx or ..xxOutput2NoteIn the first example the two gates in the first layer are connected to the same inputs, but first computes "and" while second computes "nand", and as such their output is always different no matter what the input is and whether Hibiki is in love or not. The second layer has "or" and "and" gates both connected to the two gates in the first layer. If Hibiki is not in love, the "and" gate will produce 0 and the "or" gate will produce 1 no matter what input features are equal to, with the final "or" gate in the third layer always producing the final answer of 1. If Hibiki is in love, "and" gate in the second layer will produce 1 and "or" gate will produce 0 no matter what the input is, with the final "or" gate in the third layer producing the final answer of 0. Thus, if both gates in the second layer are kept, the output of the circuit does depend on whether Hibiki is in love. If any of the two gates in the second layer is dropped, the output of the circuit will no longer depend on whether Hibiki is in love or not, and hence the answer is 1.In the second example no matter what gates are left in the second layer, the output of the circuit will depend on whether Hibiki is in love or not.In the third example if Hibiki keeps second, third and fourth gates in the second layer, the circuit will not depend on whether Hibiki is in love or not. Alternatively, he can keep the first and the last gates. The former requires removing two gates, the latter requires removing three gates, so the former is better, and the answer is 2. | Input2 2 2and xx nand xxand xx or xx | Output1 | 1 second | 256 megabytes | ['*3200'] |
E. Nikita and Order Statisticstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikita likes tasks on order statistics, for example, he can easily find the k-th number in increasing order on a segment of an array. But now Nikita wonders how many segments of an array there are such that a given number x is the k-th number in increasing order on this segment. In other words, you should find the number of segments of a given array such that there are exactly k numbers of this segment which are less than x.Nikita wants to get answer for this question for each k from 0 to n, where n is the size of the array.InputThe first line contains two integers n and x (1 \le n \le 2 \cdot 10^5, -10^9 \le x \le 10^9).The second line contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the given array.OutputPrint n+1 integers, where the i-th number is the answer for Nikita's question for k=i-1.ExamplesInput5 31 2 3 4 5Output6 5 4 0 0 0 Input2 6-5 9Output1 2 0 Input6 99-1 -1 -1 -1 -1 -1Output0 6 5 4 3 2 1 | Input5 31 2 3 4 5 | Output6 5 4 0 0 0 | 2 seconds | 256 megabytes | ['chinese remainder theorem', 'fft', 'math', '*2300'] |
D. Compute Powertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou need to execute several tasks, each associated with number of processors it needs, and the compute power it will consume.You have sufficient number of analog computers, each with enough processors for any task. Each computer can execute up to one task at a time, and no more than two tasks total. The first task can be any, the second task on each computer must use strictly less power than the first. You will assign between 1 and 2 tasks to each computer. You will then first execute the first task on each computer, wait for all of them to complete, and then execute the second task on each computer that has two tasks assigned.If the average compute power per utilized processor (the sum of all consumed powers for all tasks presently running divided by the number of utilized processors) across all computers exceeds some unknown threshold during the execution of the first tasks, the entire system will blow up. There is no restriction on the second tasks execution. Find the lowest threshold for which it is possible.Due to the specifics of the task, you need to print the answer multiplied by 1000 and rounded up.InputThe first line contains a single integer n (1 ≤ n ≤ 50) — the number of tasks.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108), where ai represents the amount of power required for the i-th task.The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100), where bi is the number of processors that i-th task will utilize.OutputPrint a single integer value — the lowest threshold for which it is possible to assign all tasks in such a way that the system will not blow up after the first round of computation, multiplied by 1000 and rounded up.ExamplesInput68 10 9 9 8 101 1 1 1 1 1Output9000Input68 10 9 9 8 101 10 5 5 1 10Output1160NoteIn the first example the best strategy is to run each task on a separate computer, getting average compute per processor during the first round equal to 9.In the second task it is best to run tasks with compute 10 and 9 on one computer, tasks with compute 10 and 8 on another, and tasks with compute 9 and 8 on the last, averaging (10 + 10 + 9) / (10 + 10 + 5) = 1.16 compute power per processor during the first round. | Input68 10 9 9 8 101 1 1 1 1 1 | Output9000 | 1 second | 256 megabytes | ['binary search', 'dp', 'greedy', '*2500'] |
C. Careful Maneuveringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to 100.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with x=0 (with not necessarily integer y-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.InputThe first line contains two integers n and m (1 \le n, m \le 60), the number of enemy spaceships with x = -100 and the number of enemy spaceships with x = 100, respectively.The second line contains n integers y_{1,1}, y_{1,2}, \ldots, y_{1,n} (|y_{1,i}| \le 10\,000) — the y-coordinates of the spaceships in the first group.The third line contains m integers y_{2,1}, y_{2,2}, \ldots, y_{2,m} (|y_{2,i}| \le 10\,000) — the y-coordinates of the spaceships in the second group.The y coordinates are not guaranteed to be unique, even within a group.OutputPrint a single integer – the largest number of enemy spaceships that can be destroyed.ExamplesInput3 91 2 31 2 3 7 8 9 11 12 13Output9Input5 51 2 3 4 51 2 3 4 5Output10NoteIn the first example the first spaceship can be positioned at (0, 2), and the second – at (0, 7). This way all the enemy spaceships in the first group and 6 out of 9 spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at (0, 3), and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships. | Input3 91 2 31 2 3 7 8 9 11 12 13 | Output9 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'geometry', '*2100'] |
B. Open Communicationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you.Both participants communicated to each other a set of pairs of numbers, that includes the pair given to them. Each pair in the communicated sets comprises two different numbers.Determine if you can with certainty deduce the common number, or if you can determine with certainty that both participants know the number but you do not.InputThe first line contains two integers n and m (1 \le n, m \le 12) — the number of pairs the first participant communicated to the second and vice versa.The second line contains n pairs of integers, each between 1 and 9, — pairs of numbers communicated from first participant to the second.The third line contains m pairs of integers, each between 1 and 9, — pairs of numbers communicated from the second participant to the first.All pairs within each set are distinct (in particular, if there is a pair (1,2), there will be no pair (2,1) within the same set), and no pair contains the same number twice.It is guaranteed that the two sets do not contradict the statements, in other words, there is pair from the first set and a pair from the second set that share exactly one number.OutputIf you can deduce the shared number with certainty, print that number.If you can with certainty deduce that both participants know the shared number, but you do not know it, print 0.Otherwise print -1.ExamplesInput2 21 2 3 41 5 3 4Output1Input2 21 2 3 41 5 6 4Output0Input2 31 2 4 51 2 1 3 2 3Output-1NoteIn the first example the first participant communicated pairs (1,2) and (3,4), and the second communicated (1,5), (3,4). Since we know that the actual pairs they received share exactly one number, it can't be that they both have (3,4). Thus, the first participant has (1,2) and the second has (1,5), and at this point you already know the shared number is 1.In the second example either the first participant has (1,2) and the second has (1,5), or the first has (3,4) and the second has (6,4). In the first case both of them know the shared number is 1, in the second case both of them know the shared number is 4. You don't have enough information to tell 1 and 4 apart.In the third case if the first participant was given (1,2), they don't know what the shared number is, since from their perspective the second participant might have been given either (1,3), in which case the shared number is 1, or (2,3), in which case the shared number is 2. While the second participant does know the number with certainty, neither you nor the first participant do, so the output is -1. | Input2 21 2 3 41 5 3 4 | Output1 | 1 second | 256 megabytes | ['bitmasks', 'brute force', '*1900'] |
A. Two Squarestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two squares, one with sides parallel to the coordinate axes, and another one with sides at 45 degrees to the coordinate axes. Find whether the two squares intersect.The interior of the square is considered to be part of the square, i.e. if one square is completely inside another, they intersect. If the two squares only share one common point, they are also considered to intersect.InputThe input data consists of two lines, one for each square, both containing 4 pairs of integers. Each pair represents coordinates of one vertex of the square. Coordinates within each line are either in clockwise or counterclockwise order.The first line contains the coordinates of the square with sides parallel to the coordinate axes, the second line contains the coordinates of the square at 45 degrees.All the values are integer and between -100 and 100.OutputPrint "Yes" if squares intersect, otherwise print "No".You can print each letter in any case (upper or lower).ExamplesInput0 0 6 0 6 6 0 61 3 3 5 5 3 3 1OutputYESInput0 0 6 0 6 6 0 67 3 9 5 11 3 9 1OutputNOInput6 0 6 6 0 6 0 07 4 4 7 7 10 10 7OutputYESNoteIn the first example the second square lies entirely within the first square, so they do intersect.In the second sample squares do not have any points in common.Here are images corresponding to the samples: | Input0 0 6 0 6 6 0 61 3 3 5 5 3 3 1 | OutputYES | 1 second | 256 megabytes | ['geometry', 'implementation', '*1600'] |
E. Nastya and King-Shamanstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya likes reading and even spends whole days in a library sometimes. Today she found a chronicle of Byteland in the library, and it stated that there lived shamans long time ago. It is known that at every moment there was exactly one shaman in Byteland, and there were n shamans in total enumerated with integers from 1 to n in the order they lived. Also, each shaman had a magic power which can now be expressed as an integer.The chronicle includes a list of powers of the n shamans. Also, some shamans can be king-shamans, if they gathered all the power of their predecessors, i.e. their power is exactly the sum of powers of all previous shamans. Nastya is interested in whether there was at least one king-shaman in Byteland.Unfortunately many of the powers are unreadable in the list, so Nastya is doing the following: Initially she supposes some power for each shaman. After that she changes the power of some shaman q times (the shamans can differ) and after that wants to check if there is at least one king-shaman in the list. If yes, she wants to know the index of any king-shaman. Unfortunately the list is too large and Nastya wants you to help her.InputThe first line contains two integers n and q (1 ≤ n, q ≤ 2·105).The second line contains n integers a1, ..., an (0 ≤ ai ≤ 109), where ai is the magic power of the i-th shaman.After that q lines follow, the i-th of them contains two integers pi and xi (1 ≤ pi ≤ n, 0 ≤ xi ≤ 109) that mean that the new power of the pi-th shaman is xi.OutputPrint q lines, the i-th of them should contain - 1, if after the i-th change there are no shaman-kings, and otherwise a single integer j, where j is an index of some king-shaman after the i-th change.If there are multiple king-shamans after each change, print the index of any of them.ExamplesInput2 11 31 2Output-1Input3 42 2 31 11 22 43 6Output32-13Input10 70 3 1 4 6 2 7 8 10 12 51 39 364 104 91 21 0Output1-19-14-11NoteIn the first example powers of shamans after the first change are equal to (2, 3). The answer equals - 1, because the sum of powers of shamans before the first shaman is equal to 0, and before the second is equal to 2.In the second example after the first change the powers are equal to (1, 2, 3). The answer is equal to 3, because the power of the third shaman is equal to 3, and the sum of powers of the first and the second shaman is also 1 + 2 = 3. After the second change the powers become equal to (2, 2, 3), where the answer equals 2. After the third change the powers become equal to (2, 4, 3), where the answer equals - 1. After the fourth change the powers become equal to (2, 4, 6), where the answer equals 3. | Input2 11 31 2 | Output-1 | 3 seconds | 256 megabytes | ['binary search', 'data structures', '*2500'] |
D. Nastya and a Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that , where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments. Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.InputThe first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.OutputIn the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.ExamplesInput1 11Output1Input4 26 3 8 1Output2NoteIn the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because .There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because . Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because . | Input1 11 | Output1 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', '*2100'] |
C. Nastya and a Wardrobetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year. Nastya owns x dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for k + 1 months.Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109 + 7, because it is easy to see that it is always integer.InputThe only line contains two integers x and k (0 ≤ x, k ≤ 1018), where x is the initial number of dresses and k + 1 is the number of months in a year in Byteland.OutputIn the only line print a single integer — the expected number of dresses Nastya will own one year later modulo 109 + 7.ExamplesInput2 0Output4Input2 1Output7Input3 2Output21NoteIn the first example a year consists on only one month, so the wardrobe does not eat dresses at all.In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6 + 8) / 2 = 7. | Input2 0 | Output4 | 1 second | 256 megabytes | ['math', '*1600'] |
B. Nastya Studies Informaticstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the greatest common divisor of a and b, and LCM(a, b) denotes the least common multiple of a and b.You are given two integers x and y. You are to find the number of good pairs of integers (a, b) such that l ≤ a, b ≤ r. Note that pairs (a, b) and (b, a) are considered different if a ≠ b.InputThe only line contains four integers l, r, x, y (1 ≤ l ≤ r ≤ 109, 1 ≤ x ≤ y ≤ 109).OutputIn the only line print the only integer — the answer for the problem.ExamplesInput1 2 1 2Output2Input1 12 1 12Output4Input50 100 3 30Output0NoteIn the first example there are two suitable good pairs of integers (a, b): (1, 2) and (2, 1).In the second example there are four suitable good pairs of integers (a, b): (1, 12), (12, 1), (3, 4) and (4, 3).In the third example there are good pairs of integers, for example, (3, 30), but none of them fits the condition l ≤ a, b ≤ r. | Input1 2 1 2 | Output2 | 1 second | 256 megabytes | ['math', 'number theory', '*1600'] |
A. Nastya and an Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.InputThe first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array.The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.OutputPrint a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.ExamplesInput51 1 1 1 1Output1Input32 0 -1Output2Input45 -6 -5 1Output4NoteIn the first example you can add - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add - 2 on the first second, then the array becomes equal to [0, 0, - 3]. On the second second you can add 3 to the third (the only non-zero) element. | Input51 1 1 1 1 | Output1 | 1 second | 256 megabytes | ['implementation', 'sortings', '*800'] |
F. Concise and cleartime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the number at the first glance. Could it be shortened? For example, instead of 1000000 you could write 10^{6}, instead of 1000000000 —10^{9}, instead of 1000000007 — 10^{9}+7.Vasya decided that, to be concise, the notation should follow several rules: the notation should only consist of numbers, operations of addition ("+"), multiplication ("*") and exponentiation ("^"), in particular, the use of braces is forbidden; the use of several exponentiation operations in a row is forbidden, for example, writing "2^3^4" is unacceptable; the value of the resulting expression equals to the initial number; the notation should consist of the minimal amount of symbols. Given n, find the equivalent concise notation for it.InputThe only line contains a single integer n (1 \leq n \leq 10\,000\,000\,000).OutputOutput a concise notation of the number n. If there are several concise notations, output any of them.ExamplesInput2018Output2018Input1000000007Output10^9+7Input10000000000Output100^5Input2000000000Output2*10^9NoteThe third sample allows the answer 10^10 also of the length 5. | Input2018 | Output2018 | 2 seconds | 256 megabytes | ['brute force', 'greedy', 'implementation', 'math', '*2700'] |
E. Bus Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.In the morning, Vasya was waiting the bus to the university on the bus stop. Vasya's thoughts were hazy and so he couldn't remember the right bus' number quite right and got onto the bus with the number n.In the bus, Vasya thought that he could get the order of the digits in the number of the bus wrong. Futhermore, he could "see" some digits several times, but the digits he saw were definitely in the real number of the bus. For example, if Vasya saw the number 2028, it could mean that the real bus number could be 2028, 8022, 2820 or just 820. However, numbers 80, 22208, 52 definitely couldn't be the number of the bus. Also, real bus number couldn't start with the digit 0, this meaning that, for example, number 082 couldn't be the real bus number too.Given n, determine the total number of possible bus number variants.InputThe first line contains one integer n (1 \leq n \leq 10^{18}) — the number of the bus that was seen by Vasya. It is guaranteed that this number does not start with 0.OutputOutput a single integer — the amount of possible variants of the real bus number.ExamplesInput97Output2Input2028Output13NoteIn the first sample, only variants 97 and 79 are possible.In the second sample, the variants (in the increasing order) are the following: 208, 280, 802, 820, 2028, 2082, 2208, 2280, 2802, 2820, 8022, 8202, 8220. | Input97 | Output2 | 1 second | 256 megabytes | ['brute force', 'combinatorics', 'math', '*1800'] |
D. Bishwocktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBishwock is a chess figure that consists of three squares resembling an "L-bar". This figure can be rotated by 90, 180 and 270 degrees so it can have four possible states: XX XX .X X.X. .X XX XX Bishwocks don't attack any squares and can even occupy on the adjacent squares as long as they don't occupy the same square. Vasya has a board with 2\times n squares onto which he wants to put some bishwocks. To his dismay, several squares on this board are already occupied by pawns and Vasya can't put bishwocks there. However, pawns also don't attack bishwocks and they can occupy adjacent squares peacefully.Knowing the positions of pawns on the board, help Vasya to determine the maximum amount of bishwocks he can put onto the board so that they wouldn't occupy the same squares and wouldn't occupy squares with pawns.InputThe input contains two nonempty strings that describe Vasya's board. Those strings contain only symbols "0" (zero) that denote the empty squares and symbols "X" (uppercase English letter) that denote the squares occupied by pawns. Strings are nonempty and are of the same length that does not exceed 100.OutputOutput a single integer — the maximum amount of bishwocks that can be placed onto the given board.ExamplesInput0000Output1Input00X00X0XXX00XXX0X00X00Output4Input0X0X00X0X0Output0Input0XXX000000Output2 | Input0000 | Output1 | 1 second | 256 megabytes | ['dp', 'greedy', '*1500'] |
C. Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself.This means the process of eating candies is the following: in the beginning Vasya chooses a single integer k, same for all days. After that, in the morning he eats k candies from the box (if there are less than k candies in the box, he eats them all), then in the evening Petya eats 10\% of the candies remaining in the box. If there are still candies left in the box, the process repeats — next day Vasya eats k candies again, and Petya — 10\% of the candies left in a box, and so on.If the amount of candies in the box is not divisible by 10, Petya rounds the amount he takes from the box down. For example, if there were 97 candies in the box, Petya would eat only 9 of them. In particular, if there are less than 10 candies in a box, Petya won't eat any at all.Your task is to find out the minimal amount of k that can be chosen by Vasya so that he would eat at least half of the n candies he initially got. Note that the number k must be integer.InputThe first line contains a single integer n (1 \leq n \leq 10^{18}) — the initial amount of candies in the box.OutputOutput a single integer — the minimal amount of k that would allow Vasya to eat at least half of candies he got.ExampleInput68Output3NoteIn the sample, the amount of candies, with k=3, would change in the following way (Vasya eats first):68 \to 65 \to 59 \to 56 \to 51 \to 48 \to 44 \to 41 \\ \to 37 \to 34 \to 31 \to 28 \to 26 \to 23 \to 21 \to 18 \to 17 \to 14 \\ \to 13 \to 10 \to 9 \to 6 \to 6 \to 3 \to 3 \to 0.In total, Vasya would eat 39 candies, while Petya — 29. | Input68 | Output3 | 1 second | 256 megabytes | ['binary search', 'implementation', '*1500'] |
B. Getting an Atime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTranslator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — 4.5 would be rounded up to 5 (as in example 3), but 4.4 would be rounded down to 4.This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than 5 (maybe even the dreaded 2). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get 5 for the course. Of course, Vasya will get 5 for the lab works he chooses to redo.Help Vasya — calculate the minimum amount of lab works Vasya has to redo.InputThe first line contains a single integer n — the number of Vasya's grades (1 \leq n \leq 100).The second line contains n integers from 2 to 5 — Vasya's grades for his lab works.OutputOutput a single integer — the minimum amount of lab works that Vasya has to redo. It can be shown that Vasya can always redo enough lab works to get a 5.ExamplesInput34 4 4Output2Input45 4 5 5Output0Input45 3 3 5Output1NoteIn the first sample, it is enough to redo two lab works to make two 4s into 5s.In the second sample, Vasya's average is already 4.75 so he doesn't have to redo anything to get a 5.In the second sample Vasya has to redo one lab work to get rid of one of the 3s, that will make the average exactly 4.5 so the final grade would be 5. | Input34 4 4 | Output2 | 1 second | 256 megabytes | ['greedy', 'sortings', '*900'] |
A. If at first you don't succeed...time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.Some of them celebrated in the BugDonalds restaurant, some of them — in the BeaverKing restaurant, the most successful ones were fast enough to celebrate in both of restaurants. Students which didn't pass the exam didn't celebrate in any of those restaurants and elected to stay home to prepare for their reexamination. However, this quickly bored Vasya and he started checking celebration photos on the Kilogramm. He found out that, in total, BugDonalds was visited by A students, BeaverKing — by B students and C students visited both restaurants. Vasya also knows that there are N students in his group.Based on this info, Vasya wants to determine either if his data contradicts itself or, if it doesn't, how many students in his group didn't pass the exam. Can you help him so he won't waste his valuable preparation time?InputThe first line contains four integers — A, B, C and N (0 \leq A, B, C, N \leq 100).OutputIf a distribution of N students exists in which A students visited BugDonalds, B — BeaverKing, C — both of the restaurants and at least one student is left home (it is known that Vasya didn't pass the exam and stayed at home), output one integer — amount of students (including Vasya) who did not pass the exam. If such a distribution does not exist and Vasya made a mistake while determining the numbers A, B, C or N (as in samples 2 and 3), output -1.ExamplesInput10 10 5 20Output5Input2 2 0 4Output-1Input2 2 2 1Output-1NoteThe first sample describes following situation: 5 only visited BugDonalds, 5 students only visited BeaverKing, 5 visited both of them and 5 students (including Vasya) didn't pass the exam.In the second sample 2 students only visited BugDonalds and 2 only visited BeaverKing, but that means all 4 students in group passed the exam which contradicts the fact that Vasya didn't pass meaning that this situation is impossible.The third sample describes a situation where 2 students visited BugDonalds but the group has only 1 which makes it clearly impossible. | Input10 10 5 20 | Output5 | 1 second | 256 megabytes | ['implementation', '*1000'] |
G. GCD Countingtime limit per test4.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices).For every integer from 1 to 2 \cdot 10^5 you have to count the number of pairs (x, y) (1 \le x \le y \le n) such that g(x, y) is equal to this number.InputThe first line contains one integer n — the number of vertices (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 2 \cdot 10^5) — the numbers written on vertices.Then n - 1 lines follow, each containing two integers x and y (1 \le x, y \le n, x \ne y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.OutputFor every integer i from 1 to 2 \cdot 10^5 do the following: if there is no pair (x, y) such that x \le y and g(x, y) = i, don't output anything. Otherwise output two integers: i and the number of aforementioned pairs. You have to consider the values of i in ascending order.See the examples for better understanding.ExamplesInput31 2 31 22 3Output1 42 13 1Input61 2 4 8 16 321 66 33 44 26 5Output1 62 54 68 116 232 1Input49 16 144 61 32 34 3Output1 12 13 16 29 216 2144 1 | Input31 2 31 22 3 | Output1 42 13 1 | 4.5 seconds | 256 megabytes | ['divide and conquer', 'dp', 'dsu', 'number theory', 'trees', '*2400'] |
F. Flow Controltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i.The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i units of water per second from junction x_i to junction y_i (if f_i is negative, then the pipe will distribute |f_i| units of water per second from junction y_i to junction x_i). It is allowed to set f_i to any integer from -2 \cdot 10^9 to 2 \cdot 10^9.In order for the system to work properly, there are some constraints: for every i \in [1, n], i-th junction has a number s_i associated with it meaning that the difference between incoming and outcoming flow for i-th junction must be exactly s_i (if s_i is not negative, then i-th junction must receive s_i units of water per second; if it is negative, then i-th junction must transfer |s_i| units of water per second to other junctions).Can you choose the integers f_1, f_2, ..., f_m in such a way that all requirements on incoming and outcoming flows are satisfied?InputThe first line contains an integer n (1 \le n \le 2 \cdot 10^5) — the number of junctions.The second line contains n integers s_1, s_2, \dots, s_n (-10^4 \le s_i \le 10^4) — constraints for the junctions.The third line contains an integer m (0 \le m \le 2 \cdot 10^5) — the number of pipes.i-th of the next m lines contains two integers x_i and y_i (1 \le x_i, y_i \le n, x_i \ne y_i) — the description of i-th pipe. It is guaranteed that each unordered pair (x, y) will appear no more than once in the input (it means that there won't be any pairs (x, y) or (y, x) after the first occurrence of (x, y)). It is guaranteed that for each pair of junctions there exists a path along the pipes connecting them.OutputIf you can choose such integer numbers f_1, f_2, \dots, f_m in such a way that all requirements on incoming and outcoming flows are satisfied, then output "Possible" in the first line. Then output m lines, i-th line should contain f_i — the chosen setting numbers for the pipes. Pipes are numbered in order they appear in the input.Otherwise output "Impossible" in the only line.ExamplesInput43 -10 6 151 23 22 43 43 1OutputPossible4-68-77Input43 -10 6 451 23 22 43 43 1OutputImpossible | Input43 -10 6 151 23 22 43 43 1 | OutputPossible4-68-77 | 2 seconds | 256 megabytes | ['dfs and similar', 'dp', 'greedy', 'trees', '*2400'] |
E. Post Lampstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek's house is located on a street which can be represented as the OX axis. This street is really dark, so Adilbek wants to install some post lamps to illuminate it. Street has n positions to install lamps, they correspond to the integer numbers from 0 to n - 1 on the OX axis. However, some positions are blocked and no post lamp can be placed there.There are post lamps of different types which differ only by their power. When placed in position x, post lamp of power l illuminates the segment [x; x + l]. The power of each post lamp is always a positive integer number.The post lamp shop provides an infinite amount of lamps of each type from power 1 to power k. Though each customer is only allowed to order post lamps of exactly one type. Post lamps of power l cost a_l each.What is the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street? If some lamps illuminate any other segment of the street, Adilbek does not care, so, for example, he may place a lamp of power 3 in position n - 1 (even though its illumination zone doesn't completely belong to segment [0; n]).InputThe first line contains three integer numbers n, m and k (1 \le k \le n \le 10^6, 0 \le m \le n) — the length of the segment of the street Adilbek wants to illuminate, the number of the blocked positions and the maximum power of the post lamp available.The second line contains m integer numbers s_1, s_2, \dots, s_m (0 \le s_1 < s_2 < \dots s_m < n) — the blocked positions.The third line contains k integer numbers a_1, a_2, \dots, a_k (1 \le a_i \le 10^6) — the costs of the post lamps.OutputPrint the minimal total cost of the post lamps of exactly one type Adilbek can buy to illuminate the entire segment [0; n] of the street.If illumintaing the entire segment [0; n] is impossible, print -1.ExamplesInput6 2 31 31 2 3Output6Input4 3 41 2 31 10 100 1000Output1000Input5 1 503 3 3 3 3Output-1Input7 4 32 4 5 63 14 15Output-1 | Input6 2 31 31 2 3 | Output6 | 2 seconds | 256 megabytes | ['brute force', 'greedy', '*2100'] |
D. Graph And Its Complementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven three numbers n, a, b. You need to find an adjacency matrix of such an undirected graph that the number of components in it is equal to a, and the number of components in its complement is b. The matrix must be symmetric, and all digits on the main diagonal must be zeroes.In an undirected graph loops (edges from a vertex to itself) are not allowed. It can be at most one edge between a pair of vertices.The adjacency matrix of an undirected graph is a square matrix of size n consisting only of "0" and "1", where n is the number of vertices of the graph and the i-th row and the i-th column correspond to the i-th vertex of the graph. The cell (i,j) of the adjacency matrix contains 1 if and only if the i-th and j-th vertices in the graph are connected by an edge.A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting this pair of vertices, but adding any other vertex to X violates this rule.The complement or inverse of a graph G is a graph H on the same vertices such that two distinct vertices of H are adjacent if and only if they are not adjacent in G.InputIn a single line, three numbers are given n, a, b \,(1 \le n \le 1000, 1 \le a, b \le n): is the number of vertexes of the graph, the required number of connectivity components in it, and the required amount of the connectivity component in it's complement. OutputIf there is no graph that satisfies these constraints on a single line, print "NO" (without quotes).Otherwise, on the first line, print "YES"(without quotes). In each of the next n lines, output n digits such that j-th digit of i-th line must be 1 if and only if there is an edge between vertices i and j in G (and 0 otherwise). Note that the matrix must be symmetric, and all digits on the main diagonal must be zeroes. If there are several matrices that satisfy the conditions — output any of them.ExamplesInput3 1 2OutputYES001001110Input3 3 3OutputNO | Input3 1 2 | OutputYES001001110 | 2 seconds | 256 megabytes | ['constructive algorithms', 'graphs', 'implementation', '*1700'] |
C. Bracket Sequences Concatenation Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string containing only characters "(" and ")".A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You are given n bracket sequences s_1, s_2, \dots , s_n. Calculate the number of pairs i, j \, (1 \le i, j \le n) such that the bracket sequence s_i + s_j is a regular bracket sequence. Operation + means concatenation i.e. "()(" + ")()" = "()()()".If s_i + s_j and s_j + s_i are regular bracket sequences and i \ne j, then both pairs (i, j) and (j, i) must be counted in the answer. Also, if s_i + s_i is a regular bracket sequence, the pair (i, i) must be counted in the answer.InputThe first line contains one integer n \, (1 \le n \le 3 \cdot 10^5) — the number of bracket sequences. The following n lines contain bracket sequences — non-empty strings consisting only of characters "(" and ")". The sum of lengths of all bracket sequences does not exceed 3 \cdot 10^5.OutputIn the single line print a single integer — the number of pairs i, j \, (1 \le i, j \le n) such that the bracket sequence s_i + s_j is a regular bracket sequence.ExamplesInput3)()(Output2Input2()()Output4NoteIn the first example, suitable pairs are (3, 1) and (2, 2).In the second example, any pair is suitable, namely (1, 1), (1, 2), (2, 1), (2, 2). | Input3)()( | Output2 | 2 seconds | 256 megabytes | ['implementation', '*1500'] |
B. Micro-Worldtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have n bacteria in the Petri dish and size of the i-th bacteria is a_i. Also you know intergalactic positive integer constant K.The i-th bacteria can swallow the j-th bacteria if and only if a_i > a_j and a_i \le a_j + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria i can swallow any bacteria j if a_i > a_j and a_i \le a_j + K. The swallow operations go one after another.For example, the sequence of bacteria sizes a=[101, 53, 42, 102, 101, 55, 54] and K=1. The one of possible sequences of swallows is: [101, 53, 42, 102, \underline{101}, 55, 54] \to [101, \underline{53}, 42, 102, 55, 54] \to [\underline{101}, 42, 102, 55, 54] \to [42, 102, 55, \underline{54}] \to [42, 102, 55]. In total there are 3 bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.InputThe first line contains two space separated positive integers n and K (1 \le n \le 2 \cdot 10^5, 1 \le K \le 10^6) — number of bacteria and intergalactic constant K.The second line contains n space separated integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6) — sizes of bacteria you have.OutputPrint the only integer — minimal possible number of bacteria can remain.ExamplesInput7 1101 53 42 102 101 55 54Output3Input6 520 15 10 15 20 25Output1Input7 10000001 1 1 1 1 1 1Output7NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: [20, 15, 10, 15, \underline{20}, 25] \to [20, 15, 10, \underline{15}, 25] \to [20, 15, \underline{10}, 25] \to [20, \underline{15}, 25] \to [\underline{20}, 25] \to [25].In the third example no bacteria can swallow any other bacteria. | Input7 1101 53 42 102 101 55 54 | Output3 | 2 seconds | 256 megabytes | ['greedy', 'sortings', '*1200'] |
A. Commentary Boxestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland Football Cup starts really soon! Commentators from all over the world come to the event.Organizers have already built n commentary boxes. m regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.If n is not divisible by m, it is impossible to distribute the boxes to the delegations at the moment.Organizers can build a new commentary box paying a burles and demolish a commentary box paying b burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by m)?InputThe only line contains four integer numbers n, m, a and b (1 \le n, m \le 10^{12}, 1 \le a, b \le 100), where n is the initial number of the commentary boxes, m is the number of delegations to come, a is the fee to build a box and b is the fee to demolish a box.OutputOutput the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by m). It is allowed that the final number of the boxes is equal to 0.ExamplesInput9 7 3 8Output15Input2 7 3 7Output14Input30 6 17 19Output0NoteIn the first example organizers can build 5 boxes to make the total of 14 paying 3 burles for the each of them.In the second example organizers can demolish 2 boxes to make the total of 0 paying 7 burles for the each of them.In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get 5 boxes. | Input9 7 3 8 | Output15 | 2 seconds | 256 megabytes | ['implementation', 'math', '*1000'] |
E. A Trance of Nightfalltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output The cool breeze blows gently, the flowing water ripples steadily."Flowing and passing like this, the water isn't gone ultimately; Waxing and waning like that, the moon doesn't shrink or grow eventually.""Everything is transient in a way and perennial in another."Kanno doesn't seem to make much sense out of Mino's isolated words, but maybe it's time that they enjoy the gentle breeze and the night sky — the inexhaustible gifts from nature.Gazing into the sky of stars, Kanno indulges in a night's tranquil dreams. There is a set S of n points on a coordinate plane.Kanno starts from a point P that can be chosen on the plane. P is not added to S if it doesn't belong to S. Then the following sequence of operations (altogether called a move) is repeated several times, in the given order: Choose a line l such that it passes through at least two elements in S and passes through Kanno's current position. If there are multiple such lines, one is chosen equiprobably. Move to one of the points that belong to S and lie on l. The destination is chosen equiprobably among all possible ones, including Kanno's current position (if it does belong to S). There are q queries each consisting of two integers (t_i, m_i). For each query, you're to help Kanno maximize the probability of the stopping position being the t_i-th element in S after m_i moves with a proper selection of P, and output this maximum probability. Note that according to rule 1, P should belong to at least one line that passes through at least two points from S.InputThe first line contains a positive integer n (2 \leq n \leq 200) — the number of points in S.The i-th of the following n lines contains two space-separated integers x_i and y_i (-10^4 \leq x_i, y_i \leq 10^4) — the coordinates of the i-th point in S. The input guarantees that for all 1 \leq i \lt j \leq n, (x_i, y_i) \neq (x_j, y_j) holds.The next line contains a positive integer q (1 \leq q \leq 200) — the number of queries.Each of the following q lines contains two space-separated integers t and m (1 \leq t_i \leq n, 1 \leq m_i \leq 10^4) — the index of the target point and the number of moves, respectively.OutputOutput q lines each containing a decimal number — the i-th among them denotes the maximum probability of staying on the t_i-th point after m_i steps, with a proper choice of starting position P.Your answer will be considered correct if each number in your output differs from the corresponding one in jury's answer by at most 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if |a - b| \le 10^{-6}.ExampleInput50 01 32 23 14 4101 12 13 14 15 13 23 33 43 53 6Output0.500000000000000000000.500000000000000000000.333333333333333314830.500000000000000000000.500000000000000000000.185185185185185174910.152263374485596708620.144947416552354824140.143321648122745504140.14296036624949901017NoteThe points in S and possible candidates for line l are depicted in the following figure. For the first query, when P = (-1, -3), l is uniquely determined to be 3x = y, and thus Kanno will move to (0, 0) with a probability of \frac 1 2.For the third query, when P = (2, 2), l is chosen equiprobably between x + y = 4 and x = y. Kanno will then move to the other four points with a probability of \frac 1 2 \cdot \frac 1 3 = \frac 1 6 each, or stay at (2, 2) with a probability of \frac 1 3. | Input50 01 32 23 14 4101 12 13 14 15 13 23 33 43 53 6 | Output0.500000000000000000000.500000000000000000000.333333333333333314830.500000000000000000000.500000000000000000000.185185185185185174910.152263374485596708620.144947416552354824140.143321648122745504140.14296036624949901017 | 2 seconds | 256 megabytes | ['dp', 'geometry', 'matrices', 'probabilities', '*2700'] |
D. A Shade of Moonlighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Gathering darkness shrouds the woods and the world. The moon sheds its light on the boat and the river."To curtain off the moonlight should be hardly possible; the shades present its mellow beauty and restful nature." Intonates Mino."See? The clouds are coming." Kanno gazes into the distance."That can't be better," Mino turns to Kanno. The sky can be seen as a one-dimensional axis. The moon is at the origin whose coordinate is 0.There are n clouds floating in the sky. Each cloud has the same length l. The i-th initially covers the range of (x_i, x_i + l) (endpoints excluded). Initially, it moves at a velocity of v_i, which equals either 1 or -1.Furthermore, no pair of clouds intersect initially, that is, for all 1 \leq i \lt j \leq n, \lvert x_i - x_j \rvert \geq l.With a wind velocity of w, the velocity of the i-th cloud becomes v_i + w. That is, its coordinate increases by v_i + w during each unit of time. Note that the wind can be strong and clouds can change their direction.You are to help Mino count the number of pairs (i, j) (i < j), such that with a proper choice of wind velocity w not exceeding w_\mathrm{max} in absolute value (possibly negative and/or fractional), the i-th and j-th clouds both cover the moon at the same future moment. This w doesn't need to be the same across different pairs.InputThe first line contains three space-separated integers n, l, and w_\mathrm{max} (1 \leq n \leq 10^5, 1 \leq l, w_\mathrm{max} \leq 10^8) — the number of clouds, the length of each cloud and the maximum wind speed, respectively.The i-th of the following n lines contains two space-separated integers x_i and v_i (-10^8 \leq x_i \leq 10^8, v_i \in \{-1, 1\}) — the initial position and the velocity of the i-th cloud, respectively.The input guarantees that for all 1 \leq i \lt j \leq n, \lvert x_i - x_j \rvert \geq l.OutputOutput one integer — the number of unordered pairs of clouds such that it's possible that clouds from each pair cover the moon at the same future moment with a proper choice of wind velocity w.ExamplesInput5 1 2-2 12 13 -15 -17 -1Output4Input4 10 1-20 1-10 -10 110 -1Output1NoteIn the first example, the initial positions and velocities of clouds are illustrated below. The pairs are: (1, 3), covering the moon at time 2.5 with w = -0.4; (1, 4), covering the moon at time 3.5 with w = -0.6; (1, 5), covering the moon at time 4.5 with w = -0.7; (2, 5), covering the moon at time 2.5 with w = -2. Below is the positions of clouds at time 2.5 with w = -0.4. At this moment, the 1-st and 3-rd clouds both cover the moon. In the second example, the only pair is (1, 4), covering the moon at time 15 with w = 0.Note that all the times and wind velocities given above are just examples among infinitely many choices. | Input5 1 2-2 12 13 -15 -17 -1 | Output4 | 2 seconds | 256 megabytes | ['binary search', 'geometry', 'math', 'sortings', 'two pointers', '*2500'] |
C. A Mist of Florescencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output As the boat drifts down the river, a wood full of blossoms shows up on the riverfront."I've been here once," Mino exclaims with delight, "it's breathtakingly amazing.""What is it like?""Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?" There are four kinds of flowers in the wood, Amaranths, Begonias, Centaureas and Dianthuses.The wood can be represented by a rectangular grid of n rows and m columns. In each cell of the grid, there is exactly one type of flowers.According to Mino, the numbers of connected components formed by each kind of flowers are a, b, c and d respectively. Two cells are considered in the same connected component if and only if a path exists between them that moves between cells sharing common edges and passes only through cells containing the same flowers.You are to help Kanno depict such a grid of flowers, with n and m arbitrarily chosen under the constraints given below. It can be shown that at least one solution exists under the constraints of this problem.Note that you can choose arbitrary n and m under the constraints below, they are not given in the input.InputThe first and only line of input contains four space-separated integers a, b, c and d (1 \leq a, b, c, d \leq 100) — the required number of connected components of Amaranths, Begonias, Centaureas and Dianthuses, respectively.OutputIn the first line, output two space-separated integers n and m (1 \leq n, m \leq 50) — the number of rows and the number of columns in the grid respectively.Then output n lines each consisting of m consecutive English letters, representing one row of the grid. Each letter should be among 'A', 'B', 'C' and 'D', representing Amaranths, Begonias, Centaureas and Dianthuses, respectively.In case there are multiple solutions, print any. You can output each letter in either case (upper or lower).ExamplesInput5 3 2 1Output4 7DDDDDDDDABACADDBABACDDDDDDDDInput50 50 1 1Output4 50CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCABABABABABABABABABABABABABABABABABABABABABABABABABBABABABABABABABABABABABABABABABABABABABABABABABABADDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDInput1 6 4 5Output7 7DDDDDDDDDDBDBDDDCDCDDDBDADBDDDCDCDDDBDBDDDDDDDDDDNoteIn the first example, each cell of Amaranths, Begonias and Centaureas forms a connected component, while all the Dianthuses form one. | Input5 3 2 1 | Output4 7DDDDDDDDABACADDBABACDDDDDDDD | 1 second | 256 megabytes | ['constructive algorithms', 'graphs', '*1800'] |
B. A Tide of Riverscapetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output Walking along a riverside, Mino silently takes a note of something."Time," Mino thinks aloud."What?""Time and tide wait for no man," explains Mino. "My name, taken from the river, always reminds me of this.""And what are you recording?""You see it, tide. Everything has its own period, and I think I've figured out this one," says Mino with confidence.Doubtfully, Kanno peeks at Mino's records. The records are expressed as a string s of characters '0', '1' and '.', where '0' denotes a low tide, '1' denotes a high tide, and '.' denotes an unknown one (either high or low).You are to help Mino determine whether it's possible that after replacing each '.' independently with '0' or '1', a given integer p is not a period of the resulting string. In case the answer is yes, please also show such a replacement to Mino.In this problem, a positive integer p is considered a period of string s, if for all 1 \leq i \leq \lvert s \rvert - p, the i-th and (i + p)-th characters of s are the same. Here \lvert s \rvert is the length of s.InputThe first line contains two space-separated integers n and p (1 \leq p \leq n \leq 2000) — the length of the given string and the supposed period, respectively.The second line contains a string s of n characters — Mino's records. s only contains characters '0', '1' and '.', and contains at least one '.' character.OutputOutput one line — if it's possible that p is not a period of the resulting string, output any one of such strings; otherwise output "No" (without quotes, you can print letters in any case (upper or lower)).ExamplesInput10 71.0.1.0.1.Output1000100010Input10 61.0.1.1000Output1001101000Input10 91........1OutputNoNoteIn the first example, 7 is not a period of the resulting string because the 1-st and 8-th characters of it are different.In the second example, 6 is not a period of the resulting string because the 4-th and 10-th characters of it are different.In the third example, 9 is always a period because the only constraint that the first and last characters are the same is already satisfied.Note that there are multiple acceptable answers for the first two examples, you can print any of them. | Input10 71.0.1.0.1. | Output1000100010 | 1 second | 256 megabytes | ['constructive algorithms', 'strings', '*1200'] |
A. A Blend of Springtimetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output When the curtains are opened, a canvas unfolds outside. Kanno marvels at all the blonde colours along the riverside — not tangerines, but blossoms instead."What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone.""But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic. The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.InputThe first and only line of input contains a non-empty string s consisting of uppercase English letters 'A', 'B', 'C' and characters '.' (dots) only (\lvert s \rvert \leq 100) — denoting cells containing an amber flower, a buff one, a canary yellow one, and no flowers, respectively.OutputOutput "Yes" if it's possible that all three colours appear in some cell, and "No" otherwise.You can print each letter in any case (upper or lower).ExamplesInput.BAC.OutputYesInputAA..CBOutputNoNoteIn the first example, the buff and canary yellow flowers can leave their petals in the central cell, blending all three colours in it.In the second example, it's impossible to satisfy the requirement because there is no way that amber and buff meet in any cell. | Input.BAC. | OutputYes | 1 second | 256 megabytes | ['implementation', 'strings', '*900'] |
F. Rain and Umbrellastime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i-th segment which is in the rain is represented as [l_i, r_i] (0 \le l_i < r_i \le a).There are m umbrellas lying on the line, the i-th umbrella is located at point x_i (0 \le x_i \le a) and has weight p_i. When Polycarp begins his journey, he doesn't have any umbrellas.During his journey from x = 0 to x = a Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from x to x + 1 if a segment [x, x + 1] is in the rain (i.e. if there exists some i such that l_i \le x and x + 1 \le r_i).The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.Can Polycarp make his way from point x = 0 to point x = a? If yes, find the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.InputThe first line contains three integers a, n and m (1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil) — the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.Each of the next n lines contains two integers l_i and r_i (0 \le l_i < r_i \le a) — the borders of the i-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments i and j either r_i < l_j or r_j < l_i.Each of the next m lines contains two integers x_i and p_i (0 \le x_i \le a, 1 \le p_i \le 10^5) — the location and the weight of the i-th umbrella.OutputPrint "-1" (without quotes) if Polycarp can't make his way from point x = 0 to point x = a. Otherwise print one integer — the minimum total fatigue after reaching x = a, if Polycarp picks up and throws away umbrellas optimally.ExamplesInput10 2 43 78 100 103 48 11 2Output14Input10 1 10 90 5Output45Input10 1 10 91 5Output-1NoteIn the first example the only possible strategy is to take the fourth umbrella at the point x = 1, keep it till the point x = 7 (the total fatigue at x = 7 will be equal to 12), throw it away, move on from x = 7 to x = 8 without an umbrella, take the third umbrella at x = 8 and keep it till the end (the total fatigue at x = 10 will be equal to 14). In the second example the only possible strategy is to take the first umbrella, move with it till the point x = 9, throw it away and proceed without an umbrella till the end. | Input10 2 43 78 100 103 48 11 2 | Output14 | 2 seconds | 256 megabytes | ['dp', '*2100'] |
E. Divisibility by 25time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n from 1 to 10^{18} without leading zeroes.In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.What is the minimum number of moves you have to make to obtain a number that is divisible by 25? Print -1 if it is impossible to obtain a number that is divisible by 25.InputThe first line contains an integer n (1 \le n \le 10^{18}). It is guaranteed that the first (left) digit of the number n is not a zero.OutputIf it is impossible to obtain a number that is divisible by 25, print -1. Otherwise print the minimum number of moves required to obtain such number.Note that you can swap only adjacent digits in the given number.ExamplesInput5071Output4Input705Output1Input1241367Output-1NoteIn the first example one of the possible sequences of moves is 5071 \rightarrow 5701 \rightarrow 7501 \rightarrow 7510 \rightarrow 7150. | Input5071 | Output4 | 1 second | 256 megabytes | ['brute force', 'greedy', '*2100'] |
D. Points and Powers of Twotime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n distinct points on a coordinate line, the coordinate of i-th point equals to x_i. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points x_{i_1}, x_{i_2}, \dots, x_{i_m} such that for each pair x_{i_j}, x_{i_k} it is true that |x_{i_j} - x_{i_k}| = 2^d where d is some non-negative integer number (not necessarily the same for each pair of points).InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of points.The second line contains n pairwise distinct integers x_1, x_2, \dots, x_n (-10^9 \le x_i \le 10^9) — the coordinates of points.OutputIn the first line print m — the maximum possible number of points in a subset that satisfies the conditions described above.In the second line print m integers — the coordinates of points in the subset you have chosen.If there are multiple answers, print any of them.ExamplesInput63 5 4 7 10 12Output37 3 5Input5-1 2 5 8 11Output18NoteIn the first example the answer is [7, 3, 5]. Note, that |7-3|=4=2^2, |7-5|=2=2^1 and |3-5|=2=2^1. You can't find a subset having more points satisfying the required property. | Input63 5 4 7 10 12 | Output37 3 5 | 4 seconds | 256 megabytes | ['brute force', 'math', '*1800'] |
C. Equal Sumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given k sequences of integers. The length of the i-th sequence equals to n_i.You have to choose exactly two sequences i and j (i \ne j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the changed sequence j (its length will be equal to n_j - 1).Note that it's required to remove exactly one element in each of the two chosen sequences.Assume that the sum of the empty (of the length equals 0) sequence is 0.InputThe first line contains an integer k (2 \le k \le 2 \cdot 10^5) — the number of sequences.Then k pairs of lines follow, each pair containing a sequence.The first line in the i-th pair contains one integer n_i (1 \le n_i < 2 \cdot 10^5) — the length of the i-th sequence. The second line of the i-th pair contains a sequence of n_i integers a_{i, 1}, a_{i, 2}, \dots, a_{i, n_i}.The elements of sequences are integer numbers from -10^4 to 10^4.The sum of lengths of all given sequences don't exceed 2 \cdot 10^5, i.e. n_1 + n_2 + \dots + n_k \le 2 \cdot 10^5.OutputIf it is impossible to choose two sequences such that they satisfy given conditions, print "NO" (without quotes). Otherwise in the first line print "YES" (without quotes), in the second line — two integers i, x (1 \le i \le k, 1 \le x \le n_i), in the third line — two integers j, y (1 \le j \le k, 1 \le y \le n_j). It means that the sum of the elements of the i-th sequence without the element with index x equals to the sum of the elements of the j-th sequence without the element with index y.Two chosen sequences must be distinct, i.e. i \ne j. You can print them in any order.If there are multiple possible answers, print any of them.ExamplesInput252 3 1 3 261 1 2 2 2 1OutputYES2 61 2Input31551 1 1 1 122 3OutputNOInput462 2 2 2 2 252 2 2 2 232 2 252 2 2 2 2OutputYES2 24 1NoteIn the first example there are two sequences [2, 3, 1, 3, 2] and [1, 1, 2, 2, 2, 1]. You can remove the second element from the first sequence to get [2, 1, 3, 2] and you can remove the sixth element from the second sequence to get [1, 1, 2, 2, 2]. The sums of the both resulting sequences equal to 8, i.e. the sums are equal. | Input252 3 1 3 261 1 2 2 2 1 | OutputYES2 61 2 | 2 seconds | 256 megabytes | ['implementation', 'sortings', '*1400'] |
B. Substrings Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way that they form a. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".InputThe first line contains an integer n (1 \le n \le 100) — the number of strings.The next n lines contain the given strings. The number of letters in each string is from 1 to 100, inclusive. Each string consists of lowercase English letters.Some strings might be equal.OutputIf it is impossible to reorder n given strings in required order, print "NO" (without quotes).Otherwise print "YES" (without quotes) and n given strings in required order.ExamplesInput5aabaabacababaabaOutputYESabaabaabaabacabaInput5aabacababaabaababOutputNOInput3qwertyqwertyqwertyOutputYESqwertyqwertyqwertyNoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba". | Input5aabaabacababaaba | OutputYESabaabaabaabacaba | 1 second | 256 megabytes | ['sortings', 'strings', '*1100'] |
A. Diverse Teamtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n students in a school class, the rating of the i-th student on Codehorses is a_i. You have to form a team consisting of k students (1 \le k \le n) such that the ratings of all team members are distinct.If it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print k distinct numbers which should be the indices of students in the team you form. If there are multiple answers, print any of them.InputThe first line contains two integers n and k (1 \le k \le n \le 100) — the number of students and the size of the team you have to form.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the rating of i-th student.OutputIf it is impossible to form a suitable team, print "NO" (without quotes). Otherwise print "YES", and then print k distinct integers from 1 to n which should be the indices of students in the team you form. All the ratings of the students in the team should be distinct. You may print the indices in any order. If there are multiple answers, print any of them.Assume that the students are numbered from 1 to n.ExamplesInput5 315 13 15 15 12OutputYES1 2 5 Input5 415 13 15 15 12OutputNOInput4 420 10 40 30OutputYES1 2 3 4 NoteAll possible answers for the first example: {1 2 5} {2 3 5} {2 4 5} Note that the order does not matter. | Input5 315 13 15 15 12 | OutputYES1 2 5 | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
C. Three displaystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are n displays placed along a road, and the i-th of them can display a text with font size s_i only. Maria Stepanovna wants to rent such three displays with indices i < j < k that the font size increases if you move along the road in a particular direction. Namely, the condition s_i < s_j < s_k should be held.The rent cost is for the i-th display is c_i. Please determine the smallest cost Maria Stepanovna should pay.InputThe first line contains a single integer n (3 \le n \le 3\,000) — the number of displays.The second line contains n integers s_1, s_2, \ldots, s_n (1 \le s_i \le 10^9) — the font sizes on the displays in the order they stand along the road.The third line contains n integers c_1, c_2, \ldots, c_n (1 \le c_i \le 10^8) — the rent costs for each display.OutputIf there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices i < j < k such that s_i < s_j < s_k.ExamplesInput52 4 5 4 1040 30 20 10 40Output90Input3100 101 1002 4 5Output-1Input101 2 3 4 5 6 7 8 9 1010 13 11 14 15 12 13 13 18 13Output33NoteIn the first example you can, for example, choose displays 1, 4 and 5, because s_1 < s_4 < s_5 (2 < 4 < 10), and the rent cost is 40 + 10 + 40 = 90.In the second example you can't select a valid triple of indices, so the answer is -1. | Input52 4 5 4 1040 30 20 10 40 | Output90 | 1 second | 256 megabytes | ['brute force', 'dp', 'implementation', '*1400'] |
B. High School: Become Humantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYear 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him.InputOn the only line of input there are two integers x and y (1 \le x, y \le 10^{9}).OutputIf x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes).ExamplesInput5 8Output>Input10 3Output<Input6 6Output=NoteIn the first example 5^8 = 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 \cdot 5 = 390625, and 8^5 = 8 \cdot 8 \cdot 8 \cdot 8 \cdot 8 = 32768. So you should print '>'.In the second example 10^3 = 1000 < 3^{10} = 59049.In the third example 6^6 = 46656 = 6^6. | Input5 8 | Output> | 1 second | 256 megabytes | ['math', '*1100'] |
A. Infinity Gauntlettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: the Power Gem of purple color, the Time Gem of green color, the Space Gem of blue color, the Soul Gem of orange color, the Reality Gem of red color, the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.InputIn the first line of input there is one integer n (0 \le n \le 6) — the number of Gems in Infinity Gauntlet.In next n lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.OutputIn the first line output one integer m (0 \le m \le 6) — the number of absent Gems.Then in m lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.ExamplesInput4redpurpleyelloworangeOutput2SpaceTimeInput0Output6TimeMindSoulPowerRealitySpaceNoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six. | Input4redpurpleyelloworange | Output2SpaceTime | 1 second | 256 megabytes | ['implementation', '*800'] |
F. Oppa Funcan Style Remasteredtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSurely you have seen insane videos by South Korean rapper PSY, such as "Gangnam Style", "Gentleman" and "Daddy". You might also hear that PSY has been recording video "Oppa Funcan Style" two years ago (unfortunately we couldn't find it on the internet). We will remind you what this hit looked like (you can find original description here):On the ground there are n platforms, which are numbered with integers from 1 to n, on i-th platform there is a dancer with number i. Further, every second all the dancers standing on the platform with number i jump to the platform with the number f(i). The moving rule f is selected in advance and is not changed throughout the clip.The duration of the clip was k seconds and the rule f was chosen in such a way that after k seconds all dancers were in their initial positions (i.e. the i-th dancer stood on the platform with the number i). That allowed to loop the clip and collect even more likes.PSY knows that enhanced versions of old artworks become more and more popular every day. So he decided to release a remastered-version of his video.In his case "enhanced version" means even more insanity, so the number of platforms can be up to 10^{18}! But the video director said that if some dancer stays on the same platform all the time, then the viewer will get bored and will turn off the video immediately. Therefore, for all x from 1 to n f(x) \neq x must hold.Big part of classic video's success was in that looping, so in the remastered version all dancers should return to their initial positions in the end of the clip as well.PSY hasn't decided on the exact number of platforms and video duration yet, so he asks you to check if there is a good rule f for different options.InputIn the first line of input there is one integer t (1 \le t \le 10^{4}) — the number of options for n and k to check.In the next t lines the options are given: each option is described with two integers n and k (1 \le n \le 10^{18}, 1 \le k \le 10^{15}) — the number of dancers and the duration in seconds.It is guaranteed that the number of different values of k in one test is not greater than 50.OutputPrint t lines. If the i-th option of the video is feasible, print "YES" (without quotes) in i-th line, otherwise print "NO" (without quotes).ExampleInput37 73 85 6OutputYESNOYES | Input37 73 85 6 | OutputYESNOYES | 5 seconds | 256 megabytes | ['graphs', 'math', 'number theory', 'shortest paths', '*3300'] |
E. Prince's Problemtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet the main characters of this problem be personages from some recent movie. New Avengers seem to make a lot of buzz. I didn't watch any part of the franchise and don't know its heroes well, but it won't stop me from using them in this problem statement. So, Thanos and Dr. Strange are doing their superhero and supervillain stuff, but then suddenly they stumble across a regular competitive programming problem.You are given a tree with n vertices.In each vertex v there is positive integer a_{v}.You have to answer q queries.Each query has a from u v x.You have to calculate \prod_{w \in P} gcd(x, a_{w}) \mod (10^{9} + 7), where P is a set of vertices on path from u to v. In other words, you are to calculate the product of gcd(x, a_{w}) for all vertices w on the path from u to v. As it might be large, compute it modulo 10^9+7. Here gcd(s, t) denotes the greatest common divisor of s and t.Note that the numbers in vertices do not change after queries.I suppose that you are more interested in superhero business of Thanos and Dr. Strange than in them solving the problem. So you are invited to solve this problem instead of them.InputIn the first line of input there is one integer n (1 \le n \le 10^{5}) — the size of the tree.In the next n-1 lines the edges of the tree are described. The i-th edge is described with two integers u_{i} and v_{i} (1 \le u_{i}, v_{i} \le n) and it connects the vertices u_{i} and v_{i}. It is guaranteed that graph with these edges is a tree.In the next line there are n integers a_1, a_2, \ldots, a_n (1 \le a_{v} \le 10^{7}).In the next line there is one integer q (1 \le q \le 10^{5}) — the number of queries.And in the next q lines the queries are described. Each query is described with three integers u_{i}, v_{i} and x_{i} (1 \le u_{i}, v_{i} \le n, 1 \le x_{i} \le 10^{7}).OutputPrint q numbers — the answers to the queries in the order they are given in the input. Print each answer modulo 10^9+7 = 1000000007. Print each number on a separate line.ExamplesInput41 21 31 46 4 9 532 3 62 3 23 4 7Output3641Input61 22 32 41 55 6100000 200000 500000 40000 800000 25000033 5 100000006 2 35000004 1 64000Output19600012250999998215 | Input41 21 31 46 4 9 532 3 62 3 23 4 7 | Output3641 | 3 seconds | 512 megabytes | ['brute force', 'data structures', 'math', 'number theory', 'trees', '*2800'] |
D. Perfect Encodingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are working as an analyst in a company working on a new system for big data storage. This system will store n different objects. Each object should have a unique ID.To create the system, you choose the parameters of the system — integers m \ge 1 and b_{1}, b_{2}, \ldots, b_{m}. With these parameters an ID of some object in the system is an array of integers [a_{1}, a_{2}, \ldots, a_{m}] where 1 \le a_{i} \le b_{i} holds for every 1 \le i \le m.Developers say that production costs are proportional to \sum_{i=1}^{m} b_{i}. You are asked to choose parameters m and b_{i} so that the system will be able to assign unique IDs to n different objects and production costs are minimized. Note that you don't have to use all available IDs.InputIn the only line of input there is one positive integer n. The length of the decimal representation of n is no greater than 1.5 \cdot 10^{6}. The integer does not contain leading zeros.OutputPrint one number — minimal value of \sum_{i=1}^{m} b_{i}.ExamplesInput36Output10Input37Output11Input12345678901234567890123456789Output177 | Input36 | Output10 | 2 seconds | 256 megabytes | ['fft', 'math', '*3100'] |
C. AND Graphtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set of size m with integer elements between 0 and 2^{n}-1 inclusive. Let's build an undirected graph on these integers in the following way: connect two integers x and y with an edge if and only if x \& y = 0. Here \& is the bitwise AND operation. Count the number of connected components in that graph.InputIn the first line of input there are two integers n and m (0 \le n \le 22, 1 \le m \le 2^{n}).In the second line there are m integers a_1, a_2, \ldots, a_m (0 \le a_{i} < 2^{n}) — the elements of the set. All a_{i} are distinct.OutputPrint the number of connected components.ExamplesInput2 31 2 3Output2Input5 55 19 10 20 12Output2NoteGraph from first sample:Graph from second sample: | Input2 31 2 3 | Output2 | 4 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'dsu', 'graphs', '*2500'] |
B. Petr and Permutationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements 7n+1 times instead of 3n times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.InputIn the first line of input there is one integer n (10^{3} \le n \le 10^{6}).In the second line there are n distinct integers between 1 and n — the permutation of size n from the test.It is guaranteed that all tests except for sample are generated this way: First we choose n — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.OutputIf the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).ExampleInput52 4 5 1 3OutputPetrNotePlease note that the sample is not a valid test (because of limitations for n) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden. | Input52 4 5 1 3 | OutputPetr | 2 seconds | 256 megabytes | ['combinatorics', 'math', '*1800'] |
A. Fairtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputSome company is going to hold a fair in Byteland. There are n towns in Byteland and m two-way roads between towns. Of course, you can reach any town from any other town using roads.There are k types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least s different types of goods. It costs d(u,v) coins to bring goods from town u to town v where d(u,v) is the length of the shortest path from u to v. Length of a path is the number of roads in this path.The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of n towns.InputThere are 4 integers n, m, k, s in the first line of input (1 \le n \le 10^{5}, 0 \le m \le 10^{5}, 1 \le s \le k \le min(n, 100)) — the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair.In the next line there are n integers a_1, a_2, \ldots, a_n (1 \le a_{i} \le k), where a_i is the type of goods produced in the i-th town. It is guaranteed that all integers between 1 and k occur at least once among integers a_{i}.In the next m lines roads are described. Each road is described by two integers u v (1 \le u, v \le n, u \ne v) — the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads.OutputPrint n numbers, the i-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town i. Separate numbers with spaces.ExamplesInput5 5 4 31 2 4 3 21 22 33 44 14 5Output2 2 2 2 3 Input7 6 3 21 2 3 3 2 2 11 22 33 42 55 66 7Output1 1 1 2 2 1 1 NoteLet's look at the first sample.To hold a fair in town 1 you can bring goods from towns 1 (0 coins), 2 (1 coin) and 4 (1 coin). Total numbers of coins is 2.Town 2: Goods from towns 2 (0), 1 (1), 3 (1). Sum equals 2.Town 3: Goods from towns 3 (0), 2 (1), 4 (1). Sum equals 2.Town 4: Goods from towns 4 (0), 1 (1), 5 (1). Sum equals 2.Town 5: Goods from towns 5 (0), 4 (1), 3 (2). Sum equals 3. | Input5 5 4 31 2 4 3 21 22 33 44 14 5 | Output2 2 2 2 3 | 2 seconds | 512 megabytes | ['graphs', 'greedy', 'number theory', 'shortest paths', '*1600'] |
G. Team Playerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n players numbered from 0 to n-1 with ranks. The i-th player has rank i.Players can form teams: the team should consist of three players and no pair of players in the team should have a conflict. The rank of the team is calculated using the following algorithm: let i, j, k be the ranks of players in the team and i < j < k, then the rank of the team is equal to A \cdot i + B \cdot j + C \cdot k.You are given information about the pairs of players who have a conflict. Calculate the total sum of ranks over all possible valid teams modulo 2^{64}.InputThe first line contains two space-separated integers n and m (3 \le n \le 2 \cdot 10^5, 0 \le m \le 2 \cdot 10^5) — the number of players and the number of conflicting pairs.The second line contains three space-separated integers A, B and C (1 \le A, B, C \le 10^6) — coefficients for team rank calculation.Each of the next m lines contains two space-separated integers u_i and v_i (0 \le u_i, v_i < n, u_i \neq v_i) — pair of conflicting players.It's guaranteed that each unordered pair of players appears in the input file no more than once.OutputPrint single integer — the total sum of ranks over all possible teams modulo 2^{64}.ExamplesInput4 02 3 4Output64Input4 12 3 41 0Output38Input6 41 5 30 33 55 44 3Output164NoteIn the first example all 4 teams are valid, i.e. triples: {0, 1, 2}, {0, 1, 3}, {0, 2, 3} {1, 2, 3}.In the second example teams are following: {0, 2, 3}, {1, 2, 3}.In the third example teams are following: {0, 1, 2}, {0, 1, 4}, {0, 1, 5}, {0, 2, 4}, {0, 2, 5}, {1, 2, 3}, {1, 2, 4}, {1, 2, 5}. | Input4 02 3 4 | Output64 | 2 seconds | 256 megabytes | ['combinatorics', '*2700'] |
F. Isomorphic Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of lowercase English letters.For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S and T for which f(si) = ti. Formally: f(si) = ti for any index i, for any character there is exactly one character that f(x) = y, for any character there is exactly one character that f(x) = y. For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best".You have to handle m queries characterized by three integers x, y, len (1 ≤ x, y ≤ n - len + 1). For each query check if two substrings s[x... x + len - 1] and s[y... y + len - 1] are isomorphic.InputThe first line contains two space-separated integers n and m (1 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105) — the length of the string s and the number of queries.The second line contains string s consisting of n lowercase English letters.The following m lines contain a single query on each line: xi, yi and leni (1 ≤ xi, yi ≤ n, 1 ≤ leni ≤ n - max(xi, yi) + 1) — the description of the pair of the substrings to check.OutputFor each query in a separate line print "YES" if substrings s[xi... xi + leni - 1] and s[yi... yi + leni - 1] are isomorphic and "NO" otherwise.ExampleInput7 4abacaba1 1 11 4 22 1 32 4 3OutputYESYESNOYESNoteThe queries in the example are following: substrings "a" and "a" are isomorphic: f(a) = a; substrings "ab" and "ca" are isomorphic: f(a) = c, f(b) = a; substrings "bac" and "aba" are not isomorphic since f(b) and f(c) must be equal to a at same time; substrings "bac" and "cab" are isomorphic: f(b) = c, f(a) = a, f(c) = b. | Input7 4abacaba1 1 11 4 22 1 32 4 3 | OutputYESYESNOYES | 3 seconds | 256 megabytes | ['hashing', 'strings', '*2300'] |
E. Pencils and Boxestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that: Each pencil belongs to exactly one box; Each non-empty box has at least k pencils in it; If pencils i and j belong to the same box, then |ai - aj| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≤ d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".InputThe first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·105, 0 ≤ d ≤ 109) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — saturation of color of each pencil.OutputPrint "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".ExamplesInput6 3 107 2 7 7 4 2OutputYESInput6 2 34 5 3 13 4 10OutputYESInput3 2 510 16 22OutputNONoteIn the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box. | Input6 3 107 2 7 7 4 2 | OutputYES | 2 seconds | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', 'two pointers', '*2100'] |
D. Sand Fortresstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle: h1 ≤ H: no sand from the leftmost spot should go over the fence; For any |hi - hi + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen; : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.InputThe only line contains two integer numbers n and H (1 ≤ n, H ≤ 1018) — the number of sand packs you have and the height of the fence, respectively.OutputPrint the minimum number of spots you can occupy so the all the castle building conditions hold.ExamplesInput5 2Output3Input6 8Output3NoteHere are the heights of some valid castles: n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...] n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots occupied) The first list for both cases is the optimal answer, 3 spots are occupied in them.And here are some invalid ones: n = 5, H = 2, [3, 2, 0, ...], [2, 3, 0, ...], [1, 0, 2, 2, ...] n = 6, H = 8, [2, 2, 2, 0, ...], [6, 0, ...], [1, 4, 1, 0...], [2, 2, 1, 0, ...] | Input5 2 | Output3 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'math', '*2100'] |
C. Liebig's Barrelstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have m = n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.Let volume vj of barrel j be equal to the length of the minimal stave in it. You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.InputThe first line contains three space-separated integers n, k and l (1 ≤ n, k ≤ 105, 1 ≤ n·k ≤ 105, 0 ≤ l ≤ 109).The second line contains m = n·k space-separated integers a1, a2, ..., am (1 ≤ ai ≤ 109) — lengths of staves.OutputPrint single integer — maximal total sum of the volumes of barrels or 0 if it's impossible to construct exactly n barrels satisfying the condition |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.ExamplesInput4 2 12 2 1 2 3 2 2 3Output7Input2 1 010 10Output20Input1 2 15 2Output2Input3 2 11 2 3 4 5 6Output0NoteIn the first example you can form the following barrels: [1, 2], [2, 2], [2, 3], [2, 3].In the second example you can form the following barrels: [10], [10].In the third example you can form the following barrels: [2, 5].In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough. | Input4 2 12 2 1 2 3 2 2 3 | Output7 | 2 seconds | 256 megabytes | ['greedy', '*1500'] |
B. Switches and Lampstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.InputThe first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps.The following n lines contain m characters each. The character ai, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise.It is guaranteed that if you press all n switches all m lamps will be turned on.OutputPrint "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.ExamplesInput4 510101010000011110000OutputYESInput4 510100010000011000101OutputNO | Input4 510101010000011110000 | OutputYES | 3 seconds | 256 megabytes | ['implementation', '*1200'] |
A. Chess Placingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to .In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).InputThe first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard. The second line of the input contains integer numbers (1 ≤ pi ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.OutputPrint one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.ExamplesInput61 2 6Output2Input101 2 3 4 5Output10NoteIn the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.In the second example the possible strategy is to move in 4 moves, then in 3 moves, in 2 moves and in 1 move. | Input61 2 6 | Output2 | 1 second | 256 megabytes | ['implementation', '*1100'] |
B. Minesweepertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle n \times m, where each cell is either empty, or contains a digit from 1 to 8, or a bomb. The field is valid if for each cell: if there is a digit k in the cell, then exactly k neighboring cells have bombs. if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most 8 neighboring cells).InputThe first line contains two integers n and m (1 \le n, m \le 100) — the sizes of the field.The next n lines contain the description of the field. Each line contains m characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from 1 to 8, inclusive.OutputPrint "YES", if the field is valid and "NO" otherwise.You can choose the case (lower or upper) for each letter arbitrarily.ExamplesInput3 31111*1111OutputYESInput2 4*.*.1211OutputNONoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article. | Input3 31111*1111 | OutputYES | 1 second | 256 megabytes | ['implementation', '*1100'] |
A. Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo players play a game.Initially there are n integers a_1, a_2, \ldots, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after n - 1 turns if both players make optimal moves.InputThe first line contains one integer n (1 \le n \le 1000) — the number of numbers on the board.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).OutputPrint one number that will be left on the board.ExamplesInput32 1 3Output2Input32 2 2Output2NoteIn the first sample, the first player erases 3 and the second erases 1. 2 is left on the board.In the second sample, 2 is left on the board regardless of the actions of the players. | Input32 1 3 | Output2 | 2 seconds | 256 megabytes | ['sortings', '*800'] |
E. NN countrytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the NN country, there are n cities, numbered from 1 to n, and n - 1 roads, connecting them. There is a roads path between any two cities.There are m bidirectional bus routes between cities. Buses drive between two cities taking the shortest path with stops in every city they drive through. Travelling by bus, you can travel from any stop on the route to any other. You can travel between cities only by bus.You are interested in q questions: is it possible to get from one city to another and what is the minimum number of buses you need to use for it?InputThe first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of cities.The second line contains n - 1 integers p_2, p_3, \ldots, p_n (1 \le p_i < i), where p_i means that cities p_i and i are connected by road.The third line contains a single integer m (1 \le m \le 2 \cdot 10^5) — the number of bus routes.Each of the next m lines contains 2 integers a and b (1 \le a, b \le n, a \neq b), meaning that there is a bus route between cities a and b. It is possible that there is more than one route between two cities.The next line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of questions you are interested in.Each of the next q lines contains 2 integers v and u (1 \le v, u \le n, v \neq u), meaning that you are interested if it is possible to get from city v to city u and what is the minimum number of buses you need to use for it.OutputPrint the answer for each question on a separate line. If there is no way to get from one city to another, print -1. Otherwise print the minimum number of buses you have to use.ExamplesInput71 1 1 4 5 644 25 41 36 764 53 57 24 53 25 3Output13-1123Input71 1 2 3 4 144 73 57 67 664 63 13 22 76 35 3Output1-1-11-11Note Routes for first sample are marked on the picture. | Input71 1 1 4 5 644 25 41 36 764 53 57 24 53 25 3 | Output13-1123 | 3 seconds | 256 megabytes | ['binary search', 'data structures', 'trees', '*2800'] |
D. Arkady and Rectanglestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputArkady has got an infinite plane painted in color 0. Then he draws n rectangles filled with paint with sides parallel to the Cartesian coordinate axes, one after another. The color of the i-th rectangle is i (rectangles are enumerated from 1 to n in the order he draws them). It is possible that new rectangles cover some of the previous ones completely or partially.Count the number of different colors on the plane after Arkady draws all the rectangles.InputThe first line contains a single integer n (1 \le n \le 100\,000) — the number of rectangles.The i-th of the next n lines contains 4 integers x_1, y_1, x_2 and y_2 (-10^9 \le x_1 < x_2 \le 10^9, -10^9 \le y_1 < y_2 \le 10^9) — the coordinates of corners of the i-th rectangle.OutputIn the single line print the number of different colors in the plane, including color 0.ExamplesInput5-1 -1 1 1-4 0 0 40 0 4 4-4 -4 0 00 -4 4 0Output5Input40 0 4 4-4 -4 0 00 -4 4 0-2 -4 2 4Output5Note That's how the plane looks in the first sample That's how the plane looks in the second sample0 = white, 1 = cyan, 2 = blue, 3 = purple, 4 = yellow, 5 = red. | Input5-1 -1 1 1-4 0 0 40 0 4 4-4 -4 0 00 -4 4 0 | Output5 | 4 seconds | 256 megabytes | ['data structures', '*3300'] |
C. Elevatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou work in a big office. It is a 9 floor building with an elevator that can accommodate up to 4 people. It is your responsibility to manage this elevator.Today you are late, so there are queues on some floors already. For each person you know the floor where he currently is and the floor he wants to reach. Also, you know the order in which people came to the elevator.According to the company's rules, if an employee comes to the elevator earlier than another one, he has to enter the elevator earlier too (even if these employees stay on different floors). Note that the employees are allowed to leave the elevator in arbitrary order.The elevator has two commands: Go up or down one floor. The movement takes 1 second. Open the doors on the current floor. During this operation all the employees who have reached their destination get out of the elevator. Then all the employees on the floor get in the elevator in the order they are queued up while it doesn't contradict the company's rules and there is enough space in the elevator. Each employee spends 1 second to get inside and outside the elevator. Initially the elevator is empty and is located on the floor 1.You are interested what is the minimum possible time you need to spend to deliver all the employees to their destination. It is not necessary to return the elevator to the floor 1.InputThe first line contains an integer n (1 ≤ n ≤ 2000) — the number of employees.The i-th of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 9, ai ≠ bi) — the floor on which an employee initially is, and the floor he wants to reach.The employees are given in the order they came to the elevator.OutputPrint a single integer — the minimal possible time in seconds.ExamplesInput23 55 3Output10Input25 33 5Output12Note Explaination for the first sample t = 0 t = 2 t = 3 t = 5 t = 6 t = 7 t = 9 t = 10 | Input23 55 3 | Output10 | 3 seconds | 256 megabytes | ['dp', 'graphs', 'shortest paths', '*2400'] |
B. XOR-pyramidtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor an array b of length m we define the function f as f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} where \oplus is bitwise exclusive OR.For example, f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15You are given an array a and a few queries. Each query is represented as two integers l and r. The answer is the maximum value of f on all continuous subsegments of the array a_l, a_{l+1}, \ldots, a_r.InputThe first line contains a single integer n (1 \le n \le 5000) — the length of a.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 2^{30}-1) — the elements of the array.The third line contains a single integer q (1 \le q \le 100\,000) — the number of queries.Each of the next q lines contains a query represented as two integers l, r (1 \le l \le r \le n).OutputPrint q lines — the answers for the queries.ExamplesInput38 4 122 31 2Output512Input61 2 4 8 16 3241 62 53 41 2Output6030123NoteIn first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.In second sample, optimal segment for first query are [3,6], for second query — [2,5], for third — [3,4], for fourth — [1,2]. | Input38 4 122 31 2 | Output512 | 2 seconds | 512 megabytes | ['dp', '*1800'] |
A. Finite or not?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.InputThe first line contains a single integer n (1 \le n \le 10^5) — the number of queries.Next n lines contain queries, one per line. Each line contains three integers p, q, and b (0 \le p \le 10^{18}, 1 \le q \le 10^{18}, 2 \le b \le 10^{18}). All numbers are given in notation with base 10.OutputFor each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.ExamplesInput26 12 104 3 10OutputFiniteInfiniteInput41 1 29 36 24 12 33 5 4OutputFiniteFiniteFiniteInfiniteNote\frac{6}{12} = \frac{1}{2} = 0,5_{10}\frac{4}{3} = 1,(3)_{10}\frac{9}{36} = \frac{1}{4} = 0,01_2\frac{4}{12} = \frac{1}{3} = 0,1_3 | Input26 12 104 3 10 | OutputFiniteInfinite | 1 second | 256 megabytes | ['implementation', 'math', '*1700'] |
F. The Meeting Place Cannot Be Changedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetr is a detective in Braginsk. Somebody stole a huge amount of money from a bank and Petr is to catch him. Somebody told Petr that some luxurious car moves along the roads without stopping.Petr knows that it is the robbers who drive the car. The roads in Braginsk are one-directional and each of them connects two intersections. Petr wants to select one intersection such that if the robbers continue to drive the roads indefinitely, they will sooner or later come to that intersection. The initial position of the robbers is unknown. Find such an intersection that fits the requirements.InputThe first line of the input contains two integers n and m (2 \leq n \le 10^5, 2 \leq m \leq 5 \cdot 10^5) — the number of intersections and the number of directed roads in Braginsk, respectively.Each of the next m lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — the start and finish of the i-th directed road. It is guaranteed that the robbers can move along the roads indefinitely.OutputPrint a single integer k — the intersection Petr needs to choose. If there are multiple answers, print any. If there are no such intersections, print -1.ExamplesInput5 61 22 33 13 44 55 3Output3Input3 31 22 33 1Output1NoteIn the first example the robbers can move, for example, along the following routes: (1-2-3-1), (3-4-5-3), (1-2-3-4-5-3-1). We can show that if Petr chooses the 3-rd intersection, he will eventually meet the robbers independently of their route. | Input5 61 22 33 13 44 55 3 | Output3 | 1 second | 256 megabytes | ['dfs and similar', 'graphs', '*2700'] |
E. Billiardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider a billiard table of rectangular size n \times m with four pockets. Let's introduce a coordinate system with the origin at the lower left corner (see the picture). There is one ball at the point (x, y) currently. Max comes to the table and strikes the ball. The ball starts moving along a line that is parallel to one of the axes or that makes a 45^{\circ} angle with them. We will assume that: the angles between the directions of the ball before and after a collision with a side are equal, the ball moves indefinitely long, it only stops when it falls into a pocket, the ball can be considered as a point, it falls into a pocket if and only if its coordinates coincide with one of the pockets, initially the ball is not in a pocket. Note that the ball can move along some side, in this case the ball will just fall into the pocket at the end of the side.Your task is to determine whether the ball will fall into a pocket eventually, and if yes, which of the four pockets it will be.InputThe only line contains 6 integers n, m, x, y, v_x, v_y (1 \leq n, m \leq 10^9, 0 \leq x \leq n; 0 \leq y \leq m; -1 \leq v_x, v_y \leq 1; (v_x, v_y) \neq (0, 0)) — the width of the table, the length of the table, the x-coordinate of the initial position of the ball, the y-coordinate of the initial position of the ball, the x-component of its initial speed and the y-component of its initial speed, respectively. It is guaranteed that the ball is not initially in a pocket.OutputPrint the coordinates of the pocket the ball will fall into, or -1 if the ball will move indefinitely.ExamplesInput4 3 2 2 -1 1Output0 0Input4 4 2 0 1 1Output-1Input10 10 10 1 -1 0Output-1NoteThe first sample: The second sample: In the third sample the ball will never change its y coordinate, so the ball will never fall into a pocket. | Input4 3 2 2 -1 1 | Output0 0 | 1 second | 256 megabytes | ['geometry', 'number theory', '*2600'] |
D. Sharktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer k that if the shark in some day traveled the distance strictly less than k, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to k; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least k.The shark never returned to the same location after it has moved from it. Thus, in the sequence of n days we can find consecutive nonempty segments when the shark traveled the distance less than k in each of the days: each such segment corresponds to one location. Max wants to choose such k that the lengths of all such segments are equal.Find such integer k, that the number of locations is as large as possible. If there are several such k, print the smallest one.InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of days.The second line contains n distinct positive integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the distance traveled in each of the day.OutputPrint a single integer k, such that the shark was in each location the same number of days, the number of locations is maximum possible satisfying the first condition, k is smallest possible satisfying the first and second conditions. ExamplesInput81 2 7 3 4 8 5 6Output7Input625 1 2 3 14 36Output2NoteIn the first example the shark travels inside a location on days 1 and 2 (first location), then on 4-th and 5-th days (second location), then on 7-th and 8-th days (third location). There are three locations in total.In the second example the shark only moves inside a location on the 2-nd day, so there is only one location. | Input81 2 7 3 4 8 5 6 | Output7 | 1 second | 256 megabytes | ['brute force', 'data structures', 'dsu', 'trees', '*1900'] |
C. Cut 'em all!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given a tree with n vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.InputThe first line contains an integer n (1 \le n \le 10^5) denoting the size of the tree. The next n - 1 lines contain two integers u, v (1 \le u, v \le n) each, describing the vertices connected by the i-th edge.It's guaranteed that the given edges form a tree.OutputOutput a single integer k — the maximum number of edges that can be removed to leave all connected components with even size, or -1 if it is impossible to remove edges in order to satisfy this property.ExamplesInput42 44 13 1Output1Input31 21 3Output-1Input107 18 48 104 76 59 33 52 102 5Output4Input21 2Output0NoteIn the first example you can remove the edge between vertices 1 and 4. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is -1. | Input42 44 13 1 | Output1 | 1 second | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'greedy', 'trees', '*1500'] |
B. Bus of Characterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the Bus of Characters there are n rows of seat, each having 2 seats. The width of both seats in the i-th row is w_i centimeters. All integers w_i are distinct.Initially the bus is empty. On each of 2n stops one passenger enters the bus. There are two types of passengers: an introvert always chooses a row where both seats are empty. Among these rows he chooses the one with the smallest seats width and takes one of the seats in it; an extrovert always chooses a row where exactly one seat is occupied (by an introvert). Among these rows he chooses the one with the largest seats width and takes the vacant place in it. You are given the seats width in each row and the order the passengers enter the bus. Determine which row each passenger will take.InputThe first line contains a single integer n (1 \le n \le 200\,000) — the number of rows in the bus.The second line contains the sequence of integers w_1, w_2, \dots, w_n (1 \le w_i \le 10^{9}), where w_i is the width of each of the seats in the i-th row. It is guaranteed that all w_i are distinct.The third line contains a string of length 2n, consisting of digits '0' and '1' — the description of the order the passengers enter the bus. If the j-th character is '0', then the passenger that enters the bus on the j-th stop is an introvert. If the j-th character is '1', the the passenger that enters the bus on the j-th stop is an extrovert. It is guaranteed that the number of extroverts equals the number of introverts (i. e. both numbers equal n), and for each extrovert there always is a suitable row.OutputPrint 2n integers — the rows the passengers will take. The order of passengers should be the same as in input.ExamplesInput23 10011Output2 1 1 2 Input610 8 9 11 13 5010010011101Output6 6 2 3 3 1 4 4 1 2 5 5 NoteIn the first example the first passenger (introvert) chooses the row 2, because it has the seats with smallest width. The second passenger (introvert) chooses the row 1, because it is the only empty row now. The third passenger (extrovert) chooses the row 1, because it has exactly one occupied seat and the seat width is the largest among such rows. The fourth passenger (extrovert) chooses the row 2, because it is the only row with an empty place. | Input23 10011 | Output2 1 1 2 | 2 seconds | 256 megabytes | ['data structures', 'greedy', 'implementation', '*1300'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.