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
C. Ela and Cricketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEla likes Chess a lot. During breaks, she usually challenges her co-worker in DTL to some chess games. She's not an expert at classic chess, but she's very interested in Chess variants, where she has to adapt to new rules and test her tactical mindset to win the game.The problem, which involves a non-standard chess pieces type that is described below, reads: given 3 white crickets on a n \cdot n board, arranged in an "L" shape next to each other, there are no other pieces on the board. Ela wants to know with a finite number of moves, can she put any white cricket on the square on row x, column y?An "L"-shape piece arrangement can only be one of the below: For simplicity, we describe the rules for crickets on the board where only three white crickets are. It can move horizontally, vertically, or diagonally, but only to a square in some direction that is immediately after another cricket piece (so that it must jump over it). If the square immediately behind the piece is unoccupied, the cricket will occupy the square. Otherwise (when the square is occupied by another cricket, or does not exist), the cricket isn't allowed to make such a move.See an example of valid crickets' moves on the pictures in the Note section.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains n (4 \le n \le 10^5) — denotes the size of the chessboard.The second line of each test case contains 6 numbers: r_1, c_1, r_2, c_2, r_3, c_3 (1 \le r_1, c_1, r_2, c_2, r_3, c_3 \le n) — coordinates of the crickets. The input ensures that the three crickets are arranged in an "L" shape that the legend stated.The third line of each test case contains 2 numbers: x, y (1 \le x, y \le n) — coordinates of the target square.OutputFor each test case, print "YES" or "NO" to denotes whether Ela can put a cricket on the target square.ExampleInput 687 2 8 2 7 15 182 2 1 2 2 15 582 2 1 2 2 16 681 1 1 2 2 15 582 2 1 2 2 18 888 8 8 7 7 84 8Output YES NO YES NO YES YES NoteHere's the solution for the first test case. The red square denotes where the crickets need to reach. Note that in chess horizontals are counted from bottom to top, as well as on this picture.
687 2 8 2 7 15 182 2 1 2 2 15 582 2 1 2 2 16 681 1 1 2 2 15 582 2 1 2 2 18 888 8 8 7 7 84 8
YES NO YES NO YES YES
1 second
256 megabytes
['constructive algorithms', 'games', 'implementation', 'math', '*1500']
B. Ela's Fitness and the Luxury Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWhile working at DTL, Ela is very aware of her physical and mental health. She started to practice various sports, such as Archery, Yoga, and Football.Since she started engaging in sports activities, Ela switches to trying a new sport on days she considers being "Luxury" days. She counts the days since she started these activities, in which the day she starts is numbered as day 1. A "Luxury" day is the day in which the number of this day is a luxurious number. An integer x is called a luxurious number if it is divisible by {\lfloor \sqrt{x} \rfloor}.Here \lfloor r \rfloor denotes the "floor" of a real number r. In other words, it's the largest integer not greater than r.For example: 8, 56, 100 are luxurious numbers, since 8 is divisible by \lfloor \sqrt{8} \rfloor = \lfloor 2.8284 \rfloor = 2, 56 is divisible \lfloor \sqrt{56} \rfloor = \lfloor 7.4833 \rfloor = 7, and 100 is divisible by \lfloor \sqrt{100} \rfloor = \lfloor 10 \rfloor = 10, respectively. On the other hand 5, 40 are not, since 5 are not divisible by \lfloor \sqrt{5} \rfloor = \lfloor 2.2361 \rfloor = 2, and 40 are not divisible by \lfloor \sqrt{40} \rfloor = \lfloor 6.3246 \rfloor = 6.Being a friend of Ela, you want to engage in these fitness activities with her to keep her and yourself accompanied (and have fun together, of course). Between day l and day r, you want to know how many times she changes the activities.InputEach test contains multiple test cases. The first line has the number of test cases t (1 \le t \le 10\ 000). The description of the test cases follows.The only line of each test case contains two integers l and r (1 \le l \le r \le 10^{18}) — the intervals at which you want to know how many times Ela changes her sports.OutputFor each test case, output an integer that denotes the answer.ExampleInput 58 198 20119 1211 1000000000000000001234567891011 1000000000000000000Output 5 6 2 948683296 2996666667 NoteIn the first test case, 5 luxury numbers in range [8, 19] are: 8, 9, 12, 15, 16.
58 198 20119 1211 1000000000000000001234567891011 1000000000000000000
5 6 2 948683296 2996666667
1 second
256 megabytes
['binary search', 'implementation', 'math', '*1300']
A. Ela Sorting Bookstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEla loves reading a lot, just like her new co-workers in DTL! On her first day after becoming an engineer in DTL, she is challenged by a co-worker to sort a heap of books into different compartments on the shelf.n books must be split into k compartments on the bookshelf (n is divisible by k). Each book is represented by a lowercase Latin letter from 'a' to 'y' inclusively, which is the beginning letter in the title of the book.Ela must stack exactly \frac{n}{k} books in each compartment. After the books are stacked, for each compartment indexed from 1 to k, she takes the minimum excluded (MEX) letter of the multiset of letters formed by letters representing all books in that compartment, then combines the resulting letters into a string. The first letter of the resulting string is the MEX letter of the multiset of letters formed by the first compartment, the second letter of the resulting string is the MEX letter of the multiset of letters formed by the second compartment, ... and so on. Please note, under the constraint of this problem, MEX letter can always be determined for any multiset found in this problem because 'z' is not used.What is the lexicographically greatest resulting string possible that Ela can create?A string a is lexicographically greater than a string b if and only if one of the following holds: b is a prefix of a, but b \ne a; in the first position where a and b differ, the string a has a letter that appears later in the alphabet than the corresponding letter in b. The minimum excluded (MEX) letter of a multiset of letters is the letter that appears earliest in the alphabet and is not contained in the multiset. For example, if a multiset of letters contains 7 letters 'b', 'a', 'b', 'c', 'e', 'c', 'f' respectively, then the MEX letter of this compartment is 'd', because 'd' is not included in the multiset, and all letters comes before 'd' in the alphabet, namely 'a', 'b' and 'c', are included in the multiset.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains two integers n and k (1 \le n \le 200; 1 \le k \le n). It is guaranteed that n is divisible by k.The second line of each test case contains a string of n lowercase Latin letters from 'a' to 'y' inclusively. Each letter represents the starting letter of the title of a book in the initial heap.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, output a string of k letters which is the most optimal string that Ela can find.ExampleInput 512 3cabccadabaac12 6cabccadabaac12 12cabccadabaac25 1abcdefghijklmnopqrstuvwxy10 5bcdxedbcfgOutput edb ccbbba bbbbbaaaaaaa z aaaaa NoteIn the first test case, the books can be divided into 3 compartments as below: the first compartment contains the books with indices 1, 2, 3, 7: multiset_1 = \{'c', 'a', 'b', 'd'\} \rightarrow MEX(multiset_1) = 'e' the second compartment contains the books with indices 4, 5, 6, 9 : multiset_2 = \{'c', 'c', 'a', 'b'\} \rightarrow MEX(multiset_2) = 'd' the third compartment contains the remaining books 8, 10, 11, 12 : multiset_3 = \{ 'a', 'a', 'a', 'c'\} \rightarrow MEX(multiset_3) = 'b' Therefore, the answer is 'edb'. It can be proven that there is no way that Ela can arrange the books so that it results in a lexicographically greater string.
512 3cabccadabaac12 6cabccadabaac12 12cabccadabaac25 1abcdefghijklmnopqrstuvwxy10 5bcdxedbcfg
edb ccbbba bbbbbaaaaaaa z aaaaa
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*900']
E. Swap and Taketime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou're given an array consisting of n integers. You have to perform n turns.Initially your score is 0.On the i-th turn, you are allowed to leave the array as it is or swap any one pair of 2 adjacent elements in the array and change exactly one of them to 0(and leave the value of other element unchanged) after swapping. In either case(whether you swap or not), after this you add a_i to your score. What's the maximum possible score you can get?InputThe first line contains a single integer n (2 \le n \le 500).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^6).OutputPrint a single integer — the maximum possible score.ExamplesInput 2 3 1 Output 6 Input 5 7 3 9 6 12 Output 52 NoteIn the first example, to get the maximum score we do as follows. Do nothing on the first turn, add 3 to the score. Swap the first and the second elements and turn 1 to 0 on the second turn, and add 3 to the score. The final score is 6.
2 3 1
6
2 seconds
1024 megabytes
['dp', 'greedy', '*2600']
D. Equal Binary Subsequencestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEverool has a binary string s of length 2n. Note that a binary string is a string consisting of only characters 0 and 1. He wants to partition s into two disjoint equal subsequences. He needs your help to do it.You are allowed to do the following operation exactly once. You can choose any subsequence (possibly empty) of s and rotate it right by one position. In other words, you can select a sequence of indices b_1, b_2, \ldots, b_m, where 1 \le b_1 < b_2 < \ldots < b_m \le 2n. After that you simultaneously set s_{b_1} := s_{b_m}, s_{b_2} := s_{b_1}, \ldots, s_{b_m} := s_{b_{m-1}}.Can you partition s into two disjoint equal subsequences after performing the allowed operation exactly once?A partition of s into two disjoint equal subsequences s^p and s^q is two increasing arrays of indices p_1, p_2, \ldots, p_n and q_1, q_2, \ldots, q_n, such that each integer from 1 to 2n is encountered in either p or q exactly once, s^p = s_{p_1} s_{p_2} \ldots s_{p_n}, s^q = s_{q_1} s_{q_2} \ldots s_{q_n}, and s^p = s^q.If it is not possible to partition after performing any kind of operation, report -1. If it is possible to do the operation and partition s into two disjoint subsequences s^p and s^q, such that s^p = s^q, print elements of b and indices of s^p, i. e. the values p_1, p_2, \ldots, p_n.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5), where 2n is the length of the binary string.The second line of each test case contains the binary string s of length 2n.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, follow the following output format.If there is no solution, print -1. Otherwise, In the first line, print an integer m (0 \leq m \leq 2n), followed by m distinct indices b_1, b_2, ..., b_m(in increasing order). In the second line, print n distinct indices p_1, p_2, ..., p_n (in increasing order). If there are multiple solutions, print any.ExampleInput 4 2 1010 3 100010 2 1111 2 1110 Output 0 1 2 2 3 5 1 2 5 3 2 3 4 1 4 -1 NoteIn the first test case, b is empty. So string s is not changed. Now s^p = s_1 s_2 = \mathtt{10}, and s^q = s_3s_4 = \mathtt{10}.In the second test case, b=[3,5]. Initially s_3=\mathtt{0}, and s_5=\mathtt{1}. On performing the operation, we simultaneously set s_3=\mathtt{1}, and s_5=\mathtt{0}.So s is updated to 101000 on performing the operation.Now if we take characters at indices [1,2,5] in s^p, we get s_1=\mathtt{100}. Also characters at indices [3,4,6] are in s^q. Thus s^q=100. We are done as s^p=s^q.In fourth test case, it can be proved that it is not possible to partition the string after performing any operation.
4 2 1010 3 100010 2 1111 2 1110
0 1 2 2 3 5 1 2 5 3 2 3 4 1 4 -1
1 second
256 megabytes
['constructive algorithms', 'geometry', 'greedy', 'implementation', 'strings', '*2200']
C2. Good Subarrays (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of this problem. In this version, we have queries. Note that we do not have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array b of length m is good if for all i the i-th element is greater than or equal to i. In other words, b is good if and only if b_i \geq i for all i (1 \leq i \leq m).You are given an array a consisting of n positive integers, and you are asked q queries. In each query, you are given two integers p and x (1 \leq p,x \leq n). You have to do a_p := x (assign x to a_p). In the updated array, find the number of pairs of indices (l, r), where 1 \le l \le r \le n, such that the array [a_l, a_{l+1}, \ldots, a_r] is good.Note that all queries are independent, which means after each query, the initial array a is restored. InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n).The third line contains an integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.Each of the next q lines contains two integers p_j and x_j (1 \leq p_j, x_j \leq n) – the description of the j-th query.OutputFor each query, print the number of suitable pairs of indices after making the change. ExamplesInput 4 2 4 1 4 3 2 4 3 3 2 1 Output 6 10 5 Input 5 1 1 3 2 1 3 1 3 2 5 4 5 Output 7 9 8 NoteHere are notes for first example.In first query, after update a=[2,4,1,4]. Now (1,1), (2,2), (3,3), (4,4), (1,2), and (3,4) are suitable pairs.In second query, after update a=[2,4,3,4]. Now all subarrays of a are good.In third query, after update a=[2,1,1,4]. Now (1,1), (2,2), (3,3), (4,4), and (3,4) are suitable.
4 2 4 1 4 3 2 4 3 3 2 1
6 10 5
3 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'two pointers', '*2400']
C1. Good Subarrays (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array b of length m is good if for all i the i-th element is greater than or equal to i. In other words, b is good if and only if b_i \geq i for all i (1 \leq i \leq m).You are given an array a consisting of n positive integers. Find the number of pairs of indices (l, r), where 1 \le l \le r \le n, such that the array [a_l, a_{l+1}, \ldots, a_r] is good.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 2 \cdot 10^5). Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5), the length of the array a.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq n), representing the array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the number of suitable pairs of indices.ExampleInput 331 2 331 1 142 1 4 3Output 6 3 7 NoteIn the first test case, all subarrays of a are good, so all pairs are suitable.In the second test case, the pairs (1, 1), (2, 2), and (3, 3) are suitable. For example, when (l, r) = (1, 2), the array b=[1,1] is not good because b_2 < 2.
331 2 331 1 142 1 4 3
6 3 7
1 second
256 megabytes
['binary search', 'data structures', 'schedules', 'two pointers', '*1300']
B. Playing with GCDtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a of length n. Does there exist an array b consisting of n+1 positive integers such that a_i=\gcd (b_i,b_{i+1}) for all i (1 \leq i \leq n)? Note that \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^5). Description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 10^5) — the length of the array a.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n representing the array a (1 \leq a_i \leq 10^4).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output "YES" if such b exists, otherwise output "NO". You can print each letter in any case (upper or lower).ExampleInput 4134324 234 2 441 1 1 1Output YES YES NO YES NoteIn the first test case, we can take b=[343,343].In the second test case, one possibility for b is b=[12,8,6].In the third test case, it can be proved that there does not exist any array b that fulfills all the conditions.
4134324 234 2 441 1 1 1
YES YES NO YES
1 second
256 megabytes
['math', 'number theory', '*1200']
A. Make A Equal to Btime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b of n elements, each element is either 0 or 1.You can make operations of 2 kinds. Pick an index i and change a_i to 1-a_i. Rearrange the array a however you want. Find the minimum number of operations required to make a equal to b.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 400) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 100) — the length of the arrays a and b.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (a_i is 0 or 1), representing the array a.The third line of each test case contains n space-separated integers b_1,b_2,\ldots,b_n (b_i is 0 or 1), representing the array b.OutputFor each test case, print the minimum number of operations required to make a equal to b.ExampleInput 531 0 10 0 141 1 0 00 1 1 121 11 141 0 0 10 1 1 0101Output 1 2 0 1 1 NoteIn the first case, we need only one operation: change a_1 to 1-a_i. Now a = [0, 0] which is equal to b.In the second case, the optimal way is to rearrange a to get the array [0, 1, 11. Now a = [0, 0, 1] which is equal to b.In the second case, one of optimal ways would be to first change a_3 to 1 - a_3, then rearrange a.In the third case, no operation is needed.In the fourth case, the optimal way is to rearrange a to get the array [0, 1, 1, 0].
531 0 10 0 141 1 0 00 1 1 121 11 141 0 0 10 1 1 0101
1 2 0 1 1
1 second
256 megabytes
['brute force', 'greedy', 'sortings', '*800']
F. Pebbles and Beadstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are two currencies: pebbles and beads. Initially you have a pebbles, b beads.There are n days, each day you can exchange one currency for another at some exchange rate.On day i, you can exchange -p_i \leq x \leq p_i pebbles for -q_i \leq y \leq q_i beads or vice versa. It's allowed not to perform an exchange at all. Meanwhile, if you perform an exchange, the proportion x \cdot q_i = -y \cdot p_i must be fulfilled. Fractional exchanges are allowed.You can perform no more than one such exchange in one day. The numbers of pebbles and beads you have must always remain non-negative.Please solve the following n problems independently: for each day i, output the maximum number of pebbles that you can have at the end of day i if you perform exchanges optimally.InputThe first line of the input contains a single integer t (1 \le t \le 10^3) — the number of test cases. The description of test cases follows.The first line of each test case contains three integers n, a and b (1 \le n \le 300\,000, 0 \le a, b \le 10^9) — the number of days and the initial number of pebbles and beads respectively.The second line of each test case contains n integers: p_1, p_2, \ldots, p_n (1 \le p_i \le 10^9).The third line of each test case contains n integers: q_1, q_2, \ldots, q_n (1 \le q_i \le 10^9).It is guaranteed that the sum of n over all test cases doesn't exceed 300\,000.OutputOutput n numbers — the maximum number of pebbles at the end of each day.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{\left|a - b\right|}{\max(1, \left|b\right|)} \le 10^{-6}.ExampleInput 32 6 02 34 23 0 64 2 102 3 101 10 10331000Output 6 8 4 6 9.000000 10.33NoteIn the image below you can see the solutions for the first two test cases. In each line there is an optimal sequence of actions for each day.In the first test case, the optimal strategy for the first day is to do no action at all, as we can only decrease the number of pebbles. The optimal strategy for the second day is at first to exchange 1 pebble for 2 beads, which is a correct exchange, since 1 \cdot 4 = 2 \cdot 2, and then to exchange 2 beads for 3 pebbles.
32 6 02 34 23 0 64 2 102 3 101 10 10331000
6 8 4 6 9.000000 10.33
4 seconds
256 megabytes
['data structures', 'geometry', '*2900']
E. House Planningtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n houses in your city arranged on an axis at points h_1, h_2, \ldots, h_n. You want to build a new house for yourself and consider two options where to place it: points p_1 and p_2.As you like visiting friends, you have calculated in advance the distances from both options to all existing houses. More formally, you have calculated two arrays d_1, d_2: d_{i, j} = \left|p_i - h_j\right|, where |x| defines the absolute value of x.After a long time of inactivity you have forgotten the locations of the houses h and the options p_1, p_2. But your diary still keeps two arrays — d_1, d_2, whose authenticity you doubt. Also, the values inside each array could be shuffled, so values at the same positions of d_1 and d_2 may correspond to different houses. Pay attention, that values from one array could not get to another, in other words, all values in the array d_1 correspond the distances from p_1 to the houses, and in the array d_2  — from p_2 to the houses.Also pay attention, that the locations of the houses h_i and the considered options p_j could match. For example, the next locations are correct: h = \{1, 0, 3, 3\}, p = \{1, 1\}, that could correspond to already shuffled d_1 = \{0, 2, 1, 2\}, d_2 = \{2, 2, 1, 0\}.Check whether there are locations of houses h and considered points p_1, p_2, for which the founded arrays of distances would be correct. If it is possible, find appropriate locations of houses and considered options. InputThe first line of the input contains a single integer t (1 \le t \le 10^3) — the number of test cases. The description of test cases follows.The first line of each test case contains one integer n (1 \le n \le 10^3) — the length of arrays d_1, d_2.The next two lines contain n integers each: arrays d_1 and d_2 (0 \le d_{i, j} \le 10^9) respectively.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^3.OutputFor each test case, output a single line "NO" if there is no answer.Otherwise output three lines. The first line must contain "YES". In the second line, print n integers h_1, h_2, \ldots, h_n. In the third line print two integers p_1, p_2.It must be satisfied that 0 \le h_i, p_1, p_2 \le 2 \cdot 10^9. We can show that if there is an answer, then there is one satisfying these constraints.If there are several answers, output any of them.ExampleInput 4155210 125 20210 3326 6940 2 1 22 2 1 0Output YES 5 0 10 NO YES 0 43 33 69 YES 1 0 3 3 1 1NoteIn the image below you can see the sample solutions. Planned houses are shown in bright colours: pink and purple. Existing houses are dim. In test case 1, the first planned house is located at point 0, the second at point 10. The existing house is located at point 5 and is at a distance of 5 from both planned houses. It can be shown that there is no answer for test case 2. In test case 3, the planned houses are located at points 33 and 69. Note that in test case 4, both plans are located at point 1, where one of the existing houses is located at the same time. It is a correct placement.
4155210 125 20210 3326 6940 2 1 22 2 1 0
YES 5 0 10 NO YES 0 43 33 69 YES 1 0 3 3 1 1
3 seconds
256 megabytes
['constructive algorithms', 'data structures', 'graph matchings', 'greedy', '*2400']
D. Meta-settime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou like the card board game "Set". Each card contains k features, each of which is equal to a value from the set \{0, 1, 2\}. The deck contains all possible variants of cards, that is, there are 3^k different cards in total.A feature for three cards is called good if it is the same for these cards or pairwise distinct. Three cards are called a set if all k features are good for them.For example, the cards (0, 0, 0), (0, 2, 1), and (0, 1, 2) form a set, but the cards (0, 2, 2), (2, 1, 2), and (1, 2, 0) do not, as, for example, the last feature is not good.A group of five cards is called a meta-set, if there is strictly more than one set among them. How many meta-sets there are among given n distinct cards?InputThe first line of the input contains two integers n and k (1 \le n \le 10^3, 1 \le k \le 20) — the number of cards on a table and the number of card features. The description of the cards follows in the next n lines.Each line describing a card contains k integers c_{i, 1}, c_{i, 2}, \ldots, c_{i, k} (0 \le c_{i, j} \le 2) — card features. It is guaranteed that all cards are distinct.OutputOutput one integer — the number of meta-sets.ExamplesInput 8 4 0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 2 0 0 1 0 0 1 0 0 0 2 2 0 0 Output 1 Input 7 4 0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 2 0 0 1 0 0 0 2 0 0 Output 3 Input 9 2 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 Output 54 Input 20 4 0 2 0 0 0 2 2 2 0 2 2 1 0 2 0 1 1 2 2 0 1 2 1 0 1 2 2 1 1 2 0 1 1 1 2 2 1 1 0 2 1 1 2 1 1 1 1 1 2 1 2 0 2 1 1 2 2 1 2 1 2 1 1 1 0 1 1 2 0 0 1 0 2 2 0 0 2 0 0 2 Output 0 NoteLet's draw the cards indicating the first four features. The first feature will indicate the number of objects on a card: 1, 2, 3. The second one is the color: red, green, purple. The third is the shape: oval, diamond, squiggle. The fourth is filling: open, striped, solid.You can see the first three tests below. For the first two tests, the meta-sets are highlighted.In the first test, the only meta-set is the five cards (0000,\ 0001,\ 0002,\ 0010,\ 0020). The sets in it are the triples (0000,\ 0001,\ 0002) and (0000,\ 0010,\ 0020). Also, a set is the triple (0100,\ 1000,\ 2200) which does not belong to any meta-set. In the second test, the following groups of five cards are meta-sets: (0000,\ 0001,\ 0002,\ 0010,\ 0020), (0000,\ 0001,\ 0002,\ 0100,\ 0200), (0000,\ 0010,\ 0020,\ 0100,\ 0200). In there third test, there are 54 meta-sets.
8 4 0 0 0 0 0 0 0 1 0 0 0 2 0 0 1 0 0 0 2 0 0 1 0 0 1 0 0 0 2 2 0 0
1
4 seconds
256 megabytes
['brute force', 'combinatorics', 'data structures', 'hashing', 'math', '*1700']
C. Phase Shifttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere was a string s which was supposed to be encrypted. For this reason, all 26 lowercase English letters were arranged in a circle in some order, afterwards, each letter in s was replaced with the one that follows in clockwise order, in that way the string t was obtained. You are given a string t. Determine the lexicographically smallest string s that could be a prototype of the given string t.A string a is lexicographically smaller than a string b of the same length if and only if: in the first position where a and b differ, the string a has a letter, that appears earlier in the alphabet than the corresponding letter in b. InputThe first line of the input contains a single integer t (1 \le t \le 3 \cdot 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of the string t.The next line contains the string t of the length n, containing lowercase English letters.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, output a single line containing the lexicographically smallest string s which could be a prototype of t.ExampleInput 51a2ba10codeforces26abcdefghijklmnopqrstuvwxyz26abcdefghijklmnopqrstuvwxzyOutput b ac abcdebfadg bcdefghijklmnopqrstuvwxyza bcdefghijklmnopqrstuvwxyaz NoteIn the first test case, we couldn't have the string "a", since the letter a would transit to itself. Lexicographically the second string "b" is suitable as an answer.In the second test case, the string "aa" is not suitable, since a would transit to itself. "ab" is not suitable, since the circle would be closed with 2 letters, but it must contain all 26. The next string "ac" is suitable.Below you can see the schemes for the first three test cases. The non-involved letters are skipped, they can be arbitrary placed in the gaps.
51a2ba10codeforces26abcdefghijklmnopqrstuvwxyz26abcdefghijklmnopqrstuvwxzy
b ac abcdebfadg bcdefghijklmnopqrstuvwxyza bcdefghijklmnopqrstuvwxyaz
3 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', 'greedy', 'implementation', 'strings', '*1400']
B. Tea with Tangerinestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n pieces of tangerine peel, the i-th of them has size a_i. In one step it is possible to divide one piece of size x into two pieces of positive integer sizes y and z so that y + z = x.You want that for each pair of pieces, their sizes differ strictly less than twice. In other words, there should not be two pieces of size x and y, such that 2x \le y. What is the minimum possible number of steps needed to satisfy the condition?InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains the integer n (1 \le n \le 100).Then one line follows, containing n integers a_1 \le a_2 \le \ldots \le a_n (1 \le a_i \le 10^7).OutputFor each test case, output a single line containing the minimum number of steps.ExampleInput 351 2 3 4 5110335600 900 1300 2000 2550Output 10 0 4 NoteIn the first test case, we initially have a piece of size 1, so all final pieces must have size 1. The total number of steps is: 0 + 1 + 2 + 3 + 4 = 10.In the second test case, we have just one piece, so we don't need to do anything, and the answer is 0 steps.In the third test case, one of the possible cut options is: 600,\ 900,\ (600 | 700),\ (1000 | 1000),\ (1000 | 1000 | 550). You can see this option in the picture below. The maximum piece has size 1000, and it is less than 2 times bigger than the minimum piece of size 550. 4 steps are done. We can show that it is the minimum possible number of steps.
351 2 3 4 5110335600 900 1300 2000 2550
10 0 4
1 second
256 megabytes
['greedy', 'math', '*900']
A. Working Weektime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour working week consists of n days numbered from 1 to n, after day n goes day 1 again. And 3 of them are days off. One of the days off is the last day, day n. You have to decide when the other two are.Choosing days off, you pursue two goals: No two days should go one after the other. Note that you can't make day 1 a day off because it follows day n. Working segments framed by days off should be as dissimilar as possible in duration. More specifically, if the segments are of size l_1, l_2, and l_3 days long, you want to maximize \min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|). Output the maximum value of \min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|) that can be obtained.InputThe first line of the input contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of test cases follows.The only line of each test case contains the integer n (6 \le n \le 10^9).OutputFor each test case, output one integer — the maximum possible obtained value.ExampleInput 36101033Output 0 1 342 NoteIn the image below you can see the example solutions for the first two test cases. Chosen days off are shown in purple. Working segments are underlined in green.In test case 1, the only options for days off are days 2, 3, and 4 (because 1 and 5 are next to day n). So the only way to place them without selecting neighboring days is to choose days 2 and 4. Thus, l_1 = l_2 = l_3 = 1, and the answer \min(|l_1 - l_2|, |l_2 - l_3|, |l_3 - l_1|) = 0. For test case 2, one possible way to choose days off is shown. The working segments have the lengths of 2, 1, and 4 days. So the minimum difference is 1 = \min(1, 3, 2) = \min(|2 - 1|, |1 - 4|, |4 - 2|). It can be shown that there is no way to make it larger.
36101033
0 1 342
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
F. Zeros and Onestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet S be the Thue-Morse sequence. In other words, S is the 0-indexed binary string with infinite length that can be constructed as follows: Initially, let S be "0". Then, we perform the following operation infinitely many times: concatenate S with a copy of itself with flipped bits.For example, here are the first four iterations: IterationS before iterationS before iteration with flipped bitsConcatenated S1010120110011030110100101101001401101001100101100110100110010110\ldots\ldots\ldots\ldots You are given two positive integers n and m. Find the number of positions where the strings S_0 S_1 \ldots S_{m-1} and S_n S_{n + 1} \ldots S_{n + m - 1} are different. InputEach test contains multiple test cases. The first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The first and only line of each test case contains two positive integers, n and m respectively (1 \leq n,m \leq 10^{18}).OutputFor each testcase, output a non-negative integer — the Hamming distance between the two required strings.ExampleInput 61 15 1034 21173 3419124639 5634877212073412269 96221437021Output 1 6 95 20 28208137 48102976088 NoteThe string S is equal to 0110100110010110....In the first test case, S_0 is "0", and S_1 is "1". The Hamming distance between the two strings is 1.In the second test case, S_0 S_1 \ldots S_9 is "0110100110", and S_5 S_6 \ldots S_{14} is "0011001011". The Hamming distance between the two strings is 6.
61 15 1034 21173 3419124639 5634877212073412269 96221437021
1 6 95 20 28208137 48102976088
3 seconds
256 megabytes
['bitmasks', 'divide and conquer', 'dp', 'math', '*2500']
E. Rectangular Congruencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a prime number n, and an array of n integers b_1,b_2,\ldots, b_n, where 0 \leq b_i < n for each 1 \le i \leq n.You have to find a matrix a of size n \times n such that all of the following requirements hold: 0 \le a_{i,j} < n for all 1 \le i, j \le n. a_{r_1, c_1} + a_{r_2, c_2} \not\equiv a_{r_1, c_2} + a_{r_2, c_1} \pmod n for all positive integers r_1, r_2, c_1, and c_2 such that 1 \le r_1 < r_2 \le n and 1 \le c_1 < c_2 \le n. a_{i,i} = b_i for all 1 \le i \leq n. Here x \not \equiv y \pmod m denotes that x and y give different remainders when divided by m.If there are multiple solutions, output any. It can be shown that such a matrix always exists under the given constraints.InputThe first line contains a single positive integer n (2 \le n < 350). The second line contains n integers b_1, b_2, \ldots, b_n (0 \le b_i < n) — the required values on the main diagonal of the matrix.It is guaranteed that n is prime.OutputPrint n lines. On the i-th line, print n integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, n}, each separated with a space.If there are multiple solutions, output any.ExamplesInput 2 0 0 Output 0 1 0 0Input 3 1 1 1 Output 1 2 2 1 1 0 1 0 1Input 5 1 4 1 2 4 Output 1 0 1 3 4 1 4 3 1 0 2 4 1 0 2 1 2 2 2 2 2 2 0 1 4NoteIn the first example, the answer is valid because all entries are non-negative integers less than n = 2, and a_{1,1}+a_{2,2} \not\equiv a_{1,2}+a_{2,1} \pmod 2 (because a_{1,1}+a_{2,2} = 0 + 0 \equiv 0 \pmod 2 and a_{1,2}+a_{2,1} = 1 + 0 \equiv 1 \pmod 2 ). Moreover, the values on the main diagonals are equal to 0,0 as required.In the second example, the answer is correct because all entries are non-negative integers less than n = 3, and the second condition is satisfied for all quadruplets (r_1, r_2, c_1, c_2). For example: When r_1=1, r_2=2, c_1=1 and c_2=2, a_{1,1}+a_{2,2} \not\equiv a_{1,2}+a_{2,1} \pmod 3 because a_{1,1}+a_{2,2} = 1 + 1 \equiv 2 \pmod 3 and a_{1,2}+a_{2,1} = 2 + 1 \equiv 0 \pmod 3 . When r_1=2, r_2=3, c_1=1, and c_2=3, a_{2,1}+a_{3,3} \not\equiv a_{2,3}+a_{3,1} \pmod 3 because a_{2,1}+a_{3,3} = 1 + 1 \equiv 2 \pmod 3 and a_{2,3}+a_{3,1} = 0 + 1 \equiv 1 \pmod 3 . Moreover, the values on the main diagonal are equal to 1,1,1 as required.
2 0 0
0 1 0 0
1 second
256 megabytes
['constructive algorithms', 'number theory', '*2100']
D. Slime Escapetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a game called Slime Escape. The game takes place on a number line. Initially, there are n slimes. For all positive integers i where 1 \le i \le n, the i-th slime is located at position i and has health a_i. You are controlling the slime at position k. There are two escapes located at positions 0 and n+1. Your goal is to reach any one of the two escapes by performing any number of game moves.In one game move, you move your slime to the left or right by one position. However, if there is another slime in the new position, you must absorb it. When absorbing a slime, the health of your slime would be increased by the health of the absorbed slime, then the absorbed slime would be removed from the game.Note that some slimes might have negative health, so your health would decrease when absorbing such slimes. You lose the game immediately if your slime has negative health at any moment during the game.Can you reach one of two escapes by performing any number of game moves, without ever losing the game?InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 20\,000) — the number of test cases. Description of the test cases follows.The first line of each test case contains two positive integers n, k (3 \leq n \leq 200\,000, 1 \leq k \leq n) — the number of slimes and the position of your slime.The second line of each test case contains n integers, a_1, a_2, \ldots, a_n (-10^9 \leq a_i \leq 10^9) — the health of the slimes.It is guaranteed that health of your slime is non-negative (a_k \geq 0), and all other slimes have non-zero health (a_i \ne 0 for i \ne k).It is guaranteed that the sum of n over all test cases does not exceed 200\,000.OutputFor each test case, print "YES" (without quotes) if you can escape without losing, and "NO" (without quotes) otherwise.ExampleInput 67 4-1 -2 -3 6 -2 -3 -13 1232 -500 -7007 4-1 -2 -4 6 -2 -4 -18 4-100 10 -7 6 -2 -3 6 -108 2-999 0 -2 3 4 5 6 77 37 3 3 4 2 1 1Output YES YES NO YES NO YES NoteIn the first test case, you control the slime at position 4 with health 6. One way to escape is to absorb the slimes at positions 5, 6, and 7. Your slime escapes with 0 health at position 8.In the second test case, you control the slime with 232 health at position 1. Since your slime is already located next to the escape at position 0, you can move to it without absorbing any slime.In the third test case, it can be shown that your slime would always have a negative health before reaching any one of two escapes.In the fourth test case, you control the slime at position 4 with health 6. The following describes a possible sequence of moves to win: Absorb the slimes at positions 5, 6, and 7: your health becomes 4 after absorbing the slime with health -2; becomes 1 after absorbing the slime with health -3; and becomes 7 after absorbing the slime with health 6. Absorb the slimes at positions 3, and 2: your health becomes 7-7+10=10. Absorb the slime at position 8: your health becomes 10-10=0. Use the escape at position 9. Since your slime has maintained non-negative health at all times, you have won.
67 4-1 -2 -3 6 -2 -3 -13 1232 -500 -7007 4-1 -2 -4 6 -2 -4 -18 4-100 10 -7 6 -2 -3 6 -108 2-999 0 -2 3 4 5 6 77 37 3 3 4 2 1 1
YES YES NO YES NO YES
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'two pointers', '*1800']
C. Removing Smallest Multiplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a set S, which contains the first n positive integers: 1, 2, \ldots, n.You can perform the following operation on S any number of times (possibly zero): Choose a positive integer k where 1 \le k \le n, such that there exists a multiple of k in S. Then, delete the smallest multiple of k from S. This operation requires a cost of k. You are given a set T, which is a subset of S. Find the minimum possible total cost of operations such that S would be transformed into T. We can show that such a transformation is always possible.InputThe first line of the input contains a single integer t (1 \le t \le 10\,000) — the number of test cases. The description of the test cases follows.The first line contains a single positive integer n (1 \le n \le 10^6).The second line of each test case contains a binary string of length n, describing the set T. The i-th character of the string is '1' if and only if i is an element of T, and '0' otherwise.It is guaranteed that the sum of n over all test cases does not exceed 10^6. OutputFor each test case, output one non-negative integer — the minimum possible total cost of operations such that S would be transformed into T.ExampleInput 6611111171101001400004001081001010115110011100101100Output 0 11 4 4 17 60 NoteIn the first test case, we shall not perform any operations as S is already equal to T, which is the set \{1, 2, 3, 4, 5, 6\}.In the second test case, initially, S = \{1, 2, 3, 4, 5, 6, 7\}, and T = \{1, 2, 4, 7\}. We shall perform the following operations: Choose k=3, then delete 3 from S. Choose k=3, then delete 6 from S. Choose k=5, then delete 5 from S. The total cost is 3+3+5 = 11. It can be shown that this is the smallest cost possible.In the third test case, initially, S = \{1, 2, 3, 4\} and T = \{\} (empty set). We shall perform 4 operations of k=1 to delete 1, 2, 3, and 4.In the fourth test case, initially, S = \{1, 2, 3, 4\} and T = \{3\}. We shall perform two operations with k=1 to delete 1 and 2, then perform one operation with k=2 to delete 4.
6611111171101001400004001081001010115110011100101100
0 11 4 4 17 60
2 seconds
256 megabytes
['greedy', 'math', '*1200']
B. Bright, Nice, Brillianttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a pyramid which consists of n floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the i-th floor consists of i rooms.Denote the j-th room on the i-th floor as (i,j). For all positive integers i and j such that 1 \le j \le i < n, there are 2 one-way staircases which lead from (i,j) to (i+1,j) and from (i,j) to (i+1,j+1) respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room (i, j) to be the number of rooms with a torch from which you can reach the room (i, j) through a non-negative number of staircases.For example, when n=5 and torches are placed in the rooms (1,1), (2,1), (3,2), (4,1), (4,3), and (5,3), the pyramid can be illustrated as follows: In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room (4,2) (the room with a star) has brightness 3. In the picture below, the rooms from where you can reach (4,2) have red border. The brightness is 3 since there are three torches among these rooms. The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms (1,1), (2,1), (3,1), ..., (n,1).Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The only line of each test case contains a single positive integer n (1 \le n \le 500) — the number of floors in the pyramid.It is guaranteed that the sum of n over all test cases does not exceed 500.OutputFor each test case, output n lines, the arrangement of torches in the pyramid.The i-th line should contain i integers, each separated with a space. The j-th integer on the i-th line should be 1 if room (i,j) has a torch, and 0 otherwise.We can show that an answer always exists. If there are multiple answers, output any one of them.ExampleInput 3123Output 1 1 1 1 1 1 1 1 0 1 NoteIn the third test case, torches are placed in (1,1), (2,1), (2,2), (3,1), and (3,3). The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness 3.The brilliance of the pyramid is 1+2+3 = 6. It can be shown that no arrangements with n=3 will have a greater brilliance.
3123
1 1 1 1 1 1 1 1 0 1
1 second
256 megabytes
['constructive algorithms', '*800']
A. Select Three Stickstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n sticks with positive integral length a_1, a_2, \ldots, a_n.You can perform the following operation any number of times (possibly zero): choose one stick, then either increase or decrease its length by 1. After each operation, all sticks should have positive lengths. What is the minimum number of operations that you have to perform such that it is possible to select three of the n sticks and use them without breaking to form an equilateral triangle?An equilateral triangle is a triangle where all of its three sides have the same length.InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 300) — the number of sticks.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the lengths of the sticks.It is guaranteed that the sum of n over all test cases does not exceed 300. OutputFor each test case, print one integer on a single line — the minimum number of operations to be made.ExampleInput 431 2 347 3 7 353 4 2 1 183 1 4 1 5 9 2 6Output 2 4 1 1 NoteIn the first test case, you can increase the length of the first stick by 1, then decrease the length of the third stick by 1. In total, you perform 2 operations, such that the three sticks form an equilateral triangle of side length 2.In the fourth test case, you can decrease the length of the seventh stick by 1. An equilateral triangle of side length 1 can be selected and formed by the second, fourth, and seventh sticks.
431 2 347 3 7 353 4 2 1 183 1 4 1 5 9 2 6
2 4 1 1
1 second
256 megabytes
['brute force', 'greedy', 'sortings', '*800']
E. Conveyortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a conveyor with 120 rows and 120 columns. Each row and column is numbered from 0 to 119, and the cell in i-th row and j-th column is denoted as (i, j). The top leftmost cell is (0, 0). Each cell has a belt, and all belts are initially facing to the right.Initially, a slime ball is on the belt of (0, 0), and other belts are empty. Every second, the state of the conveyor changes as follows: All slime balls on the conveyor move one cell in the direction of the belt at the same time. If there is no cell in the moved position, the slime gets out of the conveyor, and if two slime balls move to the same cell, they merge into one. All belts with slime ball in the previous second change direction at the same time: belts facing to the right become facing to the down, and vice versa. A new slime ball is placed on cell (0, 0). There are q queries, each being three integers t, x, and y. You have to find out if there is a slime at the cell (x, y) after t seconds from the start. Can you do it?InputThe first line contains one integer q (1 \le q \le 10^4) — the number of queries.The only line of each query contains three integers t, x, and y (0 \le t \le 10^{18}, 0 \le x, y < 120).OutputPrint the answer for each test case, one per line. If there is a slime ball in the cell (x, y) after t seconds from the initial state, print "YES". Otherwise, print "NO".ExampleInput 61 1 05 1 30 0 02 4 52 0 21547748756 100 111Output NO YES YES NO YES YES NoteThe state of conveyor with t = 0. Red arrow represents the direction of each belt, and blue figure represents slime.The state of conveyor with t = 1.The state of conveyor with t = 2.
61 1 05 1 30 0 02 4 52 0 21547748756 100 111
NO YES YES NO YES YES
3 seconds
256 megabytes
['constructive algorithms', 'dp', 'math', '*2700']
D2. Zero-One (Hard Version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of this problem. In this version, n \le 5000 holds, and this version has no restriction between x and y. You can make hacks only if both versions of the problem are solved.You are given two binary strings a and b, both of length n. You can do the following operation any number of times (possibly zero). Select two indices l and r (l < r). Change a_l to (1 - a_l), and a_r to (1 - a_r). If l + 1 = r, the cost of the operation is x. Otherwise, the cost is y. You have to find the minimum cost needed to make a equal to b or say there is no way to do so.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of three lines. The first line of each test case contains three integers n, x, and y (5 \le n \le 5000, 1 \le x, y \le 10^9) — the length of the strings, and the costs per operation.The second line of each test case contains the string a of length n. The string only consists of digits 0 and 1.The third line of each test case contains the string b of length n. The string only consists of digits 0 and 1.It is guaranteed that the sum of n over all test cases doesn't exceed 5000.OutputFor each test case, if there is no way to make a equal to b, print -1. Otherwise, print the minimum cost needed to make a equal to b.ExampleInput 65 8 901001001016 2 110000011000005 7 201000110117 8 3011100101000016 3 40100011010005 10 10110001100Output 8 10 -1 6 7 0 NoteIn the first test case, selecting indices 2 and 3 costs 8, which is the minimum.In the second test case, we can perform the following operations. Select indices 1 and 2. It costs 2, and a is 110001 now. Select indices 2 and 3. It costs 2, and a is 101001 now. Select indices 3 and 4. It costs 2, and a is 100101 now. Select indices 4 and 5. It costs 2, and a is 100011 now. Select indices 5 and 6. It costs 2, and a is 100000 now. The total cost is 10.In the third test case, we cannot make a equal to b using any number of operations.In the fourth test case, we can perform the following operations. Select indices 3 and 6. It costs 3, and a is 0101011 now. Select indices 4 and 6. It costs 3, and a is 0100001 now. The total cost is 6.In the fifth test case, we can perform the following operations. Select indices 1 and 6. It costs 4, and a is 110000 now. Select indices 2 and 3. It costs 3, and a is 101000 now. The total cost is 7.In the sixth test case, we don't have to perform any operation.
65 8 901001001016 2 110000011000005 7 201000110117 8 3011100101000016 3 40100011010005 10 10110001100
8 10 -1 6 7 0
3 seconds
512 megabytes
['dp', 'greedy', '*2000']
D1. Zero-One (Easy Version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. In this version, n \le 3000, x \ge y holds. You can make hacks only if both versions of the problem are solved.You are given two binary strings a and b, both of length n. You can do the following operation any number of times (possibly zero). Select two indices l and r (l < r). Change a_l to (1 - a_l), and a_r to (1 - a_r). If l + 1 = r, the cost of the operation is x. Otherwise, the cost is y. You have to find the minimum cost needed to make a equal to b or say there is no way to do so.InputThe first line contains one integer t (1 \le t \le 600) — the number of test cases.Each test case consists of three lines. The first line of each test case contains three integers n, x, and y (5 \le n \le 3000, 1 \le y \le x \le 10^9) — the length of the strings, and the costs per operation.The second line of each test case contains the string a of length n. The string only consists of digits 0 and 1.The third line of each test case contains the string b of length n. The string only consists of digits 0 and 1.It is guaranteed that the sum of n over all test cases doesn't exceed 3000.OutputFor each test case, if there is no way to make a equal to b, print -1. Otherwise, print the minimum cost needed to make a equal to b.ExampleInput 45 8 701001001015 7 201000110117 8 3011100101000015 10 10110001100Output 8 -1 6 0 NoteIn the first test case, selecting indices 2 and 3 costs 8, which is the minimum possible cost.In the second test case, we cannot make a equal to b using any number of operations.In the third test case, we can perform the following operations: Select indices 3 and 6. It costs 3, and a is 0101011 now. Select indices 4 and 6. It costs 3, and a is 0100001 now. The total cost is 6.In the fourth test case, we don't have to perform any operations.
45 8 701001001015 7 201000110117 8 3011100101000015 10 10110001100
8 -1 6 0
3 seconds
512 megabytes
['constructive algorithms', 'greedy', 'math', '*1400']
C. Parity Shuffle Sortingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a with n non-negative integers. You can apply the following operation on it. Choose two indices l and r (1 \le l < r \le n). If a_l + a_r is odd, do a_r := a_l. If a_l + a_r is even, do a_l := a_r. Find any sequence of at most n operations that makes a non-decreasing. It can be proven that it is always possible. Note that you do not have to minimize the number of operations.An array a_1, a_2, \ldots, a_n is non-decreasing if and only if a_1 \le a_2 \le \ldots \le a_n.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases.Each test case consists of two lines. The first line of each test case contains one integer n (1 \le n \le 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9)  — the array itself.It is guaranteed that the sum of n over all test cases doesn't exceed 10^5.OutputFor each test case, print one integer m (0 \le m \le n), the number of operations, in the first line.Then print m lines. Each line must contain two integers l_i, r_i, which are the indices you chose in the i-th operation (1 \le l_i < r_i \le n).If there are multiple solutions, print any of them.ExampleInput 327 851 1000000000 3 0 510Output 0 2 3 4 1 2 0 NoteIn the second test case, a changes like this: Select indices 3 and 4. a_3 + a_4 = 3 is odd, so do a_4 := a_3. a = [1, 1000000000, 3, 3, 5] now. Select indices 1 and 2. a_1 + a_2 = 1000000001 is odd, so do a_2 := a_1. a = [1, 1, 3, 3, 5] now, and it is non-decreasing. In the first and third test cases, a is already non-decreasing.
327 851 1000000000 3 0 510
0 2 3 4 1 2 0
2 seconds
256 megabytes
['constructive algorithms', 'sortings', '*1300']
B. Rule of Leaguetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a badminton championship in which n players take part. The players are numbered from 1 to n. The championship proceeds as follows: player 1 and player 2 play a game, then the winner and player 3 play a game, and then the winner and player 4 play a game, and so on. So, n-1 games are played, and the winner of the last game becomes the champion. There are no draws in the games.You want to find out the result of championship. Currently, you only know the following information: Each player has either won x games or y games in the championship. Given n, x, and y, find out if there is a result that matches this information.InputThe first line contains one integer t (1 \le t \le 10^5) — the number of test cases.The only line of each test case contains three integers n, x, y (2 \le n \le 10^5, 0 \le x, y < n).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputPrint the answer for each test case, one per line. If there is no result that matches the given information about n, x, y, print -1. Otherwise, print n-1 space separated integers, where the i-th integer is the player number of the winner of the i-th game. If there are multiple valid results, print any.ExampleInput 55 2 08 1 23 0 02 0 16 3 0Output 1 1 4 4 -1 -1 2 -1 NoteIn the first test case, player 1 and player 4 won x times, player 2 and player 3 won y times.In the second, third, and fifth test cases, no valid result exists.
55 2 08 1 23 0 02 0 16 3 0
1 1 4 4 -1 -1 2 -1
2 seconds
256 megabytes
['constructive algorithms', 'math', '*900']
A. Consecutive Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a with n integers. You can perform the following operation at most k times: Choose two indices i and j, in which i \,\bmod\, k = j \,\bmod\, k (1 \le i < j \le n). Swap a_i and a_j. After performing all operations, you have to select k consecutive elements, and the sum of the k elements becomes your score. Find the maximum score you can get.Here x \bmod y denotes the remainder from dividing x by y.InputThe first line contains one integer t (1 \le t \le 600) — the number of test cases.Each test case consists of two lines. The first line of each test case contains two integers n and k (1 \le k \le n \le 100) — the length of the array and the number in the statement above.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9)  — the array itself.OutputFor each test case, print the maximum score you can get, one per line.ExampleInput 53 25 6 01 175 37 0 4 0 44 22 7 3 43 31000000000 1000000000 999999997Output 11 7 15 10 2999999997 NoteIn the first test case, we can get a score of 11 if we select a_1, a_2 without performing any operations.In the third test case, we can get a score of 15 if we first swap a_1 with a_4 and then select a_3, a_4, a_5.
53 25 6 01 175 37 0 4 0 44 22 7 3 43 31000000000 1000000000 999999997
11 7 15 10 2999999997
1 second
256 megabytes
['greedy', 'sortings', '*800']
E. Locationtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two arrays of integers a_1, a_2, \ldots, a_n and b_1, b_2, \ldots, b_n. You need to handle q queries of the following two types: 1 l r x: assign a_i := x for all l \leq i \leq r; 2 l r: find the minimum value of the following expression among all l \leq i \leq r: \frac{\operatorname{lcm}(a_i, b_i)}{\gcd(a_i, b_i)}.In this problem \gcd(x, y) denotes the greatest common divisor of x and y, and \operatorname{lcm}(x, y) denotes the least common multiple of x and y.InputThe first line contains two integers n and q (1 \leq n, q \leq 5 \cdot 10^4) — the number of numbers in the arrays a and b and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 5 \cdot 10^4) — the elements of the array a.The third line contains n integers b_1, b_2, \ldots, b_n (1 \leq b_i \leq 5 \cdot 10^4) — the elements of the array b.Then q lines follow, j-th of which starts with an integer t_j (1 \leq t_j \leq 2) and means that the j-th query has type t_j.If t_j = 1, it is followed by three integers l_j, r_j, and x_j (1 \leq l_j \leq r_j \leq n, 1 \leq x_j \leq 5 \cdot 10^4).If t_j = 2, it is followed by two integers l_j and r_j (1 \leq l_j \leq r_j \leq n).It is guaranteed that there is at least one query of type 2.OutputFor each query of the second type, output the minimum value of the expression.ExamplesInput 10 106 10 15 4 9 25 2 3 5 301 2 3 4 6 9 12 15 18 302 1 101 7 10 92 5 101 1 6 142 4 72 3 91 2 9 302 1 42 3 72 5 10Output 1 2 12 2 10 5 2 Input 4 410 2 12 51 12 16 12 2 41 2 3 181 2 2 102 2 3Output 5 30 NoteIn the first example: For the first query we can choose i = 4. So the value is \frac{\operatorname{lcm}(4, 4)}{\gcd(4, 4)} = \frac{4}{4} = 1. After the second query the array a = [6, 10, 15, 4, 9, 25, 9, 9, 9, 9]. For the third query we can choose i = 9. So the value is \frac{\operatorname{lcm}(9, 18)}{\gcd(9, 18)} = \frac{18}{9} = 2.In the second: For the first query we can choose i = 4. So the value is \frac{\operatorname{lcm}(1, 5)}{\gcd(1, 5)} = \frac{5}{1} = 5. After the second query the array a = [10, 18, 18, 5]. After the third query the array a = [10, 10, 18, 5]. For the fourth query we can choose i = 2. So the value is \frac{\operatorname{lcm}(10, 12)}{\gcd(10, 12)} = \frac{60}{2} = 30.
10 106 10 15 4 9 25 2 3 5 301 2 3 4 6 9 12 15 18 302 1 101 7 10 92 5 101 1 6 142 4 72 3 91 2 9 302 1 42 3 72 5 10
1 2 12 2 10 5 2
3 seconds
512 megabytes
['data structures', 'dp', 'math', 'number theory', '*2800']
D2. Balance (Hard version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version there are remove queries.Initially you have a set containing one element — 0. You need to handle q queries of the following types:+ x — add the integer x to the set. It is guaranteed that this integer is not contained in the set; - x — remove the integer x from the set. It is guaranteed that this integer is contained in the set; ? k — find the k\text{-mex} of the set. In our problem, we define the k\text{-mex} of a set of integers as the smallest non-negative integer x that is divisible by k and which is not contained in the set.InputThe first line contains an integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.The following q lines describe the queries.An addition query of integer x is given in the format + x (1 \leq x \leq 10^{18}). It is guaranteed that x is not contained in the set.A remove query of integer x is given in the format - x (1 \leq x \leq 10^{18}). It is guaranteed that x is contained in the set.A search query of k\text{-mex} is given in the format ? k (1 \leq k \leq 10^{18}).It is guaranteed that there is at least one query of type ?.OutputFor each query of type ? output a single integer — the k\text{-mex} of the set.ExamplesInput 18+ 1+ 2? 1+ 4? 2+ 6? 3+ 7+ 8? 1? 2+ 5? 1+ 1000000000000000000? 1000000000000000000- 4? 1? 2Output 3 6 3 3 10 3 2000000000000000000 3 4 Input 10+ 100? 100+ 200? 100- 100? 100+ 50? 50- 50? 50Output 200 300 100 100 50 NoteIn the first example:After the first and second queries, the set will contain elements \{0, 1, 2\}. The smallest non-negative number that is divisible by 1 and is not in the set is 3.After the fourth query, the set will contain the elements \{0, 1, 2, 4\}. The smallest non-negative number that is divisible by 2 and is not in the set is 6.In the second example: Initially, the set contains only the element \{0\}. After adding an integer 100 the set contains elements \{0, 100\}. 100\text{-mex} of the set is 200. After adding an integer 200 the set contains elements \{0, 100, 200\}. 100\text{-mex} of the set 300. After removing an integer 100 the set contains elements \{0, 200\}. 100\text{-mex} of the set is 100. After adding an integer 50 the set contains elements \{0, 50, 200\}. 50\text{-mex} of the set is 100. After removing an integer 50 the set contains elements \{0, 200\}. 100\text{-mex} of the set is 50.
18+ 1+ 2? 1+ 4? 2+ 6? 3+ 7+ 8? 1? 2+ 5? 1+ 1000000000000000000? 1000000000000000000- 4? 1? 2
3 6 3 3 10 3 2000000000000000000 3 4
3 seconds
256 megabytes
['brute force', 'data structures', 'number theory', '*2400']
D1. Balance (Easy version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version there are no "remove" queries.Initially you have a set containing one element — 0. You need to handle q queries of the following types:+ x — add the integer x to the set. It is guaranteed that this integer is not contained in the set; ? k — find the k\text{-mex} of the set. In our problem, we define the k\text{-mex} of a set of integers as the smallest non-negative integer x that is divisible by k and which is not contained in the set.InputThe first line contains an integer q (1 \leq q \leq 2 \cdot 10^5) — the number of queries.The following q lines describe the queries.An addition query of integer x is given in the format + x (1 \leq x \leq 10^{18}). It is guaranteed that x was not contained in the set.A search query of k\text{-mex} is given in the format ? k (1 \leq k \leq 10^{18}).It is guaranteed that there will be at least one query of type ?.OutputFor each query of type ? output a single integer — the k\text{-mex} of the set.ExamplesInput 15+ 1+ 2? 1+ 4? 2+ 6? 3+ 7+ 8? 1? 2+ 5? 1+ 1000000000000000000? 1000000000000000000Output 3 6 3 3 10 3 2000000000000000000 Input 6+ 100? 100+ 200? 100+ 50? 50Output 200 300 150 NoteIn the first example:After the first and second queries, the set will contain elements \{0, 1, 2\}. The smallest non-negative number that is divisible by 1 and is not contained in the set is 3.After the fourth query, the set will contain the elements \{0, 1, 2, 4\}. The smallest non-negative number that is divisible by 2 and is not contained in the set is 6.In the second example: Initially, the set contains only the element \{0\}. After adding an integer 100 the set contains elements \{0, 100\}. 100\text{-mex} of the set is 200. After adding an integer 200 the set contains elements \{0, 100, 200\}. 100\text{-mex} of the set is 300. After adding an integer 50 the set contains elements \{0, 50, 100, 200\}. 50\text{-mex} of the set is 150.
15+ 1+ 2? 1+ 4? 2+ 6? 3+ 7+ 8? 1? 2+ 5? 1+ 1000000000000000000? 1000000000000000000
3 6 3 3 10 3 2000000000000000000
3 seconds
256 megabytes
['brute force', 'data structures', 'implementation', 'number theory', '*1500']
C2. Sheikh (Hard Version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version q = n.You are given an array of integers a_1, a_2, \ldots, a_n.The cost of a subsegment of the array [l, r], 1 \leq l \leq r \leq n, is the value f(l, r) = \operatorname{sum}(l, r) - \operatorname{xor}(l, r), where \operatorname{sum}(l, r) = a_l + a_{l+1} + \ldots + a_r, and \operatorname{xor}(l, r) = a_l \oplus a_{l+1} \oplus \ldots \oplus a_r (\oplus stands for bitwise XOR).You will have q queries. Each query is given by a pair of numbers L_i, R_i, where 1 \leq L_i \leq R_i \leq n. You need to find the subsegment [l, r], L_i \leq l \leq r \leq R_i, with maximum value f(l, r). If there are several answers, then among them you need to find a subsegment with the minimum length, that is, the minimum value of r - l + 1.InputEach test consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and q (1 \leq n \leq 10^5, q = n) — the length of the array and the number of queries.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9) — array elements.i-th of the next q lines of each test case contains two integers L_i and R_i (1 \leq L_i \leq R_i \leq n) — the boundaries in which we need to find the segment.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.It is guaranteed that L_1 = 1 and R_1 = n.OutputFor each test case print q pairs of numbers L_i \leq l \leq r \leq R_i such that the value f(l, r) is maximum and among such the length r - l + 1 is minimum. If there are several correct answers, print any of them.ExampleInput 61 101 12 25 101 22 23 30 2 41 31 22 34 40 12 8 31 41 32 42 35 521 32 32 32 101 51 41 32 53 57 70 1 0 1 0 1 01 73 62 51 44 72 62 7Output 1 1 1 1 2 2 1 1 1 1 2 2 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 3 4 2 4 4 6 2 4 2 4 4 6 2 4 2 4 NoteIn all test cases, the first query is considered.In the first test case, f(1, 1) = 0 - 0 = 0.In the second test case, f(1, 1) = 5 - 5 = 0, f(2, 2) = 10 - 10 = 0. Note that f(1, 2) = (10 + 5) - (10 \oplus 5) = 0, but we need to find a subsegment with the minimum length among the maximum values of f(l, r). So, only segments [1, 1] and [2, 2] are the correct answers.In the fourth test case, f(2, 3) = (12 + 8) - (12 \oplus 8) = 16. There are two correct answers in the fifth test case, since f(2, 3) = f(3, 4) and their lengths are equal.
61 101 12 25 101 22 23 30 2 41 31 22 34 40 12 8 31 41 32 42 35 521 32 32 32 101 51 41 32 53 57 70 1 0 1 0 1 01 73 62 51 44 72 62 7
1 1 1 1 2 2 1 1 1 1 2 2 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 3 4 2 4 4 6 2 4 2 4 4 6 2 4 2 4
4 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'greedy', 'implementation', 'two pointers', '*2100']
C1. Sheikh (Easy version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version q = 1.You are given an array of integers a_1, a_2, \ldots, a_n.The cost of a subsegment of the array [l, r], 1 \leq l \leq r \leq n, is the value f(l, r) = \operatorname{sum}(l, r) - \operatorname{xor}(l, r), where \operatorname{sum}(l, r) = a_l + a_{l+1} + \ldots + a_r, and \operatorname{xor}(l, r) = a_l \oplus a_{l+1} \oplus \ldots \oplus a_r (\oplus stands for bitwise XOR).You will have q = 1 query. Each query is given by a pair of numbers L_i, R_i, where 1 \leq L_i \leq R_i \leq n. You need to find the subsegment [l, r], L_i \leq l \leq r \leq R_i, with maximum value f(l, r). If there are several answers, then among them you need to find a subsegment with the minimum length, that is, the minimum value of r - l + 1.InputEach test consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and q (1 \leq n \leq 10^5, q = 1) — the length of the array and the number of queries.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \leq a_i \leq 10^9) — array elements.i-th of the next q lines of each test case contains two integers L_i and R_i (1 \leq L_i \leq R_i \leq n) — the boundaries in which we need to find the segment.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.It is guaranteed that L_1 = 1 and R_1 = n.OutputFor each test case print q pairs of numbers L_i \leq l \leq r \leq R_i such that the value f(l, r) is maximum and among such the length r - l + 1 is minimum. If there are several correct answers, print any of them.ExampleInput 61 101 12 15 101 23 10 2 41 34 10 12 8 31 45 121 32 32 32 101 57 10 1 0 1 0 1 01 7Output 1 1 1 1 1 1 2 3 2 3 2 4 NoteIn the first test case, f(1, 1) = 0 - 0 = 0.In the second test case, f(1, 1) = 5 - 5 = 0, f(2, 2) = 10 - 10 = 0. Note that f(1, 2) = (10 + 5) - (10 \oplus 5) = 0, but we need to find a subsegment with the minimum length among the maximum values of f(l, r). So, only segments [1, 1] and [2, 2] are the correct answers.In the fourth test case, f(2, 3) = (12 + 8) - (12 \oplus 8) = 16. There are two correct answers in the fifth test case, since f(2, 3) = f(3, 4) and their lengths are equal.
61 101 12 15 101 23 10 2 41 34 10 12 8 31 45 121 32 32 32 101 57 10 1 0 1 0 1 01 7
1 1 1 1 1 1 2 3 2 3 2 4
4 seconds
256 megabytes
['binary search', 'bitmasks', 'greedy', 'two pointers', '*1800']
B. Ugutime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string consisting only of the characters 0 and 1. You are given a binary string s_1 s_2 \ldots s_n. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following: Select an arbitrary index 1 \leq i \leq n in the string; For all j \geq i, change the value in the j-th position to the opposite, that is, if s_j = 1, then make s_j = 0, and vice versa.What is the minimum number of operations needed to make the string non-decreasing?InputEach test consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases. The description of test cases follows.The first line of each test cases a single integer n (1 \leq n \leq 10^5) — the length of the string.The second line of each test case contains a binary string s of length n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum number of operations that are needed to make the string non-decreasing.ExampleInput 811210310141100511001610001010000011000070101010Output 0 1 2 1 2 3 1 5 NoteIn the first test case, the string is already non-decreasing.In the second test case, you can select i = 1 and then s = \mathtt{01}.In the third test case, you can select i = 1 and get s = \mathtt{010}, and then select i = 2. As a result, we get s = \mathtt{001}, that is, a non-decreasing string.In the sixth test case, you can select i = 5 at the first iteration and get s = \mathtt{100001}. Then choose i = 2, then s = \mathtt{111110}. Then we select i = 1, getting the non-decreasing string s = \mathtt{000001}.
811210310141100511001610001010000011000070101010
0 1 2 1 2 3 1 5
1 second
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', '*900']
A. Bestietime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers a_1, a_2, \ldots, a_n. Friends asked you to make the greatest common divisor (GCD) of all numbers in the array equal to 1. In one operation, you can do the following: Select an arbitrary index in the array 1 \leq i \leq n; Make a_i = \gcd(a_i, i), where \gcd(x, y) denotes the GCD of integers x and y. The cost of such an operation is n - i + 1.You need to find the minimum total cost of operations we need to perform so that the GCD of the all array numbers becomes equal to 1.InputEach test consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 5\,000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 20) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the elements of the array.OutputFor each test case, output a single integer — the minimum total cost of operations that will need to be performed so that the GCD of all numbers in the array becomes equal to 1.We can show that it's always possible to do so.ExampleInput 9111222 433 6 945 10 15 205120 60 80 40 806150 90 180 120 60 3062 4 6 9 12 18630 60 90 120 125 125Output 0 1 2 2 1 3 3 0 1 NoteIn the first test case, the GCD of the entire array is already equal to 1, so there is no need to perform operations.In the second test case, select i = 1. After this operation, a_1 = \gcd(2, 1) = 1. The cost of this operation is 1.In the third test case, you can select i = 1, after that the array a will be equal to [1, 4]. The GCD of this array is 1, and the total cost is 2.In the fourth test case, you can select i = 2, after that the array a will be equal to [3, 2, 9]. The GCD of this array is 1, and the total cost is 2.In the sixth test case, you can select i = 4 and i = 5, after that the array a will be equal to [120, 60, 80, 4, 5]. The GCD of this array is 1, and the total cost is 3.
9111222 433 6 945 10 15 205120 60 80 40 806150 90 180 120 60 3062 4 6 9 12 18630 60 90 120 125 125
0 1 2 2 1 3 3 0 1
1 second
256 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'implementation', 'math', 'number theory', '*1000']
F. Function Sumtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you have an integer array a_1, a_2, \dots, a_n.Let \operatorname{lsl}(i) be the number of indices j (1 \le j < i) such that a_j < a_i.Analogically, let \operatorname{grr}(i) be the number of indices j (i < j \le n) such that a_j > a_i.Let's name position i good in the array a if \operatorname{lsl}(i) < \operatorname{grr}(i).Finally, let's define a function f on array a f(a) as the sum of all a_i such that i is good in a.Given two integers n and k, find the sum of f(a) over all arrays a of size n such that 1 \leq a_i \leq k for all 1 \leq i \leq n modulo 998\,244\,353.InputThe first and only line contains two integers n and k (1 \leq n \leq 50; 2 \leq k < 998\,244\,353).OutputOutput a single integer — the sum of f over all arrays a of size n modulo 998\,244\,353.ExamplesInput 3 3 Output 28 Input 5 6 Output 34475 Input 12 30 Output 920711694 NoteIn the first test case: f([1,1,1]) = 0f([2,2,3]) = 2 + 2 = 4f([1,1,2]) = 1 + 1 = 2f([2,3,1]) = 2f([1,1,3]) = 1 + 1 = 2f([2,3,2]) = 2f([1,2,1]) = 1f([2,3,3]) = 2f([1,2,2]) = 1f([3,1,1]) = 0f([1,2,3]) = 1f([3,1,2]) = 1f([1,3,1]) = 1f([3,1,3]) = 1f([1,3,2]) = 1f([3,2,1]) = 0f([1,3,3]) = 1f([3,2,2]) = 0f([2,1,1]) = 0f([3,2,3]) = 2f([2,1,2]) = 1f([3,3,1]) = 0f([2,1,3]) = 2 + 1 = 3f([3,3,2]) = 0f([2,2,1]) = 0f([3,3,3]) = 0f([2,2,2]) = 0 Adding up all of these values, we get 28 as the answer.
3 3
28
4 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'fft', 'math', '*2500']
E. Graph Costtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an initially empty undirected graph with n nodes, numbered from 1 to n (i. e. n nodes and 0 edges). You want to add m edges to the graph, so the graph won't contain any self-loop or multiple edges.If an edge connecting two nodes u and v is added, its weight must be equal to the greatest common divisor of u and v, i. e. \gcd(u, v).In order to add edges to the graph, you can repeat the following process any number of times (possibly zero): choose an integer k \ge 1; add exactly k edges to the graph, each having a weight equal to k + 1. Adding these k edges costs k + 1 in total. Note that you can't create self-loops or multiple edges. Also, if you can't add k edges of weight k + 1, you can't choose such k.For example, if you can add 5 more edges to the graph of weight 6, you may add them, and it will cost 6 for the whole pack of 5 edges. But if you can only add 4 edges of weight 6 to the graph, you can't perform this operation for k = 5.Given two integers n and m, find the minimum total cost to form a graph of n vertices and exactly m edges using the operation above. If such a graph can't be constructed, output -1.Note that the final graph may consist of several connected components.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains two integers n and m (2 \leq n \leq 10^6; 1 \leq m \leq \frac{n(n-1)}{2}).It is guaranteed that the sum of n over all test cases does not exceed 10^6. OutputFor each test case, print the minimum cost to build the graph, or -1 if you can't build such a graph.ExampleInput 44 16 109 410 11Output 2 -1 7 21 NoteIn the first test case, we can add an edge between the vertices 2 and 4 with \gcd = 2. This is the only possible way to add 1 edge that will cost 2.In the second test case, there is no way to add 10 edges, so the answer is -1.In the third test case, we can add the following edges: k = 1: edge of weight 2 between vertices 2 and 4 (\gcd(2, 4) = 2). Cost: 2; k = 1: edge of weight 2 between vertices 4 and 6 (\gcd(4, 6) = 2). Cost: 2; k = 2: edges of weight 3: (3, 6) and (3, 9) (\gcd(3, 6) = \gcd(3, 9) = 3). Cost: 3. As a result, we added 1 + 1 + 2 = 4 edges with total cost 2 + 2 + 3 = 7, which is the minimal possible cost.
44 16 109 410 11
2 -1 7 21
2 seconds
256 megabytes
['dp', 'greedy', 'math', 'number theory', '*2000']
D. Valiant's New Maptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGame studio "DbZ Games" wants to introduce another map in their popular game "Valiant". This time, the map named "Panvel" will be based on the city of Mumbai.Mumbai can be represented as n \times m cellular grid. Each cell (i, j) (1 \le i \le n; 1 \le j \le m) of the grid is occupied by a cuboid building of height a_{i,j}.This time, DbZ Games want to make a map that has perfect vertical gameplay. That's why they want to choose an l \times l square inside Mumbai, such that each building inside the square has a height of at least l.Can you help DbZ Games find such a square of the maximum possible size l?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 1000). Description of the test cases follows.The first line of each test case contains two positive integers n and m (1 \le n \le m; 1 \leq n \cdot m \leq 10^6).The i-th of next n lines contains m integers a_{i,1}, a_{i,2}, \dots, a_{i,m} (1 \leq a_{i,j} \leq 10^6) — heights of buildings on the i-th row.It's guaranteed that the sum of n \cdot m over all test cases doesn't exceed 10^6.OutputFor each test case, print the maximum side length l of the square DbZ Games can choose.ExampleInput 42 22 34 51 31 2 32 34 4 32 1 45 61 9 4 6 5 810 9 5 8 11 624 42 32 8 11 123 1 9 69 13 313 22 60 12 14 17Output 2 1 1 3 NoteIn the first test case, we can choose the square of side l = 2 (i. e. the whole grid) since the heights of all buildings are greater than or equal to 2.In the second test case, we can only choose the side as 1, so the answer is 1.In the third test case, there are no squares of size 2 that have all buildings of height at least 2, so the answer is 1.
42 22 34 51 31 2 32 34 4 32 1 45 61 9 4 6 5 810 9 5 8 11 624 42 32 8 11 123 1 9 69 13 313 22 60 12 14 17
2 1 1 3
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'dp', 'two pointers', '*1700']
C. Even Subarraystime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \dots, a_n (1 \le a_i \le n).Find the number of subarrays of a whose \operatorname{XOR} has an even number of divisors. In other words, find all pairs of indices (i, j) (i \le j) such that a_i \oplus a_{i + 1} \oplus \dots \oplus a_j has an even number of divisors.For example, numbers 2, 3, 5 or 6 have an even number of divisors, while 1 and 4 — odd. Consider that 0 has an odd number of divisors in this task.Here \operatorname{XOR} (or \oplus) denotes the bitwise XOR operation.Print the number of subarrays but multiplied by 2022... Okay, let's stop. Just print the actual answer.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 2 \cdot 10^5) — the length of the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, print the number of subarrays, whose \operatorname{XOR} has an even number of divisors.ExampleInput 433 1 254 2 1 5 344 4 4 475 7 3 7 1 7 3Output 4 11 0 20 NoteIn the first test case, there are 4 subarrays whose \operatorname{XOR} has an even number of divisors: [3], [3,1], [1,2], [2].In the second test case, there are 11 subarrays whose \operatorname{XOR} has an even number of divisors: [4,2], [4,2,1], [4,2,1,5], [2], [2,1], [2,1,5], [2,1,5,3], [1,5,3], [5], [5,3], [3].In the third test case, there is no subarray whose \operatorname{XOR} has an even number of divisors since \operatorname{XOR} of any subarray is either 4 or 0.
433 1 254 2 1 5 344 4 4 475 7 3 7 1 7 3
4 11 0 20
2.5 seconds
256 megabytes
['bitmasks', 'brute force', 'hashing', 'math', 'number theory', '*1700']
B. Kill Demodogstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDemodogs from the Upside-down have attacked Hawkins again. El wants to reach Mike and also kill as many Demodogs in the way as possible.Hawkins can be represented as an n \times n grid. The number of Demodogs in a cell at the i-th row and the j-th column is i \cdot j. El is at position (1, 1) of the grid, and she has to reach (n, n) where she can find Mike. The only directions she can move are the right (from (i, j) to (i, j + 1)) and the down (from (i, j) to (i + 1, j)). She can't go out of the grid, as there are doors to the Upside-down at the boundaries. Calculate the maximum possible number of Demodogs \mathrm{ans} she can kill on the way, considering that she kills all Demodogs in cells she visits (including starting and finishing cells).Print 2022 \cdot \mathrm{ans} modulo 10^9 + 7. Modulo 10^9 + 7 because the result can be too large and multiplied by 2022 because we are never gonna see it again!(Note, you firstly multiply by 2022 and only after that take the remainder.)InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains one integer n (2 \leq n \leq 10^9) — the size of the grid.OutputFor each test case, print a single integer — the maximum number of Demodogs that can be killed multiplied by 2022, modulo 10^9 + 7.ExampleInput 423501000000000Output 14154 44484 171010650 999589541 NoteIn the first test case, for any path chosen by her the number of Demodogs to be killed would be 7, so the answer would be 2022 \cdot 7 = 14154.
423501000000000
14154 44484 171010650 999589541
1 second
256 megabytes
['greedy', 'math', '*1100']
A. Joey Takes Moneytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJoey is low on money. His friend Chandler wants to lend Joey some money, but can't give him directly, as Joey is too proud of himself to accept it. So, in order to trick him, Chandler asks Joey to play a game.In this game, Chandler gives Joey an array a_1, a_2, \dots, a_n (n \geq 2) of positive integers (a_i \ge 1).Joey can perform the following operation on the array any number of times: Take two indices i and j (1 \le i < j \le n). Choose two integers x and y (x, y \ge 1) such that x \cdot y = a_i \cdot a_j. Replace a_i by x and a_j by y. In the end, Joey will get the money equal to the sum of elements of the final array. Find the maximum amount of money \mathrm{ans} Joey can get but print 2022 \cdot \mathrm{ans}. Why multiplied by 2022? Because we are never gonna see it again!It is guaranteed that the product of all the elements of the array a doesn't exceed 10^{12}. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 4000). Description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 50) — the length of the array a.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^6) — the array itself.It's guaranteed that the product of all a_i doesn't exceed 10^{12} (i. e. a_1 \cdot a_2 \cdot \ldots \cdot a_n \le 10^{12}).OutputFor each test case, print the maximum money Joey can get multiplied by 2022.ExampleInput 332 3 221 331000000 1000000 1Output 28308 8088 2022000000004044 NoteIn the first test case, Joey can do the following: He chooses i = 1 and j = 2 (so he has a[i] \cdot a[j] = 6), chooses x = 6 and y = 1 and makes a[i] = 6 and a[j] = 1. [2, 3, 2] \xrightarrow[x = 6,\; y = 1]{i = 1,\; j = 2} [6, 1, 2] He chooses i = 1 and j = 3 (so he has a[i] \cdot a[j] = 12), chooses x = 12 and y = 1 and makes a[i] = 12 and a[j] = 1. [6, 1, 2] \xrightarrow[x = 12,\; y = 1]{i = 1,\; j = 3} [12, 1, 1] The sum is 14 which is the maximum of all possible sums. The answer is 2022 \cdot 14 = 28308.
332 3 221 331000000 1000000 1
28308 8088 2022000000004044
1 second
256 megabytes
['greedy', 'math', '*800']
F. Almost Sortedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n and a positive integer k. Consider a permutation q of length n such that for any integers i and j, where 1 \le i < j \le n, we have p_{q_i} \le p_{q_j} + k.Find the minimum possible number of inversions in a permutation q.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).An inversion in a permutation a is a pair of indices i and j (1 \le i, j \le n) such that i < j, but a_i > a_j.InputThe first line contains two integers n and k (1 \le n \le 5000, 1 \le k \le 8).The second line contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n).OutputPrint the minimum possible number of inversions in the permutation q.ExamplesInput 1 1 1 Output 0Input 3 1 2 3 1 Output 1Input 5 2 5 4 3 2 1 Output 6Input 10 3 5 8 6 10 2 7 4 1 9 3 Output 18NoteIn the first example, the only permutation is q = [1] (0 inversions). Then p_{q_1} = 1.In the second example, the only permutation with 1 inversion is q = [1, 3, 2]. Then p_{q_1} = 2, p_{q_2} = 1, p_{q_3} = 3. In the third example, one of the possible permutations with 6 inversions is q = [3, 4, 5, 1, 2]. Then p_{q_1} = 3, p_{q_2} = 2, p_{q_3} = 1, p_{q_4} = 5, p_{q_5} = 4.
1 1 1
0
2 seconds
256 megabytes
['bitmasks', 'data structures', 'dp', '*2700']
E. Maximums and Minimumstime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n of positive integers.Find the number of pairs of indices (l, r), where 1 \le l \le r \le n, that pass the check. The check is performed in the following manner: The minimum and maximum numbers are found among a_l, a_{l+1}, \ldots, a_r. The check is passed if the maximum number is divisible by the minimum number. InputThe first line contains a single integer t (1 \le t \le 10) — the number of test cases. Then the test cases follow.Each test case consists of two lines.The first line contains a single integer n (1 \le n \le 5 \cdot 10^5) — the size of the array.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print a single integer — the number of pairs of indices that pass the check.ExampleInput 61122 422 342 4 7 14716 5 18 7 7 12 14616 14 2 6 16 2Output 1 3 2 7 10 19 NoteBelow x \mid y denotes that y is divisible by x.In the first test case, there is one pair (1, 1), the maximum for this pair is 1, the minimum is also 1, 1 \mid 1, so the check is passed, and the answer is 1.In the second test case, there are 3 segments: (1, 1): the maximum is 2, the minimum is 2, 2 \mid 2, so the check is passed. (1, 2): the maximum is 4, the minimum is 2, 2 \mid 4, so the check is passed. (2, 2): the maximum is 4, the minimum is 4, 4 \mid 4, so the check is passed. In the third test case, there are 3 segments: (1, 1): the maximum is 2, the minimum is 2, 2 \mid 2, so the check is passed. (1, 2): the maximum is 3, the minimum is 2, 3 isn't divisible by 2, so the check is failed. (2, 2): the maximum is 3, the minimum is 3, 3 \mid 3, so the check is passed.
61122 422 342 4 7 14716 5 18 7 7 12 14616 14 2 6 16 2
1 3 2 7 10 19
5 seconds
512 megabytes
['combinatorics', 'data structures', 'divide and conquer', 'number theory', '*2700']
D. Prefixes and Suffixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have two strings s_1 and s_2 of length n, consisting of lowercase English letters. You can perform the following operation any (possibly zero) number of times: Choose a positive integer 1 \leq k \leq n. Swap the prefix of the string s_1 and the suffix of the string s_2 of length k. Is it possible to make these two strings equal by doing described operations?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then the test cases follow.Each test case consists of three lines.The first line contains a single integer n (1 \le n \le 10^5) — the length of the strings s_1 and s_2. The second line contains the string s_1 of length n, consisting of lowercase English letters.The third line contains the string s_2 of length n, consisting of lowercase English letters.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print "YES" if it is possible to make the strings equal, and "NO" otherwise.ExampleInput 73cbcaba5abcaacbabb5abcaacbabz1aa1ab6abadaaadaaba8abcabdaaadabcabaOutput YES YES NO YES NO NO YES NoteIn the first test case: Initially s_1 = \mathtt{cbc}, s_2 = \mathtt{aba}. Operation with k = 1, after the operation s_1 = \mathtt{abc}, s_2 = \mathtt{abc}. In the second test case: Initially s_1 = \mathtt{abcaa}, s_2 = \mathtt{cbabb}. Operation with k = 2, after the operation s_1 = \mathtt{bbcaa}, s_2 = \mathtt{cbaab}. Operation with k = 3, after the operation s_1 = \mathtt{aabaa}, s_2 = \mathtt{cbbbc}. Operation with k = 1, after the operation s_1 = \mathtt{cabaa}, s_2 = \mathtt{cbbba}. Operation with k = 2, after the operation s_1 = \mathtt{babaa}, s_2 = \mathtt{cbbca}. Operation with k = 1, after the operation s_1 = \mathtt{aabaa}, s_2 = \mathtt{cbbcb}. Operation with k = 2, after the operation s_1 = \mathtt{cbbaa}, s_2 = \mathtt{cbbaa}. In the third test case, it's impossible to make strings equal.
73cbcaba5abcaacbabb5abcaacbabz1aa1ab6abadaaadaaba8abcabdaaadabcaba
YES YES NO YES NO NO YES
1 second
256 megabytes
['constructive algorithms', 'strings', 'two pointers', '*2200']
C. Minimum Notationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a string s consisting of digits from 0 to 9 inclusive. You can perform the following operation any (possibly zero) number of times: You can choose a position i and delete a digit d on the i-th position. Then insert the digit \min{(d + 1, 9)} on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string a is lexicographically smaller than a string b of the same length if and only if the following holds: in the first position where a and b differ, the string a has a smaller digit than the corresponding digit in b. InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then the test cases follow.Each test case consists of a single line that contains one string s (1 \le |s| \le 2 \cdot 10^5) — the string consisting of digits. Please note that s is just a string consisting of digits, so leading zeros are allowed.It is guaranteed that the sum of lengths of s over all test cases does not exceed 2 \cdot 10^5.OutputPrint a single string — the minimum string that is possible to obtain.ExampleInput 404829901314752277691991Output 02599 9 01 111334567888999 NoteIn the first test case: Delete 8 and insert 9 at the end of the notation. The resulting notation is 04299. Delete 4 and insert 5 in the 3-rd position of the notation. The resulting notation is 02599. Nothing needs to be done in the second and third test cases.
404829901314752277691991
02599 9 01 111334567888999
1 second
256 megabytes
['data structures', 'greedy', 'math', 'sortings', '*1200']
B. Meeting on the Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people live on the coordinate line, the i-th one lives at the point x_i (1 \le i \le n). They want to choose a position x_0 to meet. The i-th person will spend |x_i - x_0| minutes to get to the meeting place. Also, the i-th person needs t_i minutes to get dressed, so in total he or she needs t_i + |x_i - x_0| minutes. Here |y| denotes the absolute value of y.These people ask you to find a position x_0 that minimizes the time in which all n people can gather at the meeting place. InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases. Then the test cases follow.Each test case consists of three lines.The first line contains a single integer n (1 \le n \le 10^5) — the number of people. The second line contains n integers x_1, x_2, \dots, x_n (0 \le x_i \le 10^{8}) — the positions of the people.The third line contains n integers t_1, t_2, \dots, t_n (0 \le t_i \le 10^{8}), where t_i is the time i-th person needs to get dressed.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single real number — the optimum position x_0. It can be shown that the optimal position x_0 is unique.Your answer will be considered correct if its absolute or relative error does not exceed 10^{−6}. Formally, let your answer be a, the jury's answer be b. Your answer will be considered correct if \frac{|a−b|}{max(1,|b|)} \le 10^{−6}.ExampleInput 710323 10 021 40 031 2 30 0 031 2 34 1 233 3 35 3 365 4 7 2 10 43 2 5 1 4 6Output 0 2 2.5 2 1 3 6 Note In the 1-st test case there is one person, so it is efficient to choose his or her position for the meeting place. Then he or she will get to it in 3 minutes, that he or she need to get dressed. In the 2-nd test case there are 2 people who don't need time to get dressed. Each of them needs one minute to get to position 2. In the 5-th test case the 1-st person needs 4 minutes to get to position 1 (4 minutes to get dressed and 0 minutes on the way); the 2-nd person needs 2 minutes to get to position 1 (1 minute to get dressed and 1 minute on the way); the 3-rd person needs 4 minutes to get to position 1 (2 minutes to get dressed and 2 minutes on the way).
710323 10 021 40 031 2 30 0 031 2 34 1 233 3 35 3 365 4 7 2 10 43 2 5 1 4 6
0 2 2.5 2 1 3 6
2 seconds
256 megabytes
['binary search', 'geometry', 'greedy', 'implementation', 'math', 'ternary search', '*1600']
A. Planetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Vogons wanted to build a new hyperspace highway through a distant system with n planets. The i-th planet is on the orbit a_i, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that. The first machine in one operation can destroy any planet at cost of 1 Triganic Pu. The second machine in one operation can destroy all planets on a single orbit in this system at the cost of c Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases. Then the test cases follow.Each test case consists of two lines.The first line contains two integers n and c (1 \le n, c \le 100) — the number of planets and the cost of the second machine usage.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 100), where a_i is the orbit of the i-th planet.OutputFor each test case print a single integer — the minimum cost of destroying all planets.ExamplesInput 410 12 1 4 5 2 4 5 5 1 25 23 2 1 2 22 21 12 21 2Output 4 4 2 2 Input 11 1001Output 1 NoteIn the first test case, the cost of using both machines is the same, so you can always use the second one and destroy all planets in orbit 1, all planets in orbit 2, all planets in orbit 4, all planets in orbit 5.In the second test case, it is advantageous to use the second machine for 2 Triganic Pus to destroy all the planets in orbit 2, then destroy the remaining two planets using the first machine.In the third test case, you can use the first machine twice or the second machine once.In the fourth test case, it is advantageous to use the first machine twice.
410 12 1 4 5 2 4 5 5 1 25 23 2 1 2 22 21 12 21 2
4 4 2 2
1 second
256 megabytes
['data structures', 'greedy', 'sortings', '*800']
G. Cut Substringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two non-empty strings s and t, consisting of Latin letters.In one move, you can choose an occurrence of the string t in the string s and replace it with dots.Your task is to remove all occurrences of the string t in the string s in the minimum number of moves, and also calculate how many different sequences of moves of the minimum length exist.Two sequences of moves are considered different if the sets of indices at which the removed occurrences of the string t in s begin differ. For example, the sets \{1, 2, 3\} and \{1, 2, 4\} are considered different, the sets \{2, 4, 6\} and \{2, 6\} — too, but sets \{3, 5\} and \{5, 3\} — not.For example, let the string s = "abababacababa" and the string t = "aba". We can remove all occurrences of the string t in 2 moves by cutting out the occurrences of the string t at the 3th and 9th positions. In this case, the string s is an example of the form "ab...bac...ba". It is also possible to cut occurrences of the string t at the 3th and 11th positions. There are two different sequences of minimum length moves.Since the answer can be large, output it modulo 10^9 + 7.InputThe first line of the input contains a single integer q (1 \le q \le 50) — the number of test cases. The descriptions of the sets follow.The first line of each set contains a non-empty string s (1 \le |s| \le 500) consisting of lowercase Latin letters.The second line of each set contains a non-empty string t (1 \le |t| \le 500) consisting of lowercase Latin letters.It is guaranteed that the sum of string lengths s over all test cases does not exceed 500. Similarly, it is guaranteed that the sum of string lengths t over all test cases does not exceed 500.OutputFor each test case print two integers — the minimum number of moves and the number of different optimal sequences, modulo 10^9 + 7.ExampleInput 8abababacababaabadddddddddddxyzxyzxyzabcabcdabacabaabacaabcdefaaaaaaaaaaaaaaaaaaaOutput 2 2 1 4 2 1 0 1 1 1 0 1 8 1 3 6 NoteThe first test case is explained in the statement.In the second case, it is enough to cut any of the four occurrences.In the third case, string s is the concatenation of two strings t = "xyz", so there is a unique optimal sequence of 2 moves.In the fourth and sixth cases, the string s initially contains no occurrences of the string t.In the fifth case, the string s contains exactly one occurrence of the string t.
8abababacababaabadddddddddddxyzxyzxyzabcabcdabacabaabacaabcdefaaaaaaaaaaaaaaaaaaa
2 2 1 4 2 1 0 1 1 1 0 1 8 1 3 6
2 seconds
256 megabytes
['combinatorics', 'dp', 'hashing', 'strings', 'two pointers', '*2100']
F. Kirei and the Linear Functiontime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven the string s of decimal digits (0-9) of length n.A substring is a sequence of consecutive characters of a string. The substring of this string is defined by a pair of indexes — with its left and right ends. So, each pair of indexes (l, r), where 1 \le l \le r \le n, corresponds to a substring of the string s. We will define as v(l,r) the numeric value of the corresponding substring (leading zeros are allowed in it).For example, if n=7, s="1003004", then v(1,3)=100, v(2,3)=0 and v(2,7)=3004.You are given n, s and an integer w (1 \le w < n).You need to process m queries, each of which is characterized by 3 numbers l_i, r_i, k_i (1 \le l_i \le r_i \le n; 0 \le k_i \le 8).The answer to the ith query is such a pair of substrings of length w that if we denote them as (L_1, L_1+w-1) and (L_2, L_2+w-1), then: L_1 \ne L_2, that is, the substrings are different; the remainder of dividing a number v(L_1, L_1+w-1) \cdot v(l_i, r_i) + v(L_2, L_2 + w - 1) by 9 is equal to k_i. If there are many matching substring pairs, then find a pair where L_1 is as small as possible. If there are many matching pairs in this case, then minimize L_2.Note that the answer may not exist.InputThe first line contains a single integer t (1 \le t \le 10^4) — number of input test cases.The first line of each test case contains a string s, which contains only the characters 0-9 and has a length n (2 \le n \le 2 \cdot 10^5).The second line contains two integers w, m (1 \le w < n, 1 \le m \le 2 \cdot 10^5), where n — is the length of the given string s. The number w denotes the lengths of the substrings being searched for, and m is the number of queries to be processed.The following m lines contain integers l_i, r_i, k_i (1 \le l_i \le r_i \le n, 0 \le k_i \le 8) — ith query parameters.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. It is also guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each request, print in a separate line: left borders of the required substrings: L_1 and L_2; -1 -1 otherwise, if there is no solution. If there are several solutions, minimize L_1 first, and minimize L_2 second.ExampleInput 510030044 11 2 11795720074 22 7 32 7 41112 12 2 600001 21 4 01 4 14841 52 2 02 3 71 2 53 3 82 2 6Output 2 4 1 5 1 2 -1 -1 1 2 -1 -1 1 3 1 3 -1 -1 -1 -1 -1 -1 NoteConsider the first test case of example inputs. In this test case n=7, s="1003004", w=4 and one query l_1=1, r_1=2, k_1=1. Note that v(1,2)=10. We need to find a pair of substrings of length 4 such that v(L_1, L_1+3)\cdot10+v(L_2,L_2+3) has a remainder of k_1=1 when divided by 9. The values L_1=2, L_2=4 actually satisfy all the requirements: v(L_1, L_1+w-1)=v(2,5)=30, v(L_2, L_2+w-1)=v(4,7)=3004. Indeed, 30\cdot10+3004=3304, which has a remainder of 1 when divided by 9. It can be shown that L_1=2 is the minimum possible value, and L_2=4 is the minimum possible with L_1=2.
510030044 11 2 11795720074 22 7 32 7 41112 12 2 600001 21 4 01 4 14841 52 2 02 3 71 2 53 3 82 2 6
2 4 1 5 1 2 -1 -1 1 2 -1 -1 1 3 1 3 -1 -1 -1 -1 -1 -1
3 seconds
256 megabytes
['hashing', 'math', '*1900']
E. Guess the Cycle Sizetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of n vertices (3 \le n \le 10^{18}). A cyclic graph is an undirected graph of n vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly n. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where 1 \le a, b \le 10^{18} and a \neq b. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex a to vertex b, or -1 if \max(a, b) > n. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number n) by making no more than 50 queries.Note that the interactor is implemented in such a way that for any ordered pair (a, b), it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is 50.InteractionYou can make no more than 50 of queries. To make a query, output on a separate line: "? a b", where 1 \le a, b \le 10^{18} and a \neq b. In response to the query, the interactor will output on a separate line the length of a random simple path from vertex a to vertex b (not to be confused with the path from b to a), or -1 if \max(a, b) > n. The interactor chooses one of the two paths with equal probability. If your program gets a number 0 as a result of a query, it means that the verdict for your solution is already defined as "wrong answer" (for example, you made more than 50 queries or made an invalid query). In this case, your program should terminate immediately. Otherwise, in this scenario you may get a random verdict "Execution error", "Exceeded time limit" or some other verdict instead of "Wrong answer".The answer, like queries, print on a separate line. The output of the answer is not counted as a query when counting them. To print it, use the following format: "! n": the expected size of the hidden graph (3 \le n \le 10^{18}). After that, your program should terminate.After the output of the next query, be sure to use stream cleaning functions so that some of your output is not left in some buffer. For example, in C++ you should use function flush(stdout), in Java call System.out.flush(), in Pascal flush(output) and stdout.flush() for Python.Note that the interactor is implemented in such a way that for any ordered pair (a, b), it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is 50.ExampleInput 1 2 -1Output ? 1 2 ? 1 3 ? 1 4 ! 3NoteIn the first example, the graph could look like this The lengths of the simple paths between all pairs of vertices in this case are 1 or 2. The first query finds out that one of the simple paths from vertex 1 to vertex 2 has a length of 1. With the second query, we find out that one of the simple paths from vertex 1 to vertex 3 has length 2. In the third query, we find out that vertex 4 is not in the graph. Consequently, the size of the graph is 3.
1 2 -1
? 1 2 ? 1 3 ? 1 4 ! 3
1 second
256 megabytes
['interactive', 'probabilities', '*1800']
D. Friends and the Restauranttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA group of n friends decide to go to a restaurant. Each of the friends plans to order meals for x_i burles and has a total of y_i burles (1 \le i \le n). The friends decide to split their visit to the restaurant into several days. Each day, some group of at least two friends goes to the restaurant. Each of the friends visits the restaurant no more than once (that is, these groups do not intersect). These groups must satisfy the condition that the total budget of each group must be not less than the amount of burles that the friends in the group are going to spend at the restaurant. In other words, the sum of all x_i values in the group must not exceed the sum of y_i values in the group.What is the maximum number of days friends can visit the restaurant?For example, let there be n = 6 friends for whom x = [8, 3, 9, 2, 4, 5] and y = [5, 3, 1, 4, 5, 10]. Then: first and sixth friends can go to the restaurant on the first day. They will spend 8+5=13 burles at the restaurant, and their total budget is 5+10=15 burles. Since 15 \ge 13, they can actually form a group. friends with indices 2, 4, 5 can form a second group. They will spend 3+2+4=9 burles at the restaurant, and their total budget will be 3+4+5=12 burles (12 \ge 9). It can be shown that they will not be able to form more groups so that each group has at least two friends and each group can pay the bill.So, the maximum number of groups the friends can split into is 2. Friends will visit the restaurant for a maximum of two days. Note that the 3-rd friend will not visit the restaurant at all.Output the maximum number of days the friends can visit the restaurant for given n, x and y.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case contains a single integer n (2 \le n \le 10^5) — the number of friends.The second line of each test case contains exactly n integers x_1, x_2, \dots, x_n (1 \le x_i \le 10^9). The value of x_i corresponds to the number of burles that the friend numbered i plans to spend at the restaurant.The third line of each test case contains exactly n integers y_1, y_2, \dots, y_n (1 \le y_i \le 10^9). The value y_i corresponds to the number of burles that the friend numbered i has.It is guaranteed that the sum of n values over all test cases does not exceed 10^5.OutputFor each test case, print the maximum number of days to visit the restaurant. If friends cannot form even one group to visit the restaurant, print 0.ExampleInput 668 3 9 2 4 55 3 1 4 5 1041 2 3 41 1 2 232 3 71 3 1062 3 6 9 5 73 2 7 10 6 1065 4 2 1 8 1001 1 1 1 1 20061 4 1 2 4 21 3 3 2 3 4Output 2 0 1 3 1 3 NoteThe first test case in explained in the problem statement.In the second test case, friends cannot form at least one group of two or more people.In the third test case, one way to visit the restaurant in one day is to go in a group of all three friends (1+3+10 \ge 2+3+7). Note that they do not have the option of splitting into two groups.
668 3 9 2 4 55 3 1 4 5 1041 2 3 41 1 2 232 3 71 3 1062 3 6 9 5 73 2 7 10 6 1065 4 2 1 8 1001 1 1 1 1 20061 4 1 2 4 21 3 3 2 3 4
2 0 1 3 1 3
2 seconds
256 megabytes
['greedy', 'sortings', 'two pointers', '*1200']
C. Jumping on Tilestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string s.In other words, you are given a string s consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from i-th tile to j-th tile has a cost equal to |index(s_i) - index(s_j)|, where index(c) is the index of the letter c in the alphabet (for example, index('a')=1, index('b')=2, ..., index('z')=26) .Polycarp wants to get to the n-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string s on which he should jump.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test.Each test case is given by the string s (2 \le |s| \le 2 \cdot 10^5), where |s| — is the length of string s. The string s consists of lowercase Latin letters.It is guaranteed that the sum of string lengths s over all test cases does not exceed 2 \cdot 10^5.OutputThe answer to each test case consists of two lines.In the first line print two integers cost, m, where cost is the minimum total cost of the path, and m is the maximum number of visited tiles Polycarp can make to get to n-th tiles for the minimum total cost cost (i.e. the number of jumps is m-1).In the next line print m different numbers j_1, j_2, \dots, j_m (1 \le j_i \le |s|) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be 1 (that is, j_1=1) and the last number must be the value of |s| (that is, j_m=|s|).If there are multiple answers, print any of them.ExampleInput 6logiccodeforcesbcaaaaaaaaaaaaadbaadabadtoOutput 9 4 1 4 3 5 16 10 1 8 3 4 9 5 2 6 7 10 1 2 1 3 0 11 1 8 10 4 3 5 7 2 9 6 11 3 10 1 9 5 4 7 3 8 6 2 10 5 2 1 2 NoteIn the first test case, the required path corresponds to the picture: In this case, the minimum possible total cost of the path is achieved. Since index('l')=12, index('o')=15, index('g')=7, index('i')=9, index('c')=3, then the total cost of the path is |12-9|+|9-7|+|7-3|=3+2+4=9.
6logiccodeforcesbcaaaaaaaaaaaaadbaadabadto
9 4 1 4 3 5 16 10 1 8 3 4 9 5 2 6 7 10 1 2 1 3 0 11 1 8 10 4 3 5 7 2 9 6 11 3 10 1 9 5 4 7 3 8 6 2 10 5 2 1 2
1 second
256 megabytes
['constructive algorithms', 'strings', '*1100']
B. Decode Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a string s consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string s from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than 10), then just writes it out; if the letter number is a two-digit number (greater than or equal to 10), then it writes it out and adds the number 0 after. For example, if the string s is code, then Polycarp will encode this string as follows: 'c' — is the 3-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o' — is the 15-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd' — is the 4-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e' — is the 5-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string t resulting from encoding the string s. Your task is to decode it (get the original string s by t).InputThe first line of the input contains an integer q (1 \le q \le 10^4) — the number of test cases in the input.The descriptions of the test cases follow.The first line of description of each test case contains one integer n (1 \le n \le 50) — the length of the given code.The second line of the description of each test case contains a string t of length n — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string t is obtained.OutputFor each test case output the required string s — the string that gives string t as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.ExampleInput 963150454110071213121612012018315045615018035190711111107111110051111142606Output code aj abacaba ll codeforces aaaak aaaaj aaaaa zf NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to 1, so 1 will be appended to the code. The number of the letter j is 10, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than 10 and are encoded as one digit. The original string is abacaba.In the fourth test case, the string s is equal to ll. The letter l has the number 12 and is encoded as 120. So ll is indeed 120120.
963150454110071213121612012018315045615018035190711111107111110051111142606
code aj abacaba ll codeforces aaaak aaaaj aaaaa zf
1 second
256 megabytes
['greedy', 'strings', '*800']
A. Two Elevatorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad went into his appartment house entrance, now he is on the 1-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that: the first elevator is currently on the floor a (it is currently motionless), the second elevator is located on floor b and goes to floor c (b \ne c). Please note, if b=1, then the elevator is already leaving the floor 1 and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor 1. If you call the second one, then first it will reach the floor c and only then it will go to the floor 1. It takes |x - y| seconds for each elevator to move from floor x to floor y.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.InputThe first line of the input contains the only t (1 \le t \le 10^4) — the number of test cases.This is followed by t lines, three integers each a, b and c (1 \le a, b, c \le 10^8, b \ne c) — floor numbers described in the statement.OutputOutput t numbers, each of which is the answer to the corresponding test case. As an answer, output: 1, if it is better to call the first elevator; 2, if it is better to call the second one; 3, if it doesn't matter which elevator to call (both elevators will arrive in the same time). ExampleInput 31 2 33 1 23 2 1Output 1 3 2 NoteIn the first test case of the example, the first elevator is already on the floor of 1.In the second test case of the example, when called, the elevators would move as follows: At the time of the call, the first elevator is on the floor of 3, and the second one is on the floor of 1, but is already going to another floor; in 1 second after the call, the first elevator would be on the floor 2, the second one would also reach the floor 2 and now can go to the floor 1; in 2 seconds, any elevator would reach the floor 1. In the third test case of the example, the first elevator will arrive in 2 seconds, and the second in 1.
31 2 33 1 23 2 1
1 3 2
1 second
256 megabytes
['math', '*800']
G. Illuminationtime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputConsider a segment [0, d] of the coordinate line. There are n lanterns and m points of interest in this segment.For each lantern, you can choose its power — an integer between 0 and d (inclusive). A lantern with coordinate x illuminates the point of interest with coordinate y if |x - y| is less than or equal to the power of the lantern.A way to choose the power values for all lanterns is considered valid if every point of interest is illuminated by at least one lantern.You have to process q queries. Each query is represented by one integer f_i. To answer the i-th query, you have to: add a lantern on coordinate f_i; calculate the number of valid ways to assign power values to all lanterns, and print it modulo 998244353; remove the lantern you just added. InputThe first line contains three integers d, n and m (4 \le d \le 3 \cdot 10^5; 1 \le n \le 2 \cdot 10^5; 1 \le m \le 16) — the size of the segment, the number of lanterns and the number of points of interest, respectively.The second line contains n integers l_1, l_2, \dots, l_n (1 \le l_i \le d - 1), where l_i is the coordinate of the i-th lantern.The third line contains m integers p_1, p_2, \dots, p_m (1 \le p_i \le d - 1), where p_i is the coordinate of the i-th point of interest.The fourth line contains one integer q (1 \le q \le 5 \cdot 10^5) — the number of queries.The fifth line contains q integers f_1, f_2, \dots, f_q (1 \le f_i \le d - 1), where f_i is the integer representing the i-th query.Additional constraint on the input: during the processing of each query, no coordinate contains more than one object (i. e. there cannot be two or more lanterns with the same coordinate, two or more points of interest with the same coordinate, or a lantern and a point of interest with the same coordinate).OutputFor each query, print one integer — the answer to it, taken modulo 998244353.ExamplesInput 6 1 1 4 3 3 2 1 5 Output 48 47 47 Input 6 1 2 4 2 5 2 1 3 Output 44 46 Input 20 1 2 11 15 7 1 8 Output 413 Input 20 3 5 5 7 18 1 6 3 10 19 5 4 17 15 8 9 Output 190431 187503 188085 189903 189708
6 1 1 4 3 3 2 1 5
48 47 47
8 seconds
512 megabytes
['binary search', 'bitmasks', 'brute force', 'combinatorics', 'dp', 'math', 'two pointers', '*2700']
F. Fishermentime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n fishermen who have just returned from a fishing trip. The i-th fisherman has caught a fish of size a_i.The fishermen will choose some order in which they are going to tell the size of the fish they caught (the order is just a permutation of size n). However, they are not entirely honest, and they may "increase" the size of the fish they have caught.Formally, suppose the chosen order of the fishermen is [p_1, p_2, p_3, \dots, p_n]. Let b_i be the value which the i-th fisherman in the order will tell to the other fishermen. The values b_i are chosen as follows: the first fisherman in the order just honestly tells the actual size of the fish he has caught, so b_1 = a_{p_1}; every other fisherman wants to tell a value that is strictly greater than the value told by the previous fisherman, and is divisible by the size of the fish that the fisherman has caught. So, for i > 1, b_i is the smallest integer that is both strictly greater than b_{i-1} and divisible by a_{p_i}. For example, let n = 7, a = [1, 8, 2, 3, 2, 2, 3]. If the chosen order is p = [1, 6, 7, 5, 3, 2, 4], then: b_1 = a_{p_1} = 1; b_2 is the smallest integer divisible by 2 and greater than 1, which is 2; b_3 is the smallest integer divisible by 3 and greater than 2, which is 3; b_4 is the smallest integer divisible by 2 and greater than 3, which is 4; b_5 is the smallest integer divisible by 2 and greater than 4, which is 6; b_6 is the smallest integer divisible by 8 and greater than 6, which is 8; b_7 is the smallest integer divisible by 3 and greater than 8, which is 9. You have to choose the order of fishermen in a way that yields the minimum possible \sum\limits_{i=1}^{n} b_i.InputThe first line contains one integer n (1 \le n \le 1000) — the number of fishermen.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6).OutputPrint one integer — the minimum possible value of \sum\limits_{i=1}^{n} b_i you can obtain by choosing the order of fishermen optimally.ExamplesInput 7 1 8 2 3 2 2 3 Output 33 Input 10 5 6 5 6 5 6 5 6 5 6 Output 165
7 1 8 2 3 2 2 3
33
6 seconds
512 megabytes
['flows', 'graph matchings', 'greedy', '*3100']
E. Red-Black Peppertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is going to host a party for his friends. He prepared n dishes and is about to serve them. First, he has to add some powdered pepper to each of them — otherwise, the dishes will be pretty tasteless.The i-th dish has two values a_i and b_i — its tastiness with red pepper added or black pepper added, respectively. Monocarp won't add both peppers to any dish, won't add any pepper multiple times, and won't leave any dish without the pepper added.Before adding the pepper, Monocarp should first purchase the said pepper in some shop. There are m shops in his local area. The j-th of them has packages of red pepper sufficient for x_j servings and packages of black pepper sufficient for y_j servings.Monocarp goes to exactly one shop, purchases multiple (possibly, zero) packages of each pepper in such a way that each dish will get the pepper added once, and no pepper is left. More formally, if he purchases x red pepper packages and y black pepper packages, then x and y should be non-negative and x \cdot x_j + y \cdot y_j should be equal to n.For each shop, determine the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages in the said way, print -1.InputThe first line contains a single integer n (1 \le n \le 3 \cdot 10^5) — the number of dishes.The i-th of the next n lines contains two integers a_i and b_i (1 \le a_i, b_i \le 10^9) — the tastiness of the i-th dish with red pepper added or black pepper added, respectively.The next line contains a single integer m (1 \le m \le 3 \cdot 10^5) — the number of shops.The j-th of the next m lines contains two integers x_j and y_j (1 \le x_j, y_j \le n) — the number of servings the red and the black pepper packages are sufficient for in the j-th shop, respectively.OutputPrint m integers. For each shop, print the maximum total tastiness of the dishes after Monocarp buys pepper packages only in this shop and adds the pepper to the dishes. If it's impossible to purchase the packages so that each dish will get the pepper added once and no pepper is left, print -1.ExamplesInput 3 5 10 100 50 2 2 4 2 3 1 1 3 2 2 2 Output 62 112 107 -1 Input 10 3 1 2 3 1 1 2 1 6 3 1 4 4 3 1 3 5 3 5 4 10 8 10 9 3 1 4 2 5 8 3 3 5 1 6 7 2 6 7 3 1 Output 26 -1 36 30 -1 26 34 26 -1 36 NoteConsider the first example.In the first shop, Monocarp can only buy 0 red pepper packages and 1 black pepper package. Black pepper added to all dishes will sum up to 10 + 50 + 2 = 62.In the second shop, Monocarp can buy any number of red and black pepper packages: 0 and 3, 1 and 2, 2 and 1 or 3 and 0. The optimal choice turns out to be either 1 and 2 or 2 and 1. Monocarp can add black pepper to the first dish, red pepper to the second dish and any pepper to the third dish, the total is 10 + 100 + 2 = 112.In the third shop, Monocarp can only buy 1 red pepper package and 0 black pepper packages. Red pepper added to all dishes will sum up to 5 + 100 + 2 = 107.In the fourth shop, Monocarp can only buy an even total number of packages. Since n is odd, it's impossible to get exactly n packages. Thus, the answer is -1.
3 5 10 100 50 2 2 4 2 3 1 1 3 2 2 2
62 112 107 -1
2 seconds
256 megabytes
['brute force', 'data structures', 'greedy', 'math', 'number theory', '*2300']
D. Letter Pickingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. Initially, they are given a non-empty string s, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty.Alice starts, then they alternate moves. In one move, a player takes either the first or the last letter of the string s, removes it from s and prepends (adds to the beginning) it to their own string.The game ends when the string s becomes empty. The winner is the player with a lexicographically smaller string. If the players' strings are equal, then it's a draw.A string a is lexicographically smaller than a string b if there exists such position i that a_j = b_j for all j < i and a_i < b_i.What is the result of the game if both players play optimally (e. g. both players try to win; if they can't, then try to draw)?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Each testcase consists of a single line — a non-empty string s, consisting of lowercase Latin letters. The length of the string s is even.The total length of the strings over all testcases doesn't exceed 2000.OutputFor each testcase, print the result of the game if both players play optimally. If Alice wins, print "Alice". If Bob wins, print "Bob". If it's a draw, print "Draw".ExampleInput 2forcesabbaOutput Alice Draw NoteOne of the possible games Alice and Bob can play in the first testcase: Alice picks the first letter in s: s="orces", a="f", b=""; Bob picks the last letter in s: s="orce", a="f", b="s"; Alice picks the last letter in s: s="orc", a="ef", b="s"; Bob picks the first letter in s: s="rc", a="ef", b="os"; Alice picks the last letter in s: s="r", a="cef", b="os"; Bob picks the remaining letter in s: s="", a="cef", b="ros". Alice wins because "cef" < "ros". Neither of the players follows any strategy in this particular example game, so it doesn't show that Alice wins if both play optimally.
2forcesabba
Alice Draw
2 seconds
512 megabytes
['constructive algorithms', 'dp', 'games', 'two pointers', '*1800']
C. Digital Logarithmtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define f(x) for a positive integer x as the length of the base-10 representation of x without leading zeros. I like to call it a digital logarithm. Similar to a digital root, if you are familiar with that.You are given two arrays a and b, each containing n positive integers. In one operation, you do the following: pick some integer i from 1 to n; assign either f(a_i) to a_i or f(b_i) to b_i. Two arrays are considered similar to each other if you can rearrange the elements in both of them, so that they are equal (e. g. a_i = b_i for all i from 1 to n).What's the smallest number of operations required to make a and b similar to each other?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of the testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in each of the arrays.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i < 10^9).The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_j < 10^9).The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print the smallest number of operations required to make a and b similar to each other.ExampleInput 411100041 2 3 43 1 4 232 9 31 100 91075019 709259 5 611271314 9024533 81871864 9 3 6 48659503 2 371245467 6 7 37376159 8 364036498 52295554 169Output 2 0 2 18 NoteIn the first testcase, you can apply the digital logarithm to b_1 twice.In the second testcase, the arrays are already similar to each other.In the third testcase, you can first apply the digital logarithm to a_1, then to b_2.
411100041 2 3 43 1 4 232 9 31 100 91075019 709259 5 611271314 9024533 81871864 9 3 6 48659503 2 371245467 6 7 37376159 8 364036498 52295554 169
2 0 2 18
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*1400']
B. Best Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define the value of the permutation p of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once) as follows: initially, an integer variable x is equal to 0; if x < p_1, then add p_1 to x (set x = x + p_1), otherwise assign 0 to x; if x < p_2, then add p_2 to x (set x = x + p_2), otherwise assign 0 to x; ... if x < p_n, then add p_n to x (set x = x + p_n), otherwise assign 0 to x; the value of the permutation is x at the end of this process. For example, for p = [4, 5, 1, 2, 3, 6], the value of x changes as follows: 0, 4, 9, 0, 2, 5, 11, so the value of the permutation is 11.You are given an integer n. Find a permutation p of size n with the maximum possible value among all permutations of size n. If there are several such permutations, you can print any of them.InputThe first line contains one integer t (1 \le t \le 97) — the number of test cases.The only line of each test case contains one integer n (4 \le n \le 100).OutputFor each test case, print n integers — the permutation p of size n with the maximum possible value among all permutations of size n.ExampleInput 3456Output 2 1 3 4 1 2 3 4 5 4 5 1 2 3 6
3456
2 1 3 4 1 2 3 4 5 4 5 1 2 3 6
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*800']
A. Colored Balls: Revisitedtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe title is a reference to the very first Educational Round from our writers team, Educational Round 18.There is a bag, containing colored balls. There are n different colors of balls, numbered from 1 to n. There are \mathit{cnt}_i balls of color i in the bag. The total amount of balls in the bag is odd (e. g. \mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n is odd).In one move, you can choose two balls with different colors and take them out of the bag.At some point, all the remaining balls in the bag will have the same color. That's when you can't make moves anymore.Find any possible color of the remaining balls.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 20) — the number of colors.The second line contains n integers \mathit{cnt}_1, \mathit{cnt}_2, \dots, \mathit{cnt}_n (1 \le \mathit{cnt}_i \le 100) — the amount of balls of each color in the bag.The total amount of balls in the bag is odd (e. g. \mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n is odd).OutputFor each testcase, print a single integer — any possible color of the remaining balls, after you made some moves and can't make moves anymore.ExampleInput 331 1 11924 7Output 3 1 2 NoteIn the first testcase, your first and only move can be one of the following: take balls with colors 1 and 2; take balls with colors 1 and 3; take balls with colors 2 and 3. After the move, exactly one ball will remain. Its color can be 3, 2 or 1 depending on the move.In the second testcase, you can't make moves at all — there is only color of balls already. This color is 1.In the third testcase, you can keep removing one ball of color 1 and one ball of color 2 until there are no more balls of color 1. At the end, three balls of color 2 remain.
331 1 11924 7
3 1 2
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', 'sortings', '*800']
H. Mainak and the Bleeding Polygontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMainak has a convex polygon \mathcal P with n vertices labelled as A_1, A_2, \ldots, A_n in a counter-clockwise fashion. The coordinates of the i-th point A_i are given by (x_i, y_i), where x_i and y_i are both integers.Further, it is known that the interior angle at A_i is either a right angle or a proper obtuse angle. Formally it is known that: 90 ^ \circ \le \angle A_{i - 1}A_{i}A_{i + 1} < 180 ^ \circ, \forall i \in \{1, 2, \ldots, n\} where we conventionally consider A_0 = A_n and A_{n + 1} = A_1. Mainak's friend insisted that all points Q such that there exists a chord of the polygon \mathcal P passing through Q with length not exceeding 1, must be coloured \color{red}{\text{red}}. Mainak wants you to find the area of the coloured region formed by the \color{red}{\text{red}} points.Formally, determine the area of the region \mathcal S = \{Q \in \mathcal{P} | Q \text{ is coloured } \color{red}{\text{red}}\}.Recall that a chord of a polygon is a line segment between two points lying on the boundary (i.e. vertices or points on edges) of the polygon. InputThe first line contains an integer n (4 \le n \le 5000) — the number of vertices of a polygon \mathcal P.The i-th line of the next n lines contain two integers x_i and y_i (-10^9 \le x_i, y_i \le 10^9) — the coordinates of A_i.Additional constraint on the input: The vertices form a convex polygon and are listed in counter-clockwise order. It is also guaranteed that all interior angles are in the range [90^\circ ; 180^\circ ).OutputPrint the area of the region coloured in \color{red}{\text{red}}.Your answer is considered correct if its absolute or relative error does not exceed 10^{-4}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-4}.ExamplesInput 4 4 5 4 1 7 1 7 5 Output 1.17809724510Input 5 -3 3 3 1 4 2 -1 9 -2 9 Output 1.07823651333NoteIn the first example, the polygon \mathcal P can be visualised on the Cartesian Plane as:
4 4 5 4 1 7 1 7 5
1.17809724510
1 second
256 megabytes
['binary search', 'geometry', 'implementation', 'math', '*3500']
G. A Certain Magical Partytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people at a party. The i-th person has an amount of happiness a_i.Every person has a certain kind of personality which can be represented as a binary integer b. If b = 0, it means the happiness of the person will increase if he tells the story to someone strictly less happy than them. If b = 1, it means the happiness of the person will increase if he tells the story to someone strictly more happy than them.Let us define a speaking order as an ordering of the people from left to right. Now the following process occurs. We go from left to right. The current person tells the story to all people other than himself. Note that all happiness values stay constant while this happens. After the person is done, he counts the number of people who currently have strictly less/more happiness than him as per his kind of personality, and his happiness increases by that value. Note that only the current person's happiness value increases.As the organizer of the party, you don't want anyone to leave sad. Therefore, you want to count the number of speaking orders such that at the end of the process all n people have equal happiness.Two speaking orders are considered different if there exists at least one person who does not have the same position in the two speaking orders.InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of people.The second line contains a sequence of n integers a_1,a_2,...,a_n (1 \leq a_i \leq 2n)  — the happiness values.The third line contains a sequence of n binary numbers b_1,b_2,...,b_n (b_i \in \{0,1\})  — the kinds of personality.OutputOutput the number of different valid speaking orders. Since this number can be large, output it modulo 998244353.ExamplesInput 4 1 2 4 4 1 1 0 0 Output 2 Input 4 3 4 3 1 0 1 0 0 Output 0 Input 21 1 2 19 19 19 19 19 19 19 19 19 21 21 21 21 21 21 21 21 21 21 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 Output 49439766 NoteHere is the explanation for the first example. One valid speaking order is [2,1,4,3] (here, we have written the indices of each person). Each step shows the current happiness values and results.Step 1: [1,2,4,4] \rightarrow Person 2 tells the story to others. Since his kind of personality is 1, his happiness increases by 2 since persons 3 and 4 have strictly greater happiness.Step 2: [1,4,4,4] \rightarrow Person 1 tells the story to others. Since his kind of personality is 1, his happiness increases by 3 since persons 2, 3 and 4 have strictly greater happiness.Step 3: [4,4,4,4] \rightarrow Person 4 tells the story to others. Since his kind of personality is 0, his happiness increases by 0 since no one has strictly lesser happiness.Step 4: [4,4,4,4] \rightarrow Person 3 tells the story to others. Since his kind of personality is 0, his happiness increases by 0 since no one has strictly lesser happiness.At the end, everyone has equal happiness.Note that [2,1,3,4] is also a valid answer for this example.It can be shown that there is no valid ordering for the second example.
4 1 2 4 4 1 1 0 0
2
2 seconds
256 megabytes
['combinatorics', 'data structures', 'greedy', 'sortings', '*3300']
F. Late For Work (submissions are not allowed)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem was copied by the author from another online platform. Codeforces strongly condemns this action and therefore further submissions to this problem are not accepted.Debajyoti has a very important meeting to attend and he is already very late. Harsh, his driver, needs to take Debajyoti to the destination for the meeting as fast as possible.Harsh needs to pick up Debajyoti from his home and take him to the destination so that Debajyoti can attend the meeting in time. A straight road with n traffic lights connects the home and the destination for the interview. The traffic lights are numbered in order from 1 to n.Each traffic light cycles after t seconds. The i-th traffic light is \color{green}{\text{green}} (in which case Harsh can cross the traffic light) for the first g_i seconds, and \color{red}{\text{red}} (in which case Harsh must wait for the light to turn \color{green}{\text{green}}) for the remaining (t−g_i) seconds, after which the pattern repeats. Each light's cycle repeats indefinitely and initially, the i-th light is c_i seconds into its cycle (a light with c_i=0 has just turned \color{green}{\text{green}}). In the case that Harsh arrives at a light at the same time it changes colour, he will obey the new colour. Formally, the i-th traffic light is \color{green}{\text{green}} from [0,g_i) and \color{red}{\text{red}} from [g_i,t) (after which it repeats the cycle). The i-th traffic light is initially at the c_i-th second of its cycle.From the i-th traffic light, exactly d_i seconds are required to travel to the next traffic light (that is to the (i+1)-th light). Debajyoti's home is located just before the first light and Debajyoti drops for the interview as soon as he passes the n-th light. In other words, no time is required to reach the first light from Debajyoti's home or to reach the interview centre from the n-th light.Harsh does not know how much longer it will take for Debajyoti to get ready. While waiting, he wonders what is the minimum possible amount of time he will spend driving provided he starts the moment Debajyoti arrives, which can be anywhere between 0 to \infty seconds from now. Can you tell Harsh the minimum possible amount of time he needs to spend on the road?Please note that Harsh can only start or stop driving at integer moments of time.InputThe first line of input will contain two integers, n and t (2 \le n \le 2 \cdot 10^5, 2 \le t \le 10^9) denoting the number of traffic lights and the cycle length of the traffic lights respectively.n lines of input follow. The i-th line will contain two integers g_i and c_i (1 \le g_i < t, 0 \le c_i < t) describing the i-th traffic light.The following line of input contains n−1 integers d_1, d_2, \ldots, d_{n-1} (0 \le d_i \le 10^9) — the time taken to travel from the i-th to the (i+1)-th traffic light.OutputOutput a single integer — the minimum possible amount of time Harsh will spend driving.ExamplesInput 5 10 4 2 7 3 3 6 5 2 8 0 1 2 3 4 Output 11 Input 6 9 5 3 5 5 7 0 5 8 7 7 6 6 0 0 0 0 0 Output 3 NoteIn the first example, Harsh can do the following: Initially, the 5 traffic lights are at the following seconds in their cycle: \{2,3,6,2,0\}. An optimal time for Harsh to start is if Debajyoti arrives after 1 second. Note that this 1 second will not be counted in the final answer. The lights will be now at \{3,4,7,3,1\}, so Harsh can drive from the 1-st light to the 2-nd light, which requires 1 second to travel. The lights are now at \{4,5,8,4,2\}, so Harsh can continue driving, without stopping, to the 3-rd light, which requires 2 seconds to travel. The lights are now at \{6,7,0,6,4\}, so Harsh continues to the 4-th light, which requires 3 seconds to travel. The lights are now at \{9,0,3,9,7\}. Harsh must wait 1 second for the 4-th light to turn green before going to the 5-th light, which requires 4 seconds to travel. The lights are now at \{4,5,8,4,2\}, so Harsh can continue traveling, without stopping, to the meeting destination. The total time that Harsh had to drive for is 1+2+3+1+4=11 seconds.In the second example, Harsh can do the following: Initially, the 6 traffic lights are at the following seconds in their cycle: \{3,5,0,8,7,6\}. An optimal time for Harsh to start is if Debajyoti arrives after 1 second. Note that this 1 second will not be counted in the final answer. The lights will be now at \{4,6,1,0,8,7\}, so Harsh can drive from the 1-st light to the 2-nd light, which requires 0 seconds to travel. The lights are still at \{4,6,1,0,8,7\}. Harsh must wait 3 seconds for the 2-nd light to turn green, before going to the 3-rd light, which requires 0 seconds to travel. The lights are now at \{7,0,4,3,2,1\}, so Harsh continues to the 4-th light, which requires 0 seconds to travel. The lights are still at \{7,0,4,3,2,1\}, so Harsh continues to the 5-th light, which requires 0 seconds to travel. The lights are still at \{7,0,4,3,2,1\}, so Harsh continues to the 6-th light, which requires 0 seconds to travel. The lights are still at \{7,0,4,3,2,1\}, so Harsh can continue traveling, without stopping, to the meeting destination. The total time that Harsh had to drive for is 0+3+0+0+0=3 seconds.
5 10 4 2 7 3 3 6 5 2 8 0 1 2 3 4
11
3 seconds
256 megabytes
['data structures', 'greedy', 'schedules', 'shortest paths', '*2900']
E. Almost Perfecttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation p of length n is called almost perfect if for all integer 1 \leq i \leq n, it holds that \lvert p_i - p^{-1}_i \rvert \le 1, where p^{-1} is the inverse permutation of p (i.e. p^{-1}_{k_1} = k_2 if and only if p_{k_2} = k_1).Count the number of almost perfect permutations of length n modulo 998244353.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of each test case follows.The first and only line of each test case contains a single integer n (1 \leq n \leq 3 \cdot 10^5) — the length of the permutation.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output a single integer — the number of almost perfect permutations of length n modulo 998244353.ExampleInput 32350Output 2 4 830690567 NoteFor n = 2, both permutations [1, 2], and [2, 1] are almost perfect.For n = 3, there are only 6 permutations. Having a look at all of them gives us: [1, 2, 3] is an almost perfect permutation. [1, 3, 2] is an almost perfect permutation. [2, 1, 3] is an almost perfect permutation. [2, 3, 1] is NOT an almost perfect permutation (\lvert p_2 - p^{-1}_2 \rvert = \lvert 3 - 1 \rvert = 2). [3, 1, 2] is NOT an almost perfect permutation (\lvert p_2 - p^{-1}_2 \rvert = \lvert 1 - 3 \rvert = 2). [3, 2, 1] is an almost perfect permutation. So we get 4 almost perfect permutations.
32350
2 4 830690567
3 seconds
256 megabytes
['combinatorics', 'fft', 'math', '*2400']
D. Edge Splittime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a connected, undirected and unweighted graph with n vertices and m edges. Notice the limit on the number of edges: m \le n + 2.Let's say we color some of the edges red and the remaining edges blue. Now consider only the red edges and count the number of connected components in the graph. Let this value be c_1. Similarly, consider only the blue edges and count the number of connected components in the graph. Let this value be c_2.Find an assignment of colors to the edges such that the quantity c_1+c_2 is minimised.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains two integers n and m (2 \le n \le 2 \cdot 10^5; n-1 \leq m \leq \min{\left(n+2,\frac{n \cdot (n-1)}{2}\right)}) — the number of vertices and the number of edges respectively.m lines follow. The i-th line contains two integers u_i and v_i (1 \le u_i,v_i \le n, u_i \ne v_i) denoting that the i-th edge goes between vertices u_i and v_i. The input is guaranteed to have no multiple edges or self loops. The graph is also guaranteed to be connected.It is guaranteed that the sum of n over all test cases does not exceed 10^6. It is guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^6.OutputFor each test case, output a binary string of length m. The i-th character of the string should be 1 if the i-th edge should be colored red, and 0 if it should be colored blue. If there are multiple ways to assign colors to edges that give the minimum answer, you may output any.ExampleInput 45 71 22 33 44 55 11 33 54 41 22 31 43 46 71 21 33 44 51 45 66 22 11 2Output 0111010 1001 0001111 0 Note The corresponding graph of the first test case is: c_1 + c_2 = 1 + 2 = 3 The corresponding graph of the second test case is: c_1 + c_2 = 2 + 2 = 4
45 71 22 33 44 55 11 33 54 41 22 31 43 46 71 21 33 44 51 45 66 22 11 2
0111010 1001 0001111 0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'probabilities', 'trees', '*2000']
C. Jatayu's Balanced Bracket Sequencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLast summer, Feluda gifted Lalmohan-Babu a balanced bracket sequence s of length 2 n.Topshe was bored during his summer vacations, and hence he decided to draw an undirected graph of 2 n vertices using the balanced bracket sequence s. For any two distinct vertices i and j (1 \le i < j \le 2 n), Topshe draws an edge (undirected and unweighted) between these two nodes if and only if the subsegment s[i \ldots j] forms a balanced bracket sequence.Determine the number of connected components in Topshe's graph.See the Notes section for definitions of the underlined terms.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of opening brackets in string s.The second line of each test case contains a string s of length 2 n — a balanced bracket sequence consisting of n opening brackets "(", and n closing brackets ")".It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single integer — the number of connected components in Topshe's graph.ExampleInput 41()3()(())3((()))4(())(())Output 1 2 3 3 NoteSample explanation:In the first test case, the graph constructed from the bracket sequence (), is just a graph containing nodes 1 and 2 connected by a single edge. In the second test case, the graph constructed from the bracket sequence ()(()) would be the following (containing two connected components): Definition of Underlined Terms: A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not. The subsegment s[l \ldots r] denotes the sequence [s_l, s_{l + 1}, \ldots, s_r]. 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 these vertices, but adding any other vertex to X violates this rule.
41()3()(())3((()))4(())(())
1 2 3 3
2 seconds
256 megabytes
['data structures', 'dsu', 'graphs', 'greedy', '*1300']
B. Mainak and Interesting Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMainak has two positive integers n and m.Mainak finds a sequence a_1, a_2, \ldots, a_n of n positive integers interesting, if for all integers i (1 \le i \le n), the bitwise XOR of all elements in a which are strictly less than a_i is 0. Formally if p_i is the bitwise XOR of all elements in a which are strictly less than a_i, then a is an interesting sequence if p_1 = p_2 = \ldots = p_n = 0.For example, sequences [1,3,2,3,1,2,3], [4,4,4,4], [25] are interesting, whereas [1,2,3,4] (p_2 = 1 \ne 0), [4,1,1,2,4] (p_1 = 1 \oplus 1 \oplus 2 = 2 \ne 0), [29,30,30] (p_2 = 29 \ne 0) aren't interesting.Here a \oplus b denotes bitwise XOR of integers a and b.Find any interesting sequence a_1, a_2, \ldots, a_n (or report that there exists no such sequence) such that the sum of the elements in the sequence a is equal to m, i.e. a_1 + a_2 \ldots + a_n = m.As a reminder, the bitwise XOR of an empty sequence is considered to be 0.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Description of the test cases follows.The first line and the only line of each test case contains two integers n and m (1 \le n \le 10^5, 1 \le m \le 10^9) — the length of the sequence and the sum of the elements.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, if there exists some interesting sequence, output "Yes" on the first line, otherwise output "No". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).If the answer is "Yes", output n positive integers a_1, a_2, \ldots, a_n (a_i \ge 1), forming an interesting sequence such that a_1 + a_2 \ldots + a_n = m. If there are multiple solutions, output any.ExampleInput 4 1 3 6 12 2 1 3 6 Output Yes 3 Yes 1 3 2 2 3 1 No Yes 2 2 2 Note In the first test case, [3] is the only interesting sequence of length 1 having sum 3. In the third test case, there is no sequence of length 2 having sum of elements equal to 1, so there is no such interesting sequence. In the fourth test case, p_1 = p_2 = p_3 = 0, because bitwise XOR of an empty sequence is 0.
4 1 3 6 12 2 1 3 6
Yes 3 Yes 1 3 2 2 3 1 No Yes 2 2 2
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'math', '*1100']
A. Mainak and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMainak has an array a_1, a_2, \ldots, a_n of n positive integers. He will do the following operation to this array exactly once: Pick a subsegment of this array and cyclically rotate it by any amount. Formally, he can do the following exactly once: Pick two integers l and r, such that 1 \le l \le r \le n, and any positive integer k. Repeat this k times: set a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l (all changes happen at the same time). Mainak wants to maximize the value of (a_n - a_1) after exactly one such operation. Determine the maximum value of (a_n - a_1) that he can obtain.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 50) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2000).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 999).It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output a single integer — the maximum value of (a_n - a_1) that Mainak can obtain by doing the operation exactly once.ExampleInput 561 3 9 11 5 712039 99 99942 1 8 132 1 5Output 10 0 990 7 4 Note In the first test case, we can rotate the subarray from index 3 to index 6 by an amount of 2 (i.e. choose l = 3, r = 6 and k = 2) to get the optimal array: [1, 3, \underline{9, 11, 5, 7}] \longrightarrow [1, 3, \underline{5, 7, 9, 11}] So the answer is a_n - a_1 = 11 - 1 = 10. In the second testcase, it is optimal to rotate the subarray starting and ending at index 1 and rotating it by an amount of 2. In the fourth testcase, it is optimal to rotate the subarray starting from index 1 to index 4 and rotating it by an amount of 3. So the answer is 8 - 1 = 7.
561 3 9 11 5 712039 99 99942 1 8 132 1 5
10 0 990 7 4
1 second
256 megabytes
['greedy', 'math', '*900']
M. Moving Both Handstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek is playing one of his favourite board games. In the game, there is a directed graph with N vertices and M edges. In the graph, edge i connects two different vertices U_i and V_i with a length of W_i. By using the i-th edge, something can move from U_i to V_i, but not from V_i to U_i.To play this game, initially Pak Chanek must place both of his hands onto two different vertices. In one move, he can move one of his hands to another vertex using an edge. To move a hand from vertex U_i to vertex V_i, Pak Chanek needs a time of W_i seconds. Note that Pak Chanek can only move one hand at a time. This game ends when both of Pak Chanek's hands are on the same vertex.Pak Chanek has several questions. For each p satisfying 2 \leq p \leq N, you need to find the minimum time in seconds needed for Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex 1 and vertex p, or report if it is impossible.InputThe first line contains two integers N and M (2 \leq N \leq 10^5, 0 \leq M \leq 2 \cdot 10^5) — the number of vertices and edges in the graph.The i-th of the next M lines contains three 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) — a directed edge that connects two different vertices U_i and V_i with a length of W_i. There is no pair of different edges i and j such that U_i = U_j and V_i = V_j.OutputOutput a line containing N-1 integers. The j-th integer represents the minimum time in seconds needed by Pak Chanek to end the game if initially Pak Chanek's left hand and right hand are placed on vertex 1 and vertex j+1, or -1 if it is impossible.ExampleInput 5 7 1 2 2 2 4 1 4 1 4 2 5 3 5 4 1 5 2 4 2 1 1 Output 1 -1 3 4 NoteIf initially Pak Chanek's left hand is on vertex 1 and his right hand is on vertex 5, Pak Chanek can do the following moves: Move his right hand to vertex 4 in 1 second. Move his left hand to vertex 2 in 2 seconds. Move his left hand to vertex 4 in 1 second. In total it needs 1+2+1=4 seconds. It can be proven that there is no other way that is faster.
5 7 1 2 2 2 4 1 4 1 4 2 5 3 5 4 1 5 2 4 2 1 1
1 -1 3 4
1 second
256 megabytes
['dp', 'graphs', 'shortest paths', '*1800']
L. Lemper Cooking Competitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek is participating in a lemper cooking competition. In the competition, Pak Chanek has to cook lempers with N stoves that are arranged sequentially from stove 1 to stove N. Initially, stove i has a temperature of A_i degrees. A stove can have a negative temperature.Pak Chanek realises that, in order for his lempers to be cooked, he needs to keep the temperature of each stove at a non-negative value. To make it happen, Pak Chanek can do zero or more operations. In one operation, Pak Chanek chooses one stove i with 2 \leq i \leq N-1, then: changes the temperature of stove i-1 into A_{i-1} := A_{i-1} + A_{i}, changes the temperature of stove i+1 into A_{i+1} := A_{i+1} + A_{i}, and changes the temperature of stove i into A_i := -A_i. Pak Chanek wants to know the minimum number of operations he needs to do such that the temperatures of all stoves are at non-negative values. Help Pak Chanek by telling him the minimum number of operations needed or by reporting if it is not possible to do.InputThe first line contains a single integer N (1 \le N \le 10^5) — the number of stoves.The second line contains N integers A_1, A_2, \ldots, A_N (-10^9 \leq A_i \leq 10^9) — the initial temperatures of the stoves.OutputOutput an integer representing the minimum number of operations needed to make the temperatures of all stoves at non-negative values or output -1 if it is not possible.ExamplesInput 7 2 -1 -1 5 2 -2 9 Output 4 Input 5 -1 -2 -3 -4 -5 Output -1 NoteFor the first example, a sequence of operations that can be done is as follows: Pak Chanek does an operation to stove 3, A = [2, -2, 1, 4, 2, -2, 9]. Pak Chanek does an operation to stove 2, A = [0, 2, -1, 4, 2, -2, 9]. Pak Chanek does an operation to stove 3, A = [0, 1, 1, 3, 2, -2, 9]. Pak Chanek does an operation to stove 6, A = [0, 1, 1, 3, 0, 2, 7]. There is no other sequence of operations such that the number of operations needed is fewer than 4.
7 2 -1 -1 5 2 -2 9
4
1 second
256 megabytes
['data structures', '*2400']
K. Kingdom of Criticismtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek is visiting a kingdom that earned a nickname "Kingdom of Criticism" because of how often its residents criticise each aspect of the kingdom. One aspect that is often criticised is the heights of the buildings. The kingdom has N buildings. Initially, building i has a height of A_i units.At any point in time, the residents can give a new criticism, namely they currently do not like buildings with heights between l and r units inclusive for some two integers l and r. It is known that r-l is always odd.In 1 minute, the kingdom's construction team can increase or decrease the height of any building by 1 unit as long as the height still becomes a positive number. Each time they receive the current criticism from the residents, the kingdom's construction team makes it so that there are no buildings with heights between l and r units inclusive in the minimum time possible. It can be obtained that there is only one way to do this. Note that the construction team only cares about the current criticism from the residents. All previous criticisms are forgotten.There will be Q queries that you must solve. Each query is one of the three following possibilities: 1 k w: The kingdom's construction team changes the height of building k to be w units (1 \leq k \leq N, 1 \leq w \leq 10^9). 2 k: The kingdom's construction team wants you to find the height of building k (1 \leq k \leq N). 3 l r: The residents currently do not like buildings with heights between l and r units inclusive (2 \leq l \leq r \leq 10^9-1, r-l is odd). Note that each change in height still persists to the next queries.InputThe first line contains a single integer N (1 \leq N \leq 4 \cdot 10^5) — the number buildings in the kingdom.The second line contains N integers A_1, A_2, \ldots, A_N (1 \leq A_i \leq 10^9) — the initial heights of the buildings.The next line contains a single integer Q (1 \leq Q \leq 4 \cdot 10^5) — the number of queries.The j-th of the next Q lines contains the j-th query as described. There is at least one query of type 2.OutputFor each query of type 2, output a line containing an integer representing the height of the building asked.ExampleInput 5 2 6 5 6 2 9 1 5 10 2 5 1 1 3 3 3 6 3 8 9 1 2 9 2 3 2 2 2 4 Output 10 7 9 7 NoteAfter the 1-st query, the height of each building is 2, 6, 5, 6, 10.After the 3-rd query, the height of each building is 3, 6, 5, 6, 10.After the 4-th query, the height of each building is 2, 7, 7, 7, 10.After the 5-th query, the height of each building is 2, 7, 7, 7, 10.After the 6-th query, the height of each building is 2, 9, 7, 7, 10.
5 2 6 5 6 2 9 1 5 10 2 5 1 1 3 3 3 6 3 8 9 1 2 9 2 3 2 2 2 4
10 7 9 7
3 seconds
512 megabytes
['data structures', 'dsu', '*2500']
J. Journeytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, Pak Chanek who is already bored of being alone at home decided to go traveling. While looking for an appropriate place, he found that Londonesia has an interesting structure.According to the information gathered by Pak Chanek, there are N cities numbered from 1 to N. The cities are connected to each other with N-1 two-directional roads, with the i-th road connecting cities U_i and V_i, and taking a time of W_i hours to be traversed. In other words, Londonesia's structure forms a tree.Pak Chanek wants to go on a journey in Londonesia starting and ending in any city (not necessarily the same city) such that each city is visited at least once with the least time possible. In order for the journey to end quicker, Pak Chanek also carries an instant teleportation device for moving from one city to any city that can only be used at most once. Help Pak Chanek for finding the minimum time needed.Notes: Pak Chanek only needs to visit each city at least once. Pak Chanek does not have to traverse each road. In the journey, a city or a road can be visited more than once. InputThe first line contains a single integer N (1 \le N \le 10^5) — the number of cities in Londonesia.The i-th of the next N-1 lines contains three integers U_i, V_i, and W_i (1 \le U_i, V_i \le N, 1 \le W_i \le 10^9) — a two-directional road that connects cities U_i and V_i that takes W_i hours to be traversed. The roads in Londonesia form a tree.OutputOutput one integer, which represents the minimum time in hours that is needed to visit each city at least once.ExamplesInput 4 1 2 4 2 3 5 3 4 4 Output 8 Input 5 1 2 45 1 3 50 1 4 10 1 5 65 Output 115 NoteIn the first example, the journey that has the minimum time is 2 → 1 \xrightarrow{\text{teleport}} 4 → 3.In the second example, the journey that has the minimum time is 3 → 1 → 4 → 1 → 2 \xrightarrow{\text{teleport}} 5.
4 1 2 4 2 3 5 3 4 4
8
1 second
256 megabytes
['dp', 'trees', '*2500']
I. Imitating the Key Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has a tree called the key tree. This tree consists of N vertices and N-1 edges. The edges of the tree are numbered from 1 to N-1 with edge i connecting vertices U_i and V_i. Initially, each edge of the key tree does not have a weight.Formally, a path with length k in a graph is a sequence [v_1, e_1, v_2, e_2, v_3, e_3, \ldots, v_k, e_k, v_{k+1}] such that: For each i, v_i is a vertex and e_i is an edge. For each i, e_i connects vertices v_i and v_{i+1}. A circuit is a path that starts and ends on the same vertex.A path in a graph is said to be simple if and only if the path does not use the same edge more than once. Note that a simple path can use the same vertex more than once.The cost of a simple path in a weighted graph is defined as the maximum weight of all edges it traverses.Count the number of distinct undirected weighted graphs that satisfy the following conditions: The graph has N vertices and 2N-2 edges. For each pair of different vertices (x, y), there exists a simple circuit that goes through vertices x and y in the graph. The weight of each edge in the graph is an integer between 1 and 2N-2 inclusive. Each edge has distinct weights. The graph is formed in a way such that there is a way to assign a weight W_i to each edge i in the key tree that satisfies the following conditions: For each pair of edges (i, j), if i<j, then W_i<W_j. For each pair of different vertex indices (x, y), the cost of the only simple path from vertex x to y in the key tree is equal to the minimum cost of a simple circuit that goes through vertices x and y in the graph. Note that the graph is allowed to have multi-edges, but is not allowed to have self-loops. Print the answer modulo 998\,244\,353.Two graphs are considered distinct if and only if there exists a triple (a, b, c) such that there exists an edge that connects vertices a and b with weight c in one graph, but not in the other.InputThe first line contains a single integer N (2 \le N \le 10^5) — the number of vertices in the key tree.The i-th of the next N-1 lines contains two integers U_i and V_i (1 \le U_i, V_i \le N) — an edge connecting vertices U_i and V_i. The graph in the input is a tree.OutputAn integer representing the number of distinct undirected weighted graphs that satisfy the conditions of the problem modulo 998\,244\,353.ExampleInput 4 3 2 1 3 4 3 Output 540 NoteThe following is an example of a graph that satisfies.The following is an assignment of edge weights in the key tree that corresponds to the graph above.As an example, consider a pair of vertex indices (1, 4). The circuit in the graph for this pair of vertices is 3 \xrightarrow{2} 2 \xrightarrow{4} 4 \xrightarrow{6} 2 \xrightarrow{1} 1 \xrightarrow{5} 3 with a cost of 6. The path in the key tree for this pair of vertices is 1 \xrightarrow{5} 3 \xrightarrow{6} 4 with a cost of 6.
4 3 2 1 3 4 3
540
1 second
256 megabytes
['combinatorics', 'dsu', 'trees', '*2800']
H. Hot Black Hot Whitetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOne day, you are accepted as being Dr. Chanek's assistant. The first task given by Dr. Chanek to you is to take care and store his magical stones.Dr. Chanek has N magical stones with N being an even number. Those magical stones are numbered from 1 to N. Magical stone i has a strength of A_i. A magical stone can be painted with two colours, namely the colour black or the colour white. You are tasked to paint the magical stones with the colour black or white and store the magical stones into a magic box with a magic coefficient Z (0 \leq Z \leq 2). The painting of the magical stones must be done in a way such that there are \frac{N}{2} black magical stones and \frac{N}{2} white magical stones.Define \text{concat}(x, y) for two integers x and y as the result of concatenating the digits of x to the left of y in their decimal representation without changing the order. As an example, \text{concat}(10, 24) will result in 1024.For a magic box with a magic coefficient Z, magical stone i will react with magical stone j if the colours of both stones are different and \text{concat}(A_i, A_j) \times \text{concat}(A_j, A_i) + A_i \times A_j \equiv Z \mod 3. A magical stone that is reacting will be very hot and dangerous. Because of that, you must colour the magical stones and determine the magic coefficient Z of the magic box in a way such that there is no magical stone that reacts, or report if it is impossible.InputThe first line contains a single even integer N (2 \le N \le 10^5) — the number of magical stones Dr. Chanek has.The second line contains N integer A_1, A_2, \ldots, A_N (1 \leq A_i \leq 10^9) — the strengths of all magical stones.OutputIf it is not possible to satisfy the condition of the problem, output -1.Otherwise, output two lines. The first line contains an integer Z denoting the magic coefficient of the magic box. The second line contains a string S of length N. S_i is 0 if magical stone i is coloured black or 1 if magical stone i is coloured white. If there are more than one possibilities of colouring and choosing the magic coefficient Z, output any of them.ExampleInput 4 4 10 9 14 Output 0 1001 NoteBy giving the above colouring, it can be seen that: i=1, j=2 \longrightarrow \text{concat}(4, 10) \times \text{concat}(10, 4) + 10 \times 4 = 410 \times 104 + 40 = 42680 \equiv 2 \mod 3 i=1, j=3 \longrightarrow \text{concat}(4, 9) \times \text{concat}(9, 4) + 4 \times 9 = 49 \times 94 + 36 = 4642 \equiv 1 \mod 3 i=4, j=2 \longrightarrow \text{concat}(14, 10) \times \text{concat}(10, 14) + 10 \times 14 = 1410 \times 1014 + 140 = 1429880 \equiv 2 \mod 3 i=4, j=3 \longrightarrow \text{concat}(14, 9) \times \text{concat}(9, 14) + 14 \times 9 = 149 \times 914 + 126 = 136312 \equiv 1 \mod 3 Because of that, by choosing Z = 0, it can be guaranteed that there is no magical stone that reacts.
4 4 10 9 14
0 1001
1 second
256 megabytes
['constructive algorithms', 'math', '*1800']
G. Garagetime limit per test1 secondmemory limit per test128 megabytesinputstandard inputoutputstandard outputPak Chanek plans to build a garage. He wants the garage to consist of a square and a right triangle that are arranged like the following illustration. Define a and b as the lengths of two of the sides in the right triangle as shown in the illustration. An integer x is suitable if and only if we can construct a garage with assigning positive integer values for the lengths a and b (a<b) so that the area of the square at the bottom is exactly x. As a good friend of Pak Chanek, you are asked to help him find the N-th smallest suitable number.InputThe only line contains a single integer N (1 \leq N \leq 10^9).OutputAn integer that represents the N-th smallest suitable number.ExampleInput 3 Output 7 NoteThe 3-rd smallest suitable number is 7. A square area of 7 can be obtained by assigning a=3 and b=4.
3
7
1 second
128 megabytes
['binary search', 'geometry', 'math', '*1500']
F. Field Photographytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek is traveling to Manado. It turns out that OSN (Indonesian National Scientific Olympiad) 2019 is being held. The contestants of OSN 2019 are currently lining up in a field to be photographed. The field is shaped like a grid of size N \times 10^{100} with N rows and 10^{100} columns. The rows are numbered from 1 to N from north to south, the columns are numbered from 1 to 10^{100} from west to east. The tile in row r and column c is denoted as (r,c).There are N provinces that participate in OSN 2019. Initially, each contestant who represents province i stands in tile (i, p) for each p satisfying L_i \leq p \leq R_i. So, we can see that there are R_i-L_i+1 contestants who represent province i.Pak Chanek has a variable Z that is initially equal to 0. In one operation, Pak Chanek can choose a row i and a positive integer k. Then, Pak Chanek will do one of the two following possibilities: Move all contestants in row i exactly k tiles to the west. In other words, a contestant who is in (i, p) is moved to (i, p-k). Move all contestants in row i exactly k tiles to the east. In other words, a contestant who is in (i, p) is moved to (i, p+k). After each operation, the value of Z will change into Z \text{ OR } k, with \text{OR} being the bitwise OR operation. Note that Pak Chanek can do operations to the same row more than once. Also note that Pak Chanek is not allowed to move contestants out of the grid.There are Q questions. For the j-th question, you are given a positive integer W_j, Pak Chanek must do zero or more operations so that the final value of Z is exactly W_j. Define M as the biggest number such that after all operations, there is at least one column that contains exactly M contestants. For each question, you must find the biggest possible M for all sequences of operations that can be done by Pak Chanek. Note that the operations done by Pak Chanek for one question do not carry over to other questions.InputThe first line contains a single integer N (1 \leq N \leq 10^5) — the number of rows in the grid and also the number of provinces that participate in OSN 2019.The i-th of the next N lines contains two integers L_i and R_i (1 \leq L_i \leq R_i \leq 10^9) describing the positions of the contestants who represent province i.The next line contains a single integer Q (1 \leq Q \leq 10^5) — the number of questions.The j-th of the next Q lines contains a single integer W_j (1 \leq W_j \leq 10^9) — the required final value of Z for the j-th question.OutputOutput Q lines, with the j-th line containing an integer that is the answer to the j-th question.ExampleInput 3 1 5 10 11 8 8 2 12 5 Output 2 3 NoteFor the 1-st question, Pak Chanek can do the following operations to get M=2: Move all contestants in row 2 to the east by 4 tiles. Z changes into 0 \text{ OR } 4 = 4. Move all contestants in row 1 to the east by 12 tiles. Z changes into 4 \text{ OR } 12 = 12. Now, columns 14 and 15 each contains exactly 2 contestants.For the 2-nd question, Pak Chanek can do the following operations to get M=3: Move all contestants in row 3 to the east by 4 tiles. Z changes into 0 \text{ OR } 4 = 4. Move all contestants in row 3 to the west by 1 tiles. Z changes into 4 \text{ OR } 1 = 5. Move all contestants in row 1 to the east by 5 tiles. Z changes into 5 \text{ OR } 5 = 5. Move all contestants in row 1 to the east by 5 tiles. Z changes into 5 \text{ OR } 5 = 5. Now, column 11 contains exactly 3 contestants.The following is an illustration of the example operations for the 2-nd question.
3 1 5 10 11 8 8 2 12 5
2 3
1 second
256 megabytes
['bitmasks', 'data structures', 'sortings', '*2100']
E. Electrical Efficiencytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn the country of Dengkleknesia, there are N factories numbered from 1 to N. Factory i has an electrical coefficient of A_i. There are also N-1 power lines with the j-th power line connecting factory U_j and factory V_j. It can be guaranteed that each factory in Dengkleknesia is connected to all other factories in Dengkleknesia through one or more power lines. In other words, the collection of factories forms a tree. Each pair of different factories in Dengkleknesia can use one or more existing power lines to transfer electricity to each other. However, each power line needs to be turned on first so that electricity can pass through it.Define f(x, y, z) as the minimum number of power lines that need to be turned on so that factory x can make electrical transfers to factory y and factory z. Also define g(x, y, z) as the number of distinct prime factors of \text{GCD}(A_x, A_y, A_z).To measure the electrical efficiency, you must find the sum of f(x, y, z) \times g(x, y, z) for all combinations of (x, y, z) such that 1 \leq x < y < z \leq N. Because the answer can be very large, you just need to output the answer modulo 998\,244\,353.Note: \text{GCD}(k_1, k_2, k_3) is the greatest common divisor of k_1, k_2, and k_3, which is the biggest integer that simultaneously divides k_1, k_2, and k_3.InputThe first line contains a single integer N (1 \le N \le 2 \cdot 10^5) — the number of factories in Dengkleknesia.The second line contains N integers A_1, A_2, \dots, A_N (1 \leq A_i \leq 2 \cdot 10^5) — the electrical coefficients of the factories.The j-th of the next N-1 lines contains two integers U_j and V_j (1 \le U_j, V_j \le N) — a power line that connects cities U_j and V_j. The collection of factories forms a tree.OutputAn integer representing the sum of f(x, y, z) \times g(x, y, z) for all combinations of (x, y, z) such that 1 \leq x < y < z \leq N, modulo 998\,244\,353ExamplesInput 3 1 2 3 1 2 2 3 Output 0 Input 4 6 14 6 6 1 2 2 3 2 4 Output 12 NoteIn the first example, the only (x, y, z) possible is (1, 2, 3). Because \text{GCD}(A_1, A_2, A_3) = \text{GCD}(1, 2, 3) = 1 has 0 distinct prime factors, therefore f(x, y, z) \times g(x, y, z) = 2 \times 0 = 0.In the second example, all triples (x, y, z) that satisfy the condition are as follows: (1, 2, 3) \rightarrow f(1, 2, 3) \times g(1, 2, 3) = 2 \times 1 = 2 (1, 2, 4) \rightarrow f(1, 2, 4) \times g(1, 2, 4) = 2 \times 1 = 2 (1, 3, 4) \rightarrow f(1, 3, 4) \times g(1, 3, 4) = 3 \times 2 = 6 (2, 3, 4) \rightarrow f(2, 3, 4) \times g(2, 3, 4) = 2 \times 1 = 2 So the electrical efficiency is 2 + 2 + 6 + 2 = 12.
3 1 2 3 1 2 2 3
0
3 seconds
512 megabytes
['combinatorics', 'data structures', 'dp', 'math', 'number theory', 'trees', '*2500']
D. Deducing Sortabilitytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's say Pak Chanek has an array A consisting of N positive integers. Pak Chanek will do a number of operations. In each operation, Pak Chanek will do the following: Choose an index p (1 \leq p \leq N). Let c be the number of operations that have been done on index p before this operation. Decrease the value of A_p by 2^c. Multiply the value of A_p by 2. After each operation, all elements of A must be positive integers.An array A is said to be sortable if and only if Pak Chanek can do zero or more operations so that A_1 < A_2 < A_3 < A_4 < \ldots < A_N.Pak Chanek must find an array A that is sortable with length N such that A_1 + A_2 + A_3 + A_4 + \ldots + A_N is the minimum possible. If there are more than one possibilities, Pak Chanek must choose the array that is lexicographically minimum among them.Pak Chanek must solve the following things: Pak Chanek must print the value of A_1 + A_2 + A_3 + A_4 + \ldots + A_N for that array. Q questions will be given. For the i-th question, an integer P_i is given. Pak Chanek must print the value of A_{P_i}. Help Pak Chanek solve the problem.Note: an array B of size N is said to be lexicographically smaller than an array C that is also of size N if and only if there exists an index i such that B_i < C_i and for each j < i, B_j = C_j.InputThe first line contains two integers N and Q (1 \leq N \leq 10^9, 0 \leq Q \leq \min(N, 10^5)) — the required length of array A and the number of questions.The i-th of the next Q lines contains a single integer P_i (1 \leq P_1 < P_2 < \ldots < P_Q \leq N) — the index asked in the i-th question.OutputPrint Q+1 lines. The 1-st line contains an integer representing A_1 + A_2 + A_3 + A_4 + \ldots + A_N. For each 1 \leq i \leq Q, the (i+1)-th line contains an integer representing A_{P_i}.ExamplesInput 6 3 1 4 5 Output 17 1 3 4 Input 1 0 Output 1 NoteIn the first example, the array A obtained is [1, 2, 3, 3, 4, 4]. We can see that the array is sortable by doing the following operations: Choose index 5, then A = [1, 2, 3, 3, 6, 4]. Choose index 6, then A = [1, 2, 3, 3, 6, 6]. Choose index 4, then A = [1, 2, 3, 4, 6, 6]. Choose index 6, then A = [1, 2, 3, 4, 6, 8].
6 3 1 4 5
17 1 3 4
2 seconds
512 megabytes
['binary search', 'bitmasks', 'math', '*2900']
C. Circular Mirrortime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has a mirror in the shape of a circle. There are N lamps on the circumference numbered from 1 to N in clockwise order. The length of the arc from lamp i to lamp i+1 is D_i for 1 \leq i \leq N-1. Meanwhile, the length of the arc between lamp N and lamp 1 is D_N.Pak Chanek wants to colour the lamps with M different colours. Each lamp can be coloured with one of the M colours. However, there cannot be three different lamps such that the colours of the three lamps are the same and the triangle made by considering the three lamps as vertices is a right triangle (triangle with one of its angles being exactly 90 degrees).The following are examples of lamp colouring configurations on the circular mirror. Figure 1. an example of an incorrect colouring because lamps 1, 2, and 3 form a right triangleFigure 2. an example of a correct colouringFigure 3. an example of a correct colouring Before colouring the lamps, Pak Chanek wants to know the number of distinct colouring configurations he can make. Count the number of distinct possible lamp colouring configurations, modulo 998\,244\,353.InputThe first line contains two integers N and M (1 \le N \le 3 \cdot 10^5, 2 \le M \le 3 \cdot 10^5) — the number of lamps in the mirror and the number of different colours used.The second line contains N integers D_1, D_2, \ldots, D_N (1 \le D_i \le 10^9) — the lengths of the arcs between the lamps in the mirror.OutputAn integer representing the number of possible lamp colouring configurations, modulo 998\,244\,353.ExamplesInput 4 2 10 10 6 14 Output 10 Input 1 2 10 Output 2 NoteIn the first example, all correct lamp colouring configurations are [1, 1, 2, 1], [1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [1, 2, 2, 2], [2, 1, 1, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1], and [2, 2, 1, 2].
4 2 10 10 6 14
10
1 second
256 megabytes
['binary search', 'combinatorics', 'geometry', 'math', 'two pointers', '*2000']
B. Basketball Togethertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA basketball competition is held where the number of players in a team does not have a maximum or minimum limit (not necessarily 5 players in one team for each match). There are N candidate players in the competition that will be trained by Pak Chanek, the best basketball coach on earth. The i-th candidate player has a power of P_i.Pak Chanek will form zero or more teams from the N candidate players on the condition that each candidate player may only join in at most one team. Each of Pak Chanek's teams will be sent to compete once with an enemy team that has a power of D. In each match, the team sent is said to defeat the enemy team if the sum of powers from the formed players is strictly greater than D.One of Pak Chanek's skills is that when a team that has been formed plays in a match, he can change the power of each player in the team to be equal to the biggest player power from the team.Determine the maximum number of wins that can be achieved by Pak Chanek.InputThe first line contains two integers N and D (1 \le N \le 10^5, 1 \le D \le 10^9) — the number of candidate players and the power of the enemy team.The second line contains N integers P_1, P_2, \ldots, P_N (1 \le P_i \le 10^9) — the powers of all candidate players.OutputA line containing an integer representing the maximum number of wins that can be achieved by Pak Chanek.ExampleInput 6 180 90 80 70 60 50 100 Output 2 NoteThe 1-st team formed is a team containing players 4 and 6. The power of each player in the team becomes 100. So the total power of the team is 100 + 100 = 200 > 180.The 2-nd team formed is a team containing players 1, 2, and 5. The power of each player in the team becomes 90. So the total power of the team is 90 + 90 + 90 = 270 > 180.
6 180 90 80 70 60 50 100
2
1 second
256 megabytes
['binary search', 'greedy', 'sortings', '*1000']
A. Accumulation of Dominoestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPak Chanek has a grid that has N rows and M columns. Each row is numbered from 1 to N from top to bottom. Each column is numbered from 1 to M from left to right.Each tile in the grid contains a number. The numbers are arranged as follows: Row 1 contains integers from 1 to M from left to right. Row 2 contains integers from M+1 to 2 \times M from left to right. Row 3 contains integers from 2 \times M+1 to 3 \times M from left to right. And so on until row N. A domino is defined as two different tiles in the grid that touch by their sides. A domino is said to be tight if and only if the two numbers in the domino have a difference of exactly 1. Count the number of distinct tight dominoes in the grid.Two dominoes are said to be distinct if and only if there exists at least one tile that is in one domino, but not in the other.InputThe only line contains two integers N and M (1 \leq N, M \leq 10^9) — the number of rows and columns in the grid.OutputAn integer representing the number of distinct tight dominoes in the grid.ExamplesInput 3 4 Output 9 Input 2 1 Output 1 NoteThe picture below is the grid that Pak Chanek has in the first example. The picture below is an example of a tight domino in the grid.
3 4
9
1 second
256 megabytes
['math', '*800']
G. Even-Odd XORtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an integer n, find any array a of n distinct nonnegative integers less than 2^{31} such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.InputThe first line of the input contains an integer t (1 \leq t \leq 629) — the number of test cases.Then t lines follow, each containing a single integer n (3 \leq n \leq 2\cdot10^5) — the length of the array.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output one line containing n distinct integers that satisfy the conditions.If there are multiple answers, you can output any of them.ExampleInput 7 8 3 4 5 6 7 9 Output 4 2 1 5 0 6 7 3 2 1 3 2 1 3 0 2 0 4 5 3 4 1 2 12 3 8 1 2 3 4 5 6 7 8 2 3 7 4 0 5 6 9NoteIn the first test case the XOR on odd indices is 4 \oplus 1 \oplus 0 \oplus 7 = 2 and the XOR on even indices is 2 \oplus 5 \oplus 6 \oplus 3= 2.
7 8 3 4 5 6 7 9
4 2 1 5 0 6 7 3 2 1 3 2 1 3 0 2 0 4 5 3 4 1 2 12 3 8 1 2 3 4 5 6 7 8 2 3 7 4 0 5 6 9
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'greedy', '*1500']
F. L-shapestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn L-shape is a figure on gridded paper that looks like the first four pictures below. An L-shape contains exactly three shaded cells (denoted by *), which can be rotated in any way. You are given a rectangular grid. Determine if it contains L-shapes only, where L-shapes can't touch an edge or corner. More formally: Each shaded cell in the grid is part of exactly one L-shape, and no two L-shapes are adjacent by edge or corner. For example, the last two grids in the picture above do not satisfy the condition because the two L-shapes touch by corner and edge, respectively.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n, m \leq 50) — the number of rows and columns in the grid, respectively.Then n lines follow, each containing m characters. Each of these characters is either '.' or '*' — an empty cell or a shaded cell, respectively.OutputFor each test case, output "YES" if the grid is made up of L-shape that don't share edges or corners, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 106 10........**.**......*..*..*.........**......*.....*..**....**6 10....*...**.**......*..*..*.........**......*.....*..**....**3 3...***...4 4.*..**....**..*.5 4.*..**........**..*.3 2.****.2 3*...**3 2..***.3 3.***.***.3 3..*.**..*Output YES NO NO NO YES NO NO YES NO NO
106 10........**.**......*..*..*.........**......*.....*..**....**6 10....*...**.**......*..*..*.........**......*.....*..**....**3 3...***...4 4.*..**....**..*.5 4.*..**........**..*.3 2.****.2 3*...**3 2..***.3 3.***.***.3 3..*.**..*
YES NO NO NO YES NO NO YES NO NO
1 second
256 megabytes
['dfs and similar', 'implementation', '*1700']
E. Counting Rectanglestime limit per test6 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n rectangles, the i-th rectangle has height h_i and width w_i.You are asked q queries of the form h_s \ w_s \ h_b \ w_b. For each query output, the total area of rectangles you own that can fit a rectangle of height h_s and width w_s while also fitting in a rectangle of height h_b and width w_b. In other words, print \sum h_i \cdot w_i for i such that h_s < h_i < h_b and w_s < w_i < w_b. Please note, that if two rectangles have the same height or the same width, then they cannot fit inside each other. Also note that you cannot rotate rectangles.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).InputThe first line of the input contains an integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case two integers n, q (1 \leq n \leq 10^5; 1 \leq q \leq 10^5) — the number of rectangles you own and the number of queries.Then n lines follow, each containing two integers h_i, w_i (1 \leq h_i, w_i \leq 1000) — the height and width of the i-th rectangle.Then q lines follow, each containing four integers h_s, w_s, h_b, w_b (1 \leq h_s < h_b,\ w_s < w_b \leq 1000) — the description of each query.The sum of q over all test cases does not exceed 10^5, and the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output q lines, the i-th line containing the answer to the i-th query.ExampleInput 32 12 33 21 1 3 45 51 12 23 34 45 53 3 6 62 1 4 51 1 2 101 1 100 1001 1 3 33 1999 999999 999999 9981 1 1000 1000Output 6 41 9 0 54 4 2993004 Note In the first test case, there is only one query. We need to find the sum of areas of all rectangles that can fit a 1 \times 1 rectangle inside of it and fit into a 3 \times 4 rectangle.Only the 2 \times 3 rectangle works, because 1 < 2 (comparing heights) and 1 < 3 (comparing widths), so the 1 \times 1 rectangle fits inside, and 2 < 3 (comparing heights) and 3 < 4 (comparing widths), so it fits inside the 3 \times 4 rectangle. The 3 \times 2 rectangle is too tall to fit in a 3 \times 4 rectangle. The total area is 2 \cdot 3 = 6.
32 12 33 21 1 3 45 51 12 23 34 45 53 3 6 62 1 4 51 1 2 101 1 100 1001 1 3 33 1999 999999 999999 9981 1 1000 1000
6 41 9 0 54 4 2993004
6 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'implementation', '*1600']
D. Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The value of the line is the sum of each person's count.For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are [0, 3, 2, 3, 4], and the value is 0+3+2+3+4=12.You are given the initial arrangement of people in the line. For each k from 1 to n, determine the maximum value of the line if you can change the direction of at most k people.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2\cdot10^5) — the length of the line.The following line contains a string consisting of n characters, each of which is either L or R, representing a person facing left or right, respectively — the description of the line.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).OutputFor each test case, output n space-separated non-negative integers — the maximum value of the line if you can change the direction of at most k people for each k from 1 to n, inclusive.ExampleInput 63LLR5LRRLL1L12LRRRLLLRLLRL10LLLLLRRRRR9LRLRLRLRLOutput 3 5 5 16 16 16 16 16 0 86 95 98 101 102 102 102 102 102 102 102 102 29 38 45 52 57 62 65 68 69 70 44 50 54 56 56 56 56 56 56 NoteIn the first test case: k=1: change the direction of 1 person to make the line RLR. The total value is 2+1+0=3. k=2: change the direction of 2 people to make the line RLL. The total value is 2+1+2=5. k=3: change the direction of 2 people to make the line RLL. The total value is 2+1+2=5. Note that you have to change the direction of at most k people. In the second test case, it is optimal to only change the direction of the first person for all k from 1 to 5 (that is, make the line RRRLL).
63LLR5LRRLL1L12LRRRLLLRLLRL10LLLLLRRRRR9LRLRLRLRL
3 5 5 16 16 16 16 16 0 86 95 98 101 102 102 102 102 102 102 102 102 29 38 45 52 57 62 65 68 69 70 44 50 54 56 56 56 56 56 56
2 seconds
256 megabytes
['greedy', 'sortings', '*1100']
C. Word Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThree guys play a game: first, each person writes down n distinct words of length 3. Then, they total up the number of points as follows: if a word was written by one person — that person gets 3 points, if a word was written by two people — each of the two gets 1 point, if a word was written by all — nobody gets any points. In the end, how many points does each player have?InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 1000) — the number of words written by each person.The following three lines each contain n distinct strings — the words written by each person. Each string consists of 3 lowercase English characters.OutputFor each test case, output three space-separated integers — the number of points each of the three guys earned. You should output the answers in the same order as the input; the i-th integer should be the number of points earned by the i-th guy.ExampleInput 31abcdefabc3orz for qaqqaq orz forcod for ces5iat roc hem ica llybac ter iol ogi stsbac roc lly iol iatOutput 1 3 1 2 2 6 9 11 5 NoteIn the first test case: The word \texttt{abc} was written by the first and third guys — they each get 1 point. The word \texttt{def} was written by the second guy only — he gets 3 points.
31abcdefabc3orz for qaqqaq orz forcod for ces5iat roc hem ica llybac ter iol ogi stsbac roc lly iol iat
1 3 1 2 2 6 9 11 5
1 second
256 megabytes
['data structures', 'implementation', '*800']
B. Colourblindnesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a grid with 2 rows and n columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 100) — the number of columns of the grid.The following two lines each contain a string consisting of n characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.OutputFor each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 62RGRB4GRBGGBGB5GGGGGBBBBB7BBBBBBBRRRRRRR8RGBRRGBRRGGRRBGR1GGOutput YES NO YES NO YES YES NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.
62RGRB4GRBGGBGB5GGGGGBBBBB7BBBBBBBRRRRRRR8RGBRRGBRRGGRRBGR1GG
YES NO YES NO YES YES
1 second
256 megabytes
['implementation', '*800']
A. Spell Checktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTimur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.Today he wrote string s of length n consisting only of uppercase or lowercase Latin letters. He asks you to check if s is the correct spelling of his name.InputThe first line of the input contains an integer t (1 \leq t \leq 10^3) — the number of test cases.The first line of each test case contains an integer n (1 \leq n \leq 10) — the length of string s.The second line of each test case contains a string s consisting of only uppercase or lowercase Latin characters.OutputFor each test case, output "YES" (without quotes) if s satisfies the condition, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 105Timur5miurT5Trumi5mriTu5timur4Timr6Timuur10codeforces10TimurTimur5TIMUROutput YES YES YES YES NO NO NO NO NO NO
105Timur5miurT5Trumi5mriTu5timur4Timr6Timuur10codeforces10TimurTimur5TIMUR
YES YES YES YES NO NO NO NO NO NO
1 second
256 megabytes
['implementation', '*800']
F. Matching Reductiontime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph with n_1 vertices in the first part, n_2 vertices in the second part, and m edges. The maximum matching in this graph is the maximum possible (by size) subset of edges of this graph such that no vertex is incident to more than one chosen edge.You have to process two types of queries to this graph: 1 — remove the minimum possible number of vertices from this graph so that the size of the maximum matching gets reduced exactly by 1, and print the vertices that you have removed. Then, find any maximum matching in this graph and print the sum of indices of edges belonging to this matching; 2 — query of this type will be asked only after a query of type 1. As the answer to this query, you have to print the edges forming the maximum matching you have chosen in the previous query. Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query. Use functions fflush in C++ and BufferedWriter.flush in Java languages after each writing in your program.InputThe first line contains four integers n_1, n_2, m and q (1 \le n_1, n_2 \le 2 \cdot 10^5; 1 \le m \le \min(n_1 \cdot n_2, 2 \cdot 10^5); 1 \le q \le 2 \cdot 10^5).Then m lines follow. The i-th of them contains two integers x_i and y_i (1 \le x_i \le n_1; 1 \le y_i \le n_2) meaning that the i-th edge connects the vertex x_i in the first part and the vertex y_i in the second part. There are no pairs of vertices that are connected by more than one edge.Then q lines follow. The i-th of them contains one integer, 1 or 2, denoting the i-th query. Additional constraints on queries: the number of queries of type 1 won't exceed the size of the maximum matching in the initial graph; the number of queries of type 2 won't exceed 3; each query of type 2 is preceded by a query of type 1; your solution is allowed to read the i-th query only after printing the answer for the (i-1)-th query and flushing the output. OutputFor a query of type 1, print the answer in three lines as follows: the first line should contain the number of vertices you remove; the second line should contain the indices of vertices you remove, as follows: if you remove the vertex x from the left part, print x; if you remove the vertex y from the right part, print -y (negative index); the third line should contain the sum of indices of edges in some maximum matching in the resulting graph. The edges are numbered from 1 to m. For a query of type 2, print the answer in two lines as follows: the first line should contain the size of the maximum matching; the second line should contain the indices of the edges belonging to the maximum matching. Note that the sum of these indices should be equal to the number you printed at the end of the previous query of type 1; After printing the answer to a query, don't forget to flush the output.ExampleInput 3 4 4 4 2 2 1 3 2 1 3 4 1 2 1 2 Output 1 -4 3 === 2 1 2 === 1 2 2 === 1 2 NoteIn this problem, you may receive the verdict "Idleness Limit Exceeded" since it is in online mode. If it happens, it means that either the output format is wrong, or you don't meet some constraint of the problem. You may treat this verdict as "Wrong Answer".For your convenience, the output for queries in the example is separated by the line ===. Don't print this line in your program, it is done only to make sure that it's easy to distinguish between answers for different queries in the statement.
3 4 4 4 2 2 1 3 2 1 3 4 1 2 1 2
1 -4 3 === 2 1 2 === 1 2 2 === 1 2
8 seconds
512 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'flows', 'graph matchings', 'graphs', 'interactive', '*2800']
E. Prefix Function Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase Latin letters.You are asked q queries about it: given another string t, consisting of lowercase Latin letters, perform the following steps: concatenate s and t; calculate the prefix function of the resulting string s+t; print the values of the prefix function on positions |s|+1, |s|+2, \dots, |s|+|t| (|s| and |t| denote the lengths of strings s and t, respectively); revert the string back to s. The prefix function of a string a is a sequence p_1, p_2, \dots, p_{|a|}, where p_i is the maximum value of k such that k < i and a[1..k]=a[i-k+1..i] (a[l..r] denotes a contiguous substring of a string a from a position l to a position r, inclusive). In other words, it's the longest proper prefix of the string a[1..i] that is equal to its suffix of the same length.InputThe first line contains a non-empty string s (1 \le |s| \le 10^6), consisting of lowercase Latin letters.The second line contains a single integer q (1 \le q \le 10^5) — the number of queries.Each of the next q lines contains a query: a non-empty string t (1 \le |t| \le 10), consisting of lowercase Latin letters.OutputFor each query, print the values of the prefix function of a string s+t on positions |s|+1, |s|+2, \dots, |s|+|t|.ExamplesInput aba 6 caba aba bababa aaaa b forces Output 0 1 2 3 1 2 3 2 3 4 5 6 7 1 1 1 1 2 0 0 0 0 0 0 Input aacba 4 aaca cbbb aab ccaca Output 2 2 3 1 0 0 0 0 2 2 0 0 0 1 0 1
aba 6 caba aba bababa aaaa b forces
0 1 2 3 1 2 3 2 3 4 5 6 7 1 1 1 1 2 0 0 0 0 0 0
2 seconds
256 megabytes
['dfs and similar', 'dp', 'hashing', 'string suffix structures', 'strings', 'trees', '*2200']
D. Maximum ANDtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, consisting of n integers each.Let's define a function f(a, b) as follows: let's define an array c of size n, where c_i = a_i \oplus b_i (\oplus denotes bitwise XOR); the value of the function is c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n (i.e. bitwise AND of the entire array c). Find the maximum value of the function f(a, b) if you can reorder the array b in an arbitrary way (leaving the initial order is also an option).InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains one integer n (1 \le n \le 10^5) — the size of arrays a and b.The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i < 2^{30}).The third line contains n integers b_1, b_2, \dots, b_n (0 \le b_i < 2^{30}).The sum of n over all test cases does not exceed 10^5.OutputFor each test case print one integer — the maximum value of the function f(a, b) if you can reorder the array b in an arbitrary way.ExampleInput 351 0 0 3 32 3 2 1 031 1 10 0 380 1 2 3 4 5 6 77 6 5 4 3 2 1 0Output 2 0 7
351 0 0 3 32 3 2 1 031 1 10 0 380 1 2 3 4 5 6 77 6 5 4 3 2 1 0
2 0 7
3 seconds
256 megabytes
['bitmasks', 'dfs and similar', 'divide and conquer', 'greedy', 'sortings', '*1800']
C. Min-Max Array Transformationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n, which is sorted in non-descending order. You decided to perform the following steps to create array b_1, b_2, \dots, b_n: Create an array d consisting of n arbitrary non-negative integers. Set b_i = a_i + d_i for each b_i. Sort the array b in non-descending order. You are given the resulting array b. For each index i, calculate what is the minimum and maximum possible value of d_i you can choose in order to get the given array b.Note that the minimum (maximum) d_i-s are independent of each other, i. e. they can be obtained from different possible arrays d.InputThe first line contains the single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of arrays a, b and d.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9; a_i \le a_{i+1}) — the array a in non-descending order.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9; b_i \le b_{i+1}) — the array b in non-descending order.Additional constraints on the input: there is at least one way to obtain the array b from the a by choosing an array d consisting of non-negative integers; the sum of n doesn't exceed 2 \cdot 10^5. OutputFor each test case, print two lines. In the first line, print n integers d_1^{min}, d_2^{min}, \dots, d_n^{min}, where d_i^{min} is the minimum possible value you can add to a_i.Secondly, print n integers d_1^{max}, d_2^{max}, \dots, d_n^{max}, where d_i^{max} is the maximum possible value you can add to a_i.All d_i^{min} and d_i^{max} values are independent of each other. In other words, for each i, d_i^{min} is just the minimum value among all possible values of d_i.ExampleInput 432 3 57 11 1311000500041 2 3 41 2 3 4410 20 30 4022 33 33 55Output 5 4 2 11 10 8 4000 4000 0 0 0 0 0 0 0 0 12 2 3 15 23 13 3 15 NoteIn the first test case, in order to get d_1^{min} = 5, we can choose, for example, d = [5, 10, 6]. Then b = [2+5,3+10,5+6] = [7,13,11] = [7,11,13].For d_2^{min} = 4, we can choose d = [9, 4, 8]. Then b = [2+9,3+4,5+8] = [11,7,13] = [7,11,13].
432 3 57 11 1311000500041 2 3 41 2 3 4410 20 30 4022 33 33 55
5 4 2 11 10 8 4000 4000 0 0 0 0 0 0 0 0 12 2 3 15 23 13 3 15
2 seconds
256 megabytes
['binary search', 'greedy', 'two pointers', '*1400']
B. Deadly Lasertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe robot is placed in the top left corner of a grid, consisting of n rows and m columns, in a cell (1, 1).In one step, it can move into a cell, adjacent by a side to the current one: (x, y) \rightarrow (x, y + 1); (x, y) \rightarrow (x + 1, y); (x, y) \rightarrow (x, y - 1); (x, y) \rightarrow (x - 1, y). The robot can't move outside the grid.The cell (s_x, s_y) contains a deadly laser. If the robot comes into some cell that has distance less than or equal to d to the laser, it gets evaporated. The distance between two cells (x_1, y_1) and (x_2, y_2) is |x_1 - x_2| + |y_1 - y_2|.Print the smallest number of steps that the robot can take to reach the cell (n, m) without getting evaporated or moving outside the grid. If it's not possible to reach the cell (n, m), print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than d to the laser.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The only line of each testcase contains five integers n, m, s_x, s_y, d (2 \le n, m \le 1000; 1 \le s_x \le n; 1 \le s_y \le m; 0 \le d \le n + m) — the size of the grid, the cell that contains the laser and the evaporating distance of the laser.The laser is neither in the starting cell, nor in the ending cell ((s_x, s_y) \neq (1, 1) and (s_x, s_y) \neq (n, m)). The starting cell (1, 1) always has distance greater than d to the laser (|s_x - 1| + |s_y - 1| > d).OutputFor each testcase, print a single integer. If it's possible to reach the cell (n, m) from (1, 1) without getting evaporated or moving outside the grid, then print the smallest amount of steps it can take the robot to reach it. Otherwise, print -1.ExampleInput 32 3 1 3 02 3 1 3 15 5 3 4 1Output 3 -1 8
32 3 1 3 02 3 1 3 15 5 3 4 1
3 -1 8
2 seconds
256 megabytes
['implementation', '*1000']
A. Imagetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have an image file of size 2 \times 2, consisting of 4 pixels. Each pixel can have one of 26 different colors, denoted by lowercase Latin letters.You want to recolor some of the pixels of the image so that all 4 pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).What is the minimum number of moves you have to make in order to fulfill your goal?InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.OutputFor each test case, print one integer — the minimum number of moves you have to make so that all 4 pixels of the image have the same color.ExampleInput 5rbbrccwbaaaaabcdyyxxOutput 1 2 0 3 1 NoteLet's analyze the test cases of the example.In the first test case, you can paint the bottom left pixel and the top right pixel (which share the same color) into the color r, so all pixels have this color.In the second test case, two moves are enough: paint both top pixels, which have the same color c, into the color b; paint the bottom left pixel into the color b. In the third test case, all pixels already have the same color.In the fourth test case, you may leave any of the pixels unchanged, and paint all three other pixels into the color of that pixel in three moves.In the fifth test case, you can paint both top pixels into the color x.
5rbbrccwbaaaaabcdyyxx
1 2 0 3 1
2 seconds
512 megabytes
['greedy', 'implementation', '*800']
E. Misha and Paintingstime limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMisha has a square n \times n matrix, where the number in row i and column j is equal to a_{i, j}. Misha wants to modify the matrix to contain exactly k distinct integers. To achieve this goal, Misha can perform the following operation zero or more times: choose any square submatrix of the matrix (you choose (x_1,y_1), (x_2,y_2), such that x_1 \leq x_2, y_1 \leq y_2, x_2 - x_1 = y_2 - y_1, then submatrix is a set of cells with coordinates (x, y), such that x_1 \leq x \leq x_2, y_1 \leq y \leq y_2), choose an integer k, where 1 \leq k \leq n^2, replace all integers in the submatrix with k. Please find the minimum number of operations that Misha needs to achieve his goal.InputThe first input line contains two integers n and k (1 \leq n \leq 500, 1 \leq k \leq n^2)  — the size of the matrix and the desired amount of distinct elements in the matrix.Then n lines follows. The i-th of them contains n integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, n} (1 \leq a_{i,j} \leq n^2) — the elements of the i-th row of the matrix.OutputOutput one integer — the minimum number of operations required.ExamplesInput 3 4 1 1 1 1 1 2 3 4 5 Output 1Input 3 2 2 1 3 2 1 1 3 1 2 Output 2Input 3 3 1 1 1 1 1 2 2 2 2 Output 1Input 3 2 1 1 1 1 2 1 2 2 2 Output 0NoteIn the first test case the answer is 1, because one can change the value in the bottom right corner of the matrix to 1. The resulting matrix can be found below: 111112341 In the second test case the answer is 2. First, one can change the entire matrix to contain only 1s, and the change the value of any single cell to 2. One of the possible resulting matrices is displayed below: 111111112
3 4 1 1 1 1 1 2 3 4 5
1
3.5 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', 'math', '*2700']
D2. Xor-Subsequence (hard version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is the hard version of the problem. The only difference is that in this version a_i \le 10^9.You are given an array of n integers a_0, a_1, a_2, \ldots a_{n - 1}. Bryap wants to find the longest beautiful subsequence in the array.An array b = [b_0, b_1, \ldots, b_{m-1}], where 0 \le b_0 < b_1 < \ldots < b_{m - 1} < n, is a subsequence of length m of the array a.Subsequence b = [b_0, b_1, \ldots, b_{m-1}] of length m is called beautiful, if the following condition holds: For any p (0 \le p < m - 1) holds: a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p. Here a \oplus b denotes the bitwise XOR of a and b. For example, 2 \oplus 4 = 6 and 3 \oplus 1=2.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.InputThe first line contains a single integer t (1 \leq t \leq 10^5)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 3 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_0,a_1,...,a_{n-1} (0 \leq a_i \leq 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case print a single integer — the length of the longest beautiful subsequence.ExampleInput 321 255 2 4 3 1103 8 8 2 9 1 6 2 8 3Output 2 3 6 NoteIn the first test case, we can pick the whole array as a beautiful subsequence because 1 \oplus 1 < 2 \oplus 0.In the second test case, we can pick elements with indexes 1, 2 and 4 (in 0 indexation). For this elements holds: 2 \oplus 2 < 4 \oplus 1 and 4 \oplus 4 < 1 \oplus 2.
321 255 2 4 3 1103 8 8 2 9 1 6 2 8 3
2 3 6
2 seconds
512 megabytes
['bitmasks', 'data structures', 'dp', 'strings', 'trees', '*2400']
D1. Xor-Subsequence (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIt is the easy version of the problem. The only difference is that in this version a_i \le 200.You are given an array of n integers a_0, a_1, a_2, \ldots a_{n - 1}. Bryap wants to find the longest beautiful subsequence in the array.An array b = [b_0, b_1, \ldots, b_{m-1}], where 0 \le b_0 < b_1 < \ldots < b_{m - 1} < n, is a subsequence of length m of the array a.Subsequence b = [b_0, b_1, \ldots, b_{m-1}] of length m is called beautiful, if the following condition holds: For any p (0 \le p < m - 1) holds: a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p. Here a \oplus b denotes the bitwise XOR of a and b. For example, 2 \oplus 4 = 6 and 3 \oplus 1=2.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.InputThe first line contains a single integer t (1 \leq t \leq 10^5)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 3 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_0,a_1,...,a_{n-1} (0 \leq a_i \leq 200) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case print a single integer — the length of the longest beautiful subsequence.ExampleInput 321 255 2 4 3 1103 8 8 2 9 1 6 2 8 3Output 2 3 6 NoteIn the first test case, we can pick the whole array as a beautiful subsequence because 1 \oplus 1 < 2 \oplus 0.In the second test case, we can pick elements with indexes 1, 2 and 4 (in 0-indexation). For this elements holds: 2 \oplus 2 < 4 \oplus 1 and 4 \oplus 4 < 1 \oplus 2.
321 255 2 4 3 1103 8 8 2 9 1 6 2 8 3
2 3 6
2 seconds
512 megabytes
['bitmasks', 'brute force', 'dp', 'strings', 'trees', 'two pointers', '*1800']
C. Cornerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix consisting of n rows and m columns. Each cell of this matrix contains 0 or 1.Let's call a square of size 2 \times 2 without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing 1 and replace all numbers in it with zeroes.Find the maximum number of operations that you can do with the given matrix.InputThe first line contains one integer t (1 \leq t \leq 500) — the number of test cases. Then follow the descriptions of each test case.The first line of each test case contains two integers n and m (2 \leq n, m \leq 500) — the size of the matrix.Each of the following n lines contains a binary string of length m — the description of the matrix.It is guaranteed that the sum of n and the sum of m over all test cases does not exceed 1000.OutputFor each test case output the maximum number of operations you can do with the given matrix.ExampleInput 44 31011110111103 41110011101112 200002 21111Output 8 9 0 2 NoteIn the first testcase one of the optimal sequences of operations is the following (bold font shows l-shape figure on which operation was performed): Matrix before any operation was performed: 101111011110 Matrix after 1 operation was performed: 100101011110 Matrix after 2 operations were performed: 100100011110 Matrix after 3 operations were performed: 100100010110 Matrix after 4 operations were performed: 100000010110 Matrix after 5 operations were performed: 100000010100 Matrix after 6 operations were performed: 100000000100 Matrix after 7 operations were performed: 000000000100 Matrix after 8 operations were performed: 000000000000 In the third testcase from the sample we can not perform any operation because the matrix doesn't contain any ones.In the fourth testcase it does not matter which L-shape figure we pick in our first operation. We will always be left with single one. So we will perform 2 operations.
44 31011110111103 41110011101112 200002 21111
8 9 0 2
1 second
256 megabytes
['greedy', 'implementation', '*1200']
B. Interesting Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a that contains n integers. You can choose any proper subsegment a_l, a_{l + 1}, \ldots, a_r of this array, meaning you can choose any two integers 1 \le l \le r \le n, where r - l + 1 < n. We define the beauty of a given subsegment as the value of the following expression:\max(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) - \min(a_{1}, a_{2}, \ldots, a_{l-1}, a_{r+1}, a_{r+2}, \ldots, a_{n}) + \max(a_{l}, \ldots, a_{r}) - \min(a_{l}, \ldots, a_{r}).Please find the maximum beauty among all proper subsegments.InputThe first line contains one integer t (1 \leq t \leq 1000) — the number of test cases. Then follow the descriptions of each test case.The first line of each test case contains a single integer n (4 \leq n \leq 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_{i} \leq 10^9) — the elements of the given array.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each testcase print a single integer — the maximum beauty of a proper subsegment.ExampleInput 4 8 1 2 2 3 1 5 6 1 5 1 2 3 100 200 4 3 3 3 3 6 7 8 3 1 1 8 Output 9 297 0 14 NoteIn the first test case, the optimal segment is l = 7, r = 8. The beauty of this segment equals to (6 - 1) + (5 - 1) = 9.In the second test case, the optimal segment is l = 2, r = 4. The beauty of this segment equals (100 - 2) + (200 - 1) = 297.
4 8 1 2 2 3 1 5 6 1 5 1 2 3 100 200 4 3 3 3 3 6 7 8 3 1 1 8
9 297 0 14
1 second
256 megabytes
['brute force', 'data structures', 'greedy', 'math', 'sortings', '*800']
A. Burenka Plays with Fractionstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBurenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions (\frac{a}{b} and \frac{c}{d}) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by 0). Now she wants know the minimal number of claps to make her fractions equal (by value). Please help her and find the required number of claps!InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases. Then follow the descriptions of each test case.The only line of each test case contains four integers a, b, c and d (0 \leq a, c \leq 10^9, 1 \leq b, d \leq 10^9) — numerators and denominators of the fractions given to Burenka initially.OutputFor each test case print a single integer — the minimal number of claps Burenka needs to make her fractions equal.ExampleInput 82 1 1 16 3 2 11 2 2 30 1 0 1000 1 228 179100 3 25 6999999999 300000000 666666666 10000000033 15 0 84Output 1 0 2 0 1 1 1 1 NoteIn the first case, Burenka can multiply c by 2, then the fractions will be equal.In the second case, fractions are already equal.In the third case, Burenka can multiply a by 4, then b by 3. Then the fractions will be equal (\frac{1 \cdot 4}{2 \cdot 3} = \frac{2}{3}).
82 1 1 16 3 2 11 2 2 30 1 0 1000 1 228 179100 3 25 6999999999 300000000 666666666 10000000033 15 0 84
1 0 2 0 1 1 1 1
1 second
256 megabytes
['math', 'number theory', '*900']