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. No Prime Differencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given integers n and m. Fill an n by m grid with the integers 1 through n\cdot m, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side. It can be shown that under the given constraints, there is always a solution.InputThe first line of the input contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of the test cases follows.The first and only line of each test case contains two integers n and m (4 \le n, m \le 1000) — the dimensions of the grid.It is guaranteed that the sum of n\cdot m over all test cases does not exceed 10^6.OutputFor each test case, output n lines of m integers each, representing the final grid. Every number from 1 to n\cdot m should appear exactly once in the grid.The extra spaces and blank lines in the sample output below are only present to make the output easier to read, and are not required.If there are multiple solutions, print any of them.ExampleInput
34 45 76 4Output
16 7 1 9
12 8 2 3
13 4 10 11
14 5 6 15
29 23 17 9 5 6 2
33 27 21 15 11 7 1
32 31 25 19 20 16 10
26 30 24 18 14 8 4
35 34 28 22 13 12 3
2 3 7 11
8 9 1 10
17 13 5 4
18 14 6 12
19 23 15 21
20 24 16 22
NoteThe first sample case corresponds to the picture above. The only absolute differences between adjacent elements in this grid are 1, 4, 6, 8, and 9, none of which are prime. | 34 45 76 4 | 16 7 1 9 12 8 2 3 13 4 10 11 14 5 6 15 29 23 17 9 5 6 2 33 27 21 15 11 7 1 32 31 25 19 20 16 10 26 30 24 18 14 8 4 35 34 28 22 13 12 3 2 3 7 11 8 9 1 10 17 13 5 4 18 14 6 12 19 23 15 21 20 24 16 22 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', 'number theory', '*1400'] |
B. Minimize Permutation Subarraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of size n. You want to minimize the number of subarrays of p that are permutations. In order to do so, you must perform the following operation exactly once: Select integers i, j, where 1 \le i, j \le n, then Swap p_i and p_j. For example, if p = [5, 1, 4, 2, 3] and we choose i = 2, j = 3, the resulting array will be [5, 4, 1, 2, 3]. If instead we choose i = j = 5, the resulting array will be [5, 1, 4, 2, 3].Which choice of i and j will minimize the number of subarrays that are permutations?A permutation of length n 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 array a is a subarray of an array b if a can be obtained from b by the deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — 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 2\cdot 10^5) — the size of the permutation.The next line of each test case contains n integers p_1, p_2, \ldots p_n (1 \le p_i \le n, all p_i are distinct) — the elements of the permutation p.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output two integers i and j (1 \le i, j \le n) — the indices to swap in p.If there are multiple solutions, print any of them.ExampleInput
831 2 331 3 251 3 2 5 464 5 6 1 2 398 7 6 3 2 1 4 5 9107 10 5 1 9 8 3 2 6 4108 5 10 9 2 1 3 4 6 7102 3 5 7 10 1 8 6 4 9Output
2 3
1 1
5 2
1 4
9 5
8 8
6 10
5 4
NoteFor the first test case, there are four possible arrays after the swap: If we swap p_1 and p_2, we get the array [2, 1, 3], which has 3 subarrays that are permutations ([1], [2, 1], [2, 1, 3]). If we swap p_1 and p_3, we get the array [3, 2, 1], which has 3 subarrays that are permutations ([1], [2, 1], [3, 2, 1]). If we swap p_2 and p_3, we get the array [1, 3, 2], which has 2 subarrays that are permutations ([1], [1, 3, 2]). If we swap any element with itself, we get the array [1, 2, 3], which has 3 subarrays that are permutations ([1], [1, 2], [1, 2, 3]). So the best swap to make is positions 2 and 3.For the third sample case, after we swap elements at positions 2 and 5, the resulting array is [1, 4, 2, 5, 3]. The only subarrays that are permutations are [1] and [1, 4, 2, 5, 3]. We can show that this is minimal. | 831 2 331 3 251 3 2 5 464 5 6 1 2 398 7 6 3 2 1 4 5 9107 10 5 1 9 8 3 2 6 4108 5 10 9 2 1 3 4 6 7102 3 5 7 10 1 8 6 4 9 | 2 3 1 1 5 2 1 4 9 5 8 8 6 10 5 4 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1100'] |
A. Blackboard Listtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo integers were written on a blackboard. After that, the following step was carried out n-2 times: Select any two integers on the board, and write the absolute value of their difference on the board. After this process was complete, the list of n integers was shuffled. You are given the final list. Recover one of the initial two numbers. You do not need to recover the other one.You are guaranteed that the input can be generated using the above process.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 100) — the size of the final list.The next line of each test case contains n integers a_1, a_2, \ldots a_n (-10^9 \le a_i \le 10^9) — the shuffled list of numbers written on the blackboard.It is guaranteed that the input was generated using the process described above.OutputFor each test case, output a single integer x — one of the two initial numbers on the blackboard.If there are multiple solutions, print any of them.ExampleInput
939 2 7315 -4 114-9 1 11 -1053 0 0 0 378 16 8 0 8 16 840 0 0 01027 1 24 28 2 -1 26 25 28 276600000000 800000000 0 -200000000 1000000000 80000000030 -1000000000 1000000000Output
9
11
-9
3
8
0
-1
600000000
0
NoteFor the first test case, a can be produced by starting with either 9 and 2, and then writing down |9-2|=7, or starting with 9 and 7 and writing down |9-7|=2. So 2, 7, and 9 are all valid answers, because they all appear in at least one valid pair.For the second test case, we can show that the two initial numbers must have been -4 and 11.For the fourth test case, the starting numbers could have been either 3 and 3, or 3 and 0, so 3 and 0 are both valid answers.For the fifth test case, we can show that the starting numbers were 8 and 16. | 939 2 7315 -4 114-9 1 11 -1053 0 0 0 378 16 8 0 8 16 840 0 0 01027 1 24 28 2 -1 26 25 28 276600000000 800000000 0 -200000000 1000000000 80000000030 -1000000000 1000000000 | 9 11 -9 3 8 0 -1 600000000 0 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
F. Editorial for Twotime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland Intercollegiate Contest has just finished. Monocarp and Polycarp, as the jury, are going to conduct an editorial. Unfortunately, the time is limited, since they have to finish before the closing ceremony.There were n problems in the contest. The problems are numbered from 1 to n. The editorial for the i-th problem takes a_i minutes. Monocarp and Polycarp are going to conduct an editorial for exactly k of the problems.The editorial goes as follows. They have a full problemset of n problems before them, in order. They remove n - k problems without changing the order of the remaining k problems. Then, Monocarp takes some prefix of these k problems (possibly, an empty one or all problems). Polycarp takes the remaining suffix of them. After that, they go to different rooms and conduct editorials for their problems in parallel. So, the editorial takes as much time as the longer of these two does.Please, help Monocarp and Polycarp to choose the problems and the split in such a way that the editorial finishes as early as possible. Print the duration of the editorial.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers n and k (1 \le k \le n \le 3 \cdot 10^5) — the number of problems in the full problemset and the number of problems Monocarp and Polycarp are going to conduct an editorial for.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the time each editorial takes.The sum of n over all testcases doesn't exceed 3 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest amount of time the editorial takes, if Monocarp and Polycarp can choose which k of n problems to conduct an editorial for and how to split them among themselves.ExampleInput
65 41 10 1 1 15 31 20 5 15 35 31 20 3 15 510 610 8 20 14 3 8 6 4 16 1110 59 9 2 13 15 19 4 9 13 121 11Output
2
6
5
21
18
1
| 65 41 10 1 1 15 31 20 5 15 35 31 20 3 15 510 610 8 20 14 3 8 6 4 16 1110 59 9 2 13 15 19 4 9 13 121 11 | 2 6 5 21 18 1 | 4 seconds | 256 megabytes | ['binary search', 'data structures', 'greedy', 'implementation', '*2400'] |
E. Playoff Fixingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output2^k teams participate in a playoff tournament. The teams are numbered from 1 to 2^k, in order of decreasing strength. So, team 1 is the strongest one, team 2^k is the weakest one. A team with a smaller number always defeats a team with a larger number.First of all, the teams are arranged in some order during a procedure called seeding. Each team is assigned another unique value from 1 to 2^k, called a seed, that represents its starting position in the playoff.The tournament consists of 2^k - 1 games. They are held as follows: the teams are split into pairs: team with seed 1 plays against team with seed 2, team with seed 3 plays against team with seed 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated.After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "seed 1 vs seed 2" plays against the winner of the game "seed 3 vs seed 4", then the winner of the game "seed 5 vs seed 6" plays against the winner of the game "seed 7 vs seed 8", and so on. This process repeats until only one team remains.After the tournament ends, the teams are assigned places according to the tournament phase when they were eliminated. In particular: the winner of the tournament gets place 1; the team eliminated in the finals gets place 2; both teams eliminated in the semifinals get place 3; all teams eliminated in the quarterfinals get place 5; all teams eliminated in the 1/8 finals get place 9, and so on. Now that we established the rules, we do a little rigging. In particular, we want: team 1 (not team with seed 1) to take place 1; team 2 to take place 2; teams 3 and 4 to take place 3; teams from 5 to 8 to take place 5, and so on. For example, this picture describes one of the possible ways the tournament can go with k = 3, and the resulting places of the teams: Some seeds are already reserved for some teams (we are not the only ones rigging the tournament, apparently). We have to fill the rest of the seeds with the remaining teams to achieve the desired placements. How many ways are there to do that? Since that value might be large, print it modulo 998\,244\,353.InputThe first line contains a single integer k (0 \le k \le 19) — there are 2^k teams.The second line contains 2^k integers a_1, a_2, \dots, a_{2^k} (a_i = -1 or 1 \le a_i \le 2^k). If a_i \ne -1, then team a_i has seed i. Otherwise, the seed i is not reserved for any team.All values, that are not -1, are distinct.OutputPrint a single integer — the number of ways to fill the non-reserved seeds so that the tournament goes as planned, modulo 998\,244\,353.ExamplesInput
2
1 2 3 4
Output
0
Input
2
1 3 4 2
Output
1
Input
1
-1 -1
Output
2
Input
2
-1 -1 -1 -1
Output
16
Input
3
-1 -1 -1 -1 2 -1 -1 -1
Output
768
Input
0
1
Output
1
| 2
1 2 3 4
| 0 | 2 seconds | 256 megabytes | ['combinatorics', 'trees', '*2200'] |
D. Bracket Coloringtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: the bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); the bracket sequences ")(", "(" and ")" are not. A bracket sequence is called beautiful if one of the following conditions is satisfied: it is a regular bracket sequence; if the order of the characters in this sequence is reversed, it becomes a regular bracket sequence. For example, the bracket sequences "()()", "(())", ")))(((", "))()((" are beautiful.You are given a bracket sequence s. You have to color it in such a way that: every bracket is colored into one color; for every color, there is at least one bracket colored into that color; for every color, if you write down the sequence of brackets having that color in the order they appear, you will get a beautiful bracket sequence. Color the given bracket sequence s into the minimum number of colors according to these constraints, or report that it is impossible.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of characters in s. The second line contains s — a string of n characters, where each character is either "(" or ")".Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the answer as follows: if it is impossible to color the brackets according to the problem statement, print -1; otherwise, print two lines. In the first line, print one integer k (1 \le k \le n) — the minimum number of colors. In the second line, print n integers c_1, c_2, \dots, c_n (1 \le c_i \le k), where c_i is the color of the i-th bracket. If there are multiple answers, print any of them. ExampleInput
48((())))(4(())4))((3(()Output
2
2 2 2 1 2 2 2 1
1
1 1 1 1
1
1 1 1 1
-1
| 48((())))(4(())4))((3(() | 2 2 2 2 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 -1 | 2 seconds | 512 megabytes | ['constructive algorithms', 'greedy', '*1400'] |
C. Best Binary Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of the characters 0, 1 and/or ?. Let's call it a pattern.Let's say that the binary string (a string where each character is either 0 or 1) matches the pattern if you can replace each character ? with 0 or 1 (for each character, the choice is independent) so that the strings become equal. For example, 0010 matches ?01?, but 010 doesn't match 1??, ??, or ????.Let's define the cost of the binary string as the minimum number of operations of the form "reverse an arbitrary contiguous substring of the string" required to sort the string in non-descending order.You have to find a binary string with the minimum possible cost among those that match the given pattern. If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 3 \cdot 10^4) — the number of test cases.The first and only line of each test case contains the string s (1 \le |s| \le 3 \cdot 10^5) consisting of characters 0, 1, and/or ?.The sum of the string lengths over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print a binary string with the minimum possible cost among those that match the given pattern. If there are multiple answers, print any of them.ExampleInput
4??01?101001??10?0?1?10?10Output
00011
10100
111101
011110010
NoteIn the first test case of the example, the cost of the resulting string is 0.In the second test case, the cost of the resulting string is 2: we can reverse the substring from the 1-st character to the 5-th character, and we obtain the string 00101. Then we reverse the substring from the 3-rd to the 4-th character, and we obtain the string 00011, which is sorted in non-descending order. | 4??01?101001??10?0?1?10?10 | 00011 10100 111101 011110010 | 2 seconds | 256 megabytes | ['constructive algorithms', 'greedy', '*1000'] |
B. Comparison Stringtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n, where each character is either < or >.An array a consisting of n+1 elements is compatible with the string s if, for every i from 1 to n, the character s_i represents the result of comparing a_i and a_{i+1}, i. e.: s_i is < if and only if a_i < a_{i+1}; s_i is > if and only if a_i > a_{i+1}. For example, the array [1, 2, 5, 4, 2] is compatible with the string <<>>. There are other arrays with are compatible with that string, for example, [13, 37, 42, 37, 13].The cost of the array is the number of different elements in it. For example, the cost of [1, 2, 5, 4, 2] is 4; the cost of [13, 37, 42, 37, 13] is 3.You have to calculate the minimum cost among all arrays which are compatible with the given string s.InputThe first line contains one integer t (1 \le t \le 500) — the number of test cases.Each test case consists of two lines: the first line contains one integer n (1 \le n \le 100); the second line contains the string s, consisting of n characters. Each character of s is either < or >. OutputFor each test case, print one integer — the minimum cost among all arrays which are compatible with the given string s.ExampleInput
44<<>>4>><<5>>>>>7<><><><Output
3
3
6
2
NoteIn the first test case of the example, the array can be [13, 37, 42, 37, 13].In the second test case of the example, the array can be [42, 37, 13, 37, 42]. | 44<<>>4>><<5>>>>>7<><><>< | 3 3 6 2 | 2 seconds | 512 megabytes | ['greedy', '*900'] |
A. Grasshopper on a Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers x and k. Grasshopper starts in a point 0 on an OX axis. In one move, it can jump some integer distance, that is not divisible by k, to the left or to the right.What's the smallest number of moves it takes the grasshopper to reach point x? What are these moves? If there are multiple answers, print any of them.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.The only line of each testcase contains two integers x and k (1 \le x \le 100; 2 \le k \le 100) — the endpoint and the constraint on the jumps, respectively.OutputFor each testcase, in the first line, print a single integer n — the smallest number of moves it takes the grasshopper to reach point x.In the second line, print n integers, each of them not divisible by k. A positive integer would mean jumping to the right, a negative integer would mean jumping to the left. The endpoint after the jumps should be exactly x.Each jump distance should be from -10^9 to 10^9. In can be shown that, for any solution with the smallest number of jumps, there exists a solution with the same number of jumps such that each jump is from -10^9 to 10^9.It can be shown that the answer always exists under the given constraints. If there are multiple answers, print any of them.ExampleInput
310 210 33 4Output
2
7 3
1
10
1
3
| 310 210 33 4 | 2 7 3 1 10 1 3 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
B. Astrophysiciststime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn many, many years, far, far away, there will be a launch of the first flight to Mars. To celebrate the success, n astrophysicists working on the project will be given bonuses of a total value of k gold coins.You have to distribute the money among the astrophysicists, and to make it easier, you have to assign bonuses in silver coins. Each gold coin is worth g silver coins, so you have to distribute all k \cdot g silver coins among n people.Unfortunately, the company has some financial troubles right now. Therefore, instead of paying the number of silver coins written on the bonus, they decided to round this amount to the nearest integer number of gold coins.The rounding procedure is as follows. If an astrophysicist has bonus equal to x silver coins, and we denote r = x \bmod g, then: If r \geq \lceil \frac{g}{2} \rceil, the astrophysicist receives x + (g - r) silver coins; Otherwise, an astrophysicists receives x - r silver coins. Note that due to rounding, the total sum of actually paid money is not, in general, equal to k \cdot g silver coins. The operation a \bmod b denotes the remainder of the division of a by b. Sum of values before rounding has to be equal to k \cdot g silver coins, but some workers can be assigned 0 silver coins.You aim to distribute the bonuses so that the company saves as many silver coins due to rounding as possible. Please note that there is always a distribution in which the company spends no more than k \cdot g silver coins.InputIn the first line of input, there is one integer t (1 \leq t \leq 10^4) denoting the number of test cases.Each of the following t lines describes one test case and contains three integers n, k, g (1 \le n \le 10^9, 0 \le k \le 10^9, 2 \le g \le 10^9) — respectively the number of astrophysicists in the company, total number of gold coins to assign and the number of silver coins that one gold coin corresponds to.OutputIn a separate line for each test case, output a single integer — the maximum number of silver coins that could be saved due to rounding.ExampleInput
53 3 1002 1 1491 2 1336 16 673 8 22Output
100
0
26
72
176
NoteIn the first test case, one of the optimal assignments could be the following: First person: x = 30 silver coins: company pays 0, saves 30 silver coins, Second person: x = 140 silver coins: company pays 100, saves 40 silver coins, Third person: x = 130 silver coins: company pays 100, saves 30 silver coins. In the second test case, we could have the following assignment: First person: x = 8 silver coins: company pays 14, spends extra 6 silver coins, Second person: x = 6 silver coins: company pays 0, saves 6 silver coins. If the bonuses are assigned to 7 silver coins for both astrophysicists, then the company would have to pay an additional gold coin to cover the bonuses. | 53 3 1002 1 1491 2 1336 16 673 8 22 | 100 0 26 72 176 | 1 second | 256 megabytes | ['greedy', 'math', '*1100'] |
A. Destroyertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJohn is a lead programmer on a destroyer belonging to the space navy of the Confederacy of Independent Operating Systems. One of his tasks is checking if the electronic brains of robots were damaged during battles.A standard test is to order the robots to form one or several lines, in each line the robots should stand one after another. After that, each robot reports the number of robots standing in front of it in its line. An example of robots' arrangement (the front of the lines is on the left). The robots report the numbers above. The i-th robot reported number l_i. Unfortunately, John does not know which line each robot stands in, and can't check the reported numbers. Please determine if it is possible to form the lines in such a way that all reported numbers are correct, or not.InputThe first line contains a single integer t (1 \leq t \leq 100), denoting the number of test cases.The first line in each test case contains a single integer n (1 \le n \le 100) — the number of robots.The second line in each test case contains n integers l_1, l_2, \ldots, l_n (0 \leq l_i < 100), l_i is equal to the number of robots in front of the i-th robot in its line.The sum of n over all test cases won't exceed 200.OutputFor each test case, output "YES", if there exists a robot arrangement consistent with robots' reports. Otherwise, output "NO".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
560 1 2 0 1 090 0 0 0 1 1 1 2 230 0 219950 1 2 3 4Output
YES
YES
NO
NO
YES
NoteExample arrangement consistent with robot statements from the first example test case: Example arrangement consistent with robot statements from the second example is shown in the statement.In the third test case, the third robot claims that there are two machines in front of it. In such a case, the robot directly in front of it would have one machine in front. No robot claims that, so there is no valid arrangement. | 560 1 2 0 1 090 0 0 0 1 1 1 2 230 0 219950 1 2 3 4 | YES YES NO NO YES | 1 second | 256 megabytes | ['implementation', 'sortings', '*800'] |
F. Good Graphtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a bipartite graph G with the vertex set in the left part L, in the right part R, and m edges connecting these two sets. We know that |L| = |R| = n.For any subset S \subseteq L, let N(S) denote the set of all neighbors of vertices in S. We say that a subset S \subseteq L in graph G is tight if |S| = |N(S)|. We say that graph G is good if \forall_{S \subseteq L}, |S| \leq |N(S)|.Your task is to verify whether the graph is good and, if so, to optimize it. If the graph is not good, find a subset S \subseteq L such that |S| > |N(S)|. However, if the graph is good, your task is to find a good bipartite graph G' with the same set of vertices L \cup R, in which \forall_{S \subseteq L}, S is tight in G if and only if S is tight in G'. If there are multiple such graphs, choose one with the smallest possible number of edges. If there are still multiple such graphs, print any.InputThe first line of the input contains two integers n and m (1 \leq n \leq 10^3, 0 \leq m \leq n^2), separated by a single space. The number n denotes the number of vertices in each of the sets L and R, and the number m denotes the number of edges between them.The following m lines describe the edges. Each of them contains two integers l and r (1 \leq l \leq n, n+1 \leq r \leq 2 \cdot n), separated by a single space, indicating that there is an edge from vertex l \in L to vertex r \in R.OutputIf the graph G given in the input is not good, output one word "NO" in the first line of the output. In the second line of the output, output the number k, and in the third line, output k numbers l_1, l_2, \dots, l_k, separated by single spaces. These numbers should indicate that for the set S = \{l_1, l_2, \dots, l_k\}, |S| > |N(S)|.However, if the graph G given in the input is good, output one word "YES" in the first line of the output. In the second line of the output, output the number m', indicating the number of edges in the new, also good graph G'. Then, in the following m' lines, output the edges of the graph G' in the same format as given in the input.ExamplesInput
3 8
1 4
1 5
1 6
2 4
2 5
2 6
3 5
3 6
Output
YES
6
1 4
1 5
2 5
2 6
3 6
3 4
Input
3 4
1 4
1 5
2 6
3 6
Output
NO
2
2 3
NoteIn the first sample test, the graph G is good; thus, we are looking for an equivalent graph with the same tight sets. The only tight set is \{ 1, 2, 3 \}, which remains tight in the resulting graph. Moreover, no other set is tight in the resulting graph. One can prove that no graph with less than 6 edges and the same tight sets exists.In the second sample test, the graph G is not good. Set \{ 2, 3 \} has only one neighbour — vertex 6. Thus, |\{ 2, 3 \}| > |\{ 6 \}|, which is a prove that the input graph is not good. | 3 8
1 4
1 5
1 6
2 4
2 5
2 6
3 5
3 6
| YES 6 1 4 1 5 2 5 2 6 3 6 3 4 | 7 seconds | 256 megabytes | ['bitmasks', 'dfs and similar', 'graph matchings', 'graphs', 'implementation', '*3500'] |
E. Old Mobiletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring the latest mission of the starship U.S.S. Coder, Captain Jan Bitovsky was accidentally teleported to the surface of an unknown planet. Trying to find his way back, Jan found an artifact from planet Earth's ancient civilization — a mobile device capable of interstellar calls created by Byterola. Unfortunately, there was another problem. Even though Jan, as a representative of humans, knew perfectly the old notation of the cell phone numbers, the symbols on the device's keyboard were completely worn down and invisible to the human eye. The old keyboards had exactly m + 1 buttons, one for each digit from the base m numerical system, and one single backspace button allowing one to erase the last written digit (if nothing was written on the screen, then this button does nothing, but it's still counted as pressed).Jan would like to communicate with his crew. He needs to type a certain number (also from the base m numerical system, that is, digits from 0 to m - 1). He wants to know the expected number of button presses necessary to contact the U.S.S. Coder. Jan always chooses the most optimal buttons based on his current knowledge. Buttons are indistinguishable until pressed. Help him!InputIn the first line of input, there are two integer numbers n and m (1 \le n \le 10^6, 2 \le m \le 10^3) — the length of the number to U.S.S. Coder and the base of the numerical system.In the next and the last input line, there are n integers between 0 and m - 1: the number to type in the base m numerical system.OutputOutput the expected number of button presses modulo 1\,000\,000\,007.Formally, let M = 1\,000\,000\,007. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput
1 2
0
Output
666666674
Input
2 3
0 0
Output
916666678
Input
2 3
0 1
Output
500000009
NoteIn the first example, two digits (0 and 1) and a backspace button are available on the keyboard. Jan has no way of knowing which one is which, so he presses a random one. With probability \frac{1}{3}, he presses 0 and manages to type the crew's number. With probability \frac{1}{3}, he presses backspace, and nothing happens. Then with probability \frac{1}{2} he manages to press 0 (finishing the process). Otherwise, with probability \frac{1}{2}, he types 1, which he then needs to remove with backspace and hit the last button, which has to be 0. In this case, he needs 4 button presses.At last, he might press the 1 button first, also with probability \frac{1}{3}. Then, if he presses the backspace with a chance of 50\%, he is all set and only needs to press the last button (3 presses in total). In the worst case, he would press the 0 button first and need to remove both with backspace, then finally type the number 0 (5 presses in total).We get the expected value of \frac{16}{6}. The modular inverse of 6 modulo 1\;000\;000\;007 is 166666668, so 16 \cdot 166666668 = 666666674 \mod \; 1\;000\;000\;007 | 1 2
0
| 666666674 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'probabilities', '*3500'] |
D. Doctor's Brown Hypothesistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe rebels have been crushed in the most recent battle with the imperial forces, but there is a ray of new hope.Meanwhile, on one of the conquered planets, Luke was getting ready for an illegal street race (which should come as no surprise, given his family history). Luke arrived at the finish line with 88 miles per hour on his speedometer. After getting out of the car, he was greeted by a new reality. It turns out that the battle has not happened yet and will start in exactly k hours.The rebels have placed a single battleship on each of the n planets. m unidirectional wormholes connect the planets. Traversing each wormhole takes exactly one hour. Generals of the Imperium have planned the battle precisely, but their troops cannot dynamically adapt to changing circumstances. Because of this, it is enough for the rebels to move some ships around before the battle to confuse the enemy, secure victory and change the galaxy's fate.Owing to numerous strategical considerations, which we now omit, the rebels would like to choose two ships that will switch places so that both of them will be on the move for the whole time (exactly k hours). In other words, rebels look for two planets, x and y, such that paths of length k exist from x to y and from y to x.Because of the limited fuel supply, choosing one ship would also be acceptable. This ship should fly through the wormholes for k hours and then return to its initial planet.How many ways are there to choose the ships for completing the mission? InputIn the first line of input, there are three integer numbers n, m, and k (1 \leq n \leq 10^5, 0 \leq m \leq 2 \cdot 10^5, n^3 \leq k \leq 10^{18}) denoting respectively the number of planets, wormholes and hours left until the battle starts.The following m lines contain two integers each, x and y (1 \leq x, y \leq n, x \ne y), meaning that there is a wormhole from planet x to planet y. It is guaranteed that there are no two identical wormholes, i. e. for every two wormholes, either x_1 \neq x_2 or y_1 \neq y_2.OutputIn the first and only line, your program should output the number of possible ways of choosing a pair or a single warship for the mission.ExamplesInput
7 8 346
1 2
1 3
2 4
3 4
4 5
5 1
6 7
7 6
Output
5
Input
5 6 128
1 2
1 3
2 4
3 4
4 5
5 1
Output
6
Input
3 3 30
1 2
2 3
3 2
Output
2
NoteIn the first sample test, one can choose pairs of ships from the following planets: 2 and 5, 3 and 5, 1 and 4. Individual ships from planets 6 and 7 could also be chosen.In the second sample test, one can choose a pair of ships from the following planets: 2 and 3. Individual ships from planets 1, 2, 3, 4, and 5 could also be chosen.In the third sample test, there are no pairs of ships we can choose. Individual ships from planets 2 and 3 could also be chosen. | 7 8 346
1 2
1 3
2 4
3 4
4 5
5 1
6 7
7 6
| 5 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'math', 'number theory', '*2900'] |
C. Twin Clusterstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFamous worldwide astrophysicist Mleil waGrasse Tysok recently read about the existence of twin galaxy clusters. Before he shares this knowledge with the broader audience in his podcast called S.tarT-ok, he wants to prove their presence on his own. Mleil is aware that the vastness of the universe is astounding (almost as astounding as his observation skills) and decides to try his luck and find some new pair of twin clusters.To do so, he used his TLEscope to observe a part of the night sky that was not yet examined by humanity in which there are exactly 2^{k + 1} galaxies in a row. i-th of them consist of exactly 0 \le g_i < 4^k stars.A galaxy cluster is any non-empty contiguous segment of galaxies. Moreover, its' trait is said to be equal to the bitwise XOR of all values g_i within this range.Two galaxy clusters are considered twins if and only if they have the same traits and their corresponding segments are disjoint.Write a program that, for many scenarios, will read a description of a night sky part observed by Mleil and outputs a location of two intervals belonging to some twin clusters pair, or a single value -1 if no such pair exists.InputThe first line contains a single integer t, denoting the number of test cases that the program has to handle. The following lines contain test case descriptions, each containing exactly two lines.The first of them contains a single integer k (0 \le k \le 17).The second line contains 2^{k + 1} integers g_1, g_2, \ldots, g_{2^{k+1}} (0 \le g_i < 4^k).We guarantee that the sum of values 2^{k + 1} over all test cases does not exceed 2^{18}.OutputAnswers for all test cases should be present in separate lines. If there exist a pair of twin galaxies, then output four integers a, b, c, and d denoting their inclusive ranges [a, b] and [c, d] (the first interval does not need to start before the second one, but they have to be disjoint). If no pair of such galaxies exist, output a single value -1 instead.ExampleInput
424 15 0 7 11 8 3 210 1 2 300 0315 63 57 39 61 25 42 61 50 41 27 41 56 23 17 27Output
2 4 6 6
2 2 3 4
1 1 2 2
1 1 4 10
NoteIn the first test case we pick intervals [2, 4] and [6, 6] as our twin clusters. The trait of the first interval equals 15 \oplus 0 \oplus 7 = 8, and the trait of the second interval equals 8, so these galaxy clusters are indeed twins. | 424 15 0 7 11 8 3 210 1 2 300 0315 63 57 39 61 25 42 61 50 41 27 41 56 23 17 27 | 2 4 6 6 2 2 3 4 1 1 2 2 1 1 4 10 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'constructive algorithms', 'math', 'probabilities', '*2600'] |
B. Lotterytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people indexed with integers from 1 to n came to take part in a lottery. Each received a ticket with an integer from 0 to m.In a lottery, one integer called target is drawn uniformly from 0 to m. k tickets (or less, if there are not enough participants) with the closest numbers to the target are declared the winners. In case of a draw, a ticket belonging to the person with a smaller index is declared a winner.Bytek decided to take part in the lottery. He knows the values on the tickets of all previous participants. He can pick whatever value he wants on his ticket, but unfortunately, as he is the last one to receive it, he is indexed with an integer n + 1. Bytek wants to win the lottery. Thus, he wants to know what he should pick to maximize the chance of winning. He wants to know the smallest integer in case there are many such integers. Your task is to find it and calculate his chance of winning.InputIn the first line of the input, there are the integers n, m, and k (1 \leq n \leq 10^6, 0 \leq m \leq 10^{18}, 1 \leq k \leq 10^6).In the following line, there are n integers separated by a single space, denoting the numbers on tickets received by people participating in a lottery. These numbers are integers in the range from 0 to m.OutputYou should output two integers separated by a single space on the standard output. The first should be equal to the number of target values (from 0 to m), upon drawing which Baytek wins, given that he chooses his ticket optimally. The second should be equal to the integer Bytek should pick to maximize his chance of winning the lottery.ExamplesInput
3 6 2
1 4 5
Output
4 2
Input
7 7 1
2 4 7 3 0 1 6
Output
1 5
NoteIn the first example, Bytek wins for 4 target values (namely 0, 1, 2, 3) if he chooses integer 2, which is the lowest optimal value. If he chooses 3, he also wins in four cases, but it is not the lowest value. | 3 6 2
1 4 5
| 4 2 | 2 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'math', 'two pointers', '*2500'] |
A. k-th equalitytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider all equalities of form a + b = c, where a has A digits, b has B digits, and c has C digits. All the numbers are positive integers and are written without leading zeroes. Find the k-th lexicographically smallest equality when written as a string like above or determine that it does not exist.For example, the first three equalities satisfying A = 1, B = 1, C = 2 are 1 + 9 = 10, 2 + 8 = 10, 2 + 9 = 11. An equality s is lexicographically smaller than an equality t with the same lengths of the numbers if and only if the following holds: in the first position where s and t differ, the equality s has a smaller digit than the corresponding digit in t. InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \leq t \leq 10^3) — the number of test cases. The description of test cases follows.The first line of each test case contains integers A, B, C, k (1 \leq A, B, C \leq 6, 1 \leq k \leq 10^{12}).Each input file has at most 5 test cases which do not satisfy A, B, C \leq 3.OutputFor each test case, if there are strictly less than k valid equalities, output -1.Otherwise, output the k-th equality as a string of form a + b = c.ExampleInput
71 1 1 92 2 3 12 2 1 11 5 6 421 6 6 100000005 5 6 30315688156 6 6 1000000000000Output
2 + 1 = 3
10 + 90 = 100
-1
9 + 99996 = 100005
-1
78506 + 28543 = 107049
-1
NoteIn the first test case, the first 9 solutions are: \langle 1, 1, 2 \rangle, \langle 1, 2, 3 \rangle, \langle 1, 3, 4 \rangle, \langle 1, 4, 5 \rangle, \langle 1, 5, 6 \rangle, \langle 1, 6, 7 \rangle, \langle 1, 7, 8 \rangle, \langle 1, 8, 9 \rangle, \langle 2, 1, 3 \rangle.Int the third test case, there are no solutions as the smallest possible values for a and b are larger than the maximal possible value of c — 10 + 10 = 20 > 9.Please note that whitespaces in the output matter. | 71 1 1 92 2 3 12 2 1 11 5 6 421 6 6 100000005 5 6 30315688156 6 6 1000000000000 | 2 + 1 = 3 10 + 90 = 100 -1 9 + 99996 = 100005 -1 78506 + 28543 = 107049 -1 | 1 second | 256 megabytes | ['brute force', 'implementation', 'math', '*1700'] |
F. Typewritertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Polycarp was given an unusual typewriter as a gift! Unfortunately, the typewriter was defective and had a rather strange design.The typewriter consists of n cells numbered from left to right from 1 to n, and a carriage that moves over them. The typewriter cells contain n distinct integers from 1 to n, and each cell i initially contains the integer p_i. Before all actions, the carriage is at cell number 1 and there is nothing in its buffer storage. The cell on which the carriage is located is called the current cell. The carriage can perform five types of operations: Take the integer from the current cell, if it is not empty, and put it in the carriage buffer, if it is empty (this buffer can contain no more than one integer). Put the integer from the carriage buffer, if it is not empty, into the current cell, if it is empty. Swap the number in the carriage buffer with the number in the current cell, if both the buffer and the cell contain integers. Move the carriage from the current cell i to cell i + 1 (if i < n), while the integer in the buffer is preserved. Reset the carriage, i.e. move it to cell number 1, while the integer in the buffer is preserved. Polycarp was very interested in this typewriter, so he asks you to help him understand it and will ask you q queries of three types: Perform a cyclic shift of the sequence p to the left by k_j. Perform a cyclic shift of the sequence p to the right by k_j. Reverse the sequence p. Before and after each query, Polycarp wants to know what minimum number of carriage resets is needed for the current sequence in order to distribute the numbers to their cells (so that the number i ends up in cell number i).Note that Polycarp only wants to know the minimum number of carriage resets required to arrange the numbers in their places, but he does not actually distribute them.Help Polycarp find the answers to his queries!InputThe first line contains a single integer n (1 \le n \le 4 \cdot 10^5) — the number of cells.The second line contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the initial arrangement of integers in the cells.The third line contains a single integer q (0 \le q \le 4 \cdot 10^5) — the number of queries.Each of the next q lines describes a query from Polycarp:The j-th line, at first, contains the integer t_j (1 \le t_j \le 3) — the type of query.If the query is of type t_j = 1 or t_j = 2, then the integer k_j (1 \le k_j \le n) — the length of the shift — follows in the same line.OutputOutput q + 1 numbers — the minimum number of carriage resets required before and after each of Polycarp's queries.ExamplesInput
3
2 3 1
0
Output
1
Input
3
1 2 3
2
2 1
3
Output
0
2
1
Input
5
3 1 2 5 4
5
1 3
3
2 3
1 4
3
Output
3
2
1
2
1
2
NoteIn the first example, the answer is 1. You can understand how the carriage works using this example. In the second example, the sequences for which the answer needs to be calculated look like this: Before all queries: 1\ 2\ 3 — the answer is 0. After shifting to the right by 1: 3\ 1\ 2 — the answer is 2. After reversing the sequence: 2\ 1\ 3 — the answer is 1. In the third example, the sequences before and after each query look like this: 3\ 1\ 2\ 5\ 4 — the answer is 3. 5\ 4\ 3\ 1\ 2 — the answer is 2. 2\ 1\ 3\ 4\ 5 — the answer is 1. 3\ 4\ 5\ 2\ 1 — the answer is 2. 1\ 3\ 4\ 5\ 2 — the answer is 1. 2\ 5\ 4\ 3\ 1 — the answer is 2. | 3
2 3 1
0
| 1 | 3 seconds | 256 megabytes | ['brute force', 'math', '*2500'] |
E. MEX of LCMtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. A positive integer x is called good if it is impossible to find a subsegment^{\dagger} of the array such that the least common multiple of all its elements is equal to x.You need to find the smallest good integer.A subsegment^{\dagger} of the array a is a set of elements a_l, a_{l + 1}, \ldots, a_r for some 1 \le l \le r \le n. We will denote such subsegment as [l, r].InputEach test consists of multiple test cases. The first line of each test case contains a single integer t (1 \le t \le 5 \cdot 10^4) — 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 3 \cdot 10^5) — the length of the array a.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 a.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 smallest good integer.ExampleInput
631 2 351 2 3 4 522 311000000000121 8 4 2 3 5 7 2 9 10 11 13127 2 5 4 2 1 1 2 3 11 8 9Output
4
7
1
1
16
13
NoteIn the first test case, 4 is a good integer, and it is the smallest one, since the integers 1,2,3 appear in the array, which means that there are subsegments of the array of length 1 with least common multiples of 1,2,3. However, it is impossible to find a subsegment of the array with a least common multiple equal to 4.In the second test case, 7 is a good integer. The integers 1,2,3,4,5 appear explicitly in the array, and the integer 6 is the least common multiple of the subsegments [2, 3] and [1, 3].In the third test case, 1 is a good integer, since the least common multiples for the integer in the subsegments [1, 1], [1, 2], [2, 2] are 2,6,3, respectively. | 631 2 351 2 3 4 522 311000000000121 8 4 2 3 5 7 2 9 10 11 13127 2 5 4 2 1 1 2 3 11 8 9 | 4 7 1 1 16 13 | 2 seconds | 512 megabytes | ['binary search', 'data structures', 'implementation', 'math', 'number theory', '*2300'] |
D. Survey in Classtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputZinaida Viktorovna has n students in her history class. The homework for today included m topics, but the students had little time to prepare, so i-th student learned only topics from l_i to r_i inclusive.At the beginning of the lesson, each student holds their hand at 0. The teacher wants to ask some topics. It goes like this: The teacher asks the topic k. If the student has learned topic k, then he raises his hand by 1, otherwise he lower it by 1. Each topic Zinaida Viktorovna can ask no more than one time.Find the maximum difference of the heights of the highest and the lowest hand that can be in class after the survey.Note that the student's hand can go below 0.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 two integers n and m (2 \le n \le 10^5, 1 \le m \le 10^9) — the number of students and the number of topics, respectively.Each of the next n lines of each test case contain two integers l_i and r_i (1 \le l_i \le r_i \le m) — the endpoints of the segment of topics that i-th student has learned.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print one integer — the maximum difference of the heights of the highest and the lowest hand that can be in the class after the survey.ExampleInput
64 82 64 82 71 53 31 32 32 23 51 51 51 53 51 13 35 54 71 71 33 34 52 41 32 4Output
6
4
0
2
12
2
NoteIn the first test case, Zinaida Viktorovna can ask the topics 5, 6, 7, 8. Then the hand of the 2-nd student will be at the height of 4, and the hand of the 4-th will be at the height of -2, that is, the difference will be equal to 6.In the second test case, you can ask about the topics 1 and 3. Then the hand of the 1-st student will be at the height of 2 and the hand of the 3-rd student will be at the height of -2. So the difference will be 4.In the third test case, the difference between the highest and lowest hand will be 0 for any set of topics asked.In the fifth test case, you can ask all topics. Then the difference between the heights of the 1-st and 3-rd students' hands will be 12. | 64 82 64 82 71 53 31 32 32 23 51 51 51 53 51 13 35 54 71 71 33 34 52 41 32 4 | 6 4 0 2 12 2 | 2 seconds | 256 megabytes | ['brute force', 'data structures', 'greedy', 'implementation', 'sortings', '*1900'] |
C. Game with Reversingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They have two strings S and T of the same length n consisting of lowercase latin letters. Players take turns alternately, with Alice going first.On her turn, Alice chooses an integer i from 1 to n, one of the strings S or T, and any lowercase latin letter c, and replaces the i-th symbol in the chosen string with the character c.On his turn, Bob chooses one of the strings S or T, and reverses it. More formally, Bob makes the replacement S := \operatorname{rev}(S) or T := \operatorname{rev}(T), where \operatorname{rev}(P) = P_n P_{n-1} \ldots P_1.The game lasts until the strings S and T are equal. As soon as the strings become equal, the game ends instantly.Define the duration of the game as the total number of moves made by both players during the game. For example, if Alice made 2 moves in total, and Bob made 1 move, then the duration of this game is 3.Alice's goal is to minimize the duration of the game, and Bob's goal is to maximize the duration of the game.What will be the duration of the game, if both players play optimally? It can be shown that the game will end in a finite number of turns.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 a single integer n (1 \le n \le 10^5) — the length of the strings S and T.The second line of each test case contains a string S of length n consisting of lowercase latin letters.The third line of each test case contains a string T of length n consisting of lowercase latin letters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single number on a separate line — the duration of the described game, if both players play optimally.ExampleInput
75abcdeabxde5helloolleo2abcd7aaaaaaaabbbbba1qq6yoyoyooyoyoy8abcdefghhguedfbhOutput
1
2
3
9
0
2
6
NoteIn the first test case, in her turn, Alice can replace the third symbol of the string S with x. After that, both strings will become equal to "abxde" and the game will end after one move. Since Alice's goal is to finish the game in as few moves as possible, this move will be one of her optimal first moves, and the final answer will be 1.In the second test case, in her turn, Alice can replace the fifth symbol of the string T with h. After this move, S = "hello", T = "olleh". Then Bob makes his turn. In his turn, he must reverse one of the strings. If Bob chooses the string S, then after his turn both strings will be equal to "olleh", and if he chooses the string T, then after his turn both strings will be equal to "hello". Thus, after the presented first move of Alice, the game will definitely end in 2 moves. It can be shown that there is no strategy for Alice to finish the game in less than 2 moves, with both players playing optimally. The final answer is 2.In the third test case, in her first move, Alice can replace the second symbol of the string S with c. After this move, S = "ac", T = "cd". Then Bob makes his turn. If Bob reverses the string S, then after his turn S = "ca", T = "cd". Then it is easy to see that in this case Alice can definitely finish the game on the 3-rd move, by replacing the second symbol of the string T with a, after which both strings will become equal to "ca". If Bob reverses the string T, then after his turn S = "ac", T = "dc". In this case, Alice can also definitely finish the game on the 3rd move, by replacing the first symbol of the string S with d, after which both strings will become equal to "dc". Thus, Alice can definitely finish the game in 3 moves regardless of Bob's moves. It can be shown that the game cannot end in less than 3 moves, with both players playing optimally.In the fifth test case, the strings S and T are equal, so the game will end without starting, in 0 moves. | 75abcdeabxde5helloolleo2abcd7aaaaaaaabbbbba1qq6yoyoyooyoyoy8abcdefghhguedfbh | 1 2 3 9 0 2 6 | 1 second | 256 megabytes | ['games', 'greedy', 'math', 'strings', '*1200'] |
B. Maximum Strengthtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFedya is playing a new game called "The Legend of Link", in which one of the character's abilities is to combine two materials into one weapon. Each material has its own strength, which can be represented by a positive integer x. The strength of the resulting weapon is determined as the sum of the absolute differences of the digits in the decimal representation of the integers at each position.Formally, let the first material have strength X = \overline{x_{1}x_{2} \ldots x_{n}}, and the second material have strength Y = \overline{y_{1}y_{2} \ldots y_{n}}. Then the strength of the weapon is calculated as |x_{1} - y_{1}| + |x_{2} - y_{2}| + \ldots + |x_{n} - y_{n}|. If the integers have different lengths, then the shorter integer is padded with leading zeros.Fedya has an unlimited supply of materials with all possible strengths from L to R, inclusive. Help him find the maximum possible strength of the weapon he can obtain.An integer C = \overline{c_{1}c_{2} \ldots c_{k}} is defined as an integer obtained by sequentially writing the digits c_1, c_2, \ldots, c_k from left to right, i.e. 10^{k-1} \cdot c_1 + 10^{k-2} \cdot c_2 + \ldots + c_k.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line of each test case contains two integers L and R (1 \le L \le R < 10^{100}) — the decimal representation of the integers representing the minimum and maximum strength of the materials that Fedya has. It is guaranteed that the integers L and R do not contain leading zeros.Note that the input data may not fit into standard 32-bit or 64-bit integer data types.OutputFor each test case print one integer — the maximum possible strength of the weapon that Fedya can obtain from the given materials.ExampleInput
653 57179 23913 37132228 13222854943329752812629795 5515758193968886336688 1914Output
4
19
11
0
163
28
NoteIn the first test case, the weapon made from materials with strengths 53 and 57 will have the maximum possible strength: |5 - 5| + |3 - 7| = 4.In the second test case, the maximum strength is achieved with materials with strengths 190 and 209: |1 - 2| + |9 - 0| + |0 - 9| = 19.In the fourth test case, there is only one valid strength, so the answer is 0.In the sixth test case, the maximum strength is achieved with materials with strengths 1909 and 90: |1 - 0| + |9 - 0| + |0 - 9| + |9 - 0| = 28. Note that the shorter integer was padded with leading zeros. | 653 57179 23913 37132228 13222854943329752812629795 5515758193968886336688 1914 | 4 19 11 0 163 28 | 1 second | 256 megabytes | ['greedy', 'math', '*1000'] |
A. Unit Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n, which elements are equal to -1 and 1. Let's call the array a good if the following conditions are held at the same time: a_1 + a_2 + \ldots + a_n \ge 0; a_1 \cdot a_2 \cdot \ldots \cdot a_n = 1. In one operation, you can select an arbitrary element of the array a_i and change its value to the opposite. In other words, if a_i = -1, you can assign the value to a_i := 1, and if a_i = 1, then assign the value to a_i := -1.Determine the minimum number of operations you need to perform to make the array a good. It can be shown that this is always possible.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 500) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (a_i = \pm 1) — the elements of the array a.OutputFor each test case, output a single integer — the minimum number of operations that need to be done to make the a array good.ExampleInput
74-1 -1 1 -15-1 -1 -1 1 14-1 1 -1 13-1 -1 -151 1 1 1 11-12-1 -1Output
1
1
0
3
0
1
2
NoteIn the first test case, we can assign the value a_1 := 1. Then a_1 + a_2 + a_3 + a_4 = 1 + (-1) + 1 + (-1) = 0 \ge 0 and a_1 \cdot a_2 \cdot a_3 \cdot a_4 = 1 \cdot (-1) \cdot 1 \cdot (-1) = 1. Thus, we performed 1 operation.In the second test case, we can assign a_1 := 1. Then a_1 + a_2 + a_3 + a_4 + a_5 = 1 + (-1) + (-1) + 1 + 1 = 1 \ge 0 and a_1 \cdot a_2 \cdot a_3 \cdot a_4 \cdot a_5 = 1 \cdot (-1) \cdot (-1) \cdot 1 \cdot 1 = 1. Thus, we performed 1 operation.In the third test case, a_1 + a_2 + a_3 + a_4 = (-1) + 1 + (-1) + 1 = 0 \ge 0 and a_1 \cdot a_2 \cdot a_3 \cdot a_4 = (-1) \cdot 1 \cdot (-1) \cdot 1 = 1. Thus, all conditions are already satisfied and no operations are needed.In the fourth test case, we can assign the values a_1 := 1, a_2 := 1, a_3 := 1. Then a_1 + a_2 + a_3 = 1 + 1 + 1 = 3 \ge 0 and a_1 \cdot a_2 \cdot a_3 = 1 \cdot 1 \cdot 1 = 1. Thus, we performed 3 operations. | 74-1 -1 1 -15-1 -1 -1 1 14-1 1 -1 13-1 -1 -151 1 1 1 11-12-1 -1 | 1 1 0 3 0 1 2 | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
G. Ksyusha and Chinchillatime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKsyusha has a pet chinchilla, a tree on n vertices and huge scissors. A tree is a connected graph without cycles. During a boring physics lesson Ksyusha thought about how to entertain her pet.Chinchillas like to play with branches. A branch is a tree of 3 vertices. The branch looks like this. A cut is the removal of some (not yet cut) edge in the tree. Ksyusha has plenty of free time, so she can afford to make enough cuts so that the tree splits into branches. In other words, after several (possibly zero) cuts, each vertex must belong to exactly one branch.Help Ksyusha choose the edges to be cut or tell that it is impossible.InputThe first line contains a single integer t (1 \le t \le 10^4) — number of testcases.The first line of each testcase contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The next n - 1 rows of each testcase contain integers v_i and u_i (1 \le v_i, u_i \le n) — the numbers of vertices that the i-th edge connects.It is guaranteed that this set of edges forms a tree. It is also guaranteed that the sum of n over all testcases does not exceed 2 \cdot 10^5.OutputPrint the answer for each testcase.If the desired way to cut the tree does not exist, print -1.Otherwise, print an integer k — the number of edges to be cut. In the next line, print k different integers e_i (1 \le e_i < n) — numbers of the edges to be cut. If k = 0, print an empty string instead.If there are several solutions, you can print any.ExamplesInput
491 24 37 95 44 63 28 71 761 21 34 31 56 161 23 23 44 56 551 35 35 23 4Output
2
2 8
-1
1
3
-1
Input
421 231 23 161 23 13 43 56 192 66 99 19 71 87 38 54 7Output
-1
0
1
2
2
4 3
Note The first testcase in first test. | 491 24 37 95 44 63 28 71 761 21 34 31 56 161 23 23 44 56 551 35 35 23 4 | 2 2 8 -1 1 3 -1 | 3 seconds | 256 megabytes | ['constructive algorithms', 'dfs and similar', 'dp', 'dsu', 'greedy', 'implementation', 'trees', '*1800'] |
F. Ira and Flamencotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIra loves Spanish flamenco dance very much. She decided to start her own dance studio and found n students, ith of whom has level a_i.Ira can choose several of her students and set a dance with them. So she can set a huge number of dances, but she is only interested in magnificent dances. The dance is called magnificent if the following is true: exactly m students participate in the dance; levels of all dancers are pairwise distinct; levels of every two dancers have an absolute difference strictly less than m. For example, if m = 3 and a = [4, 2, 2, 3, 6], the following dances are magnificent (students participating in the dance are highlighted in red): [\color{red}{4}, 2, \color{red}{2}, \color{red}{3}, 6], [\color{red}{4}, \color{red}{2}, 2, \color{red}{3}, 6]. At the same time dances [\color{red}{4}, 2, 2, \color{red}{3}, 6], [4, \color{red}{2}, \color{red}{2}, \color{red}{3}, 6], [\color{red}{4}, 2, 2, \color{red}{3}, \color{red}{6}] are not magnificent.In the dance [\color{red}{4}, 2, 2, \color{red}{3}, 6] only 2 students participate, although m = 3.The dance [4, \color{red}{2}, \color{red}{2}, \color{red}{3}, 6] involves students with levels 2 and 2, although levels of all dancers must be pairwise distinct.In the dance [\color{red}{4}, 2, 2, \color{red}{3}, \color{red}{6}] students with levels 3 and 6 participate, but |3 - 6| = 3, although m = 3.Help Ira count the number of magnificent dances that she can set. Since this number can be very large, count it modulo 10^9 + 7. Two dances are considered different if the sets of students participating in them are different.InputThe first line contains a single integer t (1 \le t \le 10^4) — number of testcases.The first line of each testcase contains integers n and m (1 \le m \le n \le 2 \cdot 10^5) — the number of Ira students and the number of dancers in the magnificent dance.The second line of each testcase contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — levels of students.It is guaranteed that the sum of n over all testcases does not exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the number of magnificent dances. Since this number can be very large, print it modulo 10^9 + 7.ExampleInput
97 48 10 10 9 6 11 75 34 2 2 3 68 21 5 2 2 3 1 3 33 33 3 35 13 4 3 10 712 35 2 1 1 4 3 5 5 5 2 7 51 113 21 2 32 21 2Output
5
2
10
0
5
11
1
2
1
NoteIn the first testcase, Ira can set such magnificent dances: [\color{red}{8}, 10, 10, \color{red}{9}, \color{red}{6}, 11, \color{red}{7}], [\color{red}{8}, \color{red}{10}, 10, \color{red}{9}, 6, 11, \color{red}{7}], [\color{red}{8}, 10, \color{red}{10}, \color{red}{9}, 6, 11, \color{red}{7}], [\color{red}{8}, 10, \color{red}{10}, \color{red}{9}, 6, \color{red}{11}, 7], [\color{red}{8}, \color{red}{10}, 10, \color{red}{9}, 6, \color{red}{11}, 7].The second testcase is explained in the statements. | 97 48 10 10 9 6 11 75 34 2 2 3 68 21 5 2 2 3 1 3 33 33 3 35 13 4 3 10 712 35 2 1 1 4 3 5 5 5 2 7 51 113 21 2 32 21 2 | 5 2 10 0 5 11 1 2 1 | 2 seconds | 256 megabytes | ['combinatorics', 'constructive algorithms', 'data structures', 'implementation', 'math', 'sortings', 'two pointers', '*1700'] |
E. Round Dancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputn people came to the festival and decided to dance a few round dances. There are at least 2 people in the round dance and each person has exactly two neighbors. If there are 2 people in the round dance then they have the same neighbor on each side.You decided to find out exactly how many dances there were. But each participant of the holiday remembered exactly one neighbor. Your task is to determine what the minimum and maximum number of round dances could be.For example, if there were 6 people at the holiday, and the numbers of the neighbors they remembered are equal [2, 1, 4, 3, 6, 5], then the minimum number of round dances is1: 1 - 2 - 3 - 4 - 5 - 6 - 1 and the maximum is 3: 1 - 2 - 1 3 - 4 - 3 5 - 6 - 5 InputThe first line contains a positive number t (1 \le t \le 10^4) — the number of test cases. The following is a description of the test cases.The first line of the description of each test case contains a positive number n (2 \le n \le 2 \cdot 10^5) — the number of people at the holiday.The second line of the description of each test case contains n integers a_i (1 \le a_i \le n, a_i \neq i) — the number of the neighbor that the ith person remembered.It is guaranteed that the test cases are correct and corresponds to at least one division of people into round dances.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two integers — the minimum and maximum number of round dances that could be.ExampleInput
1062 1 4 3 6 562 3 1 5 6 492 3 2 5 6 5 8 9 822 144 3 2 152 3 4 5 165 3 4 1 1 253 5 4 1 266 3 2 5 4 365 1 4 3 4 2Output
1 3
2 2
1 3
1 1
1 2
1 1
1 1
2 2
1 2
1 1
| 1062 1 4 3 6 562 3 1 5 6 492 3 2 5 6 5 8 9 822 144 3 2 152 3 4 5 165 3 4 1 1 253 5 4 1 266 3 2 5 4 365 1 4 3 4 2 | 1 3 2 2 1 3 1 1 1 2 1 1 1 1 2 2 1 2 1 1 | 2 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'shortest paths', '*1600'] |
D. Flippertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p of length n.A permutation is an array consisting of n distinct integers from 1 to n in any order. For example, \{2,3,1,5,4\} is a permutation, while \{1,2,2\} is not (since 2 appears twice), and \{1,3,4\} is also not a permutation (as n=3, but the array contains 4).To the permutation p, you need to apply the following operation exactly once: First you choose a segment [l, r] (1 \le l \le r \le n, a segment is a continuous sequence of numbers \{p_l, p_{l+1}, \ldots, p_{r-1}, p_r\}) and reverse it. Reversing a segment means swapping pairs of numbers (p_l, p_r), (p_{l+1}, p_{r-1}), ..., (p_{l + i}, p_{r - i}) (where l + i \le r - i). Then you swap the prefix and suffix: [r+1, n] and [1, l - 1] (note that these segments may be empty). For example, given n = 5, p = \{2, \color{blue}{3}, \color{blue}{1}, 5, 4\}, if you choose the segment [l = 2, r = 3], after reversing the segment p = \{\color{green}{2}, \color{blue}{1}, \color{blue}{3}, \color{green}{5}, \color{green}{4}\}, then you swap the segments [4, 5] and [1, 1]. Thus, p = \{\color{green}{5}, \color{green}{4}, 1, 3, \color{green}{2}\}. It can be shown that this is the maximum possible result for the given permutation.You need to output the lexicographically maximum permutation that can be obtained by applying the operation described exactly once.A permutation a is lexicographically greater than permutation b if there exists an i (1 \le i \le n) such that a_j = b_j for 1 \le j < i and a_i > b_i.InputThe first line of the input contains a single integer t (1 \le t \le 1000) — the number of test cases.Then the descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2000) — the size of the permutation.The second line of each test case contains n integers: p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the permutation p itself.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output in a separate line the lexicographically maximum permutation of length n that can be obtained from p by applying the operation described in the problem exactly once.ExampleInput
952 3 1 5 494 1 6 7 2 8 5 3 944 3 2 122 163 2 4 1 5 673 2 1 5 7 6 41010 2 5 6 1 9 3 8 4 744 2 1 311Output
5 4 1 3 2
9 4 1 6 7 2 8 5 3
3 2 1 4
1 2
6 5 3 2 4 1
7 6 4 5 3 2 1
9 3 8 4 7 1 10 2 5 6
3 4 2 1
1
NoteThe first example is explained in the problem statement.In the second example, the segment [l = 9, r = 9] should be chosen.In the third example, the segment [l = 1, r = 1] should be chosen.In the fourth example, the segment [l = 1, r = 2] should be chosen.In the fifth example, the segment [l = 5, r = 6] should be chosen.In the sixth example, the segment [l = 4, r = 4] should be chosen.In the seventh example, the segment [l = 5, r = 5] should be chosen. | 952 3 1 5 494 1 6 7 2 8 5 3 944 3 2 122 163 2 4 1 5 673 2 1 5 7 6 41010 2 5 6 1 9 3 8 4 744 2 1 311 | 5 4 1 3 2 9 4 1 6 7 2 8 5 3 3 2 1 4 1 2 6 5 3 2 4 1 7 6 4 5 3 2 1 9 3 8 4 7 1 10 2 5 6 3 4 2 1 1 | 1 second | 256 megabytes | ['brute force', 'constructive algorithms', 'greedy', '*1400'] |
C. Vlad Building Beautiful Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad was given an array a of n positive integers. Now he wants to build a beautiful array b of length n from it.Vlad considers an array beautiful if all the numbers in it are positive and have the same parity. That is, all numbers in the beautiful array are greater than zero and are either all even or all odd.To build the array b, Vlad can assign each b_i either the value a_i or a_i - a_j, where any j from 1 to n can be chosen.To avoid trying to do the impossible, Vlad asks you to determine whether it is possible to build a beautiful array b of length n using his array a.InputThe first line of input contains an integer t (1 \le t \le 10^4) — the number of test cases.Then follow the descriptions of the test cases.The first line of each case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array a.The second line of each case contains n positive integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array a.It is guaranteed that the sum of n over all cases does not exceed 2 \cdot 10^5.OutputOutput t strings, each of which is the answer to the corresponding test case. As the answer, output "YES" if Vlad can build a beautiful array b, 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
752 6 8 4 351 4 7 6 942 6 4 1075 29 13 9 10000001 11 352 1 2 4 252 4 5 4 342 5 5 4Output
NO
YES
YES
YES
YES
NO
NO
| 752 6 8 4 351 4 7 6 942 6 4 1075 29 13 9 10000001 11 352 1 2 4 252 4 5 4 342 5 5 4 | NO YES YES YES YES NO NO | 1 second | 256 megabytes | ['greedy', 'math', '*800'] |
B. Restore the Weathertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a containing the weather forecast for Berlandia for the last n days. That is, a_i — is the estimated air temperature on day i (1 \le i \le n).You are also given an array b — the air temperature that was actually present on each of the days. However, all the values in array b are mixed up. Determine which day was which temperature, if you know that the weather never differs from the forecast by more than k degrees. In other words, if on day i the real air temperature was c, then the equality |a_i - c| \le k is always true.For example, let an array a = [1, 3, 5, 3, 9] of length n = 5 and k = 2 be given and an array b = [2, 5, 11, 2, 4]. Then, so that the value of b_i corresponds to the air temperature on day i, we can rearrange the elements of the array b so: [2, 2, 5, 4, 11]. Indeed: On the 1st day, |a_1 - b_1| = |1 - 2| = 1, 1 \le 2 = k is satisfied; On the 2nd day |a_2 - b_2| = |3 - 2| = 1, 1 \le 2 = k is satisfied; On the 3rd day, |a_3 - b_3| = |5 - 5| = 0, 0 \le 2 = k is satisfied; On the 4th day, |a_4 - b_4| = |3 - 4| = 1, 1 \le 2 = k is satisfied; On the 5th day, |a_5 - b_5| = |9 - 11| = 2, 2 \le 2 = k is satisfied. InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.The description of the test cases follows.The first line of each test case contains two integers n (1 \le n \le 10^5) and k (0 \le k \le10^9) — the number of days and the maximum difference between the expected and actual air temperature on each day.The second line of each test case contains exactly n integers — elements of array a (-10^9 \le a_i \le 10^9).The third line of each test case contains exactly n integers — elements of array b (-10^9 \le b_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 10^5, and that the elements of array b can always be rearranged so that the equality |a_i - b_i| \le k is true for all i.OutputOn a separate line for each test case, output exactly n numbers — the values of air temperature on each of the days in the correct order. If there is more than one answer — output any of them.ExampleInput
35 21 3 5 3 92 5 11 2 46 1-1 3 -2 0 -5 -1-4 0 -1 4 0 03 37 7 79 4 8Output
2 2 5 4 11
0 4 -1 0 -4 0
8 4 9 | 35 21 3 5 3 92 5 11 2 46 1-1 3 -2 0 -5 -1-4 0 -1 4 0 03 37 7 79 4 8 | 2 2 5 4 11 0 4 -1 0 -4 0 8 4 9 | 1 second | 256 megabytes | ['greedy', 'sortings', '*900'] |
A. Musical Puzzletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad decided to compose a melody on his guitar. Let's represent the melody as a sequence of notes corresponding to the characters 'a', 'b', 'c', 'd', 'e', 'f', and 'g'.However, Vlad is not very experienced in playing the guitar and can only record exactly two notes at a time. Vlad wants to obtain the melody s, and to do this, he can merge the recorded melodies together. In this case, the last sound of the first melody must match the first sound of the second melody.For example, if Vlad recorded the melodies "ab" and "ba", he can merge them together and obtain the melody "aba", and then merge the result with "ab" to get "abab".Help Vlad determine the minimum number of melodies consisting of two notes that he needs to record in order to obtain the melody s.InputThe first line of input contains an integer t (1 \le t \le 10^4) — the number of test cases.Following that are the descriptions of the test cases.The first line of each test case contains an integer n (2 \le n \le 50) — the length of the melody s.The second line of each test case contains a string s of length n, consisting of characters 'a', 'b', 'c', 'd', 'e', 'f', 'g'.OutputOutput t integers, each representing the answer for the corresponding test case. As the answer output minimum number of melodies consisting of two notes that Vlad needs to record.ExampleInput
54abab7abacaba6aaaaaa7abcdefg5babddOutput
2
4
1
6
4
NoteIn the first sample, you need to record the melodies "ab" and "ba", as described in the problem statement.In the second sample, you need to record the melodies "ab", "ba", "ac", and "ca".In the third sample, the only necessary melody is "aa". | 54abab7abacaba6aaaaaa7abcdefg5babdd | 2 4 1 6 4 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Zombiestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays a computer game in a post-apocalyptic setting. The zombies have taken over the world, and Polycarp with a small team of survivors is defending against hordes trying to invade their base. The zombies are invading for x minutes starting from minute 0. There are n entrances to the base, and every minute one zombie attempts to enter through every entrance.The survivors can defend the entrances against the zombies. There are two options: manually — shoot the zombies coming through a certain entrance; automatically — set up an electric fence on a certain entrance to fry the zombies. If an entrance is defended either or both ways during some minute, no zombie goes through.Every entrance is defended by a single dedicated survivor. The i-th entrance is defended manually from minute l_i until minute r_i, non-inclusive — [l_i, r_i).There are k generators that can be used to defend the entrances automatically. Every entrance should be connected to exactly one generator, but a generator can be connected to multiple entrances (or even none of them). Each generator will work for exactly m consecutive minutes. Polycarp can choose when to power on each generator independently of each other, the m minute long interval should be fully inside the [0, x) time interval.Polycarp is a weird gamer. He wants the game to be as difficult as possible for him. So he wants to connect each entrance to a generator and choose the time for each generator in such a way that as many zombies as possible enter the base. Please, help him to achieve that!InputThe first line contains four integers n, k, x and m (1 \le k \le n \le 2000; 1 \le m \le x \le 10^9) — the number of entrances, the number of generators, the duration of the zombie invasion and the duration of all generators.The i-th of the next n lines contains two integers l_i and r_i (0 \le l_i < r_i \le x) — the time interval the i-th entrance is defended manually.OutputPrint a single integer — the largest number of zombies that can enter the base after Polycarp connects each entrance to some generator and chooses the time for each generator.ExamplesInput
3 3 10 3
0 2
1 7
4 7
Output
18
Input
3 2 10 3
0 2
1 7
4 7
Output
18
Input
3 1 10 3
0 2
1 7
4 7
Output
16
Input
2 1 20 6
11 13
2 14
Output
22
Input
5 3 7 4
4 6
0 3
4 7
1 5
2 7
Output
14
Input
6 3 9 4
3 9
4 9
2 5
0 5
6 9
2 3
Output
26
| 3 3 10 3
0 2
1 7
4 7
| 18 | 4 seconds | 256 megabytes | ['binary search', 'dp', '*3200'] |
E. Combinatorics Problemtime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the binomial coefficient \binom{x}{y} is calculated as follows (x and y are non-negative integers): if x < y, then \binom{x}{y} = 0; otherwise, \binom{x}{y} = \frac{x!}{y! \cdot (x-y)!}. You are given an array a_1, a_2, \dots, a_n and an integer k. You have to calculate a new array b_1, b_2, \dots, b_n, where b_1 = (\binom{1}{k} \cdot a_1) \bmod 998244353; b_2 = (\binom{2}{k} \cdot a_1 + \binom{1}{k} \cdot a_2) \bmod 998244353; b_3 = (\binom{3}{k} \cdot a_1 + \binom{2}{k} \cdot a_2 + \binom{1}{k} \cdot a_3) \bmod 998244353, and so on. Formally, b_i = (\sum\limits_{j=1}^{i} \binom{i - j + 1}{k} \cdot a_j) \bmod 998244353.Note that the array is given in a modified way, and you have to output it in a modified way as well.InputThe only line of the input contains six integers n, a_1, x, y, m and k (1 \le n \le 10^7; 0 \le a_1, x, y < m; 2 \le m \le 998244353; 1 \le k \le 5).The array [a_1, a_2, \dots, a_n] is generated as follows: a_1 is given in the input; for 2 \le i \le n, a_i = (a_{i-1} \cdot x + y) \bmod m. OutputSince outputting up to 10^7 integers might be too slow, you have to do the following:Let c_i = b_i \cdot i (without taking modulo 998244353 after the multiplication). Print the integer c_1 \oplus c_2 \oplus \dots \oplus c_n, where \oplus denotes the bitwise XOR operator.ExampleInput
5 8 2 3 100 2
Output
1283
| 5 8 2 3 100 2
| 1283 | 4 seconds | 1024 megabytes | ['brute force', 'combinatorics', 'dp', '*2200'] |
D2. Red-Blue Operations (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the maximum values of n and q.You are given an array, consisting of n integers. Initially, all elements are red.You can apply the following operation to the array multiple times. During the i-th operation, you select an element of the array; then: if the element is red, it increases by i and becomes blue; if the element is blue, it decreases by i and becomes red. The operations are numbered from 1, i. e. during the first operation some element is changed by 1 and so on.You are asked q queries of the following form: given an integer k, what can the largest minimum in the array be if you apply exactly k operations to it? Note that the operations don't affect the array between queries, all queries are asked on the initial array a.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of elements in the array and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The third line contains q integers k_1, k_2, \dots, k_q (1 \le k_j \le 10^9).OutputFor each query, print a single integer — the largest minimum that the array can have after you apply exactly k operations to it.ExamplesInput
4 10
5 2 8 4
1 2 3 4 5 6 7 8 9 10
Output
3 4 5 6 7 8 8 10 8 12
Input
5 10
5 2 8 4 4
1 2 3 4 5 6 7 8 9 10
Output
3 4 5 6 7 8 9 8 11 8
Input
2 5
2 3
10 6 8 1 3
Output
10 7 8 3 3
| 4 10
5 2 8 4
1 2 3 4 5 6 7 8 9 10
| 3 4 5 6 7 8 8 10 8 12 | 2 seconds | 256 megabytes | ['binary search', 'constructive algorithms', 'greedy', 'implementation', 'math', '*2400'] |
D1. Red-Blue Operations (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the maximum values of n and q.You are given an array, consisting of n integers. Initially, all elements are red.You can apply the following operation to the array multiple times. During the i-th operation, you select an element of the array; then: if the element is red, it increases by i and becomes blue; if the element is blue, it decreases by i and becomes red. The operations are numbered from 1, i. e. during the first operation some element is changed by 1 and so on.You are asked q queries of the following form: given an integer k, what can the largest minimum in the array be if you apply exactly k operations to it? Note that the operations don't affect the array between queries, all queries are asked on the initial array a.InputThe first line contains two integers n and q (1 \le n, q \le 1000) — the number of elements in the array and the number of queries.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).The third line contains q integers k_1, k_2, \dots, k_q (1 \le k_j \le 10^9).OutputFor each query, print a single integer — the largest minimum that the array can have after you apply exactly k operations to it.ExamplesInput
4 10
5 2 8 4
1 2 3 4 5 6 7 8 9 10
Output
3 4 5 6 7 8 8 10 8 12
Input
5 10
5 2 8 4 4
1 2 3 4 5 6 7 8 9 10
Output
3 4 5 6 7 8 9 8 11 8
Input
2 5
2 3
10 6 8 1 3
Output
10 7 8 3 3
| 4 10
5 2 8 4
1 2 3 4 5 6 7 8 9 10
| 3 4 5 6 7 8 8 10 8 12 | 2 seconds | 256 megabytes | ['binary search', 'greedy', 'implementation', 'math', '*2100'] |
C. Contrast Valuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array of integers [a_1, a_2, \dots, a_n], let's call the value |a_1-a_2|+|a_2-a_3|+\cdots+|a_{n-1}-a_n| the contrast of the array. Note that the contrast of an array of size 1 is equal to 0.You are given an array of integers a. Your task is to build an array of b in such a way that all the following conditions are met: b is not empty, i.e there is at least one element; b is a subsequence of a, i.e b can be produced by deleting some elements from a (maybe zero); the contrast of b is equal to the contrast of a. What is the minimum possible size of the array b?InputThe first line contains a 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 3 \cdot 10^5) — the size of the array a.The second line contains n integers a_1, a_2, \cdot, a_n (0 \le a_i \le 10^9) — elements of the array itself.The sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single integer — the minimum possible size of the array b.ExampleInput
451 3 3 3 724 241 1 1 175 4 2 1 0 0 4Output
2
2
1
3
| 451 3 3 3 724 241 1 1 175 4 2 1 0 0 4 | 2 2 1 3 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1200'] |
B. Maximum Sumtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n, where all elements are different.You have to perform exactly k operations with it. During each operation, you do exactly one of the following two actions (you choose which to do yourself): find two minimum elements in the array, and delete them; find the maximum element in the array, and delete it. You have to calculate the maximum possible sum of elements in the resulting array.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines: the first line contains two integers n and k (3 \le n \le 2 \cdot 10^5; 1 \le k \le 99999; 2k < n) — the number of elements and operations, respectively. the second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9; all a_i are different) — the elements of the array. Additional constraint on the input: the sum of n does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the maximum possible sum of elements in the resulting array.ExampleInput
65 12 5 1 10 65 22 5 1 10 63 11 2 36 115 22 12 10 13 116 215 22 12 10 13 115 1999999996 999999999 999999997 999999998 999999995Output
21
11
3
62
46
3999999986
NoteIn the first testcase, applying the first operation produces the following outcome: two minimums are 1 and 2; removing them leaves the array as [5, 10, 6], with sum 21; a maximum is 10; removing it leaves the array as [2, 5, 1, 6], with sum 14. 21 is the best answer.In the second testcase, it's optimal to first erase two minimums, then a maximum. | 65 12 5 1 10 65 22 5 1 10 63 11 2 36 115 22 12 10 13 116 215 22 12 10 13 115 1999999996 999999999 999999997 999999998 999999995 | 21 11 3 62 46 3999999986 | 2 seconds | 256 megabytes | ['brute force', 'sortings', 'two pointers', '*1100'] |
A. New Palindrometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA palindrome is a string that reads the same from left to right as from right to left. For example, abacaba, aaaa, abba, racecar are palindromes.You are given a string s consisting of lowercase Latin letters. The string s is a palindrome.You have to check whether it is possible to rearrange the letters in it to get another palindrome (not equal to the given string s).InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains a string s (2 \le |s| \le 50) consisting of lowercase Latin letters. This string is a palindrome.OutputFor each test case, print YES if it is possible to rearrange the letters in the given string to get another palindrome. Otherwise, print NO. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput
3codedocggaabaaOutput
YES
NO
NO
NoteIn the first test case, it is possible to rearrange the letters in the palindrome codedoc to obtain the string ocdedco, which is different from the given string, but also a palindrome. | 3codedocggaabaa | YES NO NO | 2 seconds | 256 megabytes | ['strings', '*800'] |
B. Array mergingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b both of length n.You will merge^\dagger these arrays forming another array c of length 2 \cdot n. You have to find the maximum length of a subarray consisting of equal values across all arrays c that could be obtained.^\dagger A merge of two arrays results in an array c composed by successively taking the first element of either array (as long as that array is nonempty) and removing it. After this step, the element is appended to the back of c. We repeat this operation as long as we can (i.e. at least one array is nonempty).InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array a and b.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le 2 \cdot n) — the elements of array a.The third line of each test case contains n integers b_1,b_2,\ldots,b_n (1 \le b_i \le 2 \cdot n) — the elements of array b.It is guaranteed that the sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the maximum length of a subarray consisting of equal values across all merges.ExampleInput
412231 2 34 5 621 22 151 2 2 2 22 1 1 1 1Output
2
1
2
5
NoteIn the first test case, we can only make c=[2,2], thus the answer is 2.In the second test case, since all values are distinct, the answer must be 1.In the third test case, the arrays c we can make are [1,2,1,2], [1,2,2,1], [2,1,1,2], [2,1,2,1]. We can see that the answer is 2 when we choose c=[1,2,2,1]. | 412231 2 34 5 621 22 151 2 2 2 22 1 1 1 1 | 2 1 2 5 | 1 second | 256 megabytes | ['constructive algorithms', 'greedy', '*1000'] |
A. Twin Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^\dagger a of length n.Find any permutation b of length n such that a_1+b_1 \le a_2+b_2 \le a_3+b_3 \le \ldots \le a_n+b_n.It can be proven that a permutation b that satisfies the condition above always exists.^\dagger A permutation of length n 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).InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 2000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the length of permutations a and b.The second line of each test case contains n distinct integers a_1,a_2,\ldots,a_n (1 \le a_i \le n) — the elements of permutation a. All elements of a are distinct.Note that there is no bound on the sum of n over all test cases.OutputFor each test case, output any permutation b which satisfies the constraints mentioned in the statement. It can be proven that a permutation b that satisfies the condition above always exists.ExampleInput
551 2 4 5 321 21133 2 141 4 3 2Output
1 2 4 3 5
2 1
1
1 2 3
1 2 3 4NoteIn the first test case a=[1, 2, 4, 5, 3]. Then the permutation b=[1, 2, 4, 3, 5] satisfies the condition because 1 + 1 \le 2 + 2 \le 4 + 4 \le 5 + 3 \le 3 + 5. | 551 2 4 5 321 21133 2 141 4 3 2 | 1 2 4 3 5 2 1 1 1 2 3 1 2 3 4 | 1 second | 256 megabytes | ['constructive algorithms', '*800'] |
F. The Third Gracetime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given n intervals and m points on the number line. The i-th intervals covers coordinates [l_i,r_i] and the i-th point is on coordinate i and has coefficient p_i.Initially, all points are not activated. You should choose a subset of the m points to activate. For each of n interval, we define its cost as: 0, if there are no activated points in the interval; the coefficient of the activated point with the largest coordinate within it, otherwise. Your task is to maximize the sum of the costs of all intervals by choosing which points to activate.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (1 \le n \le 10^6, 1 \le m \le 10^6) — the number of intervals and the number of points.The following n lines of each test case contains two integers l_i and r_i (1 \le l_i \le r_i \le m) — the endpoints of the i-th interval.The following line of each test case contains m integers p_1,p_2,\ldots,p_m (0 \le p_i \le 10^9) — the coefficients of the points.It is guaranteed that the sum of n does not exceed 10^6 and the sum of m does not exceed 10^6.OutputOutput the maximum possible sum of costs of all intervals.ExampleInput
22 81 53 878 0 50 0 0 0 0 301 61 50 0 0 0 0 100Output
108
0
NoteIn the first sample, we can activate points 1 and 8. The sum of costs of all intervals will be 78+30=108.In the second sample, we will activate no points. The sum of costs of all intervals will be 0. | 22 81 53 878 0 50 0 0 0 0 301 61 50 0 0 0 0 100 | 108 0 | 5 seconds | 1024 megabytes | ['data structures', 'dp', '*3200'] |
E. Bully Sorttime limit per test10 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputOn a permutation p of length n, we define a bully swap as follows: Let i be the index of the largest element p_i such that p_i \neq i. Let j be the index of the smallest element p_j such that i < j. Swap p_i and p_j. We define f(p) as the number of bully swaps we need to perform until p becomes sorted. Note that if p is the identity permutation, f(p)=0.You are given n and a permutation p of length n. You need to process the following q updates.In each update, you are given two integers x and y. You will swap p_x and p_y and then find the value of f(p).Note that the updates are persistent. Changes made to the permutation p will apply when processing future updates.InputThe first line of the input contains two integers n and q (2 \le n \le 5 \cdot 10^5, 1 \le q \le 5 \cdot 10^4) — the length of the permutation and the number of updates.The second line of input contains n integer p_1,p_2,\ldots,p_n (1 \leq p_i \leq n) — the permutation p. All elements of p are distinct.The i-th of the next q lines of input contains two integers x_i and y_i (1 \le x_i < y_i \le n) — describing the i-th update.OutputAfter each update, output f(p).ExampleInput
8 5
6 2 1 5 3 4 7 8
1 8
2 3
4 7
7 8
3 6
Output
5
6
9
8
7
NoteAfter the first update, we have f(p)=5. The 5 bully swaps are illustrated below. [\mathbf{1}, 2, \mathbf{8}, 5, 3, 4, 7, 6], [1, 2, \mathbf{3}, 5, \mathbf{8}, 4, 7, 6], [1, 2, 3, 5, \mathbf{4}, \mathbf{8}, 7, 6], [1, 2, 3, 5, 4, \mathbf{6}, 7, \mathbf{8}], [1, 2, 3, \mathbf{4}, \mathbf{5}, 6, 7, 8]. | 8 5
6 2 1 5 3 4 7 8
1 8
2 3
4 7
7 8
3 6
| 5 6 9 8 7 | 10 seconds | 1024 megabytes | ['data structures', 'math', '*3500'] |
D. Mex Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n nodes. For each node, you either color it in 0 or 1.The value of a path (u,v) is equal to the MEX^\dagger of the colors of the nodes from the shortest path between u and v.The value of a coloring is equal to the sum of values of all paths (u,v) such that 1 \leq u \leq v \leq n.What is the maximum possible value of any coloring of the tree?^{\dagger} The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance: The MEX of [2,2,1] is 0, because 0 does not belong to the array. The MEX of [3,1,0,1] is 2, because 0 and 1 belong to the array, but 2 does not. The MEX of [0,3,1,2] is 4 because 0, 1, 2, and 3 belong to the array, but 4 does not. InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of nodes in the tree.The following n-1 lines of each test case contains 2 integers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i) — indicating an edge between vertices a_i and b_i. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the maximum possible value of any coloring of the tree.ExampleInput
431 22 341 21 31 4101 21 33 43 51 65 72 86 96 101Output
8
15
96
1
NoteIn the first sample, we will color vertex 2 in 1 and vertices 1,3 in 0. After this, we consider all paths: (1,1) with value 1 (1,2) with value 2 (1,3) with value 2 (2,2) with value 0 (2,3) with value 2 (3,3) with value 1 We notice the sum of values is 8 which is the maximum possible. | 431 22 341 21 31 4101 21 33 43 51 65 72 86 96 101 | 8 15 96 1 | 3 seconds | 256 megabytes | ['brute force', 'dp', 'trees', '*2800'] |
C. Hyperregular Bracket Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n and k intervals. The i-th interval is [l_i,r_i] where 1 \leq l_i \leq r_i \leq n.Let us call a regular bracket sequence^{\dagger,\ddagger} of length n hyperregular if for each i such that 1 \leq i \leq k, the substring \overline{s_{l_i} s_{l_{i}+1} \ldots s_{r_i}} is also a regular bracket sequence.Your task is to count the number of hyperregular bracket sequences. Since this number can be really large, you are only required to find it modulo 998\,244\,353.^\dagger A bracket sequence is a string containing only the characters "(" and ")".^\ddagger A bracket sequence is called regular if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are regular, while )(, ((), and (()))( are not.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and k (1 \le n \le 3 \cdot 10^5, 0 \le k \le 3 \cdot 10^5) — the length of the hyperregular bracket sequences and the number of intervals respectively.The following k lines of each test case contains two integers l_i and r_i (1 \le l \le r \le n).It is guaranteed that the sum of n across all test cases does not exceed 3 \cdot 10^5 and the sum of k across all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output the number of hyperregular bracket sequences modulo 998\,244\,353.ExampleInput
76 05 08 11 310 23 46 91000 3100 701200 801300 90128 51 123 2011 144 918 194 31 41 41 4Output
5
0
0
4
839415253
140
2
Note For the first testcase, the 5 hyperregular bracket strings of length 6 are: ((())), (()()), (())(), ()(()) and ()()(). For the second testcase, there are no regular bracket strings of length 5, and consequently, there are no hyperregular bracket strings of length 5. For the third testcase, there are no hyperregular bracket strings of length 8 for which the substring [1 \ldots 3] is a regular bracket string. For the fourth testcase, there 4 hyperregular bracket strings are: ((())(())), ((())()()), ()()((())) and ()()(()()) | 76 05 08 11 310 23 46 91000 3100 701200 801300 90128 51 123 2011 144 918 194 31 41 41 4 | 5 0 0 4 839415253 140 2 | 3 seconds | 256 megabytes | ['combinatorics', 'greedy', 'hashing', 'math', 'number theory', 'sortings', '*2400'] |
B. The BOSS Can Count Pairstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, both of length n.Your task is to count the number of pairs of integers (i,j) such that 1 \leq i < j \leq n and a_i \cdot a_j = b_i+b_j.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the length of the arrays.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le n) — the elements of array a.The third line of each test case contains n integers b_1,b_2,\ldots,b_n (1 \le b_i \le n) — the elements of array b.It is guaranteed that the sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the number of good pairs.ExampleInput
332 3 23 3 184 2 8 2 1 2 7 53 5 8 8 1 1 6 584 4 8 8 8 8 8 88 8 8 8 8 8 8 8Output
2
7
1
NoteIn the first sample, there are 2 good pairs: (1,2), (1,3). In the second sample, there are 7 good pairs: (1,2), (1,5), (2,8), (3,4), (4,7), (5,6), (5,7). | 332 3 23 3 184 2 8 2 1 2 7 53 5 8 8 1 1 6 584 4 8 8 8 8 8 88 8 8 8 8 8 8 8 | 2 7 1 | 4 seconds | 512 megabytes | ['brute force', 'math', '*2000'] |
A. Copil Copac Draws Treestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCopil Copac is given a list of n-1 edges describing a tree of n vertices. He decides to draw it using the following algorithm: Step 0: Draws the first vertex (vertex 1). Go to step 1. Step 1: For every edge in the input, in order: if the edge connects an already drawn vertex u to an undrawn vertex v, he will draw the undrawn vertex v and the edge. After checking every edge, go to step 2. Step 2: If all the vertices are drawn, terminate the algorithm. Else, go to step 1. The number of readings is defined as the number of times Copil Copac performs step 1.Find the number of readings needed by Copil Copac to draw the tree.InputEach test contains multiple test cases. The first line of input contains a single 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 a single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices of the tree.The following n - 1 lines of each test case contain two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i) — indicating that (u_i,v_i) is the i-th edge in the list. It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the number of readings Copil Copac needs to draw the tree.ExampleInput
264 51 31 23 41 675 62 42 71 31 24 5Output
2
3
NoteIn the first test case:After the first reading, the tree will look like this: After the second reading: Therefore, Copil Copac needs 2 readings to draw the tree. | 264 51 31 23 41 675 62 42 71 31 24 5 | 2 3 | 3 seconds | 256 megabytes | ['dfs and similar', 'dp', 'graphs', 'trees', '*1400'] |
H. Don't Blame Metime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSadly, the problem setter couldn't think of an interesting story, thus he just asks you to solve the following problem.Given an array a consisting of n positive integers, count the number of non-empty subsequences for which the bitwise \mathsf{AND} of the elements in the subsequence has exactly k set bits in its binary representation. The answer may be large, so output it modulo 10^9+7.Recall that the subsequence of an array a is a sequence that can be obtained from a by removing some (possibly, zero) elements. For example, [1, 2, 3], [3], [1, 3] are subsequences of [1, 2, 3], but [3, 2] and [4, 5, 6] are not.Note that \mathsf{AND} represents the bitwise AND operation.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 consists of two integers n and k (1 \leq n \leq 2 \cdot 10^5, 0 \le k \le 6) — the length of the array and the number of set bits that the bitwise \mathsf{AND} the counted subsequences should have in their binary representation.The second line of each test case consists of n integers a_i (0 \leq a_i \leq 63) — the array a.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 integer — the number of subsequences that have exactly k set bits in their bitwise \mathsf{AND} value's binary representation. The answer may be large, so output it modulo 10^9+7.ExampleInput
65 11 1 1 1 14 00 1 2 35 15 5 7 4 21 2312 00 2 0 2 0 2 0 2 0 2 0 210 663 0 63 5 5 63 63 4 12 13Output
31
10
10
1
4032
15
| 65 11 1 1 1 14 00 1 2 35 15 5 7 4 21 2312 00 2 0 2 0 2 0 2 0 2 0 210 663 0 63 5 5 63 63 4 12 13 | 31 10 10 1 4032 15 | 2 seconds | 256 megabytes | ['bitmasks', 'combinatorics', 'dp', 'math', '*1700'] |
G. Hits Differenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a carnival game, there is a huge pyramid of cans with 2023 rows, numbered in a regular pattern as shown. If can 9^2 is hit initially, then all cans colored red in the picture above would fall. You throw a ball at the pyramid, and it hits a single can with number n^2. This causes all cans that are stacked on top of this can to fall (that is, can n^2 falls, then the cans directly above n^2 fall, then the cans directly above those cans, and so on). For example, the picture above shows the cans that would fall if can 9^2 is hit.What is the sum of the numbers on all cans that fall? Recall that n^2 = n \times n.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The only line of each test case contains a single integer n (1 \leq n \leq 10^6) — it means that the can you hit has label n^2.OutputFor each test case, output a single integer — the sum of the numbers on all cans that fall.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++). For all valid inputs, the answer will always fit into 64-bit integer type.ExampleInput
1091234561014341000000Output
156
1
5
10
21
39
46
146
63145186
58116199242129511
NoteThe first test case is pictured in the statement. The sum of the numbers that fall is 1^2 + 2^2 + 3^2 + 5^2 + 6^2 + 9^2 = 1 + 4 + 9 + 25 + 36 + 81 = 156.In the second test case, only the can labeled 1^2 falls, so the answer is 1^2=1.In the third test case, the cans labeled 1^2 and 2^2 fall, so the answer is 1^2+2^2=1+4=5.In the fourth test case, the cans labeled 1^2 and 3^2 fall, so the answer is 1^2+3^2=1+9=10.In the fifth test case, the cans labeled 1^2, 2^2, and 4^2 fall, so the answer is 1^2+2^2+4^2=1+4+16=21. | 1091234561014341000000 | 156 1 5 10 21 39 46 146 63145186 58116199242129511 | 2.5 seconds | 256 megabytes | ['data structures', 'dp', 'implementation', 'math', '*1600'] |
F. Forever Wintertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA snowflake graph is generated from two integers x and y, both greater than 1, as follows: Start with one central vertex. Connect x new vertices to this central vertex. Connect y new vertices to each of these x vertices. For example, below is a snowflake graph for x=5 and y=3. The snowflake graph above has a central vertex 15, then x=5 vertices attached to it (3, 6, 7, 8, and 20), and then y=3 vertices attached to each of those. Given a snowflake graph, determine the values of x and y.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains two integers n and m (2 \leq n \leq 200; 1 \leq m \leq \min\left(1000, \frac{n(n-1)}{2}\right)) — the number of vertices and edges in the graph, respectively.The next m lines each contain two integers each u and v (1 \leq u, v \leq n, u \neq v) — the numbers of vertices connected by an edge. The graph does not contain multiple edges and self-loops.It is guaranteed that this graph is a snowflake graph for some integers x and y both greater than 1.OutputFor each test case, on a separate line output the values of x and y, in that order, separated by a space.ExampleInput
321 2021 205 2013 201 311 310 34 819 814 89 712 717 718 616 62 66 157 158 1520 153 157 61 21 32 42 53 63 79 89 33 66 22 15 22 74 33 8Output
5 3
2 2
2 3
NoteThe first test case is pictured in the statement. Note that the output 3 5 is incorrect, since x should be output before y. | 321 2021 205 2013 201 311 310 34 819 814 89 712 717 718 616 62 66 157 158 1520 153 157 61 21 32 42 53 63 79 89 33 66 22 15 22 74 33 8 | 5 3 2 2 2 3 | 2 seconds | 256 megabytes | ['dfs and similar', 'graphs', 'math', '*1300'] |
E. The Lakestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an n \times m grid a of non-negative integers. The value a_{i,j} represents the depth of water at the i-th row and j-th column. A lake is a set of cells such that: each cell in the set has a_{i,j} > 0, and there exists a path between any pair of cells in the lake by going up, down, left, or right a number of times and without stepping on a cell with a_{i,j} = 0. The volume of a lake is the sum of depths of all the cells in the lake.Find the largest volume of a lake in the grid.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains two integers n, m (1 \leq n, m \leq 1000) — the number of rows and columns of the grid, respectively.Then n lines follow each with m integers a_{i,j} (0 \leq a_{i,j} \leq 1000) — the depth of the water at each cell.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 10^6.OutputFor each test case, output a single integer — the largest volume of a lake in the grid.ExampleInput
53 31 2 03 4 00 0 51 103 30 1 11 0 11 1 15 51 1 1 1 11 0 0 0 11 0 5 0 11 0 0 0 11 1 1 1 15 51 1 1 1 11 0 0 0 11 1 4 0 11 0 0 0 11 1 1 1 1Output
10
0
7
16
21
| 53 31 2 03 4 00 0 51 103 30 1 11 0 11 1 15 51 1 1 1 11 0 0 0 11 0 5 0 11 0 0 0 11 1 1 1 15 51 1 1 1 11 0 0 0 11 1 4 0 11 0 0 0 11 1 1 1 1 | 10 0 7 16 21 | 3 seconds | 256 megabytes | ['dfs and similar', 'dsu', 'graphs', 'implementation', '*1100'] |
D. Gold Rushtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputInitially you have a single pile with n gold nuggets. In an operation you can do the following: Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold nuggets as the other. (All piles should have an integer number of nuggets.) One possible move is to take a pile of size 6 and split it into piles of sizes 2 and 4, which is valid since 4 is twice as large as 2. Can you make a pile with exactly m gold nuggets using zero or more operations?InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The only line of each test case contains two integers n and m (1 \leq n, m \leq 10^7) — the starting and target pile sizes, respectively.OutputFor each test case, output "YES" if you can make a pile of size exactly m, 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
116 49 44 218 2727 427 227 101 13 15 1746001 2984004Output
YES
YES
NO
NO
YES
YES
NO
YES
YES
NO
NO
NoteThe first test case is pictured in the statement. We can make a pile of size 4.In the second test case, we can perform the following operations: \{\color{red}{9}\} \to \{\color{red}{6},3\} \to \{4,2,3\}. The pile that is split apart is colored red before each operation.In the third test case, we can't perform a single operation.In the fourth test case, we can't end up with a larger pile than we started with. | 116 49 44 218 2727 427 227 101 13 15 1746001 2984004 | YES YES NO NO YES YES NO YES YES NO NO | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dp', 'implementation', '*1000'] |
C. Mr. Perfectly Finetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVictor wants to become "Mr. Perfectly Fine". For that, he needs to acquire a certain set of skills. More precisely, he has 2 skills he needs to acquire. Victor has n books. Reading book i takes him m_i minutes and will give him some (possibly none) of the required two skills, represented by a binary string of length 2.What is the minimum amount of time required so that Victor acquires all of the two skills? InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — 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 \cdot 10^5) — the number of books available.Then n lines follow. Line i contains a positive integer m_i (1 \leq m_i \leq 2 \cdot 10^5) and a binary string of length 2, where s_{i1} = 1 if reading book i acquires Victor skill 1, and s_{i1} = 0 otherwise, and s_{i2} = 1 if reading book i acquires Victor skill 2, and s_{i2} = 0 otherwise.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 integer denoting the minimum amount of minutes required for Victor to obtain both needed skills and -1 in case it's impossible to obtain the two skills after reading any amount of books. ExampleInput
642 003 104 014 0053 013 015 012 109 1015 1139 118 017 1064 016 017 018 009 011 0048 009 109 118 11Output
7
5
5
9
-1
8
NoteIn the first test case, we can use books 2 and 3, with a total amount of minutes spent equal to 3 + 4 = 7.In the second test case, we can use the books 1 and 4, with a total amount of minutes spent equal to 3 + 2 = 5.In the third test case, we have only one option and that is reading book 1 for a total amount of minutes spent equal to 5. | 642 003 104 014 0053 013 015 012 109 1015 1139 118 017 1064 016 017 018 009 011 0048 009 109 118 11 | 7 5 5 9 -1 8 | 2 seconds | 256 megabytes | ['bitmasks', 'greedy', 'implementation', '*800'] |
B. Blank Spacetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary array a of n elements, a binary array is an array consisting only of 0s and 1s. A blank space is a segment of consecutive elements consisting of only 0s. Your task is to find the length of the longest blank space.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100) — the length of the array.The second line of each test case contains n space-separated integers a_i (0 \leq a_i \leq 1) — the elements of the array.OutputFor each test case, output a single integer — the length of the longest blank space.ExampleInput
551 0 0 1 040 1 1 11031 1 191 0 0 0 1 0 0 0 1Output
2
1
1
0
3
| 551 0 0 1 040 1 1 11031 1 191 0 0 0 1 0 0 0 1 | 2 1 1 0 3 | 1 second | 256 megabytes | ['implementation', '*800'] |
A. Love Storytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTimur loves codeforces. That's why he has a string s having length 10 made containing only lowercase Latin letters. Timur wants to know how many indices string s differs from the string "codeforces".For example string s = "coolforsez" differs from "codeforces" in 4 indices, shown in bold.Help Timur by finding the number of indices where string s differs from "codeforces".Note that you can't reorder the characters in the string s.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.Each test case is one line and contains the string s, consisting of exactly 10 lowercase Latin characters.OutputFor each test case, output a single integer — the number of indices where string s differs.ExampleInput
5coolforsezcadafurciecodeforcespaiuforcesforcescodeOutput
4
5
0
4
9
| 5coolforsezcadafurciecodeforcespaiuforcesforcescode | 4 5 0 4 9 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
B. Permutation Swaptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unsorted permutation p_1, p_2, \ldots, p_n. To sort the permutation, you choose a constant k (k \ge 1) and do some operations on the permutation. In one operation, you can choose two integers i, j (1 \le j < i \le n) such that i - j = k, then swap p_i and p_j.What is the maximum value of k that you can choose to sort the given permutation?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 unsorted permutation p is a permutation such that there is at least one position i that satisfies p_i \ne i.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 a single integer n (2 \le n \le 10^{5}) — the length of the permutation p.The second line of each test case contains n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the permutation p. It is guaranteed that the given numbers form a permutation of length n and the given permutation is unsorted.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^{5}.OutputFor each test case, output the maximum value of k that you can choose to sort the given permutation.We can show that an answer always exists.ExampleInput
733 1 243 4 1 274 2 6 7 5 3 191 6 7 4 9 2 3 8 561 5 3 4 2 6103 10 5 2 9 6 7 8 1 4111 11 6 4 8 3 7 5 9 10 2Output
1
2
3
4
3
2
3
NoteIn the first test case, the maximum value of k you can choose is 1. The operations used to sort the permutation are: Swap p_2 and p_1 (2 - 1 = 1) \rightarrow p = [1, 3, 2] Swap p_2 and p_3 (3 - 2 = 1) \rightarrow p = [1, 2, 3] In the second test case, the maximum value of k you can choose is 2. The operations used to sort the permutation are: Swap p_3 and p_1 (3 - 1 = 2) \rightarrow p = [1, 4, 3, 2] Swap p_4 and p_2 (4 - 2 = 2) \rightarrow p = [1, 2, 3, 4] | 733 1 243 4 1 274 2 6 7 5 3 191 6 7 4 9 2 3 8 561 5 3 4 2 6103 10 5 2 9 6 7 8 1 4111 11 6 4 8 3 7 5 9 10 2 | 1 2 3 4 3 2 3 | 1 second | 256 megabytes | ['math', 'number theory', '*900'] |
A. Divisible Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Please find an array a_1, a_2, \ldots, a_n that is perfect.A perfect array a_1, a_2, \ldots, a_n satisfies the following criteria: 1 \le a_i \le 1000 for all 1 \le i \le n. a_i is divisible by i for all 1 \le i \le n. a_1 + a_2 + \ldots + a_n is divisible by n. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200). The description of the test cases follows.The only line of each test case contains a single positive integer n (1 \le n \le 200) — the length of the array a.OutputFor each test case, output an array a_1, a_2, \ldots, a_n that is perfect.We can show that an answer always exists. If there are multiple solutions, print any.ExampleInput
71234567Output
1
2 4
1 2 3
2 8 6 4
3 4 9 4 5
1 10 18 8 5 36
3 6 21 24 10 6 14
NoteIn the third test case: a_1 = 1 is divisible by 1. a_2 = 2 is divisible by 2. a_3 = 3 is divisible by 3. a_1 + a_2 + a_3 = 1 + 2 + 3 = 6 is divisible by 3. In the fifth test case: a_1 = 3 is divisible by 1. a_2 = 4 is divisible by 2. a_3 = 9 is divisible by 3. a_4 = 4 is divisible by 4. a_5 = 5 is divisible by 5. a_1 + a_2 + a_3 + a_4 + a_5 = 3 + 4 + 9 + 4 + 5 = 25 is divisible by 5. | 71234567 | 1 2 4 1 2 3 2 8 6 4 3 4 9 4 5 1 10 18 8 5 36 3 6 21 24 10 6 14 | 1 second | 256 megabytes | ['constructive algorithms', 'math', '*800'] |
F. Copium Permutationtime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a permutation a_1,a_2,\ldots,a_n of the first n positive integers. A subarray [l,r] is called copium if we can rearrange it so that it becomes a sequence of consecutive integers, or more formally, if \max(a_l,a_{l+1},\ldots,a_r)-\min(a_l,a_{l+1},\ldots,a_r)=r-l For each k in the range [0,n], print out the maximum number of copium subarrays of a over all ways of rearranging the last n-k elements of a.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 a single integer n (1\le n\le 2\cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n). It is guaranteed that the given numbers form a permutation 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 print n+1 integers as the answers for each k in the range [0,n].ExampleInput
555 2 1 4 342 1 4 31187 5 8 1 4 2 6 3101 4 5 3 7 8 9 2 10 6Output
15 15 11 10 9 9
10 8 8 7 7
1 1
36 30 25 19 15 13 12 9 9
55 55 41 35 35 25 22 22 19 17 17
NoteIn the first test case, the answer permutations for each k are [1,2,3,4,5], [5,4,3,2,1], [5,2,3,4,1], [5,2,1,3,4], [5,2,1,4,3], [5,2,1,4,3].In the second test case, the answer permutations for each k are [1,2,3,4], [2,1,3,4], [2,1,3,4], [2,1,4,3], [2,1,4,3]. | 555 2 1 4 342 1 4 31187 5 8 1 4 2 6 3101 4 5 3 7 8 9 2 10 6 | 15 15 11 10 9 9 10 8 8 7 7 1 1 36 30 25 19 15 13 12 9 9 55 55 41 35 35 25 22 22 19 17 17 | 2 seconds | 1024 megabytes | ['constructive algorithms', 'data structures', 'greedy', '*3500'] |
E. Bus Routestime limit per test2.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere is a country consisting of n cities and n - 1 bidirectional roads connecting them such that we can travel between any two cities using these roads. In other words, these cities and roads form a tree.There are m bus routes connecting the cities together. A bus route between city x and city y allows you to travel between any two cities in the simple path between x and y with this route.Determine if for every pair of cities u and v, you can travel from u to v using at most two bus routes.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 two integers n and m (2 \le n \le 5 \cdot 10^5, 0 \le m \le 5 \cdot 10^5) — the number of cities and the number of bus routes.Then n - 1 lines follow. Each line contains two integers u and v denoting a road connecting city u and city v (1 \le u, v \le n, u \neq v). It is guaranteed that these cities and roads form a tree.Then m lines follow. Each line contains two integers x and y denoting a bus route between city x and city y (1 \le x, y \le n).It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5 and the sum of m over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, output "YES" if you can travel between any pair of cities using at most two bus routes.Otherwise, output "NO". In the next line, output two cities x and y (1 \le x, y \le n) such that it is impossible to reach city y from city x using at most two bus routes.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput
45 21 22 33 42 51 45 25 11 22 33 42 51 52 01 26 31 22 33 44 55 61 32 54 6Output
YES
NO
1 3
NO
1 2
NO
1 6NoteHere are the graphs of test case 1, 2, and 4: Sample 1 Sample 2 Sample 4 | 45 21 22 33 42 51 45 25 11 22 33 42 51 52 01 26 31 22 33 44 55 61 32 54 6 | YES NO 1 3 NO 1 2 NO 1 6 | 2.5 seconds | 1024 megabytes | ['binary search', 'constructive algorithms', 'dfs and similar', 'greedy', 'trees', '*3400'] |
D. Two Centroidstime limit per test1.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a tree (an undirected connected acyclic graph) which initially only contains vertex 1. There will be several queries to the given tree. In the i-th query, vertex i + 1 will appear and be connected to vertex p_i (1 \le p_i \le i). After each query, please find out the least number of operations required to make the current tree has two centroids. In one operation, you can add one vertex and one edge to the tree such that it remains a tree.A vertex is called a centroid if its removal splits the tree into subtrees with at most \lfloor \frac{n}{2} \rfloor vertices each, with n as the number of vertices of the tree. For example, the centroid of the following tree is 3 because the biggest subtree after removing the centroid has 2 vertices. In the next tree, vertex 1 and 2 are both centroids. 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 a single integer n (2 \le n \le 5 \cdot 10^{5}) — the number of nodes of the final tree.The second line of each test case contains n - 1 integers p_1, p_2, \ldots, p_{n - 1} (1 \le p_i \le i) — the index of the vertex that is connected to vertex i + 1.It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^{5}.OutputFor each test case, output n - 1 integers. The i-th integer is the answer to the i-th query — the least number of operations required to make the current tree have two centroids.We can show that an answer always exists.ExampleInput
52131 141 2 371 2 3 2 5 2101 2 2 4 5 5 7 8 9Output
0
0 1
0 1 0
0 1 0 1 2 3
0 1 2 1 0 1 0 1 2NoteThe illustrations below are of the fourth example test case.After the third query: The tree already has vertices 2 and 3 as centroids, so no operations are needed.After the fourth query: Adding vertex x to the tree makes vertices 2 and 3 centroids. Only one operation is needed.After the fifth query: Adding vertex x and y to the tree makes vertices 5 and 2 centroids. Two operations are needed.After the sixth query: Adding vertex x, y, and z to the tree makes vertices 5 and 2 centroids. Three operations are needed. | 52131 141 2 371 2 3 2 5 2101 2 2 4 5 5 7 8 9 | 0 0 1 0 1 0 0 1 0 1 2 3 0 1 2 1 0 1 0 1 2 | 1.5 seconds | 1024 megabytes | ['data structures', 'dfs and similar', 'greedy', 'trees', '*2800'] |
C. Palindrome Partitiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA substring is a continuous and non-empty segment of letters from a given string, without any reorders.An even palindrome is a string that reads the same backward as forward and has an even length. For example, strings "zz", "abba", "abccba" are even palindromes, but strings "codeforces", "reality", "aba", "c" are not.A beautiful string is an even palindrome or a string that can be partitioned into some smaller even palindromes.You are given a string s, consisting of n lowercase Latin letters. Count the number of beautiful substrings of s.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 a single integer n (1 \le n \le 5\cdot 10^5).The second line of each test case contains a string s. String s consists of only lowercase Latin letters and has a length of n.It is guaranteed that the sum of n over all test cases does not exceed 5\cdot 10^5.OutputFor each test case print the number of beautiful substrings.ExampleInput
66abaaba1a2aa6abcdef12accabccbacca6abbaaaOutput
3
0
1
0
14
6
NoteIn the first test case, the beautiful substrings are "abaaba", "baab", "aa".In the last test case, the beautiful substrings are "aa" (counted twice), "abba", "bb", "bbaa", "abbaaa". | 66abaaba1a2aa6abcdef12accabccbacca6abbaaa | 3 0 1 0 14 6 | 1 second | 256 megabytes | ['binary search', 'brute force', 'data structures', 'dp', 'hashing', 'strings', '*2600'] |
B2. Range Sorting (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the easy version is the constraints on t and n.You are given an array a, consisting of n distinct integers a_1, a_2, \ldots, a_n. Define the beauty of an array p_1, p_2, \ldots p_k as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following: Choose two integers l and r (1 \le l < r \le k). Sort the subarray p_l, p_{l + 1}, \ldots, p_r in r - l seconds. Please calculate the sum of beauty over all subarrays of array a.A subarray of an array is defined as a sequence of consecutive elements of the array.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 a single integer n (1 \le n \le 3 \cdot 10^5) — the length of the array a.The second line of each test case consists of n integers a_1,a_2,\ldots, a_n (1\le a_i\le 10^9). It is guaranteed that all elements of a are pairwise distinct.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output the sum of beauty over all subarrays of array a.ExampleInput
526 433 10 644 8 7 259 8 2 4 6122 6 13 3 15 5 10 8 16 9 11 18Output
1
2
8
16
232
NoteIn the first test case: The subarray [6] is already sorted, so its beauty is 0. The subarray [4] is already sorted, so its beauty is 0. You can sort the subarray [6, 4] in one operation by choosing l = 1 and r = 2. Its beauty is equal to 1. The sum of beauty over all subarrays of the given array is equal to 0 + 0 + 1 = 1.In the second test case: The subarray [3] is already sorted, so its beauty is 0. The subarray [10] is already sorted, so its beauty is 0. The subarray [6] is already sorted, so its beauty is 0. The subarray [3, 10] is already sorted, so its beauty is 0. You can sort the subarray [10, 6] in one operation by choosing l = 1 and r = 2. Its beauty is equal to 2 - 1 = 1. You can sort the subarray [3, 10, 6] in one operation by choosing l = 2 and r = 3. Its beauty is equal to 3 - 2 = 1. The sum of beauty over all subarrays of the given array is equal to 0 + 0 + 0 + 0 + 1 + 1 = 2. | 526 433 10 644 8 7 259 8 2 4 6122 6 13 3 15 5 10 8 16 9 11 18 | 1 2 8 16 232 | 1 second | 256 megabytes | ['binary search', 'data structures', 'dp', 'greedy', '*2400'] |
B1. Range Sorting (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the hard version is the constraints on t and n.You are given an array a, consisting of n distinct integers a_1, a_2, \ldots, a_n. Define the beauty of an array p_1, p_2, \ldots p_k as the minimum amount of time needed to sort this array using an arbitrary number of range-sort operations. In each range-sort operation, you will do the following: Choose two integers l and r (1 \le l < r \le k). Sort the subarray p_l, p_{l + 1}, \ldots, p_r in r - l seconds. Please calculate the sum of beauty over all subarrays of array a.A subarray of an array is defined as a sequence of consecutive elements of the array.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 5 \cdot 10^3). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 5 \cdot 10^3) — the length of the array a.The second line of each test case consists of n integers a_1,a_2,\ldots, a_n (1\le a_i\le 10^9). It is guaranteed that all elements of a are pairwise distinct.It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^3.OutputFor each test case, output the sum of beauty over all subarrays of array a.ExampleInput
526 433 10 644 8 7 259 8 2 4 6122 6 13 3 15 5 10 8 16 9 11 18Output
1
2
8
16
232
NoteIn the first test case: The subarray [6] is already sorted, so its beauty is 0. The subarray [4] is already sorted, so its beauty is 0. You can sort the subarray [6, 4] in one operation by choosing l = 1 and r = 2. Its beauty is equal to 1. The sum of beauty over all subarrays of the given array is equal to 0 + 0 + 1 = 1.In the second test case: The subarray [3] is already sorted, so its beauty is 0. The subarray [10] is already sorted, so its beauty is 0. The subarray [6] is already sorted, so its beauty is 0. The subarray [3, 10] is already sorted, so its beauty is 0. You can sort the subarray [10, 6] in one operation by choosing l = 1 and r = 2. Its beauty is equal to 2 - 1 = 1. You can sort the subarray [3, 10, 6] in one operation by choosing l = 2 and r = 3. Its beauty is equal to 3 - 2 = 1. The sum of beauty over all subarrays of the given array is equal to 0 + 0 + 0 + 0 + 1 + 1 = 2. | 526 433 10 644 8 7 259 8 2 4 6122 6 13 3 15 5 10 8 16 9 11 18 | 1 2 8 16 232 | 1 second | 256 megabytes | ['binary search', 'dp', 'dsu', 'greedy', 'trees', 'two pointers', '*2000'] |
A. Counting Orderstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b each consisting of n integers. All elements of a are pairwise distinct.Find the number of ways to reorder a such that a_i > b_i for all 1 \le i \le n, modulo 10^9 + 7.Two ways of reordering are considered different if the resulting arrays are different.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 a single integer n (1 \le n \le 2 \cdot 10^{5}) — the length of the array a and b.The second line of each test case contains n distinct integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the array a. It is guaranteed that all elements of a are pairwise distinct.The second line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 10^9) — the array b.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^{5}.OutputFor each test case, output the number of ways to reorder array a such that a_i > b_i for all 1 \le i \le n, modulo 10^9 + 7.ExampleInput
569 6 8 4 5 24 1 5 6 3 134 3 23 4 912132 3 41 3 3122 3 7 10 23 28 29 50 69 135 420 10001 1 2 3 5 8 13 21 34 55 89 144Output
32
0
1
0
13824
| 569 6 8 4 5 24 1 5 6 3 134 3 23 4 912132 3 41 3 3122 3 7 10 23 28 29 50 69 135 420 10001 1 2 3 5 8 13 21 34 55 89 144 | 32 0 1 0 13824 | 1 second | 256 megabytes | ['combinatorics', 'math', 'sortings', 'two pointers', '*1100'] |
F. Fading into Fogtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There are n distinct hidden points with real coordinates on a two-dimensional Euclidean plane. In one query, you can ask some line ax + by + c = 0 and get the projections of all n points to this line in some order. The given projections are not exact, please read the interaction section for more clarity.Using the minimum number of queries, guess all n points and output them in some order. Here minimality means the minimum number of queries required to solve any possible test case with n points.The hidden points are fixed in advance and do not change throughout the interaction. In other words, the interactor is not adaptive.A projection of point A to line ax + by + c = 0 is the point on the line closest to A.InputThe first line contains a single integer t (1 \leq t \leq 50) — 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 25) — the number of hidden points.For each test case, it is guaranteed that for any pair of hidden points, their x coordinates differ by at least 1. Analogously, y coordinates of any pair also differ by at least 1.Coordinates x and y of all hidden points do not exceed 100 by absolute value.InteractionTo query a line ax + by + c = 0 you should print "? a b c" where all a, b and c are real numbers up to 100 by absolute value. For less precision issues numbers a and b must satisfy the condition |a| + |b| \geq 0.1, where |a| is the absolute value of a. As an answer to the query you will get n points in the form "x_1 y_1 ... x_n y_n", where points (x_i, y_i) are projections to the line ax + by + c = 0. It is guaranteed that each printed point is no more than 10^{-4} away from the real projection point. Every coordinate is printed with at most 9 decimal places.See the interaction example for more clarity.If you ask too many queries, you will get Wrong answer.To output an answer you should print "! x_1 y_1 ... x_n y_n", where (x_i, y_i) are coordinates of the hidden points. You could output the hidden points in any order. The answer would be considered correct if each of the printed points is no more than 10^{-3} away from the corresponding hidden point. Printing the answer doesn't count as a query.After printing a query or the answer, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages HacksTo make a hack, use the following test format.In the first line output a single integer t (1 \leq t \leq 50) — the number of test cases.The description of the test cases follows.In the first line of each test case output a single integer n (2 \leq n \leq 25). In the next n lines output two rational numbers each. The numbers in line i should correspond to x_i and y_i respectively. Printed points must comply with all constraints from the input section.ExampleInput
1
2
1 1 2.5 1
1.500000001 1.500000000 2 2
Output
? 0 1 -1
? 0.2 -0.2 0
! 1 3 2.5 0.500000001NoteIn the sample the hidden points are (1, 3) and (2.5, 0.5)A picture, which describes the first query:A picture, which describes the second query: | 1
2
1 1 2.5 1
1.500000001 1.500000000 2 2
| ? 0 1 -1 ? 0.2 -0.2 0 ! 1 3 2.5 0.500000001 | 4 seconds | 256 megabytes | ['geometry', 'interactive', 'math', 'probabilities', '*2800'] |
E. Walk the Runwaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA fashion tour consists of m identical runway shows in different cities. There are n models willing to participate in the tour, numbered from 1 to n. People in different cities have different views on the fashion industry, so they rate each model differently. In particular, people in city i rate model j with rating r_{i, j}.You are to choose some number of k models, and their order, let the chosen models have indices j_1, j_2, \dots, j_k in the chosen order. In each city, these k models will walk the runway one after another in this order. To make the show exciting, in each city, the ratings of models should be strictly increasing in the order of their performance. More formally, for any city i and index t (2 \leq t \leq k), the ratings must satisfy r_{i,j_{t - 1}} < r_{i,j_t}. After all, the fashion industry is all about money, so choosing model j to participate in the tour profits you p_j money. Compute the maximum total profit you can make by choosing the models and their order while satisfying all the requirements.InputThe first line contains two integers m and n (1 \leq m \leq 500, 1 \leq n \leq 5000) — the number of shows and the number of models willing to participate respectively.The second line contains n integers p_j (1 \leq p_j \leq 10^9) — the profit you get inviting the j-th model to the tour.The next m lines each contain n integers. Line number i contains n integers r_{i, j} (1 \leq r_{i, j} \leq n) — the ratings of models in city i.OutputOutput a single integer — the largest total amount of money you can get.ExamplesInput
3 5
10 10 10 10 10
1 2 3 4 5
1 5 2 3 4
2 3 4 5 1
Output
30
Input
3 5
10 10 10 10 50
1 2 3 4 5
1 5 2 3 4
2 3 4 5 1
Output
50
Input
1 1
1000000000
1
Output
1000000000
Input
5 5
1000000000 1000000000 1000000000 1000000000 1000000000
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
5 4 3 2 1
Output
5000000000
Input
1 3
1 2 3
3 3 3
Output
3
NoteIn the first example, there are 3 invited models. The show consists of models in the order [1, 3, 4].Then, the corresponding ratings in the cities are as follows: City 1 — [ 1, 3, 4 ]. City 2 — [ 1, 2, 3 ]. City 3 — [ 2, 4, 5 ]. You can see that the ratings are increasing. So the total profit is 10 + 10 + 10 = 30. It can be proven that we can't achieve a bigger profit.In the second example, we can invite the fifth model to the tour, which would result in a total profit of 50. It can be proven that we can't achieve a bigger profit.In the third example, we invite the single model to the tour, which results in a total profit of 1\,000\,000\,000.In the fourth test case, we can invite all the models and make the show in the order [ 5, 4, 3, 2, 1 ]. The total profit is 5 \cdot 1\,000\,000\,000 = 5\,000\,000\,000. | 3 5
10 10 10 10 10
1 2 3 4 5
1 5 2 3 4
2 3 4 5 1
| 30 | 2 seconds | 256 megabytes | ['bitmasks', 'brute force', 'data structures', 'dp', 'graphs', 'implementation', 'sortings', '*2400'] |
D. Running Milestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a street with n sights, with sight number i being i miles from the beginning of the street. Sight number i has beauty b_i. You want to start your morning jog l miles and end it r miles from the beginning of the street. By the time you run, you will see sights you run by (including sights at l and r miles from the start). You are interested in the 3 most beautiful sights along your jog, but every mile you run, you get more and more tired.So choose l and r, such that there are at least 3 sights you run by, and the sum of beauties of the 3 most beautiful sights minus the distance in miles you have to run is maximized. More formally, choose l and r, such that b_{i_1} + b_{i_2} + b_{i_3} - (r - l) is maximum possible, where i_1, i_2, i_3 are the indices of the three maximum elements in range [l, r].InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.The first line of each test case contains a single integer n (3 \leq n \leq 10^5).The second line of each test case contains n integers b_i (1 \leq b_i \leq 10^8) — beauties of sights i miles from the beginning of the street.It's guaranteed that the sum of all n does not exceed 10^5.OutputFor each test case output a single integer equal to the maximum value b_{i_1} + b_{i_2} + b_{i_3} - (r - l) for some running range [l, r].ExampleInput
455 1 4 2 341 1 1 169 8 7 6 5 47100000000 1 100000000 1 100000000 1 100000000Output
8
1
22
299999996
NoteIn the first example, we can choose l and r to be 1 and 5. So we visit all the sights and the three sights with the maximum beauty are the sights with indices 1, 3, and 5 with beauties 5, 4, and 3, respectively. So the total value is 5 + 4 + 3 - (5 - 1) = 8.In the second example, the range [l, r] can be [1, 3] or [2, 4], the total value is 1 + 1 + 1 - (3 - 1) = 1. | 455 1 4 2 341 1 1 169 8 7 6 5 47100000000 1 100000000 1 100000000 1 100000000 | 8 1 22 299999996 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', '*1700'] |
C. Dreaming of Freedomtime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBecause to take away a man's freedom of choice, even his freedom to make the wrong choice, is to manipulate him as though he were a puppet and not a person.— Madeleine L'EngleThere are n programmers choosing their favorite algorithm amongst m different choice options. Before the first round, all m options are available. In each round, every programmer makes a vote for one of the remaining algorithms. After the round, only the algorithms with the maximum number of votes remain. The voting process ends when there is only one option left. Determine whether the voting process can continue indefinitely or no matter how people vote, they will eventually choose a single option after some finite amount of rounds?InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.Each test case consists of a single line containing two integers n and m (1 \leq n, m \leq 10^6) — the number of people and choice options respectively.OutputFor each test case output "YES" if the programmers will eventually choose a single option, and "NO" otherwise.You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as a positive answer).ExampleInput
53 24 25 31000000 10000001 1000000Output
YES
NO
YES
NO
YES
NoteIn the first example, there are 8 ways people could vote: \{1|1|1, 1|1|2, 1|2|1, 1|2|2, 2|1|1, 2|1|2, 2|2|1, 2|2|2\}.In cases 1, 2, 3, and 5, the programmers are left with the first algorithm, and in the remaining cases people are left with the second one, so the voting ends in one round in any case.In the second example, the programmers could always vote 1|1|2|2. Both algorithms have the maximum number of votes and remain for the next round, so the voting never ends. | 53 24 25 31000000 10000001 1000000 | YES NO YES NO YES | 2.5 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*1300'] |
B. Lunatic Never Contenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of n non-negative integers. Let's define f(a, x) = [a_1 \bmod x, a_2 \bmod x, \dots, a_n \bmod x] for some positive integer x. Find the biggest x, such that f(a, x) is a palindrome.Here, a \bmod x is the remainder of the integer division of a by x.An array is a palindrome if it reads the same backward as forward. More formally, an array a of length n is a palindrome if for every i (1 \leq i \leq n) a_i = a_{n - i + 1}.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 10^5).The second line of each test case contains n integers a_i (0 \leq a_i \leq 10^9).It's guaranteed that the sum of all n does not exceed 10^5.OutputFor each test case output the biggest x, such that f(a, x) is a palindrome. If x can be infinitely large, output 0 instead.ExampleInput
421 283 0 1 2 0 3 2 1103100 1 1000000000Output
1
2
0
999999900
NoteIn the first example, f(a, x = 1) = [0, 0] which is a palindrome.In the second example, f(a, x = 2) = [1, 0, 1, 0, 0, 1, 0, 1] which is a palindrome.It can be proven that in the first two examples, no larger x satisfies the condition.In the third example, f(a, x) = [0] for any x, so we can choose it infinitely large, so the answer is 0. | 421 283 0 1 2 0 3 2 1103100 1 1000000000 | 1 2 0 999999900 | 2 seconds | 256 megabytes | ['math', 'number theory', '*1100'] |
A. Trust Nobodytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a group of n people. Some of them might be liars, who always tell lies. Other people always tell the truth. The i-th person says "There are at least l_i liars amongst us". Determine if what people are saying is contradictory, or if it is possible. If it is possible, output the number of liars in the group. If there are multiple possible answers, output any one of them.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100).The second line of each test case contains n integers l_i (0 \leq l_i \leq n) — the number said by the i-th person.It's guaranteed that the sum of all n does not exceed 10^4.OutputFor each test case output a single integer. If what people are saying is contradictory, output -1. Otherwise, output the number of liars in the group. If there are multiple possible answers, output any one of them.ExampleInput
721 222 220 0111055 5 3 3 565 3 6 6 3 5Output
1
-1
0
-1
0
3
4
NoteIn the first example, the only possible answer is that the second person is a liar, so the answer is 1 liar.In the second example, it can be proven that we can't choose the liars so that all the requirements are satisfied.In the third example, everybody tells the truth, so the answer is 0 liars. | 721 222 220 0111055 5 3 3 565 3 6 6 3 5 | 1 -1 0 -1 0 3 4 | 1 second | 256 megabytes | ['brute force', 'greedy', 'implementation', 'sortings', '*1200'] |
B. LuoTianyi and the Tabletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuoTianyi gave an array b of n \cdot m integers. She asks you to construct a table a of size n \times m, filled with these n \cdot m numbers, and each element of the array must be used exactly once. Also she asked you to maximize the following value: \sum\limits_{i=1}^{n}\sum\limits_{j=1}^{m}\left(\max\limits_{1 \le x \le i, 1 \le y \le j}a_{x,y}-\min\limits_{1 \le x \le i, 1 \le y \le j}a_{x,y}\right) This means that we consider n \cdot m subtables with the upper left corner in (1,1) and the bottom right corner in (i, j) (1 \le i \le n, 1 \le j \le m), for each such subtable calculate the difference of the maximum and minimum elements in it, then sum up all these differences. You should maximize the resulting sum.Help her find the maximal possible value, you don't need to reconstruct the table itself.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 200) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (2 \le n, m \le 100) — the number of rows and columns of the table.The second line of each test case contains n \cdot m integers b_1, b_2, \ldots, b_{n\cdot m} (-10^5 \le b_{i} \le 10^5) — the numbers you can put in the table.Note, that integers in the array b can be negative.It is guaranteed that the sum of n \cdot m over all test cases doesn't exceed 2\cdot 10^5.OutputFor each test case, output a single integer — the maximal value, that can be obtained.ExampleInput
52 21 3 1 42 2-1 -1 -1 -12 37 8 9 -3 10 83 24 8 -3 0 -7 14 3-32030 59554 16854 -85927 68060 -64460 -79547 90932 85063 82703 -12001 38762Output
9
0
64
71
1933711
NoteIn the first test case, the table is follows:4113 In the subtable with the bottom right corner in (1, 1), the difference of the maximal and minimal elements is 4 - 4 = 0.In the subtable with the bottom right corner in (1, 2), the difference of the maximal and minimal elements is 4 - 1 = 3.In the subtable with the bottom right corner in (2, 1), the difference of the maximal and minimal elements is 4 - 1 = 3.In the subtable with the bottom right corner in (2, 2), the difference of the maximal and minimal elements is 4 - 1 = 3.Then the maximum possible value is 0+3+3+3=9.In the second test case, all elements are equal, so all differences are 0, and the answer is 0. | 52 21 3 1 42 2-1 -1 -1 -12 37 8 9 -3 10 83 24 8 -3 0 -7 14 3-32030 59554 16854 -85927 68060 -64460 -79547 90932 85063 82703 -12001 38762 | 9 0 64 71 1933711 | 1 second | 256 megabytes | ['greedy', 'math', '*1000'] |
A. LuoTianyi and the Palindrome Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuoTianyi gives you a palindrome^{\dagger} string s, and she wants you to find out the length of the longest non-empty subsequence^{\ddagger} of s which is not a palindrome string. If there is no such subsequence, output -1 instead.^{\dagger} A palindrome is a string that reads the same backward as forward. For example, strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.^{\ddagger} A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from b. For example, strings "a", "aaa", "bab" are subsequences of string "abaab", but strings "codeforces", "bbb", "h" are not.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of test cases follows.The first and the only line of each test case contains a single string s (1 \le |s| \le 50) consisting of lowercase English letters — the string that LuoTianyi gives you. It's guaranteed that s is a palindrome string.OutputFor each test case, output a single integer — the length of the longest non-empty subsequence which is not a palindrome string. If there is no such subsequence, output -1.ExampleInput
4abacabaaaacodeforcesecrofedoclolOutput
6
-1
18
2
NoteIn the first test case, "abcaba" is a subsequence of "abacaba" as we can delete the third letter of "abacaba" to get "abcaba", and "abcaba" is not a palindrome string. We can prove that "abcaba" is an example of the longest subsequences of "abacaba" that isn't palindrome, so that the answer is 6.In the second test case, we can only get "a" and "aa", but they are all palindrome strings, so the answer is -1. | 4abacabaaaacodeforcesecrofedoclol | 6 -1 18 2 | 1 second | 256 megabytes | ['greedy', 'strings', '*800'] |
E. LuoTianyi and Cartridgetime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLuoTianyi is watching the anime Made in Abyss. She finds that making a Cartridge is interesting. To describe the process of making a Cartridge more clearly, she abstracts the original problem and gives you the following problem.You are given a tree T consisting of n vertices. Each vertex has values a_i and b_i and each edge has values c_j and d_j.Now you are aim to build a tree T' as follows: First, select p vertices from T (p is a number chosen by yourself) as the vertex set S' of T'. Next, select p-1 edges from T one by one (you cannot select one edge more than once). May you have chosen the j-th edge connects vertices x_j and y_j with values (c_j,d_j), then you can choose two vertices u and v in S' that satisfy the edge (x_j,y_j) is contained in the simple path from u to v in T, and link u and v in T' by the edge with values (c_j,d_j) (u and v shouldn't be contained in one connected component before in T'). A tree with three vertices, \min(A,C)=1,B+D=7, the cost is 7. Selected vertices 2 and 3 as S', used the edge (1,2) with c_j = 2 and d_j = 1 to link this vertices, now \min(A,C)=2,B+D=4, the cost is 8. Let A be the minimum of values a_i in T' and C be the minimum of values c_i in T'. Let B be the sum of b_i in T' and D be the sum of values d_i in T'. Let \min(A, C) \cdot (B + D) be the cost of T'. You need to find the maximum possible cost of T'.InputThe first line contains one integer n (3\le n \le 2\cdot 10^5) — the number of vertices in the tree T.The second line contains n integers a_1, a_2, \ldots, a_n (1\le a_i\le 2\cdot 10^5), where the i-th integer represents the a_i value of the i-th vertex.The third line contains n integers b_1, b_2, \ldots, b_n (1\le b_i\le 2\cdot 10^5), where the i-th integer represents the b_i value of the i-th vertex.Then n-1 lines follow, the j-th of them contains four integers x_j,y_j,c_j,d_j (1\le x_j,y_j\le n,1\le c_j,d_j\le 2\cdot 10^5) representing the edge (x_j,y_j) and its values c_j and d_j respectively. It's guaranteed that edges form a tree.OutputPrint a single integer — the maximum possible cost of T'.ExamplesInput
3
1 2 2
1 1 2
1 2 2 1
1 3 1 2
Output
8Input
5
2 4 2 1 1
2 4 4 4 4
2 5 3 3
3 5 2 4
4 2 5 5
5 1 1 5
Output
35Input
6
5 7 10 7 9 4
6 9 7 9 8 5
2 1 5 1
3 2 2 4
4 3 6 3
5 1 7 4
6 5 6 8
Output
216Input
5
1000 1000 1 1000 1000
1000 1000 1 1000 1000
1 2 1 1
2 3 1000 1000
3 4 1000 1000
3 5 1000 1000
Output
7000000NoteThe tree from the first example is shown in the statement.The tree from the second example is shown below: A = 1, B = 18, C = 1, D = 17, so the cost is \min(1,1) \cdot (18 + 17) = 35. | 3
1 2 2
1 1 2
1 2 2 1
1 3 1 2
| 8 | 3 seconds | 1024 megabytes | ['data structures', 'trees', '*3500'] |
D. LuoTianyi and the Functiontime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputLuoTianyi gives you an array a of n integers and the index begins from 1.Define g(i,j) as follows: g(i,j) is the largest integer x that satisfies \{a_p:i\le p\le j\}\subseteq\{a_q:x\le q\le j\} while i \le j; and g(i,j)=0 while i>j. There are q queries. For each query you are given four integers l,r,x,y, you need to calculate \sum\limits_{i=l}^{r}\sum\limits_{j=x}^{y}g(i,j).InputThe first line contains two integers n and q (1\le n,q\le 10^6) — the length of the array a and the number of queries.The second line contains n integers a_1,a_2,\ldots,a_n (1\le a_i\le n) — the elements of the array a.Next q lines describe a query. The i-th line contains four integers l,r,x,y (1\le l\le r\le n, 1\le x\le y\le n) — the integers in the i-th query.OutputPrint q lines where i-th line contains one integer — the answer for the i-th query.ExamplesInput
6 4
1 2 2 1 3 4
1 1 4 5
2 3 3 3
3 6 1 2
6 6 6 6
Output
6
6
0
6
Input
10 5
10 2 8 10 9 8 2 1 1 8
1 1 10 10
2 2 3 3
6 6 6 6
1 1 4 5
4 8 4 8
Output
4
2
6
4
80
NoteIn the first example:In the first query, the answer is g(1,4)+g(1,5)=3+3=6.x=1,2,3 can satisfies \{a_p:1\le p\le 4\}\subseteq\{a_q:x\le q\le 4\}, 3 is the largest integer so g(1,4)=3.In the second query, the answer is g(2,3)+g(3,3)=3+3=6.In the third query, the answer is 0, because all i > j and g(i,j)=0.In the fourth query, the answer is g(6,6)=6.In the second example:In the second query, the answer is g(2,3)=2.In the fourth query, the answer is g(1,4)+g(1,5)=2+2=4. | 6 4
1 2 2 1 3 4
1 1 4 5
2 3 3 3
3 6 1 2
6 6 6 6
| 6 6 0 6 | 7 seconds | 1024 megabytes | ['data structures', '*3000'] |
C. LuoTianyi and XOR-Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLuoTianyi gives you a tree with values in its vertices, and the root of the tree is vertex 1.In one operation, you can change the value in one vertex to any non-negative integer.Now you need to find the minimum number of operations you need to perform to make each path from the root to leaf^{\dagger} has a bitwise XOR value of zero.^{\dagger}A leaf in a rooted tree is a vertex that has exactly one neighbor and is not a root.InputThe first line contains a single integer n (2 \le n \le 10^5) — the number of vertices in the tree.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), the i-th number represents the value in the i-th vertex.Next n−1 lines describe the edges of the tree. The i-th line contains two integers u_i and v_i (1 \le u_i,v_i \le n, u_i \neq v_i) — the vertices connected by an edge of the tree. It's guaranteed that the given edges form a tree.OutputPrint a single integer — the minimum number of operations.ExamplesInput
6
3 5 7 5 8 4
1 2
1 3
1 4
3 5
4 6
Output
3Input
8
7 10 7 16 19 9 16 11
1 5
4 2
6 5
5 2
7 2
2 3
3 8
Output
3Input
4
1 2 1 2
1 2
2 3
4 3
Output
0Input
9
4 3 6 1 5 5 5 2 7
1 2
2 3
4 1
4 5
4 6
4 7
8 1
8 9
Output
2NoteThe tree in the first example: If we change the value in the vertex 2 to 3, the value in the vertex 5 to 4, and the value in the vertex 6 to 6, then the tree will be ok.The bitwise XOR from the root to the leaf 2 will be 3 \oplus 3=0.The bitwise XOR from the root to the leaf 5 will be 4 \oplus 7 \oplus 3=0.The bitwise XOR from the root to the leaf 6 will be 6 \oplus 5 \oplus 3=0.The tree in the second example: If we change the value in the vertex 2 to 4, the value in the vertex 3 to 27, and the value in the vertex 6 to 20, then the tree will be ok.The bitwise XOR from the root to the leaf 6 will be 20 \oplus 19 \oplus 7=0.The bitwise XOR from the root to the leaf 8 will be 11 \oplus 27 \oplus 4 \oplus 19 \oplus 7=0.The bitwise XOR from the root to the leaf 4 will be 16 \oplus 4 \oplus 19 \oplus 7=0.The bitwise XOR from the root to the leaf 7 will be 16 \oplus 4 \oplus 19 \oplus 7=0.In the third example, the only leaf is the vertex 4 and the bitwise XOR on the path to it is 1 \oplus 2 \oplus 1 \oplus 2 = 0, so we don't need to change values.In the fourth example, we can change the value in the vertex 1 to 5, and the value in the vertex 4 to 0.Here \oplus denotes the bitwise XOR operation. | 6
3 5 7 5 8 4
1 2
1 3
1 4
3 5
4 6
| 3 | 2 seconds | 256 megabytes | ['data structures', 'dfs and similar', 'dp', 'dsu', 'greedy', 'trees', '*2500'] |
B2. LuoTianyi and the Floating Islands (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version k\le n. You can make hacks only if both versions of the problem are solved. Chtholly and the floating islands. LuoTianyi now lives in a world with n floating islands. The floating islands are connected by n-1 undirected air routes, and any two of them can reach each other by passing the routes. That means, the n floating islands form a tree.One day, LuoTianyi wants to meet her friends: Chtholly, Nephren, William, .... Totally, she wants to meet k people. She doesn't know the exact positions of them, but she knows that they are in pairwise distinct islands. She define an island is good if and only if the sum of the distances^{\dagger} from it to the islands with k people is the minimal among all the n islands.Now, LuoTianyi wants to know that, if the k people are randomly set in k distinct of the n islands, then what is the expect number of the good islands? You just need to tell her the expect number modulo 10^9+7.^{\dagger}The distance between two islands is the minimum number of air routes you need to take to get from one island to the other.InputThe first line contains two integers n and k (1\le k \le n \le 2\cdot 10^5) — the number of the islands and people respectively.Next n−1 lines describe the air routes. The i-th of them contains two integers u_i and v_i (1 \le u_i,v_i \le n, u_i \neq v_i) — the islands connected by the i-th air route.OutputPrint a single integer — the expect number of the good islands modulo 10^9 + 7.Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 (\operatorname{mod} M). Output the integer equal to p \cdot q^{-1} \operatorname{mod} M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p (\operatorname{mod} M).ExamplesInput
4 2
1 2
2 3
3 4
Output
666666674
Input
5 5
1 2
2 3
3 4
3 5
Output
1
NoteIn the first example the air routes form the following tree: If the people are in the islands 1 and 2, then islands 1 and 2 will be good.The sum of the distances from island 1 or 2 to all the people is 1+0=1, which is the minimal. While the sum of the distances from island 3 to all the people is 2+1=3, which is greater than 1.Like this, when the people are in island 1 and 3, then islands 1,2 and 3 will be good.When the people are in islands 1 and 4, then islands 1,2,3 and 4 will be good.When the people are in islands 2 and 3, then islands 2 and 3 will be good.When the people are in islands 2 and 4, then islands 2,3 and 4 will be good.When the people are in islands 3 and 4, then islands 3 and 4 will be good.So the expect of the number of the good islands is \frac{16}{6}, which equals to 666666674 modulo 10^9+7.In the second example the air routes form the following tree: We can see that there is one person in each island, and only the island 3 is good. So the expect number is 1. | 4 2
1 2
2 3
3 4
| 666666674 | 2 seconds | 256 megabytes | ['combinatorics', 'dfs and similar', 'math', 'probabilities', 'trees', '*2300'] |
B1. LuoTianyi and the Floating Islands (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version k\le\min(n,3). You can make hacks only if both versions of the problem are solved. Chtholly and the floating islands. LuoTianyi now lives in a world with n floating islands. The floating islands are connected by n-1 undirected air routes, and any two of them can reach each other by passing the routes. That means, the n floating islands form a tree.One day, LuoTianyi wants to meet her friends: Chtholly, Nephren, William, .... Totally, she wants to meet k people. She doesn't know the exact positions of them, but she knows that they are in pairwise distinct islands. She define an island is good if and only if the sum of the distances^{\dagger} from it to the islands with k people is the minimal among all the n islands.Now, LuoTianyi wants to know that, if the k people are randomly set in k distinct of the n islands, then what is the expect number of the good islands? You just need to tell her the expect number modulo 10^9+7.^{\dagger}The distance between two islands is the minimum number of air routes you need to take to get from one island to the other.InputThe first line contains two integers n and k (1\le k \le \min(n,3), 1\le n \le 2\cdot 10^5) — the number of the islands and people respectively.Next n−1 lines describe the air routes. The i-th of them contains two integers u_i and v_i (1 \le u_i,v_i \le n, u_i \neq v_i) — the islands connected by the i-th air route.OutputPrint a single integer — the expect number of the good islands modulo 10^9 + 7.Formally, let M = 10^9 + 7. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 (\operatorname{mod} M). Output the integer equal to p \cdot q^{-1} \operatorname{mod} M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p (\operatorname{mod} M).ExamplesInput
4 2
1 2
2 3
3 4
Output
666666674
Input
5 1
1 2
2 3
3 4
3 5
Output
1
NoteIn the first example the air routes form the following tree: If the people are in the islands 1 and 2, then islands 1 and 2 will be good.The sum of the distances from island 1 or 2 to all the people is 1+0=1, which is the minimal. While the sum of the distances from island 3 to all the people is 2+1=3, which is greater than 1.Like this, when the people are in island 1 and 3, then islands 1,2 and 3 will be good.When the people are in islands 1 and 4, then islands 1,2,3 and 4 will be good.When the people are in islands 2 and 3, then islands 2 and 3 will be good.When the people are in islands 2 and 4, then islands 2,3 and 4 will be good.When the people are in islands 3 and 4, then islands 3 and 4 will be good.So the expect of the number of the good islands is \frac{16}{6}, which equals to 666666674 modulo 10^9+7.In the second example the air routes form the following tree: There is always the only good island, so the expected number is 1. | 4 2
1 2
2 3
3 4
| 666666674 | 2 seconds | 256 megabytes | ['combinatorics', 'math', 'probabilities', 'trees', '*1800'] |
A. LuoTianyi and the Showtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people taking part in a show about VOCALOID. They will sit in the row of seats, numbered 1 to m from left to right.The n people come and sit in order. Each person occupies a seat in one of three ways: Sit in the seat next to the left of the leftmost person who is already sitting, or if seat 1 is taken, then leave the show. If there is no one currently sitting, sit in seat m. Sit in the seat next to the right of the rightmost person who is already sitting, or if seat m is taken, then leave the show. If there is no one currently sitting, sit in seat 1. Sit in the seat numbered x_i. If this seat is taken, then leave the show. Now you want to know what is the maximum number of people that can take a seat, if you can let people into the show in any order?InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 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 m (1 \le n, m \le 10^5) — the number of people and the number of seats.The second line of each test case contains n integers x_1, x_2, \ldots, x_n (-2 \le x_i \le m, x_i \ne 0), the i-th of which describes the way in which the i-th person occupies a seat: If x_i=-1, then i-th person takes the seat in the first way. If x_i=-2, then i-th person takes the seat in the second way. If x_i > 0, then the i-th person takes a seat in the third way, i.e. he wants to sit in the seat with the number x_i or leave the show if it is occupied.. It is guaranteed that sum of n and the sum of m over all test cases don't exceed 10^5.OutputFor each test case output a single integer — the maximum number of people who can occupy a seat.ExampleInput
103 105 5 54 61 -2 -2 15 7-1 -1 4 -2 -26 75 -2 -2 -2 -2 -26 6-1 1 4 5 -1 46 8-1 -1 -1 3 -1 -26 75 -1 -2 -2 -2 -23 1-2 -2 12 55 -21 2-1Output
1
3
5
6
5
5
5
1
2
1
NoteIn the first test case, all the people want to occupy the 5 seat, so only 1 people can occupy the seat.In the second test case, we can let people in order 1, 2, 3, 4, then all but the last person can take a seat.In the third test case, we can let people into the show in that order:Let the third person in:–––3––– Let the fourth person in:–––34–– Let the fifth person in:–––345– Let the first person in:––1345– Let the second person in:–21345–Thus, all 5 people took seats.In the fifth test case, we can let people into the show in this order:Let the fourth person in:––––4– Let the third person in:–––34– Let the sixth person in, he'll leave the show because he takes the third seat the third way and has to sit in the 4 seat, but it's already taken:–––34–Let the fifth person in:––534–Let the first person in:–1534–Let the second person in:21534–Thus, 5 of people took seats.In the seventh test case, we can let people into the show in this order:Let the third person in:3––––––Let the fourth person in:34––––– Let the fifth person in:345–––– Let the sixth person in:3456––– Let the first person in:34561––Let the second person in, he will leave the show because he occupies the first way, but the 1 seat is taken:34561––Thus, 5 people took seats. | 103 105 5 54 61 -2 -2 15 7-1 -1 4 -2 -26 75 -2 -2 -2 -2 -26 6-1 1 4 5 -1 46 8-1 -1 -1 3 -1 -26 75 -1 -2 -2 -2 -23 1-2 -2 12 55 -21 2-1 | 1 3 5 6 5 5 5 1 2 1 | 2 seconds | 256 megabytes | ['greedy', 'implementation', '*1400'] |
F. Random Walktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices and n - 1 edges, and each vertex v has a counter c(v) assigned to it.Initially, there is a chip placed at vertex s and all counters, except c(s), are set to 0; c(s) is set to 1.Your goal is to place the chip at vertex t. You can achieve it by a series of moves. Suppose right now the chip is placed at the vertex v. In one move, you do the following: choose one of neighbors to of vertex v uniformly at random (to is neighbor of v if and only if there is an edge \{v, to\} in the tree); move the chip to vertex to and increase c(to) by 1; You'll repeat the move above until you reach the vertex t.For each vertex v calculate the expected value of c(v) modulo 998\,244\,353.InputThe first line contains three integers n, s and t (2 \le n \le 2 \cdot 10^5; 1 \le s, t \le n; s \neq t) — number of vertices in the tree and the starting and finishing vertices.Next n - 1 lines contain edges of the tree: one edge per line. The i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \neq v_i), denoting the edge between the nodes u_i and v_i.It's guaranteed that the given edges form a tree.OutputPrint n numbers: expected values of c(v) modulo 998\,244\,353 for each v from 1 to n.Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.ExamplesInput
3 1 3
1 2
2 3
Output
2 2 1
Input
4 1 3
1 2
2 3
1 4
Output
4 2 1 2
Input
8 2 6
6 4
6 2
5 4
3 1
2 3
7 4
8 2
Output
1 3 2 0 0 1 0 1
NoteThe tree from the first example is shown below: Let's calculate expected value E[c(1)]: P(c(1) = 0) = 0, since c(1) is set to 1 from the start. P(c(1) = 1) = \frac{1}{2}, since there is the only one series of moves that leads c(1) = 1. It's 1 \rightarrow 2 \rightarrow 3 with probability 1 \cdot \frac{1}{2}. P(c(1) = 2) = \frac{1}{4}: the only path is 1 \rightarrow_{1} 2 \rightarrow_{0.5} 1 \rightarrow_{1} 2 \rightarrow_{0.5} 3. P(c(1) = 3) = \frac{1}{8}: the only path is 1 \rightarrow_{1} 2 \rightarrow_{0.5} 1 \rightarrow_{1} 2 \rightarrow_{0.5} 1 \rightarrow_{1} 2 \rightarrow_{0.5} 3. P(c(1) = i) = \frac{1}{2^i} in general case. As a result, E[c(1)] = \sum\limits_{i=1}^{\infty}{i \frac{1}{2^i}} = 2. Image of tree in second test Image of tree in third test | 3 1 3
1 2
2 3
| 2 2 1 | 2 seconds | 256 megabytes | ['dp', 'graphs', 'math', 'probabilities', 'trees', '*2600'] |
E. Removing Graphtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on a graph. They have an undirected graph without self-loops and multiple edges. All vertices of the graph have degree equal to 2. The graph may consist of several components. Note that if such graph has n vertices, it will have exactly n edges.Alice and Bob take turn. Alice goes first. In each turn, the player can choose k (l \le k \le r; l < r) vertices that form a connected subgraph and erase these vertices from the graph, including all incident edges.The player who can't make a step loses.For example, suppose they are playing on the given graph with given l = 2 and r = 3: A valid vertex set for Alice to choose at the first move is one of the following: \{1, 2\} \{1, 3\} \{2, 3\} \{4, 5\} \{4, 6\} \{5, 6\} \{1, 2, 3\} \{4, 5, 6\} Suppose, Alice chooses subgraph \{4, 6\}.Then a valid vertex set for Bob to choose at the first move is one of the following: \{1, 2\} \{1, 3\} \{2, 3\} \{1, 2, 3\} Suppose, Bob chooses subgraph \{1, 2, 3\}.Alice can't make a move, so she loses.You are given a graph of size n and integers l and r. Who will win if both Alice and Bob play optimally.InputThe first line contains three integers n, l and r (3 \le n \le 2 \cdot 10^5; 1 \le l < r \le n) — the number of vertices in the graph, and the constraints on the number of vertices Alice or Bob can choose in one move.Next n lines contains edges of the graph: one edge per line. The i-th line contains two integers u_i and v_i (1 \le u_i, v_i \le n; u_i \neq v_i) — description of the i-th edge.It's guaranteed that the degree of each vertex of the given graph is equal to 2.OutputPrint Alice (case-insensitive) if Alice wins, or Bob otherwise.ExamplesInput
6 2 3
1 2
2 3
3 1
4 5
5 6
6 4
Output
Bob
Input
6 1 2
1 2
2 3
3 1
4 5
5 6
6 4
Output
Bob
Input
12 1 3
1 2
2 3
3 1
4 5
5 6
6 7
7 4
8 9
9 10
10 11
11 12
12 8
Output
Alice
NoteIn the first test the same input as in legend is shown.In the second test the same graph as in legend is shown, but with l = 1 and r = 2. | 6 2 3
1 2
2 3
3 1
4 5
5 6
6 4
| Bob | 2 seconds | 256 megabytes | ['brute force', 'dp', 'games', 'graphs', 'math', '*2500'] |
D. Unique Palindromestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA palindrome is a string that reads the same backwards as forwards. For example, the string abcba is palindrome, while the string abca is not.Let p(t) be the number of unique palindromic substrings of string t, i. e. the number of substrings t[l \dots r] that are palindromes themselves. Even if some substring occurs in t several times, it's counted exactly once. (The whole string t is also counted as a substring of t).For example, string t = abcbbcabcb has p(t) = 6 unique palindromic substrings: a, b, c, bb, bcb and cbbc.Now, let's define p(s, m) = p(t) where t = s[1 \dots m]. In other words, p(s, m) is the number of palindromic substrings in the prefix of s of length m. For example, p(abcbbcabcb, 5) = p(abcbb) = 5.You are given an integer n and k "conditions" (k \le 20). Let's say that string s, consisting of n lowercase Latin letters, is good if all k conditions are satisfied at the same time. A condition is a pair (x_i, c_i) and have the following meaning: p(s, x_i) = c_i, i. e. a prefix of s of length x_i contains exactly c_i unique palindromic substrings. Find a good string s or report that such s doesn't exist.Look in Notes if you need further clarifications.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 two integers n and k (3 \le n \le 2 \cdot 10^5; 1 \le k \le 20) — length of good string s and number of conditions.The second line of each test case contains k integers x_1, x_2, \dots, x_k (3 \le x_1 < x_2 < \dots < x_k = n) where x_i is the length of the prefix in the i-th condition.The third line of each test case contains k integers c_1, c_2, \dots, c_k (3 \le c_1 \le c_2 \le \dots \le c_k \le \min{\left(10^9, \frac{(n + 1) n}{2} \right)}) where c_i is the number of palindromic substrings in the i-th condition.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10 ^ 5.OutputFor each test case, if there is no good string s of length n that satisfies all conditions, print NO.Otherwise, print YES and a string s of length n, consisting of lowercase Latin letters, that satisfies all conditions. If there are multiple answers, print any of them.ExampleInput
710 25 105 63 1334 23 43 34 23 43 44 14510 34 6 104 5 810 44 6 7 104 5 7 8Output
YES
abcbbcabcb
YES
foo
YES
ayda
YES
wada
NO
YES
abcbcacbab
NO
NoteIn the first test case, string s = abcbbcabcb satisfies k = 2 conditions: p(s, x_1) = p(s, 5) = p(abcbb) = 5 = s_1. Palindromic substrings are a, b, c, bb and bcb. p(s, x_2) = p(s, 10) = p(abcbbcabcb) = 6 = s_2. Palindromic substrings are the same as above, and one extra substring cbbc. In the second test case, string foo satisfies k = 1 condition: p(foo) = 3. Palindromic substrings are f, o and oo. There are other possible answers.In the third test case, string ayda satisfies k = 2 conditions: p(ayd) = 3. Palindromic substrings are a, y and d. p(ayda) = 3. Palindromic substrings are the same. In the fourth test case, string wada satisfies k = 2 conditions: p(wad) = 3. Palindromic substrings are w, a and d. p(wada) = 4. Palindromic substrings are the same, and one extra substring ada. In the fifth test case, it can be proven that there is no string of length 4 which has 5 palindromic substrings.In the sixth test case, string abcbcacbab satisfies k = 3 conditions: p(abcb) = 4. Palindromic substrings are a, b, c and bcb. p(abcbca) = 5. Palindromic substrings are the same, and one extra substring cbc. p(abcbcacbab) = 8. Palindromic substrings are the same, and three extra substrings cac, bab and bcacb. | 710 25 105 63 1334 23 43 34 23 43 44 14510 34 6 104 5 810 44 6 7 104 5 7 8 | YES abcbbcabcb YES foo YES ayda YES wada NO YES abcbcacbab NO | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', 'strings', '*1900'] |
C. Strongly Compositetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA prime number is an integer greater than 1, which has exactly two divisors. For example, 7 is a prime, since it has two divisors \{1, 7\}. A composite number is an integer greater than 1, which has more than two different divisors.Note that the integer 1 is neither prime nor composite.Let's look at some composite number v. It has several divisors: some divisors are prime, others are composite themselves. If the number of prime divisors of v is less or equal to the number of composite divisors, let's name v as strongly composite.For example, number 12 has 6 divisors: \{1, 2, 3, 4, 6, 12\}, two divisors 2 and 3 are prime, while three divisors 4, 6 and 12 are composite. So, 12 is strongly composite. Other examples of strongly composite numbers are 4, 8, 9, 16 and so on.On the other side, divisors of 15 are \{1, 3, 5, 15\}: 3 and 5 are prime, 15 is composite. So, 15 is not a strongly composite. Other examples are: 2, 3, 5, 6, 7, 10 and so on.You are given n integers a_1, a_2, \dots, a_n (a_i > 1). You have to build an array b_1, b_2, \dots, b_k such that following conditions are satisfied: Product of all elements of array a is equal to product of all elements of array b: a_1 \cdot a_2 \cdot \ldots \cdot a_n = b_1 \cdot b_2 \cdot \ldots \cdot b_k; All elements of array b are integers greater than 1 and strongly composite; The size k of array b is the maximum possible. Find the size k of array b, or report, that there is no array b satisfying the conditions.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 1000) — the size of the array a.The second line of each test case contains n integer a_1, a_2, \dots a_n (2 \le a_i \le 10^7) — the array a itself.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, print the size k of array b, or 0, if there is no array b satisfying the conditions.ExampleInput
823 633 4 522 333 10 14225 301108093 3 3 5 5 5 7 7 72012 15 2 2 2 2 2 3 3 3 17 21 21 21 30 6 6 33 31 39Output
1
1
0
2
2
3
4
15
NoteIn the first test case, we can get array b = [18]: a_1 \cdot a_2 = 18 = b_1; 18 is strongly composite number.In the second test case, we can get array b = [60]: a_1 \cdot a_2 \cdot a_3 = 60 = b_1; 60 is strongly composite number.In the third test case, there is no array b satisfying the conditions.In the fourth test case, we can get array b = [4, 105]: a_1 \cdot a_2 \cdot a_3 = 420 = b_1 \cdot b_2; 4 and 105 are strongly composite numbers. | 823 633 4 522 333 10 14225 301108093 3 3 5 5 5 7 7 72012 15 2 2 2 2 2 3 3 3 17 21 21 21 30 6 6 33 31 39 | 1 1 0 2 2 3 4 15 | 2 seconds | 256 megabytes | ['greedy', 'math', 'number theory', '*1300'] |
B. Sort with Steptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a permutation of length n as an array p of length n, which contains every number from 1 to n exactly once.You are given a permutation p_1, p_2, \dots, p_n and a number k. You need to sort this permutation in the ascending order. In order to do it, you can repeat the following operation any number of times (possibly, zero): pick two elements of the permutation p_i and p_j such that |i - j| = k, and swap them. Unfortunately, some permutations can't be sorted with some fixed numbers k. For example, it's impossible to sort [2, 4, 3, 1] with k = 2.That's why, before starting the sorting, you can make at most one preliminary exchange: choose any pair p_i and p_j and swap them. Your task is to: check whether is it possible to sort the permutation without any preliminary exchanges, if it's not, check, whether is it possible to sort the permutation using exactly one preliminary exchange. For example, if k = 2 and permutation is [2, 4, 3, 1], then you can make a preliminary exchange of p_1 and p_4, which will produce permutation [1, 4, 3, 2], which is possible to sort with given k.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 two integers n and k (2 \le n \le 2 \cdot 10^5; 1 \le k \le n - 1) — length of the permutation, and a distance between elements that can be swapped.The second line of each test case contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — elements of the permutation p.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10 ^ 5.OutputFor each test case print 0, if it is possible to sort the permutation without preliminary exchange; 1, if it is possible to sort the permutation with one preliminary exchange, but not possible without preliminary exchange; -1, if it is not possible to sort the permutation with at most one preliminary exchange. ExampleInput
64 13 1 2 44 23 4 1 24 23 1 4 210 34 5 9 1 8 6 10 2 3 710 34 6 9 1 8 5 10 2 3 710 34 6 9 1 8 5 10 3 2 7Output
0
0
1
0
1
-1
NoteIn the first test case, there is no need in preliminary exchange, as it is possible to swap (p_1, p_2) and then (p_2, p_3).In the second test case, there is no need in preliminary exchange, as it is possible to swap (p_1, p_3) and then (p_2, p_4).In the third test case, you need to apply preliminary exchange to (p_2, p_3). After that the permutation becomes [3, 4, 1, 2] and can be sorted with k = 2. | 64 13 1 2 44 23 4 1 24 23 1 4 210 34 5 9 1 8 6 10 2 3 710 34 6 9 1 8 5 10 2 3 710 34 6 9 1 8 5 10 3 2 7 | 0 0 1 0 1 -1 | 1 second | 256 megabytes | ['brute force', 'math', 'sortings', '*900'] |
A. A-characteristictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider an array a_1, a_2, \dots, a_n consisting of numbers 1 and -1. Define A-characteristic of this array as a number of pairs of indices 1 \le i < j \le n, such that a_i \cdot a_j = 1.Find any array a with given length n with A-characteristic equal to the given value k.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The only line of each test case contains two integers n and k (2 \le n \le 100; 0 \le k \le \frac{(n-1) n}{2}) — the length of required array and required A-characteristic.OutputFor each test case, if there is no array a with given A-characteristic k, print NO.Otherwise, print YES and n numbers 1 and -1, which form the required array a. If there are multiple answers, print any of them.ExampleInput
72 02 13 13 23 35 45 5Output
YES
1 -1
YES
1 1
YES
1 -1 1
NO
YES
1 1 1
YES
-1 1 -1 1 1
NONoteIn the first test case, there is only one pair of different elements in the array, and their product is a_1 \cdot a_2 = -1 \neq 1, hence its A-characteristic is 0.In the second test case, there is only one pair of different elements in the array, and their product is a_1 \cdot a_2 = 1, hence its A-characteristic is 1.In the third test case, there are three pairs of different elements in the array, and their product are: a_1 \cdot a_2 = -1, a_1 \cdot a_3 = 1, a_2 \cdot a_3 = -1, hence its A-characteristic is 1.In the fourth test case, we can show, that there is no array with length 3, which A-characteristic is 2. | 72 02 13 13 23 35 45 5 | YES 1 -1 YES 1 1 YES 1 -1 1 NO YES 1 1 1 YES -1 1 -1 1 1 NO | 1 second | 256 megabytes | ['combinatorics', 'constructive algorithms', 'math', '*800'] |
G2. Magic Triples (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, a_i \le 10^9.For a given sequence of n integers a, a triple (i, j, k) is called magic if: 1 \le i, j, k \le n. i, j, k are pairwise distinct. there exists a positive integer b such that a_i \cdot b = a_j and a_j \cdot b = a_k. Kolya received a sequence of integers a as a gift and now wants to count the number of magic triples for it. Help him with this task!Note that there are no constraints on the order of integers i, j and k.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of the test case contains a single integer n (3 \le n \le 2 \cdot 10^5) — the length of the sequence.The second line of the test contains n integers a_1, a_2, a_3, \dots, a_n (1 \le a_i \le 10^9) — the elements of the sequence a.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of magic triples for the sequence a.ExampleInput
751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4Output
6
1
3
0
9
16
45
NoteIn the first example, there are 6 magic triples for the sequence a — (2, 3, 5), (2, 5, 3), (3, 2, 5), (3, 5, 2), (5, 2, 3), (5, 3, 2).In the second example, there is a single magic triple for the sequence a — (2, 1, 3). | 751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4 | 6 1 3 0 9 16 45 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'math', 'number theory', '*2200'] |
G1. Magic Triples (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, a_i \le 10^6.For a given sequence of n integers a, a triple (i, j, k) is called magic if: 1 \le i, j, k \le n. i, j, k are pairwise distinct. there exists a positive integer b such that a_i \cdot b = a_j and a_j \cdot b = a_k. Kolya received a sequence of integers a as a gift and now wants to count the number of magic triples for it. Help him with this task!Note that there are no constraints on the order of integers i, j and k.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of the test case contains a single integer n (3 \le n \le 2 \cdot 10^5) — the length of the sequence.The second line of the test contains n integers a_1, a_2, a_3, \dots, a_n (1 \le a_i \le 10^6) — the elements of the sequence a.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of magic triples for the sequence a.ExampleInput
751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4Output
6
1
3
0
9
16
45
NoteIn the first example, there are 6 magic triples for the sequence a — (2, 3, 5), (2, 5, 3), (3, 2, 5), (3, 5, 2), (5, 2, 3), (5, 3, 2).In the second example, there is a single magic triple for the sequence a — (2, 1, 3). | 751 7 7 2 736 2 1891 2 3 4 5 6 7 8 941000 993 986 17971 10 100 1000 10000 100000 100000081 1 2 2 4 4 8 891 1 1 2 2 2 4 4 4 | 6 1 3 0 9 16 45 | 4 seconds | 256 megabytes | ['brute force', 'data structures', 'math', 'number theory', '*1700'] |
F. Gardening Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTwo friends, Alisa and Yuki, planted a tree with n vertices in their garden. A tree is an undirected graph without cycles, loops, or multiple edges. Each edge in this tree has a length of k. Initially, vertex 1 is the root of the tree.Alisa and Yuki are growing the tree not just for fun, they want to sell it. The cost of the tree is defined as the maximum distance from the root to a vertex among all vertices of the tree. The distance between two vertices u and v is the sum of the lengths of the edges on the path from u to v.The girls took a course in gardening, so they know how to modify the tree. Alisa and Yuki can spend c coins to shift the root of the tree to one of the neighbors of the current root. This operation can be performed any number of times (possibly zero). Note that the structure of the tree is left unchanged; the only change is which vertex is the root.The friends want to sell the tree with the maximum profit. The profit is defined as the difference between the cost of the tree and the total cost of operations. The profit is cost of the tree minus the total cost of operations.Help the girls and find the maximum profit they can get by applying operations to the tree any number of times (possibly zero).InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains integers n, k, c (2 \le n \le 2 \cdot 10^5; 1 \le k, c \le 10^9) — the number of vertices in the tree, the length of each edge, and the cost of the operation.The next n - 1 lines of the test case contain pairs of integers u_i, v_i (1 \le u_i, v_i \le n) — the edges of the graph. These edges form a tree.The sum of the values of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum profit that Yuki and Alisa can get.ExampleInput
43 2 32 13 15 4 12 14 25 43 46 5 34 16 12 65 13 210 6 41 31 99 77 66 49 22 88 55 10Output
2
12
17
32
| 43 2 32 13 15 4 12 14 25 43 46 5 34 16 12 65 13 210 6 41 31 99 77 66 49 22 88 55 10 | 2 12 17 32 | 2 seconds | 256 megabytes | ['brute force', 'dfs and similar', 'dp', 'graphs', 'trees', '*1700'] |
E. Making Anti-Palindromestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase English letters. In one operation, you are allowed to swap any two characters of the string s.A string s of length n is called an anti-palindrome, if s[i] \ne s[n - i + 1] for every i (1 \le i \le n). For example, the strings "codeforces", "string" are anti-palindromes, but the strings "abacaba", "abc", "test" are not.Determine the minimum number of operations required to make the string s an anti-palindrome, or output -1, if this is not possible.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.Each test case consists of two lines. The first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line contains the string s, consisting of n lowercase English letters.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 required to make the string s an anti-palindrome, or -1 if this is not possible.ExampleInput
1010codeforces3abc10taarrrataa10dcbdbdcccc4wwww12cabbaccabaac10aadaaaaddc14aacdaaaacadcdc6abccba12dcbcaebacccdOutput
0
-1
1
1
-1
3
-1
2
2
2
NoteIn the first test case, the string "codeforces" is already an anti-palindrome, so the answer is 0.In the second test case, it can be shown that the string "abc" cannot be transformed into an anti-palindrome by performing the allowed operations, so the answer is -1.In the third test case, it is enough to swap the second and the fifth characters of the string "taarrrataa", and the new string "trararataa" will be an anti-palindrome, so the answer is 1. | 1010codeforces3abc10taarrrataa10dcbdbdcccc4wwww12cabbaccabaac10aadaaaaddc14aacdaaaacadcdc6abccba12dcbcaebacccd | 0 -1 1 1 -1 3 -1 2 2 2 | 1 second | 256 megabytes | ['greedy', 'math', 'strings', '*1600'] |
D. Super-Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence n integers, where each integer from 1 to n appears exactly once. For example, [1], [3,5,2,1,4], [1,3,2] are permutations, while [2,3,2], [4,3,1], [0] are not.Given a permutation a, we construct an array b, where b_i = (a_1 + a_2 +~\dots~+ a_i) \bmod n.A permutation of numbers [a_1, a_2, \dots, a_n] is called a super-permutation if [b_1 + 1, b_2 + 1, \dots, b_n + 1] is also a permutation of length n.Grisha became interested whether a super-permutation of length n exists. Help him solve this non-trivial problem. Output any super-permutation of length n, if it exists. Otherwise, output -1.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.Each test case consists of a single line containing one integer n (1 \le n \le 2 \cdot 10^5) — the length of the desired permutation.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output in a separate line: n integers — a super-permutation of length n, if it exists. -1, otherwise. If there are several suitable permutations, output any of them.ExampleInput
41236Output
1
2 1
-1
6 5 2 3 4 1 | 41236 | 1 2 1 -1 6 5 2 3 4 1 | 2 seconds | 256 megabytes | ['constructive algorithms', 'math', '*1200'] |
C. Bun Lovertime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTema loves cinnabon rolls — buns with cinnabon and chocolate in the shape of a "snail".Cinnabon rolls come in different sizes and are square when viewed from above. The most delicious part of a roll is the chocolate, which is poured in a thin layer over the cinnabon roll in the form of a spiral and around the bun, as in the following picture: Cinnabon rolls of sizes 4, 5, 6 For a cinnabon roll of size n, the length of the outer side of the square is n, and the length of the shortest vertical chocolate segment in the central part is one.Formally, the bun consists of two dough spirals separated by chocolate. A cinnabon roll of size n + 1 is obtained from a cinnabon roll of size n by wrapping each of the dough spirals around the cinnabon roll for another layer.It is important that a cinnabon roll of size n is defined in a unique way.Tema is interested in how much chocolate is in his cinnabon roll of size n. Since Tema has long stopped buying small cinnabon rolls, it is guaranteed that n \ge 4.Answer this non-obvious question by calculating the total length of the chocolate layer.InputThe first line of the input contains a single integer t (1 \le t \le 10^5) — the number of test cases.The following t lines describe the test cases.Each test case is described by a single integer n (4 \le n \le 10^9) — the size of the cinnabon roll.OutputOutput t integers. The i-th of them should be equal to the total length of the chocolate layer in the i-th test case.ExampleInput
4456179179179Output
26
37
50
32105178545472401
| 4456179179179 | 26 37 50 32105178545472401 | 3 seconds | 256 megabytes | ['math', '*800'] |
B. Karina and Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKarina has an array of n integers a_1, a_2, a_3, \dots, a_n. She loves multiplying numbers, so she decided that the beauty of a pair of numbers is their product. And the beauty of an array is the maximum beauty of a pair of adjacent elements in the array.For example, for n = 4, a=[3, 5, 7, 4], the beauty of the array is \max(3 \cdot 5, 5 \cdot 7, 7 \cdot 4) = \max(15, 35, 28) = 35.Karina wants her array to be as beautiful as possible. In order to achieve her goal, she can remove some elements (possibly zero) from the array. After Karina removes all elements she wants to, the array must contain at least two elements.Unfortunately, Karina doesn't have enough time to do all her tasks, so she asks you to calculate the maximum beauty of the array that she can get by removing any number of elements (possibly zero).InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of a test case contains an integer n (2 \le n \le 2 \cdot 10^5) — the length of the array a.The second line of a test case contains n integers a_1, a_2, a_3, \dots, a_n (-10^9 \le a_i \le 10^9) — the elements of the array a.The sum of all values of n across all test cases does not exceed 2 \cdot 10^5.OutputOutput t integers, each of which is the answer to the corresponding test case — the maximum beauty of the array that Karina can get.ExampleInput
745 0 2 13-1 1 052 0 -1 -4 06-8 4 3 7 1 -960 3 -2 5 -4 -421000000000 9100000007-1 -7 -2 -5 -4 -6 -3Output
10
0
4
72
16
910000000000000000
42
NoteIn the first test case of the example, to get the maximum beauty, you need to remove the 2-nd element.In the second and third test cases of the example, there is no need to remove any elements to achieve maximum beauty.In the fourth test case of the example, you need to leave only the first and last elements. | 745 0 2 13-1 1 052 0 -1 -4 06-8 4 3 7 1 -960 3 -2 5 -4 -421000000000 9100000007-1 -7 -2 -5 -4 -6 -3 | 10 0 4 72 16 910000000000000000 42 | 2 seconds | 256 megabytes | ['greedy', 'math', 'sortings', '*800'] |
A. TubeTube Feedtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMushroom Filippov cooked himself a meal and while having his lunch, he decided to watch a video on TubeTube. He can not spend more than t seconds for lunch, so he asks you for help with the selection of video.The TubeTube feed is a list of n videos, indexed from 1 to n. The i-th video lasts a_i seconds and has an entertainment value b_i. Initially, the feed is opened on the first video, and Mushroom can skip to the next video in 1 second (if the next video exists). Mushroom can skip videos any number of times (including zero).Help Mushroom choose one video that he can open and watch in t seconds. If there are several of them, he wants to choose the most entertaining one. Print the index of any appropriate video, or -1 if there is no such.InputThe first line of the input data contains a single integer q (1 \le q \le 1000) — the number of test cases in the test.The description of the test cases follows.The first line of a test case contains two integers n and t (1 \le n \le 50, 1 \le t \le 200) — the number of videos in the feed and seconds for lunch, respectively.The second line of a test case contains n integers a_1, a_2, a_3, \dots, a_n (1 \le a_i \le 100) — durations of videos. The third line of a test case contains n integers b_1, b_2, b_3, \dots, b_n (1 \le b_i \le 100) — entertainment values of videos.OutputOutput q integers, each of which is the answer to the corresponding test case. As an answer, output the index of the most entertaining video that Mushroom will have time to watch. If there are several answers, you are allowed to output any of them. Output -1, if there is no video he can watch during his lunch break.ExampleInput
55 91 5 7 6 63 4 7 1 94 44 3 3 21 2 3 45 75 5 5 5 52 1 3 9 74 3354 71 69 9642 24 99 12 17955 6677 88Output
3
2
3
-1
2
| 55 91 5 7 6 63 4 7 1 94 44 3 3 21 2 3 45 75 5 5 5 52 1 3 9 74 3354 71 69 9642 24 99 12 17955 6677 88 | 3 2 3 -1 2 | 1 second | 256 megabytes | ['brute force', 'implementation', '*800'] |
F. Timbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a beautiful alley with trees in front of a shopping mall. Unfortunately, it has to go to make space for the parking lot.The trees on the alley all grow in a single line. There are n spots for trees, index 0 is the shopping mall, index n+1 is the road and indices from 1 to n are the spots for trees. Some of them are taken — there grow trees of the same height k. No more than one tree grows in each spot.When you chop down a tree in the spot x, you can make it fall either left or right. If it falls to the left, it takes up spots from x-k to x, inclusive. If it falls to the right, it takes up spots from x to x+k, inclusive.Let m trees on the alley grow in some spots x_1, x_2, \dots, x_m. Let an alley be called unfortunate if all m trees can be chopped down in such a way that: no tree falls on the shopping mall or the road; each spot is taken up by no more than one fallen tree. Calculate the number of different unfortunate alleys with m trees of height k. Two alleys are considered different if there is a spot y such that a tree grows in y on the first alley and doesn't grow in y on the second alley.Output the number modulo 998\,244\,353.InputThe only line contains three integers n, m and k (1 \le m, k \le n \le 3 \cdot 10^5) — the number of spots for the trees, the number of trees and the height of each tree.OutputPrint a single integer — the number of different unfortunate alleys with m trees of height k, modulo 998\,244\,353. ExamplesInput
6 1 4
Output
4
Input
5 2 2
Output
0
Input
6 2 2
Output
4
Input
15 3 2
Output
311
| 6 1 4
| 4 | 2 seconds | 256 megabytes | ['combinatorics', 'dp', 'fft', 'math', '*2600'] |
E. Rearrange Bracketstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"); bracket sequences ")(", "(" and ")" are not. You are given a regular bracket sequence. In one move, you can remove a pair of adjacent brackets such that the left one is an opening bracket and the right one is a closing bracket. Then concatenate the resulting parts without changing the order. The cost of this move is the number of brackets to the right of the right bracket of this pair.The cost of the regular bracket sequence is the smallest total cost of the moves required to make the sequence empty.Actually, you are not removing any brackets. Instead, you are given a regular bracket sequence and an integer k. You can perform the following operation at most k times: extract some bracket from the sequence and insert it back at any position (between any two brackets, at the start or at the end; possibly, at the same place it was before). After all operations are performed, the bracket sequence has to be regular. What is the smallest possible cost of the resulting regular bracket sequence?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer k (0 \le k \le 5) — the maximum number of operations you can perform.The second line contains a non-empty regular bracket sequence, it consists only of characters '(' and ')'.The total length of the regular bracket sequences over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest possible cost of the regular bracket sequence after you perform at most k operations on it.ExampleInput
70()0(())1(())5()1(()()(()))2((())()(()())((())))3((())()(()())((())))Output
0
1
0
0
1
4
2
| 70()0(())1(())5()1(()()(()))2((())()(()())((())))3((())()(()())((()))) | 0 1 0 0 1 4 2 | 2 seconds | 256 megabytes | ['brute force', 'dp', 'greedy', 'sortings', 'strings', '*2100'] |
D. Black Cellstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing with a really long strip consisting of 10^{18} white cells, numbered from left to right as 0, 1, 2 and so on. You are controlling a special pointer that is initially in cell 0. Also, you have a "Shift" button you can press and hold.In one move, you can do one of three actions: move the pointer to the right (from cell x to cell x + 1); press and hold the "Shift" button; release the "Shift" button: the moment you release "Shift", all cells that were visited while "Shift" was pressed are colored in black. (Of course, you can't press Shift if you already hold it. Similarly, you can't release Shift if you haven't pressed it.)Your goal is to color at least k cells, but there is a restriction: you are given n segments [l_i, r_i] — you can color cells only inside these segments, i. e. you can color the cell x if and only if l_i \le x \le r_i for some i.What is the minimum number of moves you need to make in order to color at least k cells black?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 10^9) — the number of segments and the desired number of black cells, respectively.The second line contains n integers l_1, l_2, \dots, l_n (1 \le l_1 < l_2 < \dots < l_n \le 10^9), where l_i is the left border of the i-th segment.The third line contains n integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^9; l_i \le r_i < l_{i + 1} - 1), where r_i is the right border of the i-th segment.Additional constraints on the input: every cell belongs to at most one segment; the sum of n doesn't exceed 2 \cdot 10^5. OutputFor each test case, print the minimum number of moves to color at least k cells black, or -1 if it's impossible.ExampleInput
42 31 31 44 2010 13 16 1911 14 17 202 31 31 102 499 999999999100 1000000000Output
8
-1
7
1000000004
NoteIn the first test case, one of the optimal sequences of operations is the following: Move right: pointer is moving into cell 1; Press Shift; Release Shift: cell 1 is colored black; Move right: pointer is moving into cell 2; Move right: pointer is moving into cell 3; Press Shift; Move right: pointer is moving into cell 4; Release Shift: cells 3 and 4 are colored in black. We've colored 3 cells in 8 moves.In the second test case, we can color at most 8 cells, while we need 20 cell to color.In the third test case, one of the optimal sequences of operations is the following: Move right: pointer is moving into cell 1; Move right: pointer is moving into cell 2; Move right: pointer is moving into cell 3; Press Shift; Move right: pointer is moving into cell 4; Move right: pointer is moving into cell 5; Release Shift: cells 3, 4 and 5 are colored in black. We've colored 3 cells in 7 moves. | 42 31 31 44 2010 13 16 1911 14 17 202 31 31 102 499 999999999100 1000000000 | 8 -1 7 1000000004 | 4 seconds | 256 megabytes | ['binary search', 'brute force', 'greedy', 'math', '*1900'] |
C. Tear It Aparttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase Latin letters.In one operation, you can select several (one or more) positions in it such that no two selected positions are adjacent to each other. Then you remove the letters on the selected positions from the string. The resulting parts are concatenated without changing their order.What is the smallest number of operations required to make all the letters in s the same?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 a string s, consisting of lowercase Latin letters. Its length is from 1 to 2 \cdot 10^5.The total length of the strings over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest number of operations required to make all the letters in the given string s the same.ExampleInput
5abacabacodeforcesooooooooabcdefmewheniseearulhiiarulOutput
1
3
0
2
4
NoteIn the first testcase, you can select positions 2, 4 and 6 and remove the corresponding letters 'b', 'c' and 'b'.In the third testcase, the letters in the string are already the same, so you don't have to make any operations.In the fourth testcase, one of the possible solutions in 2 operations is the following. You can select positions 1, 4, 6 first. The string becomes "bce". Then select positions 1 and 3. The string becomes "c". All letters in it are the same, since it's just one letter. | 5abacabacodeforcesooooooooabcdefmewheniseearulhiiarul | 1 3 0 2 4 | 2 seconds | 256 megabytes | ['brute force', 'implementation', 'math', 'strings', '*1300'] |
B. Sort the Subarraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp had an array a consisting of n integers. He has decided to choose two integers l and r such that 1 \le l \le r \le n, and then sort the subarray a[l..r] (the subarray a[l..r] is the part of the array a containing the elements a_l, a_{l+1}, a_{l+2}, \dots, a_{r-1}, a_r) in non-descending order. After sorting the subarray, Monocarp has obtained a new array, which we denote as a'.For example, if a = [6, 7, 3, 4, 4, 6, 5], and Monocarp has chosen l = 2, r = 5, then a' = [6, 3, 4, 4, 7, 6, 5].You are given the arrays a and a'. Find the integers l and r that Monocarp could have chosen. If there are multiple pairs of values (l, r), find the one which corresponds to the longest subarray.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of three lines: the first line contains one integer n (2 \le n \le 2 \cdot 10^5); the second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n); the third line contains n integers a'_1, a'_2, \dots, a'_n (1 \le a'_i \le n). Additional constraints on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5; it is possible to obtain the array a' by sorting one subarray of a; a' \ne a (there exists at least one position in which these two arrays are different). OutputFor each test case, print two integers — the values of l and r (1 \le l \le r \le n). If there are multiple answers, print the values that correspond to the longest subarray. If there are still multiple answers, print any of them.ExampleInput
376 7 3 4 4 6 56 3 4 4 7 6 531 2 11 1 232 2 12 1 2Output
2 5
1 3
2 3
| 376 7 3 4 4 6 56 3 4 4 7 6 531 2 11 1 232 2 12 1 2 | 2 5 1 3 2 3 | 2 seconds | 512 megabytes | ['brute force', 'greedy', '*1100'] |
A. Matchingtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAn integer template is a string consisting of digits and/or question marks.A positive (strictly greater than 0) integer matches the integer template if it is possible to replace every question mark in the template with a digit in such a way that we get the decimal representation of that integer without any leading zeroes.For example: 42 matches 4?; 1337 matches ????; 1337 matches 1?3?; 1337 matches 1337; 3 does not match ??; 8 does not match ???8; 1337 does not match 1?7. You are given an integer template consisting of at most 5 characters. Calculate the number of positive (strictly greater than 0) integers that match it.InputThe first line contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases.Each test case consists of one line containing the string s (1 \le |s| \le 5) consisting of digits and/or question marks — the integer template for the corresponding test case.OutputFor each test case, print one integer — the number of positive (strictly greater than 0) integers that match the template.ExampleInput
8???09031??7?5?9??99Output
90
9
0
1
0
100
90
100
| 8???09031??7?5?9??99 | 90 9 0 1 0 100 90 100 | 2 seconds | 512 megabytes | ['combinatorics', 'math', '*800'] |
B. JoJo's Incredible Adventurestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDid you think there was going to be a JoJo legend here? But no, that was me, Dio!Given a binary string s of length n, consisting of characters 0 and 1. Let's build a square table of size n \times n, consisting of 0 and 1 characters as follows.In the first row of the table write the original string s. In the second row of the table write cyclic shift of the string s by one to the right. In the third row of the table, write the cyclic shift of line s by two to the right. And so on. Thus, the row with number k will contain a cyclic shift of string s by k to the right. The rows are numbered from 0 to n - 1 top-to-bottom.In the resulting table we need to find the rectangle consisting only of ones that has the largest area.We call a rectangle the set of all cells (i, j) in the table, such that x_1 \le i \le x_2 and y_1 \le j \le y_2 for some integers 0 \le x_1 \le x_2 < n and 0 \le y_1 \le y_2 < n.Recall that the cyclic shift of string s by k to the right is the string s_{n-k+1} \ldots s_n s_1 s_2 \ldots s_{n-k}. For example, the cyclic shift of the string "01011" by 0 to the right is the string itself "01011", its cyclic shift by 3 to the right is the string "01101".InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. The description of test cases follows.The first and the only line of each test case contains a single binary string s (1 \le \lvert s \rvert \le 2 \cdot 10^5), consisting of characters 0 and 1.It is guaranteed that the sum of string lengths |s| over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum area of a rectangle consisting only of ones. If there is no such rectangle, output 0.ExampleInput
501101011110101010Output
0
1
2
6
1
NoteIn the first test case, there is a table 1 \times 1 consisting of a single character 0, so there are no rectangles consisting of ones, and the answer is 0.In the second test case, there is a table 1 \times 1, consisting of a single character 1, so the answer is 1.In the third test case, there is a table: 101110011 In the fourth test case, there is a table: 011110001111100111110011111001111100 In the fifth test case, there is a table: 101010010101101010010101101010010101 Rectangles with maximum area are shown in bold. | 501101011110101010 | 0 1 2 6 1 | 1 second | 256 megabytes | ['math', 'strings', 'two pointers', '*1100'] |
A. Yura's New Nametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter holding one team contest, boy Yura got very tired and wanted to change his life and move to Japan. In honor of such a change, Yura changed his name to something nice.Fascinated by this idea he already thought up a name s consisting only of characters "_" and "^". But there's a problem — Yura likes smiley faces "^_^" and "^^". Therefore any character of the name must be a part of at least one such smiley. Note that only the consecutive characters of the name can be a smiley face.More formally, consider all occurrences of the strings "^_^" and "^^" in the string s. Then all such occurrences must cover the whole string s, possibly with intersections. For example, in the string "^^__^_^^__^" the characters at positions 3,4,9,10 and 11 are not contained inside any smileys, and the other characters at positions 1,2,5,6,7 and 8 are contained inside smileys.In one operation Jura can insert one of the characters "_" and "^" into his name s (you can insert it at any position in the string). He asks you to tell him the minimum number of operations you need to do to make the name fit Yura's criteria.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) —the number of test cases. The description of test cases follows.The first and only line of each test case contains a single string s (1 \leq |s| \leq 100), consisting of characters "_" and "^", — the name to change.OutputFor each test case, output a single integer — the minimum number of characters you need to add to the name to make it fit for Yura. If you don't need to change anything in the name, print 0.ExampleInput
7^______^___^_^^^_^___^^_^^_^^^^^_^_^^___^^_Output
5
5
1
1
0
3
2
NoteIn the first test case, you can get the following name by adding 5 characters: ^_^_^_^_^_^_^In the third test case, we can add one character "^" to the end of the name, then we get the name:^_^In the fourth test case, we can add one character "^" to the end of the name, then we get the name:^^In the fifth test case, all of the characters are already contained in smiley faces, so the answer is 0.In the seventh test case, you can add one character "^" at the beginning of the name and one character "^" at the end of the name, then you get the name:^_^ | 7^______^___^_^^^_^___^^_^^_^^^^^_^_^^___^^_ | 5 5 1 1 0 3 2 | 1 second | 256 megabytes | ['implementation', 'strings', '*800'] |
F. Willy-nilly, Crack, Into Release!time limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou have long dreamed of working in a large IT company and finally got a job there. You have studied all existing modern technologies for a long time and are ready to apply all your knowledge in practice. But then you sit down at your desk and see a sheet of paper with the company's motto printed in large letters: abcdabcdabcdabcd....The company's motto contains four main principles— a (Willi), b (Nilli), c (Crack), d (Release). Therefore, you consider strings of length n consisting of these four Latin letters. Unordered pairs of letters "ab", "bc", "cd", and "da" in this motto are adjacent, so we will call such pairs of symbols good. So, if you are given a string s of length n, and it is known that the unordered pair of symbols \{ x, y \} is good, then you can perform one of the following operations on the string: if s_n = x, then you are allowed to replace this symbol with y, if there exists 1 \le i < n such that s_i = x and s_{i+1} = \ldots = s_n = y, then you are allowed to replace the i-th symbol of the string with y, and all subsequent symbols with x. For example, the string bacdd can be replaced with one of the strings bacda, bacdc, or badcc, and the string aac can be replaced with aab or aad.A non-empty sequence of operations for the string s will be called correct if the following two conditions are met: after performing all operations, the string becomes s again, no string, except for s, will occur more than once during the operations. At the same time, the string s can occur exactly twice - before the start of the operations and after performing all operations. Now we are ready to move on to the problem statement! You have a set of strings that is initially empty. Then, each of q queries adds another string t_i to the set, or removes the string t_i from the set. After each query, you need to output the minimum and maximum size of a correct sequence of operations in which each word occurs at least once. The choice of the initial string s is up to you.InputThe first line contains two integers n and q (1 \le n \le 20, 1 \le q \le 100\,000) — the length of the strings under consideration and the number of queries to modify the set of strings.Each of the next q lines contains a string t_i (\lvert t_i \rvert = n). All strings consist of characters "a", "b", "c" and "d". If the string t_i was not in the set before the query, it is added to the set, otherwise it is removed from the set.OutputFor each of the q queries, output two integers: the minimum and maximum size of a correct sequence of operations in which each word from the set appears at least once.If there is no sequence of operations that satisfies the condition of the problem, output a single number -1.ExamplesInput
2 4
aa
ac
dd
ac
Output
2 12
4 4
-1
12 12
Input
3 2
acc
bdd
Output
2 44
28 44
NoteLet's consider the first test example. After the first query, the set of important words is equal to \{aa\}, the minimum sequence of actions has the following form: aa, ab, aa. The maximum sequence of actions that fits is aa, ab, ba, bb, bc, cb, cc, cd, dc, dd, da, ad, aa. After the second query, the set of important words is equal to \{aa, ac\}. The minimum and maximum sequences of actions are: aa, ab, ac, ad, aa. After the third query, the set of important words is equal to \{aa, ac, dd\}. There is no sequence of actions that fits the condition, so -1 should be outputted. After the fourth query, the set of important words is equal to \{aa, dd\}. The minimum and maximum sequences of actions are as follows: aa, ab, ba, bb, bc, cb, cc, cd, dc, dd, da, ad, aa. | 2 4
aa
ac
dd
ac
| 2 12 4 4 -1 12 12 | 3 seconds | 1024 megabytes | ['data structures', 'dp', '*3500'] |
E. Roads in E Citytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.As is well known, the city "E" has never had its roads repaired in its a thousand and a half years old history. And only recently the city administration repaired some of them.It is known that in total in the city "E" there are n intersections and m roads, which can be used in both directions, numbered with integers from 1 to m. The i-th road connects intersections with numbers a_i and b_i.Among all m roads, some subset of the roads has been repaired, but you do not know which one. The only information you could get from the city's road services is that you can get from any intersection to any other intersection by driving only on the roads that have been repaired.You are a young entrepreneur, and decided to organize a delivery service of fresh raw meat in the city "E" (in this city such meat is called "steaks", it is very popular among the locals). You have already recruited a staff of couriers, but the couriers are willing to travel only on repaired roads. Now you have to find out which roads have already been repaired.The city administration has given you the city for a period of time, so you can make different queries of one of three types: Block the road with the number x. In this case, movement on the road for couriers will be forbidden. Initially all roads are unblocked. Unblock the road with the number x. In this case, couriers will be able to move on the road x if it is repaired. Try to deliver the order to the intersection with the number y. In this case, one of your couriers will start moving from intersection with number s you don't know and deliver the order to intersection with number y if there is a path on unblocked repaired roads from intersection s to intersection y. It is guaranteed that intersection s will be chosen beforehand. Unfortunately, the city is placed at your complete disposal for a short period of time, so you can make no more than 100 \cdot m requests.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1\,000) — the number of test cases. The description of test cases follows.The first line contains two integers n and m (2 \le n \le 2\,000, n - 1 \le m \le 2\,000) —the number of intersections and roads in the city "E".Each of the following m lines describes one road. The i-th of these lines contains two integers a_i and b_i (1 \le a_i, b_i \le n) — the ends of the i-th road. It is guaranteed that no road connects the city to itself, while it is possible that there are several roads between a pair of different intersections.It is guaranteed that the sum of n and the sum of m over all test cases does not exceed 2\,000.InteractionOnce you have read the description of the test case, you can make queries. Queries can be of three types: "- x" (1 \le x \le m). In this case the road with the number x is blocked if it has not already been blocked. "+ x" (1 \le x \le m). In this case the road with the number x is unblocked. Note that road x must be blocked beforehand. All roads are initially unblocked. "? y" (1 \le y \le n). In this case the jury program chooses some city s. If you can get from town s to town y by unblocked repaired roads, the jury program will output 1, otherwise the jury program will output 0. Note that city s will be selected before getting information about city y, but your previous requests may be taken into account when selecting city s. In total, you can make no more than 100 \cdot m queries for each set of input data.After you have found all repaired roads, output "! c_1,\ c_2,\ c_3,\ \ldots,\ c_m", where c_i is 1 if road i is repaired, and 0 if road is not repaired. This output will not count in the total number of queries. The jury program will output 1 if your answer is correct, and 0 if the answer is not correct. If you received 0, your program must terminate immediately to receive a Wrong Answer verdict. Otherwise you can get any verdict, because the program will continue reading from the closed stream. If you read 1, move on to the next test case, or terminate the program if there is none.Note that you do not have to unblock all roads before outputting the answer. It is guaranteed that all repaired roads are fixed initially and will not be changed by the jury program depending on queries.After outputting a query or the answer do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. HacksYou can't do hacks on this problem.ExampleInput
2
2 2
1 2
2 1
1
0
1
1
3 3
1 2
2 3
3 1
1
1
1
0
1
1
1
1Output
- 1
? 1
? 2
- 2
+ 1
? 1
! 1 0
- 1
? 2
? 1
- 2
? 3
? 3
+ 1
? 3
? 2
? 1
! 1 1 1NoteIn the first test case, road 1 was repaired, while road 2 was not. For the first delivery request, intersection 1 was selected as s, and the path from intersection 1 to 1 exists. For the second delivery request, intersection 1 was selected as s. Since the only repaired road was blocked, there was no path between intersections 1 and 2. For the third delivery request, intersection 2 was selected as s, the path between intersections 2 and 1 exists along road 1, which is repaired and unblocked.In the second test case, intersections 1, 3, 1, 2, 2, 3, 1 were selected as starting intersections for delivery requests. | 2
2 2
1 2
2 1
1
0
1
1
3 3
1 2
2 3
3 1
1
1
1
0
1
1
1
1 | - 1 ? 1 ? 2 - 2 + 1 ? 1 ! 1 0 - 1 ? 2 ? 1 - 2 ? 3 ? 3 + 1 ? 3 ? 2 ? 1 ! 1 1 1 | 3 seconds | 256 megabytes | ['interactive', 'math', 'probabilities', 'trees', '*3200'] |