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
D. Flip and Reversetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s of 0's and 1's. You are allowed to perform the following operation: choose a non-empty contiguous substring of s that contains an equal number of 0's and 1's; flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; reverse the substring. For example, consider s = 00111011, and the following operation: Choose the first six characters as the substring to act upon: 00111011. Note that the number of 0's and 1's are equal, so this is a legal choice. Choosing substrings 0, 110, or the entire string would not be possible. Flip all characters in the substring: 11000111. Reverse the substring: 10001111. Find the lexicographically smallest string that can be obtained from s after zero or more operations.InputThe first line contains a single integer T (1 \leq T \leq 5 \cdot 10^5) — the number of test cases. Each of the following T lines contains a single non-empty string — the input string s for the respective test case.All strings consist of characters 0 and 1, and their total length does not exceed 5 \cdot 10^5.OutputFor each test case, on a separate line print the lexicographically smallest string that can be obtained from s after zero or more operations.ExampleInput 3 100101 1100011 10101010 Output 010110 0110110 10101010 NoteIn the first test case a single operation should be applied to the entire string.In the second test case two operations are needed: 0111001, 0110110.In the third test case the string stays the same after any operation.
3 100101 1100011 10101010
010110 0110110 10101010
2 seconds
512 megabytes
['data structures', 'graphs', 'greedy', '*3100']
C. Latin Squaretime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a square matrix of size n. Every row and every column of this matrix is a permutation of 1, 2, \ldots, n. Let a_{i, j} be the element at the intersection of i-th row and j-th column for every 1 \leq i, j \leq n. Rows are numbered 1, \ldots, n top to bottom, and columns are numbered 1, \ldots, n left to right.There are six types of operations: R: cyclically shift all columns to the right, formally, set the value of each a_{i, j} to a_{i, ((j - 2)\bmod n) + 1}; L: cyclically shift all columns to the left, formally, set the value of each a_{i, j} to a_{i, (j\bmod n) + 1}; D: cyclically shift all rows down, formally, set the value of each a_{i, j} to a_{((i - 2)\bmod n) + 1, j}; U: cyclically shift all rows up, formally, set the value of each a_{i, j} to a_{(i\bmod n) + 1, j}; I: replace the permutation read left to right in each row with its inverse. C: replace the permutation read top to bottom in each column with its inverse. Inverse of a permutation p_1, p_2, \ldots, p_n is a permutation q_1, q_2, \ldots, q_n, such that p_{q_i} = i for every 1 \leq i \leq n.One can see that after any sequence of operations every row and every column of the matrix will still be a permutation of 1, 2, \ldots, n.Given the initial matrix description, you should process m operations and output the final matrix.InputThe first line contains a single integer t (1 \leq t \leq 1000) — number of test cases. t test case descriptions follow.The first line of each test case description contains two integers n and m (1 \leq n \leq 1000, 1 \leq m \leq 10^5) — size of the matrix and number of operations.Each of the next n lines contains n integers separated by single spaces — description of the matrix a (1 \leq a_{i, j} \leq n).The last line of the description contains a string of m characters describing the operations in order, according to the format above.The sum of n does not exceed 1000, and the sum of m does not exceed 10^5.OutputFor each test case, print n lines with n integers each — the final matrix after m operations.ExampleInput 5 3 2 1 2 3 2 3 1 3 1 2 DR 3 2 1 2 3 2 3 1 3 1 2 LU 3 1 1 2 3 2 3 1 3 1 2 I 3 1 1 2 3 2 3 1 3 1 2 C 3 16 1 2 3 2 3 1 3 1 2 LDICRUCILDICRUCI Output 2 3 1 3 1 2 1 2 3 3 1 2 1 2 3 2 3 1 1 2 3 3 1 2 2 3 1 1 3 2 2 1 3 3 2 1 2 3 1 3 1 2 1 2 3 NoteLine breaks between sample test case answers are only for clarity, and don't have to be printed.
5 3 2 1 2 3 2 3 1 3 1 2 DR 3 2 1 2 3 2 3 1 3 1 2 LU 3 1 1 2 3 2 3 1 3 1 2 I 3 1 1 2 3 2 3 1 3 1 2 C 3 16 1 2 3 2 3 1 3 1 2 LDICRUCILDICRUCI
2 3 1 3 1 2 1 2 3 3 1 2 1 2 3 2 3 1 1 2 3 3 1 2 2 3 1 1 3 2 2 1 3 3 2 1 2 3 1 3 1 2 1 2 3
2 seconds
512 megabytes
['math', 'matrices', '*2700']
B. Glass Half Spilledtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n glasses on the table numbered 1, \ldots, n. The glass i can hold up to a_i units of water, and currently contains b_i units of water.You would like to choose k glasses and collect as much water in them as possible. To that effect you can pour water from one glass to another as many times as you like. However, because of the glasses' awkward shape (and totally unrelated to your natural clumsiness), each time you try to transfer any amount of water, half of the amount is spilled on the floor.Formally, suppose a glass i currently contains c_i units of water, and a glass j contains c_j units of water. Suppose you try to transfer x units from glass i to glass j (naturally, x can not exceed c_i). Then, x / 2 units is spilled on the floor. After the transfer is done, the glass i will contain c_i - x units, and the glass j will contain \min(a_j, c_j + x / 2) units (excess water that doesn't fit in the glass is also spilled).Each time you transfer water, you can arbitrarlly choose from which glass i to which glass j to pour, and also the amount x transferred can be any positive real number.For each k = 1, \ldots, n, determine the largest possible total amount of water that can be collected in arbitrarily chosen k glasses after transferring water between glasses zero or more times.InputThe first line contains a single integer n (1 \leq n \leq 100) — the number of glasses.The following n lines describe the glasses. The i-th of these lines contains two integers a_i and b_i (0 \leq b_i \leq a_i \leq 100, a_i > 0) — capacity, and water amount currently contained for the glass i, respectively.OutputPrint n real numbers — the largest amount of water that can be collected in 1, \ldots, n glasses respectively. Your answer will be accepted if each number is within 10^{-9} absolute or relative tolerance of the precise answer.ExampleInput 3 6 5 6 5 10 2 Output 7.0000000000 11.0000000000 12.0000000000 NoteIn the sample case, you can act as follows: for k = 1, transfer water from the first two glasses to the third one, spilling (5 + 5) / 2 = 5 units and securing 2 + (5 + 5) / 2 = 7 units; for k = 2, transfer water from the third glass to any of the first two, spilling 2 / 2 = 1 unit and securing 5 + 5 + 2 / 2 = 11 units; for k = 3, do nothing. All 5 + 5 + 2 = 12 units are secured.
3 6 5 6 5 10 2
7.0000000000 11.0000000000 12.0000000000
2 seconds
512 megabytes
['dp', '*2000']
A. Row GCDtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two positive integer sequences a_1, \ldots, a_n and b_1, \ldots, b_m. For each j = 1, \ldots, m find the greatest common divisor of a_1 + b_j, \ldots, a_n + b_j.InputThe first line contains two integers n and m (1 \leq n, m \leq 2 \cdot 10^5).The second line contains n integers a_1, \ldots, a_n (1 \leq a_i \leq 10^{18}).The third line contains m integers b_1, \ldots, b_m (1 \leq b_j \leq 10^{18}).OutputPrint m integers. The j-th of them should be equal to GCD(a_1 + b_j, \ldots, a_n + b_j).ExampleInput 4 4 1 25 121 169 1 2 7 23 Output 2 3 8 24
4 4 1 25 121 169 1 2 7 23
2 3 8 24
2 seconds
512 megabytes
['math', 'number theory', '*1600']
E. XOR-rangestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven integers c_{0}, c_{1}, \ldots, c_{k-1} we can define the cost of a number 0 \le x < 2^{k} as p(x) = \sum_{i=0}^{k-1} \left( \left\lfloor \frac{x}{2^{i}} \right\rfloor \bmod 2 \right) \cdot c_{i}. In other words, the cost of number x is the sum of c_{i} over the bits of x which are equal to one.Let's define the cost of array a of length n \ge 2 with elements from [0, 2^{k}) as follows: cost(a) = \sum_{i=1}^{n - 1} p(a_{i} \oplus a_{i+1}), where \oplus denotes bitwise exclusive OR operation.You have to construct an array of length n with minimal cost, given that each element should belong to the given segment: l_{i} \le a_{i} \le r_{i}.InputThe first line contains two integers n and k (2 \le n \le 50, 1 \le k \le 50) — the size of an array and bit length of the numbers in question.Next n lines contain the restrictions for elements of the array: the i-th line contains two integers l_{i} and r_{i} (0 \le l_{i} \le r_{i} < 2^{k}).The last line contains integers c_{0}, c_{1}, \ldots, c_{k-1} (0 \le c_{i} \le 10^{12}).OutputOutput one integer — the minimal cost of an array satisfying all the restrictions.ExamplesInput 4 3 3 3 5 5 6 6 1 1 5 2 7 Output 30 Input 3 3 2 2 3 4 4 6 1 10 100 Output 102 NoteIn the first example there is only one array satisfying all the restrictions — [3, 5, 6, 1] — and its cost is equal to cost([3, 5, 6, 1]) = p(3 \oplus 5) + p(5 \oplus 6) + p(6 \oplus 1) = p(6) + p(3) + p(7) = (c_{1} + c_{2}) + (c_{0} + c_{1}) + (c_{0} + c_{1} + c_{2}) = (2 + 7) + (5 + 2) + (5 + 2 + 7) = 30.In the second example the only optimal array is [2, 3, 6].
4 3 3 3 5 5 6 6 1 1 5 2 7
30
2 seconds
256 megabytes
['dp', 'greedy', '*3500']
G. Forbidden Valuetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is editing a complicated computer program. First, variable x is declared and assigned to 0. Then there are instructions of two types: set y v — assign x a value y or spend v burles to remove that instruction (thus, not reassign x); if y \dots end block — execute instructions inside the if block if the value of x is y and ignore the block otherwise. if blocks can contain set instructions and other if blocks inside them.However, when the value of x gets assigned to s, the computer breaks and immediately catches fire. Polycarp wants to prevent that from happening and spend as few burles as possible.What is the minimum amount of burles he can spend on removing set instructions to never assign x to s?InputThe first line contains two integers n and s (1 \le n \le 2 \cdot 10^5, 1 \le s \le 2 \cdot 10^5) — the number of lines in the program and the forbidden value of x.The following n lines describe the program. Each line is one of three types: set y v (0 \le y \le 2 \cdot 10^5, 1 \le v \le 10^9); if y (0 \le y \le 2 \cdot 10^5); end. Each if instruction is matched by an end instruction. Each end instruction has an if instruction to match.OutputPrint a single integer — the minimum amount of burles Polycarp can spend on removing set instructions to never assign x to s.ExamplesInput 5 1 set 1 10 set 2 15 if 2 set 1 7 end Output 17 Input 7 2 set 3 4 if 3 set 10 4 set 2 7 set 10 1 end set 4 2 Output 4 Input 9 200 if 0 set 5 5 if 5 set 100 13 end if 100 set 200 1 end end Output 1 Input 1 10 set 1 15 Output 0
5 1 set 1 10 set 2 15 if 2 set 1 7 end
17
2 seconds
256 megabytes
['data structures', 'dp', '*2900']
F. String and Operationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s consisting of n characters. These characters are among the first k lowercase letters of the Latin alphabet. You have to perform n operations with the string.During the i-th operation, you take the character that initially occupied the i-th position, and perform one of the following actions with it: swap it with the previous character in the string (if it exists). This operation is represented as L; swap it with the next character in the string (if it exists). This operation is represented as R; cyclically change it to the previous character in the alphabet (b becomes a, c becomes b, and so on; a becomes the k-th letter of the Latin alphabet). This operation is represented as D; cyclically change it to the next character in the alphabet (a becomes b, b becomes c, and so on; the k-th letter of the Latin alphabet becomes a). This operation is represented as U; do nothing. This operation is represented as 0. For example, suppose the initial string is test, k = 20, and the sequence of operations is URLD. Then the string is transformed as follows: the first operation is U, so we change the underlined letter in test to the next one in the first 20 Latin letters, which is a. The string is now aest; the second operation is R, so we swap the underlined letter with the next one in the string aest. The string is now aset; the third operation is L, so we swap the underlined letter with the previous one in the string aset (note that this is now the 2-nd character of the string, but it was initially the 3-rd one, so the 3-rd operation is performed to it). The resulting string is saet; the fourth operation is D, so we change the underlined letter in saet to the previous one in the first 20 Latin letters, which is s. The string is now saes. The result of performing the sequence of operations is saes.Given the string s and the value of k, find the lexicographically smallest string that can be obtained after applying a sequence of operations to s.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines. The first line contains two integers n and k (1 \le n \le 500; 2 \le k \le 26). The second line contains a string s consisting of n characters. Each character is one of the k first letters of the Latin alphabet (in lower case).OutputFor each test case, print one line containing the lexicographically smallest string that can be obtained from s using one sequence of operations.ExampleInput 6 4 2 bbab 7 5 cceddda 6 5 ecdaed 7 4 dcdbdaa 8 3 ccabbaca 5 7 eabba Output aaaa baccacd aabdac aabacad aaaaaaaa abadb
6 4 2 bbab 7 5 cceddda 6 5 ecdaed 7 4 dcdbdaa 8 3 ccabbaca 5 7 eabba
aaaa baccacd aabdac aabacad aaaaaaaa abadb
2 seconds
256 megabytes
['dp', 'greedy', '*2800']
E. Four Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four different integer points p_1, p_2, p_3 and p_4 on \mathit{XY} grid.In one step you can choose one of the points p_i and move it in one of four directions by one. In other words, if you have chosen point p_i = (x, y) you can move it to (x, y + 1), (x, y - 1), (x + 1, y) or (x - 1, y).Your goal to move points in such a way that they will form a square with sides parallel to \mathit{OX} and \mathit{OY} axes (a square with side 0 is allowed).What is the minimum number of steps you need to make such a square?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of four lines. Each line contains two integers x and y (0 \le x, y \le 10^9) — coordinates of one of the points p_i = (x, y).All points are different in one test case.OutputFor each test case, print the single integer — the minimum number of steps to make a square.ExampleInput 3 0 2 4 2 2 0 2 4 1 0 2 0 4 0 6 0 1 6 2 2 2 5 4 1 Output 8 7 5 NoteIn the first test case, one of the optimal solutions is shown below: Each point was moved two times, so the answer 2 + 2 + 2 + 2 = 8.In the second test case, one of the optimal solutions is shown below: The answer is 3 + 1 + 0 + 3 = 7.In the third test case, one of the optimal solutions is shown below: The answer is 1 + 1 + 2 + 1 = 5.
3 0 2 4 2 2 0 2 4 1 0 2 0 4 0 6 0 1 6 2 2 2 5 4 1
8 7 5
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'flows', 'geometry', 'greedy', 'implementation', 'math', 'ternary search', '*2400']
D. Sequence and Swapstime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a sequence a consisting of n integers a_1, a_2, \dots, a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 \le a_2 \le a_3 \le \dots \le a_n holds).To make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer i such that 1 \le i \le n and a_i > x, and swap the values of a_i and x.For example, if a = [0, 2, 3, 5, 4], x = 1, the following sequence of operations is possible: choose i = 2 (it is possible since a_2 > x), then a = [0, 1, 3, 5, 4], x = 2; choose i = 3 (it is possible since a_3 > x), then a = [0, 1, 2, 5, 4], x = 3; choose i = 4 (it is possible since a_4 > x), then a = [0, 1, 2, 3, 4], x = 5. Calculate the minimum number of operations you have to perform so that a becomes sorted, or report that it is impossible.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 two integers n and x (1 \le n \le 500, 0 \le x \le 500) — the number of elements in the sequence and the initial value of x.The second line contains n integers a_1, a_2, ..., a_n (0 \le a_i \le 500).The sum of values of n over all test cases in the input does not exceed 500.OutputFor each test case, print one integer — the minimum number of operations you have to perform to make a sorted, or -1, if it is impossible.ExampleInput 6 4 1 2 3 5 4 5 6 1 1 3 4 4 1 10 2 2 10 11 9 2 10 12 11 5 18 81 324 218 413 324 Output 3 0 0 -1 1 3
6 4 1 2 3 5 4 5 6 1 1 3 4 4 1 10 2 2 10 11 9 2 10 12 11 5 18 81 324 218 413 324
3 0 0 -1 1 3
1.5 seconds
512 megabytes
['dp', 'greedy', 'sortings', '*1600']
C. Ping-pongtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob play ping-pong with simplified rules.During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.The one who doesn't make a return loses this play. The winner of the play commences the next play. Alice starts the first play.Alice has x stamina and Bob has y. To hit the ball (while serving or returning) each player spends 1 stamina, so if they don't have any stamina, they can't return the ball (and lose the play) or can't serve the ball (in this case, the other player serves the ball instead). If both players run out of stamina, the game is over.Sometimes, it's strategically optimal not to return the ball, lose the current play, but save the stamina. On the contrary, when the server commences a play, they have to hit the ball, if they have some stamina left.Both Alice and Bob play optimally and want to, firstly, maximize their number of wins and, secondly, minimize the number of wins of their opponent.Calculate the resulting number of Alice's and Bob's wins.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first and only line of each test case contains two integers x and y (1 \le x, y \le 10^6) — Alice's and Bob's initial stamina.OutputFor each test case, print two integers — the resulting number of Alice's and Bob's wins, if both of them play optimally.ExampleInput 3 1 1 2 1 1 7 Output 0 1 1 1 0 7 NoteIn the first test case, Alice serves the ball and spends 1 stamina. Then Bob returns the ball and also spends 1 stamina. Alice can't return the ball since she has no stamina left and loses the play. Both of them ran out of stamina, so the game is over with 0 Alice's wins and 1 Bob's wins.In the second test case, Alice serves the ball and spends 1 stamina. Bob decides not to return the ball — he loses the play but saves stamina. Alice, as the winner of the last play, serves the ball in the next play and spends 1 more stamina. This time, Bob returns the ball and spends 1 stamina. Alice doesn't have any stamina left, so she can't return the ball and loses the play. Both of them ran out of stamina, so the game is over with 1 Alice's and 1 Bob's win.In the third test case, Alice serves the ball and spends 1 stamina. Bob returns the ball and spends 1 stamina. Alice ran out of stamina, so she can't return the ball and loses the play. Bob, as a winner, serves the ball in the next 6 plays. Each time Alice can't return the ball and loses each play. The game is over with 0 Alice's and 7 Bob's wins.
3 1 1 2 1 1 7
0 1 1 1 0 7
1 second
256 megabytes
['constructive algorithms', 'games', 'math', '*1100']
B. Jumpstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are standing on the \mathit{OX}-axis at point 0 and you want to move to an integer point x > 0.You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can: either jump to the point y + k or jump to the point y - 1. What is the minimum number of jumps you need to reach the point x?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains the single integer x (1 \le x \le 10^6) — the destination point.OutputFor each test case, print the single integer — the minimum number of jumps to reach x. It can be proved that we can reach any integer point x.ExampleInput 5 1 2 3 4 5 Output 1 3 2 3 4 NoteIn the first test case x = 1, so you need only one jump: the 1-st jump from 0 to 0 + 1 = 1.In the second test case x = 2. You need at least three jumps: the 1-st jump from 0 to 0 + 1 = 1; the 2-nd jump from 1 to 1 + 2 = 3; the 3-rd jump from 3 to 3 - 1 = 2; Two jumps are not enough because these are the only possible variants: the 1-st jump as -1 and the 2-nd one as -1 — you'll reach 0 -1 -1 =-2; the 1-st jump as -1 and the 2-nd one as +2 — you'll reach 0 -1 +2 = 1; the 1-st jump as +1 and the 2-nd one as -1 — you'll reach 0 +1 -1 = 0; the 1-st jump as +1 and the 2-nd one as +2 — you'll reach 0 +1 +2 = 3; In the third test case, you need two jumps: the 1-st one as +1 and the 2-nd one as +2, so 0 + 1 + 2 = 3.In the fourth test case, you need three jumps: the 1-st one as -1, the 2-nd one as +2 and the 3-rd one as +3, so 0 - 1 + 2 + 3 = 4.
5 1 2 3 4 5
1 3 2 3 4
1 second
256 megabytes
['constructive algorithms', 'math', '*1200']
A. Strange Functionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.Let's define another function g(x) = \dfrac{x}{f(f(x))} (x is a positive integer as well).Your task is the following: for the given positive integer n, calculate the number of different values of g(x) among all numbers x such that 1 \le x \le n.InputThe first line contains one integer t (1 \le t \le 100) — the number of test cases.Each test case consists of one line containing one integer n (1 \le n < 10^{100}). This integer is given without leading zeroes.OutputFor each test case, print one integer — the number of different values of the function g(x), if x can be any integer from [1, n].ExampleInput 5 4 37 998244353 1000000007 12345678901337426966631415 Output 1 2 9 10 26 NoteExplanations for the two first test cases of the example: if n = 4, then for every integer x such that 1 \le x \le n, \dfrac{x}{f(f(x))} = 1; if n = 37, then for some integers x such that 1 \le x \le n, \dfrac{x}{f(f(x))} = 1 (for example, if x = 23, f(f(x)) = 23,\dfrac{x}{f(f(x))} = 1); and for other values of x, \dfrac{x}{f(f(x))} = 10 (for example, if x = 30, f(f(x)) = 3, \dfrac{x}{f(f(x))} = 10). So, there are two different values of g(x).
5 4 37 998244353 1000000007 12345678901337426966631415
1 2 9 10 26
2 seconds
256 megabytes
['math', 'number theory', '*800']
F. Array Partitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers.Let min(l, r) be the minimum value among a_l, a_{l + 1}, \ldots, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, \ldots, a_r.Your task is to choose three positive (greater than 0) integers x, y and z such that: x + y + z = n; max(1, x) = min(x + 1, x + y) = max(x + y + 1, n). In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).Among all such triples (partitions), you can choose any.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (3 \le n \le 2 \cdot 10^5) — the length of a.The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), where a_i is the i-th element of a.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.If there are several answers, you can print any.ExampleInput 6 11 1 2 3 3 3 4 4 3 4 2 1 8 2 9 1 7 3 9 4 1 9 2 1 4 2 4 3 3 1 2 7 4 2 1 1 4 1 4 5 1 1 1 1 1 7 4 3 4 3 3 3 4 Output YES 6 1 4 NO YES 2 5 2 YES 4 1 2 YES 1 1 3 YES 2 1 4
6 11 1 2 3 3 3 4 4 3 4 2 1 8 2 9 1 7 3 9 4 1 9 2 1 4 2 4 3 3 1 2 7 4 2 1 1 4 1 4 5 1 1 1 1 1 7 4 3 4 3 3 3 4
YES 6 1 4 NO YES 2 5 2 YES 4 1 2 YES 1 1 3 YES 2 1 4
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'two pointers', '*2100']
E. Number of Simple Pathstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph consisting of n vertices and n edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.Your task is to calculate the number of simple paths of length at least 1 in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths). For example, paths [1, 2, 3] and [3, 2, 1] are considered the same.You have to answer t independent test cases.Recall that a path in the graph is a sequence of vertices v_1, v_2, \ldots, v_k such that each pair of adjacent (consecutive) vertices in this sequence is connected by an edge. The length of the path is the number of edges in it. A simple path is such a path that all vertices in it are distinct.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (3 \le n \le 2 \cdot 10^5) — the number of vertices (and the number of edges) in the graph.The next n lines of the test case describe edges: edge i is given as a pair of vertices u_i, v_i (1 \le u_i, v_i \le n, u_i \ne v_i), where u_i and v_i are vertices the i-th edge connects. For each pair of vertices (u, v), there is at most one edge between u and v. There are no edges from the vertex to itself. So, there are no self-loops and multiple edges in the graph. The graph is undirected, i. e. all its edges are bidirectional. The graph is connected, i. e. it is possible to reach any vertex from any other vertex by moving along the edges of the graph.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print one integer: the number of simple paths of length at least 1 in the given graph. Note that paths that differ only by their direction are considered the same (i. e. you have to calculate the number of undirected paths).ExampleInput 3 3 1 2 2 3 1 3 4 1 2 2 3 3 4 4 2 5 1 2 2 3 1 3 2 5 4 3 Output 6 11 18 NoteConsider the second test case of the example. It looks like that:There are 11 different simple paths: [1, 2]; [2, 3]; [3, 4]; [2, 4]; [1, 2, 4]; [1, 2, 3]; [2, 3, 4]; [2, 4, 3]; [3, 2, 4]; [1, 2, 3, 4]; [1, 2, 4, 3].
3 3 1 2 2 3 1 3 4 1 2 2 3 3 4 4 2 5 1 2 2 3 1 3 2 5 4 3
6 11 18
2 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'graphs', 'trees', '*2000']
D. Number into Sequencetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n (n > 1).Your task is to find a sequence of integers a_1, a_2, \ldots, a_k such that: each a_i is strictly greater than 1; a_1 \cdot a_2 \cdot \ldots \cdot a_k = n (i. e. the product of this sequence is n); a_{i + 1} is divisible by a_i for each i from 1 to k-1; k is the maximum possible (i. e. the length of this sequence is the maximum possible). If there are several such sequences, any of them is acceptable. It can be proven that at least one valid sequence always exists for any integer n > 1.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 5000) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (2 \le n \le 10^{10}).It is guaranteed that the sum of n does not exceed 10^{10} (\sum n \le 10^{10}).OutputFor each test case, print the answer: in the first line, print one positive integer k — the maximum possible length of a. In the second line, print k integers a_1, a_2, \ldots, a_k — the sequence of length k satisfying the conditions from the problem statement.If there are several answers, you can print any. It can be proven that at least one valid sequence always exists for any integer n > 1.ExampleInput 4 2 360 4999999937 4998207083 Output 1 2 3 2 2 90 1 4999999937 1 4998207083
4 2 360 4999999937 4998207083
1 2 3 2 2 90 1 4999999937 1 4998207083
3 seconds
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1300']
C. Sequence Transformationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence a, initially consisting of n integers.You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, \dots, a_r] such that a_i \ne x if l \le i \le r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).Note that you can not change x after you chose it.For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then: choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2]; choose l = 3, r = 3, so the resulting sequence is a = [1, 1]. Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.Your task is to find the minimum number of operations required to transform the sequence in a way described above.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n), where a_i is the i-th element of a.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.ExampleInput 5 3 1 1 1 5 1 2 3 4 5 5 1 2 3 2 1 7 1 2 3 1 2 3 1 11 2 2 1 2 3 2 1 2 3 1 2 Output 0 1 1 2 3
5 3 1 1 1 5 1 2 3 4 5 5 1 2 3 2 1 7 1 2 3 1 2 3 1 11 2 2 1 2 3 2 1 2 3 1 2
0 1 1 2 3
1 second
256 megabytes
['greedy', 'implementation', '*1200']
B. Unique Bid Auctiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is such a participant that the number he chose is unique (i. e. nobody else chose this number except him) and is minimal (i. e. among all unique values of a the minimum one is the winning one).Your task is to find the index of the participant who won the game (or -1 if there is no winner). Indexing is 1-based, i. e. the participants are numbered from 1 to n.You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. Then t test cases follow.The first line of the test case contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of participants. The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n), where a_i is the i-th participant chosen number.It is guaranteed that the sum of n does not exceed 2 \cdot 10^5 (\sum n \le 2 \cdot 10^5).OutputFor each test case, print the answer — the index of the participant who won the game (or -1 if there is no winner). Note that the answer is always unique.ExampleInput 6 2 1 1 3 2 1 3 4 2 2 2 3 1 1 5 2 3 2 4 2 6 1 1 5 5 4 4 Output -1 2 4 1 2 -1
6 2 1 1 3 2 1 3 4 2 2 2 3 1 1 5 2 3 2 4 2 6 1 1 5 5 4 4
-1 2 4 1 2 -1
1 second
256 megabytes
['implementation', '*800']
A. Special Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer n (n > 1).Recall that 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 of length 5, 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).Your task is to find a permutation p of length n that there is no index i (1 \le i \le n) such that p_i = i (so, for all i from 1 to n the condition p_i \ne i should be satisfied).You have to answer t independent test cases.If there are several answers, you can print any. It can be proven that the answer exists for each n > 1.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases. Then t test cases follow.The only line of the test case contains one integer n (2 \le n \le 100) — the length of the permutation you have to find.OutputFor each test case, print n distinct integers p_1, p_2, \ldots, p_n — a permutation that there is no index i (1 \le i \le n) such that p_i = i (so, for all i from 1 to n the condition p_i \ne i should be satisfied).If there are several answers, you can print any. It can be proven that the answer exists for each n > 1.ExampleInput 2 2 5 Output 2 1 2 1 5 3 4
2 2 5
2 1 2 1 5 3 4
1 second
256 megabytes
['constructive algorithms', 'probabilities', '*800']
F. Even Hardertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong is now developing a puzzle game. The puzzle consists of n platforms numbered from 1 to n. The player plays the game as a character that can stand on each platform and the goal of the game is to move the character from the 1-st platform to the n-th platform.The i-th platform is labeled with an integer a_i (0 \le a_i \le n-i). When the character is standing on the i-th platform, the player can move the character to any of the j-th platforms where i+1 \le j \le i+a_i. If the character is on the i-th platform where a_i=0 and i \ne n, the player loses the game.Since Gildong thinks the current game is not hard enough, he wants to make it even harder. He wants to change some (possibly zero) labels to 0 so that there remains exactly one way to win. He wants to modify the game as little as possible, so he's asking you to find the minimum number of platforms that should have their labels changed. Two ways are different if and only if there exists a platform the character gets to in one way but not in the other way.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 500).Each test case contains two lines. The first line of each test case consists of an integer n (2 \le n \le 3000) — the number of platforms of the game.The second line of each test case contains n integers. The i-th integer is a_i (0 \le a_i \le n-i) — the integer of the i-th platform.It is guaranteed that: For each test case, there is at least one way to win initially. The sum of n in all test cases doesn't exceed 3000. OutputFor each test case, print one integer — the minimum number of different labels that should be changed to 0 so that there remains exactly one way to win.ExampleInput 3 4 1 1 1 0 5 4 3 2 1 0 9 4 1 4 2 1 0 2 1 0 Output 0 3 2 NoteIn the first case, the player can only move to the next platform until they get to the 4-th platform. Since there is already only one way to win, the answer is zero.In the second case, Gildong can change a_2, a_3, and a_4 to 0 so that the game becomes 4 0 0 0 0. Now the only way the player can win is to move directly from the 1-st platform to the 5-th platform.In the third case, Gildong can change a_2 and a_8 to 0, then the only way to win is to move in the following way: 1 – 3 – 7 – 9.
3 4 1 1 1 0 5 4 3 2 1 0 9 4 1 4 2 1 0 2 1 0
0 3 2
2 seconds
512 megabytes
['dp', '*2700']
E. Dog Snackstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong is playing with his dog, Badugi. They're at a park that has n intersections and n-1 bidirectional roads, each 1 meter in length and connecting two intersections with each other. The intersections are numbered from 1 to n, and for every a and b (1 \le a, b \le n), it is possible to get to the b-th intersection from the a-th intersection using some set of roads.Gildong has put one snack at every intersection of the park. Now Gildong will give Badugi a mission to eat all of the snacks. Badugi starts at the 1-st intersection, and he will move by the following rules: Badugi looks for snacks that are as close to him as possible. Here, the distance is the length of the shortest path from Badugi's current location to the intersection with the snack. However, Badugi's sense of smell is limited to k meters, so he can only find snacks that are less than or equal to k meters away from himself. If he cannot find any such snack, he fails the mission. Among all the snacks that Badugi can smell from his current location, he chooses a snack that minimizes the distance he needs to travel from his current intersection. If there are multiple such snacks, Badugi will choose one arbitrarily. He repeats this process until he eats all n snacks. After that, he has to find the 1-st intersection again which also must be less than or equal to k meters away from the last snack he just ate. If he manages to find it, he completes the mission. Otherwise, he fails the mission. Unfortunately, Gildong doesn't know the value of k. So, he wants you to find the minimum value of k that makes it possible for Badugi to complete his mission, if Badugi moves optimally.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 10^4).The first line of each test case contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of intersections of the park.The next n-1 lines contain two integers u and v (1 \le u,v \le n, u \ne v) each, which means there is a road between intersection u and v. All roads are bidirectional and distinct.It is guaranteed that: For each test case, for every a and b (1 \le a, b \le n), it is possible to get to the b-th intersection from the a-th intersection. The sum of n in all test cases doesn't exceed 2 \cdot 10^5. OutputFor each test case, print one integer — the minimum possible value of k such that Badugi can complete the mission.ExampleInput 3 3 1 2 1 3 4 1 2 2 3 3 4 8 1 2 2 3 3 4 1 5 5 6 6 7 5 8 Output 2 3 3 NoteIn the first case, Badugi can complete his mission with k=2 by moving as follows: Initially, Badugi is at the 1-st intersection. The closest snack is obviously at the 1-st intersection, so he just eats it. Next, he looks for the closest snack, which can be either the one at the 2-nd or the one at the 3-rd intersection. Assume that he chooses the 2-nd intersection. He moves to the 2-nd intersection, which is 1 meter away, and eats the snack. Now the only remaining snack is on the 3-rd intersection, and he needs to move along 2 paths to get to it. After eating the snack at the 3-rd intersection, he needs to find the 1-st intersection again, which is only 1 meter away. As he gets back to it, he completes the mission. In the second case, the only possible sequence of moves he can make is 1 – 2 – 3 – 4 – 1. Since the distance between the 4-th intersection and the 1-st intersection is 3, k needs to be at least 3 for Badugi to complete his mission.In the third case, Badugi can make his moves as follows: 1 – 5 – 6 – 7 – 8 – 2 – 3 – 4 – 1. It can be shown that this is the only possible sequence of moves for Badugi to complete his mission with k=3.
3 3 1 2 1 3 4 1 2 2 3 3 4 8 1 2 2 3 3 4 1 5 5 6 6 7 5 8
2 3 3
3 seconds
512 megabytes
['binary search', 'dfs and similar', 'dp', 'greedy', 'trees', '*2300']
D. Checkpointstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong is developing a game consisting of n stages numbered from 1 to n. The player starts the game from the 1-st stage and should beat the stages in increasing order of the stage number. The player wins the game after beating the n-th stage.There is at most one checkpoint on each stage, and there is always a checkpoint on the 1-st stage. At the beginning of the game, only the checkpoint on the 1-st stage is activated, and all other checkpoints are deactivated. When the player gets to the i-th stage that has a checkpoint, that checkpoint is activated.For each try of a stage, the player can either beat the stage or fail the stage. If they beat the i-th stage, the player is moved to the i+1-st stage. If they fail the i-th stage, the player is moved to the most recent checkpoint they activated, and they have to beat the stages after that checkpoint again.For example, assume that n = 4 and the checkpoints are on the 1-st and 3-rd stages. The player starts at the 1-st stage. If they fail on the 1-st stage, they need to retry the 1-st stage because the checkpoint on the 1-st stage is the most recent checkpoint they activated. If the player beats the 1-st stage, they're moved to the 2-nd stage. If they fail it, they're sent back to the 1-st stage again. If they beat both the 1-st stage and the 2-nd stage, they get to the 3-rd stage and the checkpoint on the 3-rd stage is activated. Now whenever they fail on the 3-rd stage, or the 4-th stage after beating the 3-rd stage, they're sent back to the 3-rd stage. If they beat both the 3-rd stage and the 4-th stage, they win the game.Gildong is going to build the stages to have equal difficulty. He wants you to find any series of stages and checkpoints using at most 2000 stages, where the expected number of tries over all stages is exactly k, for a player whose probability of beating each stage is exactly \cfrac{1}{2}.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 50).Each test case contains exactly one line. The line consists of a single integer k (1 \le k \le 10^{18}) — the expected number of tries over all stages Gildong wants to set for a player whose probability of beating each stage is exactly \cfrac{1}{2}.OutputFor each test case, print -1 if it's impossible to construct such a series of stages and checkpoints using at most 2000 stages.Otherwise, print two lines. The first line should contain a single integer n (1 \le n \le 2000) – the number of stages. The second line should contain n integers, where the i-th integer represents whether the i-th stage has a checkpoint. The i-th integer should be 0 if the i-th stage doesn't have a checkpoint, and 1 if it has a checkpoint. Note that the first integer must be 1 according to the description.ExampleInput 4 1 2 8 12 Output -1 1 1 4 1 1 1 1 5 1 1 0 1 1 NoteIn the first and the second case, we can see that the 'easiest' series of stages is to have 1 stage with a checkpoint. This already requires 2 tries in expectation, so it is impossible to make it to require only 1 try.In the third case, it takes 2 tries in expectation to beat each stage, and the player can always retry that stage without falling back to one of the previous stages if they fail it. Therefore the total expected number of tries is 8. Note that there exists an answer with fewer stages, but you are not required to minimize the number of stages used.
4 1 2 8 12
-1 1 1 4 1 1 1 1 5 1 1 0 1 1
1 second
512 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', 'probabilities', '*1900']
C. Trianglestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong has a square board consisting of n rows and n columns of square cells, each consisting of a single digit (from 0 to 9). The cell at the j-th column of the i-th row can be represented as (i, j), and the length of the side of each cell is 1. Gildong likes big things, so for each digit d, he wants to find a triangle such that: Each vertex of the triangle is in the center of a cell. The digit of every vertex of the triangle is d. At least one side of the triangle is parallel to one of the sides of the board. You may assume that a side of length 0 is parallel to both sides of the board. The area of the triangle is maximized. Of course, he can't just be happy with finding these triangles as is. Therefore, for each digit d, he's going to change the digit of exactly one cell of the board to d, then find such a triangle. He changes it back to its original digit after he is done with each digit. Find the maximum area of the triangle he can make for each digit.Note that he can put multiple vertices of the triangle on the same cell, and the triangle can be a degenerate triangle; i.e. the area of the triangle can be 0. Also, note that he is allowed to change the digit of a cell from d to d.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 1000).The first line of each test case contains one integer n (1 \le n \le 2000) — the number of rows and columns of the board.The next n lines of each test case each contain a string of n digits without spaces. The j-th digit of the i-th line is the digit of the cell at (i, j). Each digit is one of the characters from 0 to 9.It is guaranteed that the sum of n^2 in all test cases doesn't exceed 4 \cdot 10^6.OutputFor each test case, print one line with 10 integers. The i-th integer is the maximum area of triangle Gildong can make when d = i-1, multiplied by 2.ExampleInput 5 3 000 122 001 2 57 75 4 0123 4012 3401 2340 1 9 8 42987101 98289412 38949562 87599023 92834718 83917348 19823743 38947912 Output 4 4 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 9 6 9 9 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 49 49 49 49 15 0 30 42 42 NoteIn the first case, for d=0, no matter which cell he chooses to use, the triangle with vertices at (1, 1), (1, 3), and (3, 1) is the biggest triangle with area of \cfrac{2 \cdot 2}{2} = 2. Since we should print it multiplied by 2, the answer for d=0 is 4.For d=1, Gildong can change the digit of the cell at (1, 3) into 1, making a triangle with vertices on all three 1's that has an area of 2.For d=2, Gildong can change the digit of one of the following six cells into 2 to make a triangle with an area of \cfrac{1}{2}: (1, 1), (1, 2), (1, 3), (3, 1), (3, 2), and (3, 3).For the remaining digits (from 3 to 9), the cell Gildong chooses to change will be the only cell that contains that digit. Therefore the triangle will always be a degenerate triangle with an area of 0.In the third case, for d=4, note that the triangle will be bigger than the answer if Gildong changes the digit of the cell at (1, 4) and use it along with the cells at (2, 1) and (4, 3), but this is invalid because it violates the condition that at least one side of the triangle must be parallel to one of the sides of the board.
5 3 000 122 001 2 57 75 4 0123 4012 3401 2340 1 9 8 42987101 98289412 38949562 87599023 92834718 83917348 19823743 38947912
4 4 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 9 6 9 9 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18 49 49 49 49 15 0 30 42 42
3 seconds
512 megabytes
['greedy', 'implementation', '*1700']
B. Suffix Operationstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations: Increase all elements of a suffix of the array by 1. Decrease all elements of a suffix of the array by 1. A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i \lt j \le n must also be included in the subsegment.Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 1000).Each test case contains two lines. The first line of each test case consists of an integer n (2 \le n \le 2 \cdot 10^5) — the number of elements of the array a.The second line of each test case contains n integers. The i-th integer is a_i (-5 \cdot 10^8 \le a_i \le 5 \cdot 10^8).It is guaranteed that the sum of n in all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.ExampleInput 7 2 1 1 3 -1 0 2 4 99 96 97 95 4 -3 -5 -2 1 6 1 4 3 2 4 1 5 5 0 0 0 5 9 -367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447 Output 0 1 3 4 6 5 2847372102 NoteIn the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to: Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94]. Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96]. In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to: Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2]. Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
7 2 1 1 3 -1 0 2 4 99 96 97 95 4 -3 -5 -2 1 6 1 4 3 2 4 1 5 5 0 0 0 5 9 -367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
0 1 3 4 6 5 2847372102
1 second
512 megabytes
['constructive algorithms', 'implementation', '*1400']
A. Cancel the Trainstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong's town has a train system that has 100 trains that travel from the bottom end to the top end and 100 trains that travel from the left end to the right end. The trains starting from each side are numbered from 1 to 100, respectively, and all trains have the same speed. Let's take a look at the picture below. The train system can be represented as coordinates on a 2D plane. The i-th train starting at the bottom end is initially at (i,0) and will be at (i,T) after T minutes, and the i-th train starting at the left end is initially at (0,i) and will be at (T,i) after T minutes. All trains arrive at their destinations after 101 minutes.However, Gildong found that some trains scheduled to depart at a specific time, simultaneously, are very dangerous. At this time, n trains are scheduled to depart from the bottom end and m trains are scheduled to depart from the left end. If two trains are both at (x,y) at the same time for some x and y, they will crash into each other. Therefore, he is asking you to find the minimum number of trains that should be cancelled to prevent all such crashes.InputEach test contains one or more test cases. The first line contains the number of test cases t (1 \le t \le 100).Each test case contains three lines. The first line of each test case consists of two integers n and m (1 \le n, m \le 100) — the number of trains scheduled to depart from the bottom end, and the number of trains scheduled to depart from the left end, respectively.The second line of each test case contains n integers. Each integer is a train number that is scheduled to start from the bottom end. The numbers are given in strictly increasing order, and are between 1 and 100, inclusive.The third line of each test case contains m integers. Each integer is a train number that is scheduled to start from the left end. The numbers are given in strictly increasing order, and are between 1 and 100, inclusive.OutputFor each test case, print a single integer: the minimum number of trains that should be canceled in order to prevent all crashes.ExampleInput 3 1 2 1 3 4 3 2 1 3 4 2 4 9 14 2 7 16 28 33 57 59 86 99 3 9 14 19 25 26 28 35 41 59 85 87 99 100 Output 0 1 3 NoteIn the first case, we can show that there will be no crashes if the current schedule is followed. Therefore, the answer is zero.In the second case, at T=4, there will be a crash, as can be seen in the picture below. We can prove that after canceling one of these trains, the remaining trains will not crash. Therefore, the answer is one.
3 1 2 1 3 4 3 2 1 3 4 2 4 9 14 2 7 16 28 33 57 59 86 99 3 9 14 19 25 26 28 35 41 59 85 87 99 100
0 1 3
1 second
512 megabytes
['implementation', '*800']
G. Game On Treetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree.The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): Alice either moves her chip to an adjacent vertex or doesn't move it; for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game.Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted.For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.Then n - 1 lines follow, each line contains two integers u_i, v_i (1 \le u_i, v_i \le n; u_i \ne v_i) that denote the endpoints of an edge. These edges form a tree.The next line contains one integer k (1 \le k \le n - 1) — the number of Bob's chips.The last line contains k integers a_1, a_2, ..., a_k (1 \le a_i \le n; a_i \ne a_j if i \ne j) — the vertices where the Bob's chips are initially placed.OutputPrint n integers. The i-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex i. If one of Bob's chips is already placed in vertex i, then the answer for vertex i is 0.ExamplesInput 5 2 4 3 1 3 4 3 5 2 4 5 Output 2 1 2 0 0 Input 8 4 1 8 4 4 5 6 4 2 5 4 3 1 7 3 2 8 3 Output 3 0 0 3 1 2 3 0 Input 10 2 5 4 3 7 3 7 2 5 8 3 6 8 10 7 9 7 1 4 10 6 9 1 Output 0 2 2 2 2 0 2 2 0 0
5 2 4 3 1 3 4 3 5 2 4 5
2 1 2 0 0
3 seconds
512 megabytes
['data structures', 'dfs and similar', 'greedy', 'trees', '*2700']
F. Divide Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset of powers of two. More precisely, for each i from 0 to n exclusive you have cnt_i elements equal to 2^i.In one operation, you can choose any one element 2^l > 1 and divide it into two elements 2^{l - 1}.You should perform q queries. Each query has one of two types: "1 pos val" — assign cnt_{pos} := val; "2 x k" — calculate the minimum number of operations you need to make at least k elements with value lower or equal to 2^x. Note that all queries of the second type don't change the multiset; that is, you just calculate the minimum number of operations, you don't perform them.InputThe first line contains two integers n and q (1 \le n \le 30; 1 \le q \le 2 \cdot 10^5) — the size of array cnt and the number of queries.The second line contains n integers cnt_0, cnt_1, \dots, cnt_{n - 1} (0 \le cnt_i \le 10^6).Next q lines contain queries: one per line. Each query has one of two types: "1 pos val" (0 \le pos < n; 0 \le val \le 10^6); "2 x k" (0 \le x < n; 1 \le k \le 10^{15}). It's guaranteed that there is at least one query of the second type.OutputFor each query of the second type, print the minimum number of operations you need to make at least k elements with a value lower or equal to 2^x or -1 if there is no way to do it.ExampleInput 6 11 0 1 0 0 1 0 2 1 5 2 4 18 1 1 0 2 2 5 2 0 17 1 0 3 2 1 2 1 1 4 1 4 0 1 5 1 2 2 8 Output 4 16 4 -1 0 1
6 11 0 1 0 0 1 0 2 1 5 2 4 18 1 1 0 2 2 5 2 0 17 1 0 3 2 1 2 1 1 4 1 4 0 1 5 1 2 2 8
4 16 4 -1 0 1
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*2900']
E. Two Editorialstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerland regional ICPC contest has just ended. There were m participants numbered from 1 to m, who competed on a problemset of n problems numbered from 1 to n.Now the editorial is about to take place. There are two problem authors, each of them is going to tell the tutorial to exactly k consecutive tasks of the problemset. The authors choose the segment of k consecutive tasks for themselves independently of each other. The segments can coincide, intersect or not intersect at all.The i-th participant is interested in listening to the tutorial of all consecutive tasks from l_i to r_i. Each participant always chooses to listen to only the problem author that tells the tutorials to the maximum number of tasks he is interested in. Let this maximum number be a_i. No participant can listen to both of the authors, even if their segments don't intersect.The authors want to choose the segments of k consecutive tasks for themselves in such a way that the sum of a_i over all participants is maximized.InputThe first line contains three integers n, m and k (1 \le n, m \le 2000, 1 \le k \le n) — the number of problems, the number of participants and the length of the segment of tasks each of the problem authors plans to tell the tutorial to.The i-th of the next m lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n) — the segment of tasks the i-th participant is interested in listening to the tutorial to.OutputPrint a single integer — the maximum sum of a_i over all participants.ExamplesInput 10 5 3 1 3 2 4 6 9 6 9 1 8 Output 14 Input 10 3 3 2 4 4 6 3 5 Output 8 Input 4 4 1 3 3 1 1 2 2 4 4 Output 2 Input 5 4 5 1 2 2 3 3 4 4 5 Output 8 NoteIn the first example the first author can tell the tutorial to problems from 1 to 3 and the second one — from 6 to 8. That way the sequence of a_i will be [3, 2, 3, 3, 3]. Notice that the last participant can't listen to both author, he only chooses the one that tells the maximum number of problems he's interested in.In the second example the first one can tell problems 2 to 4, the second one — 4 to 6.In the third example the first one can tell problems 1 to 1, the second one — 2 to 2. Or 4 to 4 and 3 to 3. Every pair of different problems will get the same sum of 2.In the fourth example the first one can tell problems 1 to 5, the second one — 1 to 5 as well.
10 5 3 1 3 2 4 6 9 6 9 1 8
14
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'sortings', 'two pointers', '*2500']
D. Radio Towerstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n + 2 towns located on a coordinate line, numbered from 0 to n + 1. The i-th town is located at the point i.You build a radio tower in each of the towns 1, 2, \dots, n with probability \frac{1}{2} (these events are independent). After that, you want to set the signal power on each tower to some integer from 1 to n (signal powers are not necessarily the same, but also not necessarily different). The signal from a tower located in a town i with signal power p reaches every city c such that |c - i| < p.After building the towers, you want to choose signal powers in such a way that: towns 0 and n + 1 don't get any signal from the radio towers; towns 1, 2, \dots, n get signal from exactly one radio tower each. For example, if n = 5, and you have built the towers in towns 2, 4 and 5, you may set the signal power of the tower in town 2 to 2, and the signal power of the towers in towns 4 and 5 to 1. That way, towns 0 and n + 1 don't get the signal from any tower, towns 1, 2 and 3 get the signal from the tower in town 2, town 4 gets the signal from the tower in town 4, and town 5 gets the signal from the tower in town 5.Calculate the probability that, after building the towers, you will have a way to set signal powers to meet all constraints.InputThe first (and only) line of the input contains one integer n (1 \le n \le 2 \cdot 10^5).OutputPrint one integer — the probability that there will be a way to set signal powers so that all constraints are met, taken modulo 998244353.Formally, the probability can be expressed as an irreducible fraction \frac{x}{y}. You have to print the value of x \cdot y^{-1} \bmod 998244353, where y^{-1} is an integer such that y \cdot y^{-1} \bmod 998244353 = 1.ExamplesInput 2 Output 748683265 Input 3 Output 748683265 Input 5 Output 842268673 Input 200000 Output 202370013 NoteThe real answer for the first example is \frac{1}{4}: with probability \frac{1}{4}, the towers are built in both towns 1 and 2, so we can set their signal powers to 1. The real answer for the second example is \frac{1}{4}: with probability \frac{1}{8}, the towers are built in towns 1, 2 and 3, so we can set their signal powers to 1; with probability \frac{1}{8}, only one tower in town 2 is built, and we can set its signal power to 2. The real answer for the third example is \frac{5}{32}. Note that even though the previous explanations used equal signal powers for all towers, it is not necessarily so. For example, if n = 5 and the towers are built in towns 2, 4 and 5, you may set the signal power of the tower in town 2 to 2, and the signal power of the towers in towns 4 and 5 to 1.
2
748683265
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*1600']
C. Two Bracketstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string s (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of testcases.Each of the next t lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase print a single integer — the maximum number of moves you can perform on a given string s.ExampleInput 5 () []() ([)] )]([ )[(] Output 1 2 2 0 1 NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions 1 and 2: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions 1 and 3: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions 2 and 4: ")[(]" and get ")(" as a result. You can erase nothing from it.
5 () []() ([)] )]([ )[(]
1 2 2 0 1
1 second
256 megabytes
['greedy', '*800']
B. Toy Blockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are asked to watch your nephew who likes to play with toy blocks in a strange way.He has n boxes and the i-th box has a_i blocks. His game consists of two steps: he chooses an arbitrary box i; he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes.You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains the integer n (2 \le n \le 10^5) — the number of boxes.The second line of each test case contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9) — the number of blocks in each box.It's guaranteed that the sum of n over test cases doesn't exceed 10^5.OutputFor each test case, print a single integer — the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite.ExampleInput 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 NoteIn the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks.In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal.In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1].
3 3 3 2 2 4 2 2 3 2 3 0 3 0
1 0 3
2 seconds
256 megabytes
['binary search', 'greedy', 'math', 'sortings', '*1400']
A. Robot Programtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute: move north from cell (i, j) to (i, j + 1); move east from cell (i, j) to (i + 1, j); move south from cell (i, j) to (i, j - 1); move west from cell (i, j) to (i - 1, j); stay in cell (i, j). The robot wants to reach cell (x, y) in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach (x, y) from (0, 0)?InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.Each of the next t lines contains two integers x and y (0 \le x, y \le 10^4) — the destination coordinates of the robot.OutputFor each testcase print a single integer — the minimum number of commands required for the robot to reach (x, y) from (0, 0) if no command is allowed to be executed two or more times in a row.ExampleInput 5 5 5 3 4 7 1 0 0 2 0 Output 10 7 13 0 3 NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E.
5 5 5 3 4 7 1 0 0 2 0
10 7 13 0 3
2 seconds
256 megabytes
['math', '*800']
F. Nullify The Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJeel and Ashish play a game on an n \times m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. Choose a starting cell (r_1, c_1) with non-zero value. Choose a finishing cell (r_2, c_2) such that r_1 \leq r_2 and c_1 \leq c_2. Decrease the value of the starting cell by some positive non-zero integer. Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: a shortest path is one that passes through the least number of cells; all cells on this path excluding the starting cell, but the finishing cell may be modified; the resulting value of each cell must be a non-negative integer; the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.Given the initial matrix, if both players play optimally, can you predict who will win?InputThe first line contains a single integer t (1 \leq t \leq 10) — the number of test cases. The description of each test case is as follows.The first line of each test case contains two integers n and m (1 \leq n, m \leq 100) — the dimensions of the matrix.The next n lines contain m space separated integers a_{i,j} (0 \leq a_{i,j} \leq 10^6) — the values of each cell of the matrix.OutputFor each test case, if Ashish wins the game, print "Ashish", otherwise print "Jeel" (without the quotes).ExampleInput 4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9 Output Jeel Ashish Jeel Ashish NoteIn the first test case, the only cell of the matrix is 0. There are no moves Ashish can make. Jeel is the winner.In the second test case, Ashish can choose (r_1, c_1) = (r_2, c_2) = (1,3) and reduce the cell to 0, leaving [0, 0, 0]. Jeel cannot perform any moves. Ashish wins.
4 1 1 0 1 3 0 0 5 2 2 0 1 1 0 3 3 1 2 3 4 5 6 7 8 9
Jeel Ashish Jeel Ashish
2 seconds
256 megabytes
['constructive algorithms', 'games', '*2700']
E2. Bitwise Queries (Hard Version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array a of n integers which he wants Ashish to guess. Note that n is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND i j: ask for the bitwise AND of elements a_i and a_j (1 \leq i, j \le n, i \neq j) OR i j: ask for the bitwise OR of elements a_i and a_j (1 \leq i, j \le n, i \neq j) XOR i j: ask for the bitwise XOR of elements a_i and a_j (1 \leq i, j \le n, i \neq j) Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range [0, n-1] (inclusive) and Ashish can ask no more than n+1 queries.InputThe first line of input contains one integer n (4 \le n \le 2^{16}) — the length of the array. It is guaranteed that n is a power of two.InteractionTo ask a query print a single line containing one of the following (without quotes) "AND i j" "OR i j" "XOR i j" where i and j (1 \leq i, j \le n, i \neq j) denote the indices being queried.For each query, you will receive an integer x whose value depends on the type of query. If the indices queried are invalid or you exceed the number of queries however, you will get x = -1. In this case, you should terminate the program immediately.When you have guessed the elements of the array, print a single line "! " (without quotes), followed by n space-separated integers  — the elements of the array.Guessing the array does not count towards the number of queries asked.The interactor is not adaptive. The array a does not change with queries.After printing a query do not forget to output the end of the 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 hack the solution, use the following test format:On the first line print a single integer n (4 \le n \le 2^{16}) — the length of the array. It must be a power of 2. The next line should contain n space-separated integers in the range [0, n-1] — the array a.ExampleInput 4 0 2 3 Output OR 1 2 OR 2 3 XOR 2 4 ! 0 0 2 3 NoteThe array a in the example is [0, 0, 2, 3].
4 0 2 3
OR 1 2 OR 2 3 XOR 2 4 ! 0 0 2 3
4 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'interactive', 'math', '*2300']
E1. Bitwise Queries (Easy Version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is the constraints on the number of queries.This is an interactive problem.Ridbit has a hidden array a of n integers which he wants Ashish to guess. Note that n is a power of two. Ashish is allowed to ask three different types of queries. They are of the form AND i j: ask for the bitwise AND of elements a_i and a_j (1 \leq i, j \le n, i \neq j) OR i j: ask for the bitwise OR of elements a_i and a_j (1 \leq i, j \le n, i \neq j) XOR i j: ask for the bitwise XOR of elements a_i and a_j (1 \leq i, j \le n, i \neq j) Can you help Ashish guess the elements of the array?In this version, each element takes a value in the range [0, n-1] (inclusive) and Ashish can ask no more than n+2 queries.InputThe first line of input contains one integer n (4 \le n \le 2^{16}) — the length of the array. It is guaranteed that n is a power of two.InteractionTo ask a query print a single line containing one of the following (without quotes) "AND i j" "OR i j" "XOR i j" where i and j (1 \leq i, j \le n, i \neq j) denote the indices being queried.For each query, you will receive an integer x whose value depends on the type of query. If the indices queried are invalid or you exceed the number of queries however, you will get x = -1. In this case, you should terminate the program immediately.When you have guessed the elements of the array, print a single line "! " (without quotes), followed by n space-separated integers  — the elements of the array.Guessing the array does not count towards the number of queries asked.The interactor is not adaptive. The array a does not change with queries.After printing a query do not forget to output the end of the 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 hack the solution, use the following test format:On the first line print a single integer n (4 \le n \le 2^{16}) — the length of the array. It must be a power of 2. The next line should contain n space-separated integers in the range [0, n-1] — the array a.ExampleInput 4 0 2 3 Output OR 1 2 OR 2 3 XOR 2 4 ! 0 0 2 3 NoteThe array a in the example is [0, 0, 2, 3].
4 0 2 3
OR 1 2 OR 2 3 XOR 2 4 ! 0 0 2 3
4 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'interactive', 'math', '*2000']
D. Circle Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputUtkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the player must ensure that the token stays within a (Euclidean) distance d from (0,0).In other words, if after a move the coordinates of the token are (p,q), then p^2 + q^2 \leq d^2 must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The only line of each test case contains two space separated integers d (1 \leq d \leq 10^5) and k (1 \leq k \leq d).OutputFor each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes).ExampleInput 5 2 1 5 2 10 3 25 4 15441 33 Output Utkarsh Ashish Utkarsh Utkarsh Ashish NoteIn the first test case, one possible sequence of moves can be(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2).Ashish has no moves left, so Utkarsh wins.
5 2 1 5 2 10 3 25 4 15441 33
Utkarsh Ashish Utkarsh Utkarsh Ashish
2 seconds
256 megabytes
['games', 'geometry', 'math', '*1700']
C. String Equalitytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAshish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters.He wants to convert string a into string b by performing some (possibly zero) operations on a.In one move, he can either choose an index i (1 \leq i\leq n-1) and swap a_i and a_{i+1}, or choose an index i (1 \leq i \leq n-k+1) and if a_i, a_{i+1}, \ldots, a_{i+k-1} are all equal to some character c (c \neq 'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of each test case is as follows.The first line of each test case contains two integers n (2 \leq n \leq 10^6) and k (1 \leq k \leq n).The second line of each test case contains the string a of length n consisting of lowercase English letters.The third line of each test case contains the string b of length n consisting of lowercase English letters.It is guaranteed that the sum of values n among all test cases does not exceed 10^6.OutputFor each test case, print "Yes" if Ashish can convert a into b after some moves, else print "No".You may print the letters of the answer in any case (upper or lower).ExampleInput 4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc Output No Yes No Yes NoteIn the first test case it can be shown that it is impossible to convert a into b.In the second test case,"abba" \xrightarrow{\text{inc}} "acca" \xrightarrow{\text{inc}} \ldots \xrightarrow{\text{inc}} "azza".Here "swap" denotes an operation of the first type, and "inc" denotes an operation of the second type.In the fourth test case,"aaabba" \xrightarrow{\text{swap}} "aaabab" \xrightarrow{\text{swap}} "aaaabb" \xrightarrow{\text{inc}} \ldots \xrightarrow{\text{inc}} "ddaabb" \xrightarrow{\text{inc}} \ldots \xrightarrow{\text{inc}} "ddddbb" \xrightarrow{\text{inc}} \ldots \xrightarrow{\text{inc}} "ddddcc".
4 3 3 abc bcd 4 2 abba azza 2 1 zz aa 6 2 aaabba ddddcc
No Yes No Yes
2 seconds
256 megabytes
['dp', 'greedy', 'hashing', 'implementation', 'strings', '*1400']
B. Non-Substring Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers l_i, r_i (1 \leq l_i \lt r_i \leq n). For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i\ldots r_i]. A substring s[i\ldots j] of a string s is the string formed by characters s_i s_{i+1} \ldots s_j. String a is said to be a subsequence of string b if a can be obtained from b by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length \ge 2. For example, if s is "1100110", then the subsequences s_1s_2s_4 ("1100110") and s_1s_5s_7 ("1100110") are good, while s_1s_2s_3 ("1100110") is not good. Can you help Hr0d1y answer each query?InputThe first line of the input contains a single integer t (1\leq t \leq 100) — the number of test cases. The description of each test case is as follows.The first line contains two integers n (2 \leq n \leq 100) and q (1\leq q \leq 100) — the length of the string and the number of queries. The second line contains the string s.The i-th of the next q lines contains two integers l_i and r_i (1 \leq l_i \lt r_i \leq n).OutputFor each test case, output q lines. The i-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring s[l_i...r_i], and "NO" otherwise.You may print each letter in any case (upper or lower).ExampleInput 2 6 3 001000 2 4 1 3 3 5 4 2 1111 1 4 2 3 Output YES NO YES NO YES NoteIn the first test case, s[2\ldots 4] = "010". In this case s_1s_3s_5 ("001000") and s_2s_3s_6 ("001000") are good suitable subsequences, while s_2s_3s_4 ("001000") is not good. s[1\ldots 3] = "001". No suitable good subsequence exists. s[3\ldots 5] = "100". Here s_3s_5s_6 ("001000") is a suitable good subsequence.
2 6 3 001000 2 4 1 3 3 5 4 2 1111 1 4 2 3
YES NO YES NO YES
1 second
256 megabytes
['dp', 'greedy', 'implementation', 'strings', '*900']
A. Subtract or Dividetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRidbit starts with an integer n.In one move, he can perform one of the following operations: divide n by one of its proper divisors, or subtract 1 from n if n is greater than 1. A proper divisor is a divisor of a number, excluding itself. For example, 1, 2, 4, 5, and 10 are proper divisors of 20, but 20 itself is not.What is the minimum number of moves Ridbit is required to make to reduce n to 1?InputThe first line contains a single 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^9).OutputFor each test case, output the minimum number of moves required to reduce n to 1.ExampleInput 6 1 2 3 4 6 9 Output 0 1 2 2 2 3 NoteFor the test cases in the example, n may be reduced to 1 using the following operations in sequence12 \xrightarrow{} 13 \xrightarrow{} 2 \xrightarrow{} 14 \xrightarrow{} 2 \xrightarrow{} 16 \xrightarrow{} 2 \xrightarrow{} 19 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1
6 1 2 3 4 6 9
0 1 2 2 2 3
1 second
256 megabytes
['greedy', 'math', '*800']
H2. Multithreading (Hard Version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions of the problem is that there are no updates in the easy version.There are n spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.For any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.Coloring is an assignment of colors (white and black) to the spools. A coloring is called valid if it has at least one matching. That is if the number of black spools and the number of white spools are both even.Given a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If c is a valid coloring, let f(c) denote the minimum number of such intersections out of all possible matchings. The circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so f(\text{bwbbbwww}) = 1. You are given a string s representing an unfinished coloring, with black, white, and uncolored spools. A coloring c is called s-reachable if you can achieve it by assigning colors to the uncolored spools of s without changing the others.A coloring c is chosen uniformly at random among all valid, s-reachable colorings. Compute the expected value of f(c). You should find it by modulo 998244353.There will be m updates to change one character of s. After each update, you should again compute the expected value of f(c).We can show that each answer can be written in the form \frac{p}{q} where p and q are relatively prime integers and q\not\equiv 0\pmod{998244353}. The answer by modulo 998244353 is equal to (p\cdot q^{-1}) modulo 998244353.InputThe first line contains two integers n, m (2\le n\le 2\cdot 10^5, n is even, 0\le m\le 2\cdot 10^5) — the number of spools and the number of updates, respectively.The second line contains a string s of length n — the unfinished coloring of the spools. The i-th character will be 'w', 'b', or '?', describing if the i-th spool is white, black, or uncolored, respectively.Each of the next m lines contains an integer i (1 \leq i \leq n) — the position of the character in s to be updated, and a character c (c \in \{\text{w}, \text{b}, \text{?}\}) — the new color of the spool i after the update.It is guaranteed there exists at least one uncolored spool initially and after each update.OutputPrint m+1 lines: the expected value of f(c) initially and after each update. All values should be found by modulo 998244353.ExamplesInput 8 0 bwbb?www Output 1 Input 10 3 ???ww?wb?? 4 ? 5 ? 2 w Output 436731905 218365953 374341633 530317313 Input 4 3 bw?b 1 w 2 b 1 w Output 0 0 1 1 NoteThe first test corresponds closely to the image. Coloring '?' as 'w' does not create a valid coloring because the number of black spools is odd. Then the only reachable valid coloring is 'bwbbbwww' and f(\text{bwbbbwww}) = 1, so the expected value is 1.In the second test, the string after each update is: ????w?wb?? ??????wb?? ?w????wb?? In the third test, the string after each update is: ww?b wb?b wb?b
8 0 bwbb?www
1
4 seconds
256 megabytes
['combinatorics', 'implementation', 'math', '*3300']
H1. Multithreading (Easy Version)time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions of the problem is that there are no updates in the easy version.There are n spools of thread placed on the rim of a circular table. The spools come in two types of thread: the first thread is black and the second thread is white.For any two spools of the same color, you can attach them with a thread of that color in a straight line segment. Define a matching as a way to attach spools together so that each spool is attached to exactly one other spool.Coloring is an assignment of colors (white and black) to the spools. A coloring is called valid if it has at least one matching. That is if the number of black spools and the number of white spools are both even.Given a matching, we can find the number of times some white thread intersects some black thread. We compute the number of pairs of differently colored threads that intersect instead of the number of intersection points, so one intersection point may be counted multiple times if different pairs of threads intersect at the same point. If c is a valid coloring, let f(c) denote the minimum number of such intersections out of all possible matchings. The circle above is described by the coloring bwbbbwww. After matching the spools as shown, there is one intersection between differently colored threads. It can be proven that it is the minimum possible, so f(\text{bwbbbwww}) = 1. You are given a string s representing an unfinished coloring, with black, white, and uncolored spools. A coloring c is called s-reachable if you can achieve it by assigning colors to the uncolored spools of s without changing the others.A coloring c is chosen uniformly at random among all valid, s-reachable colorings. Compute the expected value of f(c). You should find it by modulo 998244353.We can show that the answer can be written in the form \frac{p}{q} where p and q are relatively prime integers and q\not\equiv 0\pmod{998244353}. The answer by modulo 998244353 is equal to (p\cdot q^{-1}) modulo 998244353.InputThe first line contains two integers n, m (2\le n\le 2\cdot 10^5, n is even, m=0) — the number of spools and updates, respectively. There are no updates in the easy version, so it is always 0.The second line contains a string s of length n — the unfinished coloring of the spools. The i-th character will be 'w', 'b', or '?', describing if the i-th spool is white, black, or uncolored, respectively.It is guaranteed there exists at least one uncolored spool.OutputPrint the expected value of f(c) by modulo 998244353.ExamplesInput 8 0 bwbb?www Output 1 Input 10 0 ???ww?wb?? Output 436731905 Input 4 0 bw?b Output 0 NoteThe first test corresponds closely to the image. Coloring '?' as 'w' does not create a valid coloring because the number of black spools is odd. Then the only reachable valid coloring is 'bwbbbwww' and f(\text{bwbbbwww}) = 1, so the expected value is 1.It can be shown that the expected value for the second test is \frac{9}{16}.
8 0 bwbb?www
1
4 seconds
256 megabytes
['combinatorics', 'fft', 'math', '*2900']
G. Communismtime limit per test1.5 secondsmemory limit per test32 megabytesinputstandard inputoutputstandard outputPlease pay attention to the unusual memory limit in this problem.In a parallel universe, Satan is called "Trygub". For that reason, the letters of his namesake were deleted from the alphabet in ancient times.The government has n workers standing in a row and numbered with integers from 1 to n from left to right. Their job categories can be represented as a string s of length n, where the character s_i represents the job category of the i-th worker.A new law will be approved to increase the equality between the workers. The government decided to make everyone have the same job category by performing the following operation any number of times (possibly zero).There is a fixed rational parameter k=\frac ab describing how easy it is to convince the public, and it will be used to determine the success of an operation.In an operation, the government first selects a job category x with at least one worker at the current moment. Suppose i_1,\ldots, i_m (i_1<\ldots<i_m) are the positions of all the workers with job category x. If k\cdot (i_m-i_1+1)\le m, the government is able to choose any job category y with at least one worker at the current moment and change the job category of all workers with job category x to job category y.If it is possible to make all workers have job category x, we say that x is obtainable. Can you tell the government the set of obtainable job categories?InputThe first line contains three integers n, a, b (1 \le n \le 5000, 1\le a\le b\le 10^5) — the number of workers and the numerator and denominator of the parameter k, respectively.The second line contains a string s of length n, consisting of lowercase English characters — the job categories of each worker. The characters 't', 'r', 'y', 'g', 'u', and 'b' do not appear in the string s.OutputPrint an integer c equal to the number of obtainable job categories followed by c space-separated characters — the obtainable job categories sorted in the lexicographical order.ExampleInput 7 1 2 comicom Output 3 c m o NoteThe first operation must select the job category 'i' because all other job categories cannot satisfy the condition, therefore 'i' is not obtainable.Below is showed how to obtain 'c', 'm', and 'o'. The square brackets denote the segment containing all workers of the selected category, the red color denotes this category and the blue color denotes the new category after the change. Get 'c': (\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}) (\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[m}}\texttt{m}\color{#1E90FF}{\texttt{m}}\texttt{c}\color{#1E90FF}{\texttt{m]}}\texttt{m}) (\texttt{c}\color{red}{\texttt{[mmm}}\texttt{c}\color{red}{\texttt{mm]}} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[ccc}}\texttt{c}\color{#1E90FF}{\texttt{cc]}}) Get 'm': (\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}) (\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[c}}\texttt{m}\color{#1E90FF}{\texttt{c}}\texttt{c}\color{#1E90FF}{\texttt{c]}}\texttt{m}) (\color{red}{\texttt{[cc}}\texttt{m}\color{red}{\texttt{ccc]}}\texttt{m} \rightarrow \color{#1E90FF}{\texttt{[mm}}\texttt{m}\color{#1E90FF}{\texttt{mmm]}}\texttt{m}) Get 'o': (\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[c]}}\texttt{com}) (\color{red}{\texttt{[c}}\texttt{om}\color{red}{\texttt{cc]}}\texttt{om} \rightarrow \color{#1E90FF}{\texttt{[m}}\texttt{om}\color{#1E90FF}{\texttt{mm]}}\texttt{om}) (\color{red}{\texttt{[m}}\texttt{o}\color{red}{\texttt{mmm}}\texttt{o}\color{red}{\texttt{m]}} \rightarrow \color{#1E90FF}{\texttt{[o}}\texttt{o}\color{#1E90FF}{\texttt{ooo}}\texttt{o}\color{#1E90FF}{\texttt{o]}})
7 1 2 comicom
3 c m o
1.5 seconds
32 megabytes
['bitmasks', 'dp', 'trees', '*3500']
F. The Struggling Contestanttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo help those contestants who struggle a lot in contests, the headquarters of Codeforces are planning to introduce Division 5. In this new division, the tags of all problems will be announced prior to the round to help the contestants.The contest consists of n problems, where the tag of the i-th problem is denoted by an integer a_i.You want to AK (solve all problems). To do that, you must solve the problems in some order. To make the contest funnier, you created extra limitations on yourself. You do not want to solve two problems consecutively with the same tag since it is boring. Also, you are afraid of big jumps in difficulties while solving them, so you want to minimize the number of times that you solve two problems consecutively that are not adjacent in the contest order.Formally, your solve order can be described by a permutation p of length n. The cost of a permutation is defined as the number of indices i (1\le i<n) where |p_{i+1}-p_i|>1. You have the requirement that a_{p_i}\ne a_{p_{i+1}} for all 1\le i< n.You want to know the minimum possible cost of permutation that satisfies the requirement. If no permutations meet this requirement, you should report about it.InputThe first line contains a single integer t (1\leq t\leq 10^4) — the number of test cases.The first line of the description of each test case contains a single integer n (1 \le n \le 10^5) — the number of problems in the contest.The next line contains n integers a_1,a_2,\ldots a_n (1 \le a_i \le n) — the tags of the problems.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, if there are no permutations that satisfy the required condition, print -1. Otherwise, print the minimum possible cost of a permutation that satisfies the required condition.ExampleInput 4 6 2 1 2 3 1 1 5 1 1 1 2 2 8 7 7 2 7 7 1 8 7 10 1 2 3 4 1 1 2 3 4 1 Output 1 3 -1 2 NoteIn the first test case, let p=[5, 4, 3, 2, 1, 6]. The cost is 1 because we jump from p_5=1 to p_6=6, and |6-1|>1. This permutation is valid because we don't solve problems with the same tag twice in a row. We cannot find a permutation with a cost smaller than 1.In the second test case, let p=[1,5,2,4,3]. The cost is 3 because |p_2-p_1|>1, |p_3-p_2|>1, and |p_4-p_3|>1. The permutation is valid because we don't solve problems with the same tag twice in a row. We cannot find a permutation with a cost smaller than 3.In the third test case, for any order of solving the problems, we will solve two problems with the same tag consecutively, so the answer is -1.
4 6 2 1 2 3 1 1 5 1 1 1 2 2 8 7 7 2 7 7 1 8 7 10 1 2 3 4 1 1 2 3 4 1
1 3 -1 2
1 second
256 megabytes
['constructive algorithms', 'greedy', '*2400']
E. Capitalismtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.The income inequality of society is defined as \max\limits_{1 \leq i \leq n} a_i - \min\limits_{1 \leq i \leq n} a_i.You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.InputThe first line contains two integers n, m (1\le n\le 200, n-1\le m\le 2000) — the number of people and friendships, respectively.The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1\le i, j\le n, i\ne j, 0\le b\le 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.OutputPrint "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,\ldots, a_n (0\le a_i\le 10^6), where a_i denotes the income of the i-th person.We can prove that if there exists a solution, there exists one where 0\le a_i\le 10^6 for all i.If there exist multiple solutions, print any.ExamplesInput 6 6 1 2 0 3 2 0 2 5 0 6 5 1 6 3 0 2 4 1 Output YES 3 3 2 1 3 1 0 Input 4 4 1 2 1 2 3 0 3 4 1 4 1 1 Output NO Input 1 0 Output YES 0 0 NoteIn the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3: Person 2 is envious of person 1. Person 3 is envious of person 2. Person 5 is envious of person 2. Person 6 is envious of person 5 (the required direction is satisfied). Person 6 is envious of person 3. Person 2 is envious of person 4 (the required direction is satisfied). In the second test, we can show that there is no way to assign incomes to satisfy all requirements.
6 6 1 2 0 3 2 0 2 5 0 6 5 1 6 3 0 2 4 1
YES 3 3 2 1 3 1 0
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'shortest paths', '*2700']
D. Rating Compressiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs.The program works as follows. Given an integer parameter k, the program takes the minimum of each contiguous subarray of length k in a.More formally, for an array a of length n and an integer k, define the k-compression array of a as an array b of length n-k+1, such that b_j =\min_{j\le i\le j+k-1}a_iFor example, the 3-compression array of [1, 3, 4, 5, 2] is [\min\{1, 3, 4\}, \min\{3, 4, 5\}, \min\{4, 5, 2\}]=[1, 3, 2].A permutation of length m is an array consisting of m distinct integers from 1 to m 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 (m=3 but there is 4 in the array).A k-compression array will make CodeCook users happy if it will be a permutation. Given an array a, determine for all 1\leq k\leq n if CodeCook users will be happy after a k-compression of this array or not.InputThe first line contains a single integer t (1\leq t\leq 10^4) — the number of test cases.The first line of the description of each test case contains a single integer n (1\leq n\leq 3\cdot 10^5) — the length of the array.The second line of the description of each test case contains n integers a_1,\ldots,a_n (1\leq a_i\leq n) — the elements of the array.It is guaranteed, that the sum of n for all test cases does not exceed 3\cdot 10^5.OutputFor each test case, print a binary string of length n. The k-th character of the string should be 1 if CodeCook users will be happy after a k-compression of the array a, and 0 otherwise. ExampleInput 5 5 1 5 3 4 2 4 1 3 2 1 5 1 3 3 3 2 10 1 2 3 4 5 6 7 8 9 10 3 3 3 2 Output 10111 0001 00111 1111111111 000 NoteIn the first test case, a=[1, 5, 3, 4, 2]. The 1-compression of a is [1, 5, 3, 4, 2] and it is a permutation. The 2-compression of a is [1, 3, 3, 2] and it is not a permutation, since 3 appears twice. The 3-compression of a is [1, 3, 2] and it is a permutation. The 4-compression of a is [1, 2] and it is a permutation. The 5-compression of a is [1] and it is a permutation.
5 5 1 5 3 4 2 4 1 3 2 1 5 1 3 3 3 2 10 1 2 3 4 5 6 7 8 9 10 3 3 3 2
10111 0001 00111 1111111111 000
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'implementation', 'two pointers', '*1800']
C2. Errich-Tac-Toe (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration. The patterns in the first row are winning configurations. The patterns in the second row are draw configurations. In an operation, you can change an X to an O, or an O to an X. Let k denote the total number of tokens in the grid. Your task is to make the grid a draw in at most \lfloor \frac{k}{3}\rfloor (rounding down) operations.You are not required to minimize the number of operations.InputThe first line contains a single integer t (1\le t\le 100) — the number of test cases.The first line of each test case contains a single integer n (1\le n\le 300) — the size of the grid.The following n lines each contain a string of n characters, denoting the initial grid. The character in the i-th row and j-th column is '.' if the cell is empty, or it is the type of token in the cell: 'X' or 'O'.It is guaranteed that not all cells are empty.The sum of n across all test cases does not exceed 300.OutputFor each test case, print the state of the grid after applying the operations.We have proof that a solution always exists. If there are multiple solutions, print any.ExampleInput 3 3 .O. OOO .O. 6 XXXOOO XXXOOO XX..OO OO..XX OOOXXX OOOXXX 5 .OOO. OXXXO OXXXO OXXXO .OOO. Output .O. OXO .O. OXXOOX XOXOXO XX..OO OO..XX OXOXOX XOOXXO .OXO. OOXXO XXOXX OXXOO .OXO.NoteIn the first test case, there are initially three 'O' consecutive in the second row and the second column. By changing the middle token to 'X' we make the grid a draw, and we only changed 1\le \lfloor 5/3\rfloor token.In the second test case, the final grid is a draw. We only changed 8\le \lfloor 32/3\rfloor tokens.In the third test case, the final grid is a draw. We only changed 7\le \lfloor 21/3\rfloor tokens.
3 3 .O. OOO .O. 6 XXXOOO XXXOOO XX..OO OO..XX OOOXXX OOOXXX 5 .OOO. OXXXO OXXXO OXXXO .OOO.
.O. OXO .O. OXXOOX XOXOXO XX..OO OO..XX OXOXOX XOOXXO .OXO. OOXXO XXOXX OXXOO .OXO.
1 second
256 megabytes
['constructive algorithms', 'math', '*2300']
C1. Errich-Tac-Toe (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between the easy and hard versions is that tokens of type O do not appear in the input of the easy version.Errichto gave Monogon the following challenge in order to intimidate him from taking his top contributor spot on Codeforces.In a Tic-Tac-Toe grid, there are n rows and n columns. Each cell of the grid is either empty or contains a token. There are two types of tokens: X and O. If there exist three tokens of the same type consecutive in a row or column, it is a winning configuration. Otherwise, it is a draw configuration. The patterns in the first row are winning configurations. The patterns in the second row are draw configurations. In an operation, you can change an X to an O, or an O to an X. Let k denote the total number of tokens in the grid. Your task is to make the grid a draw in at most \lfloor \frac{k}{3}\rfloor (rounding down) operations.You are not required to minimize the number of operations.InputThe first line contains a single integer t (1\le t\le 100) — the number of test cases.The first line of each test case contains a single integer n (1\le n\le 300) — the size of the grid.The following n lines each contain a string of n characters, denoting the initial grid. The character in the i-th row and j-th column is '.' if the cell is empty, or it is the type of token in the cell: 'X' or 'O'.It is guaranteed that not all cells are empty.In the easy version, the character 'O' does not appear in the input.The sum of n across all test cases does not exceed 300.OutputFor each test case, print the state of the grid after applying the operations.We have proof that a solution always exists. If there are multiple solutions, print any.ExampleInput 3 3 .X. XXX .X. 6 XX.XXX XXXXXX XXX.XX XXXXXX XX.X.X XXXXXX 5 XXX.X .X..X XXX.X ..X.. ..X.. Output .X. XOX .X. XX.XXO XOXXOX OXX.XX XOOXXO XX.X.X OXXOXX XOX.X .X..X XXO.O ..X.. ..X.. NoteIn the first test case, there are initially three 'X' consecutive in the second row and the second column. By changing the middle token to 'O' we make the grid a draw, and we only changed 1\le \lfloor 5/3\rfloor token.In the second test case, we change only 9\le \lfloor 32/3\rfloor tokens, and there does not exist any three 'X' or 'O' consecutive in a row or column, so it is a draw.In the third test case, we change only 3\le \lfloor 12/3\rfloor tokens, and the resulting grid is a draw.
3 3 .X. XXX .X. 6 XX.XXX XXXXXX XXX.XX XXXXXX XX.X.X XXXXXX 5 XXX.X .X..X XXX.X ..X.. ..X..
.X. XOX .X. XX.XXO XOXXOX OXX.XX XOOXXO XX.X.X OXXOXX XOX.X .X..X XXO.O ..X.. ..X..
1 second
256 megabytes
['constructive algorithms', 'math', '*2100']
B. Balls of Steeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n distinct points (x_1, y_1),\ldots,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls.In one operation, you can select a ball i to charge it. Once charged, all balls with Manhattan distance at most k from ball i move to the position of ball i. Many balls may have the same coordinate after an operation.More formally, for all balls j such that |x_i - x_j| + |y_i - y_j| \le k, we assign x_j:=x_i and y_j:=y_i. An example of an operation. After charging the ball in the center, two other balls move to its position. On the right side, the red dot in the center is the common position of those balls. Your task is to find the minimum number of operations to move all balls to the same position, or report that this is impossible.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains two integers n, k (2 \le n \le 100, 0 \le k \le 10^6) — the number of balls and the attract power of all balls, respectively.The following n lines describe the balls' coordinates. The i-th of these lines contains two integers x_i, y_i (0 \le x_i, y_i \le 10^5) — the coordinates of the i-th ball.It is guaranteed that all points are distinct.OutputFor each test case print a single integer — the minimum number of operations to move all balls to the same position, or -1 if it is impossible.ExampleInput 3 3 2 0 0 3 3 1 1 3 3 6 7 8 8 6 9 4 1 0 0 0 1 0 2 0 3 Output -1 1 -1 NoteIn the first test case, there are three balls at (0, 0), (3, 3), and (1, 1) and the attract power is 2. It is possible to move two balls together with one operation, but not all three balls together with any number of operations.In the second test case, there are three balls at (6, 7), (8, 8), and (6, 9) and the attract power is 3. If we charge any ball, the other two will move to the same position, so we only require one operation.In the third test case, there are four balls at (0, 0), (0, 1), (0, 2), and (0, 3), and the attract power is 1. We can show that it is impossible to move all balls to the same position with a sequence of operations.
3 3 2 0 0 3 3 1 1 3 3 6 7 8 8 6 9 4 1 0 0 0 1 0 2 0 3
-1 1 -1
1 second
256 megabytes
['brute force', 'geometry', 'greedy', '*1000']
A. Avoid Trygubtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the resulting string.In other words, you should find a string b which is a permutation of symbols of the string a and "trygub" is not a subsequence of b.We have a truly marvelous proof that any string can be arranged not to contain "trygub" as a subsequence, but this problem statement is too short to contain it.InputThe first line contains a single integer t (1\le t\le 100) — the number of test cases.The first line of each test case contains a single integer n (1\le n\le 200) — the length of a.The next line contains the string a of length n, consisting of lowercase English letters.OutputFor each test case, output a string b of length n which is a permutation of characters of the string a, and such that "trygub" is not a subsequence of it.If there exist multiple possible strings b, you can print any.ExampleInput 3 11 antontrygub 15 bestcoordinator 19 trywatchinggurabruh Output bugyrtnotna bestcoordinator bruhtrywatchinggura NoteIn the first test case, "bugyrtnotna" does not contain "trygub" as a subsequence. It does contain the letters of "trygub", but not in the correct order, so it is not a subsequence.In the second test case, we did not change the order of characters because it is not needed.In the third test case, "bruhtrywatchinggura" does contain "trygu" as a subsequence, but not "trygub".
3 11 antontrygub 15 bestcoordinator 19 trywatchinggurabruh
bugyrtnotna bestcoordinator bruhtrywatchinggura
1 second
256 megabytes
['constructive algorithms', 'sortings', '*800']
B. Numbers Boxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.You can perform the following operation any number of times (possibly zero): Choose any two adjacent cells and multiply the values in them by -1. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in X, the sum of all the numbers in the grid. What is the maximum X you can achieve with these operations?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of each test case contains two integers n,m (2 \le n, m \le 10). The following n lines contain m integers each, the j-th element in the i-th line is a_{ij} (-100\leq a_{ij}\le 100).OutputFor each testcase, print one integer X, the maximum possible sum of all the values in the grid after applying the operation as many times as you want.ExampleInput 2 2 2 -1 1 1 1 3 4 0 -1 -2 -3 -1 -2 -3 -4 -2 -3 -4 -5 Output 2 30 NoteIn the first test case, there will always be at least one -1, so the answer is 2. In the second test case, we can use the operation six times to elements adjacent horizontally and get all numbers to be non-negative. So the answer is: 2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30.
2 2 2 -1 1 1 1 3 4 0 -1 -2 -3 -1 -2 -3 -4 -2 -3 -4 -5
2 30
1 second
256 megabytes
['greedy', 'math', '*1000']
A. Add Candiestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose m such that 1 \le m \le 1000Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize m.If there are several valid sequences, you can output any.InputEach test contains multiple test cases.The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first and only line of each test case contains one integer n (2 \le n\le 100). OutputFor each testcase, print two lines with your answer. In the first line print m (1\le m \le 1000) — the number of operations you want to take. In the second line print m positive integers a_1, a_2, \dots, a_m (1 \le a_i \le n), where a_j is the number of bag you chose on the j-th operation.ExampleInput 2 2 3 Output 1 2 5 3 3 3 1 2NoteIn the first case, adding 1 candy to all bags except of the second one leads to the arrangement with [2, 2] candies.In the second case, firstly you use first three operations to add 1+2+3=6 candies in total to each bag except of the third one, which gives you [7, 8, 3]. Later, you add 4 candies to second and third bag, so you have [7, 12, 7], and 5 candies to first and third bag  — and the result is [12, 12, 12].
2 2 3
1 2 5 3 3 3 1 2
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
F. Line Distancetime limit per test7.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer k and n distinct points with integer coordinates on the Euclidean plane, the i-th point has coordinates (x_i, y_i).Consider a list of all the \frac{n(n - 1)}{2} pairs of points ((x_i, y_i), (x_j, y_j)) (1 \le i < j \le n). For every such pair, write out the distance from the line through these two points to the origin (0, 0).Your goal is to calculate the k-th smallest number among these distances.InputThe first line contains two integers n, k (2 \le n \le 10^5, 1 \le k \le \frac{n(n - 1)}{2}).The i-th of the next n lines contains two integers x_i and y_i (-10^4 \le x_i, y_i \le 10^4)  — the coordinates of the i-th point. It is guaranteed that all given points are pairwise distinct.OutputYou should output one number — the k-th smallest distance from the origin. Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExampleInput 4 3 2 1 -2 -1 0 -1 -2 4 Output 0.707106780737 NoteThere are 6 pairs of points: Line 1-2 : distance 0 from the origin Line 1-3 : distance \frac{\sqrt{2}}{2} \approx 0.707106781 from the origin Line 1-4 : distance 2 from the origin Line 2-3 : distance 1 from the origin Line 2-4 : distance 2 from the origin Line 3-4 : distance \frac{2}{\sqrt{29}} \approx 0.371390676 from the origin The third smallest distance among those is approximately 0.707106781.
4 3 2 1 -2 -1 0 -1 -2 4
0.707106780737
7.5 seconds
256 megabytes
['binary search', 'data structures', 'geometry', '*3200']
E. Long Recoverytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA patient has been infected with an unknown disease. His body can be seen as an infinite grid of triangular cells which looks as follows: Two cells are neighboring if they share a side. Therefore, each cell (x, y) has exactly three neighbors: (x+1, y) (x-1, y) (x+1, y-1) if x is even and (x-1, y+1) otherwise. Initially some cells are infected, all the others are healthy. The process of recovery begins. Each second, for exactly one cell (even though there might be multiple cells that could change its state) one of the following happens: A healthy cell with at least 2 infected neighbors also becomes infected. An infected cell with at least 2 healthy neighbors also becomes healthy. If no such cell exists, the process of recovery stops. Patient is considered recovered if the process of recovery has stopped and all the cells are healthy.We're interested in a worst-case scenario: is it possible that the patient never recovers, or if it's not possible, what is the maximum possible duration of the recovery process?InputThe first line contains one integer n (1 \leq n \leq 250000)  — the number of infected cells. The i-th of the next n lines contains two space-separated integers x_i and y_i (0 \leq x_i, y_i < 500), meaning that cell (x_i, y_i) is infected. All cells (x_i, y_i) are distinct, and all other cells are considered healthy. OutputIf it is possible that the organism never fully recovers from the disease, print SICK. Otherwise, you should print RECOVERED and in the next line an integer k  — the longest possible recovery period, modulo 998244353. ExamplesInput 4 0 0 1 0 2 0 0 1 Output RECOVERED 4 Input 3 1 0 3 0 1 1 Output SICK NoteFor the first testcase, the following drawings describe the longest possible recovery process. It can be proven that there are no recovery periods of length 5 or longer, and the organism always recovers in this testcase. \hspace{40pt} \downarrow \hspace{40pt} \downarrow \hspace{40pt} \downarrow \hspace{40pt} \downarrow\hspace{15pt} RECOVEREDFor the second testcase, it is possible for the cells (2, 0), (2, 1), (0, 1) to become infected. After that, no cell can change its state, so the answer is SICK, as not all of the cells are healthy.
4 0 0 1 0 2 0 0 1
RECOVERED 4
3 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', '*3500']
D2. Frequency Problem (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array [a_1, a_2, \dots, a_n]. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains a single integer n (1 \le n \le 200\,000) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — elements of the array.OutputYou should output exactly one integer  — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.ExamplesInput 7 1 1 2 2 3 3 3 Output 6 Input 10 1 1 1 5 4 1 3 1 2 2 Output 7 Input 1 1 Output 0 NoteIn the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
7 1 1 2 2 3 3 3
6
2 seconds
256 megabytes
['data structures', 'greedy', 'two pointers', '*3000']
D1. Frequency Problem (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved.You are given an array [a_1, a_2, \dots, a_n]. Your goal is to find the length of the longest subarray of this array such that the most frequent value in it is not unique. In other words, you are looking for a subarray such that if the most frequent value occurs f times in this subarray, then at least 2 different values should occur exactly f times.An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains a single integer n (1 \le n \le 200\,000) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le min(n, 100)) — elements of the array.OutputYou should output exactly one integer  — the length of the longest subarray of the array whose most frequent value is not unique. If there is no such subarray, output 0.ExamplesInput 7 1 1 2 2 3 3 3 Output 6Input 10 1 1 1 5 4 1 3 1 2 2 Output 7Input 1 1 Output 0NoteIn the first sample, the subarray [1, 1, 2, 2, 3, 3] is good, but [1, 1, 2, 2, 3, 3, 3] isn't: in the latter there are 3 occurrences of number 3, and no other element appears 3 times.
7 1 1 2 2 3 3 3
6
2 seconds
256 megabytes
['data structures', 'greedy', '*2600']
C. Xor Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor a given sequence of distinct non-negative integers (b_1, b_2, \dots, b_k) we determine if it is good in the following way: Consider a graph on k nodes, with numbers from b_1 to b_k written on them. For every i from 1 to k: find such j (1 \le j \le k, j\neq i), for which (b_i \oplus b_j) is the smallest among all such j, where \oplus denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph. We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.You can find an example below (the picture corresponding to the first test case). Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.However, sequence (0, 1, 5, 2) is good. You are given a sequence (a_1, a_2, \dots, a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.InputThe first line contains a single integer n (2 \le n \le 200,000) — length of the sequence.The second line contains n distinct non-negative integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the elements of the sequence.OutputYou should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good.ExamplesInput 5 0 1 5 2 6 Output 1 Input 7 6 9 8 7 3 5 2 Output 2 NoteNote that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good.It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
5 0 1 5 2 6
1
2 seconds
256 megabytes
['binary search', 'bitmasks', 'data structures', 'divide and conquer', 'dp', 'trees', '*2100']
B. Catching Cheaterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings A and B representing essays of two students who are suspected cheaters. For any two strings C, D we define their similarity score S(C,D) as 4\cdot LCS(C,D) - |C| - |D|, where LCS(C,D) denotes the length of the Longest Common Subsequence of strings C and D. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. If X is a string, |X| denotes its length.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.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. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the Wikipedia page about the Longest Common Subsequence problem.InputThe first line contains two positive integers n and m (1 \leq n, m \leq 5000) — lengths of the two strings A and B. The second line contains a string consisting of n lowercase Latin letters — string A.The third line contains a string consisting of m lowercase Latin letters — string B. OutputOutput maximal S(C, D) over all pairs (C, D), where C is some substring of A, and D is some substring of B. ExamplesInput 4 5 abba babab Output 5Input 8 10 bbbbabab bbbabaaaaa Output 12Input 7 7 uiibwws qhtkxcn Output 0NoteFor the first case:abb from the first string and abab from the second string have LCS equal to abb.The result is S(abb, abab) = (4 \cdot |abb|) - |abb| - |abab| = 4 \cdot 3 - 3 - 4 = 5.
4 5 abba babab
5
1 second
256 megabytes
['dp', 'strings', '*1800']
A. Knapsacktime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: \lceil \frac{W}{2}\rceil \le C \le W. Output the list of items you will put into the knapsack or determine that fulfilling the conditions is impossible. If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights of items in the knapsack.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). Description of the test cases follows.The first line of each test case contains integers n and W (1 \le n \le 200\,000, 1\le W \le 10^{18}). The second line of each test case contains n integers w_1, w_2, \dots, w_n (1 \le w_i \le 10^9) — weights of the items.The sum of n over all test cases does not exceed 200\,000.OutputFor each test case, if there is no solution, print a single integer -1. If there exists a solution consisting of m items, print m in the first line of the output and m integers j_1, j_2, ..., j_m (1 \le j_i \le n, all j_i are distinct) in the second line of the output  — indices of the items you would like to pack into the knapsack.If there are several possible lists of items satisfying the conditions, you can output any. Note that you don't have to maximize the sum of weights items in the knapsack.ExampleInput 3 1 3 3 6 2 19 8 19 69 9 4 7 12 1 1 1 17 1 1 1 Output 1 1 -1 6 1 2 3 5 6 7NoteIn the first test case, you can take the item of weight 3 and fill the knapsack just right.In the second test case, all the items are larger than the knapsack's capacity. Therefore, the answer is -1.In the third test case, you fill the knapsack exactly in half.
3 1 3 3 6 2 19 8 19 69 9 4 7 12 1 1 1 17 1 1 1
1 1 -1 6 1 2 3 5 6 7
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1300']
B. Eliminationtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored a points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least b points in the second contest.Similarly, for the second contest, the participant on the 100-th place has c points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least d points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers a, b, c, d, please help the jury determine the smallest possible value of the cutoff score.InputYou need to process t test cases.The first line contains an integer t (1 \leq t \leq 3025) — the number of test cases. Then descriptions of t test cases follow.The first line of each test case contains four integers a, b, c, d (0 \le a,\,b,\,c,\,d \le 9; d \leq a; b \leq c). One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.OutputFor each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.ExampleInput 2 1 2 2 1 4 8 9 2 Output 3 12 NoteFor the first test case, consider the following olympiad scenario: there are 101 participants in the elimination stage, each having 1 point for the first contest and 2 points for the second contest. Hence the total score of the participant on the 100-th place is 3.For the second test case, consider the following olympiad scenario: there are 50 participants with points 5 and 9 for the first and second contest respectively; 50 participants with points 4 and 8 for the first and second contest respectively; and 50 participants with points 2 and 9 for the first and second contest respectively. Hence the total point score of the participant on the 100-th place is 12.
2 1 2 2 1 4 8 9 2
3 12
1 second
512 megabytes
['greedy', 'math', '*900']
A. Array Rearrangmenttime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i \leq x holds for each i (1 \le i \le n).InputThe first line of input contains one integer t (1 \leq t \leq 100) — the number of test cases. t blocks follow, each describing an individual test case.The first line of each test case contains two integers n and x (1 \leq n \leq 50; 1 \leq x \leq 1000) — the length of arrays a and b, and the parameter x, described in the problem statement.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_1 \le a_2 \le \dots \le a_n \leq x) — the elements of array a in non-descending order.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \leq b_1 \le b_2 \le \dots \le b_n \leq x) — the elements of array b in non-descending order.Test cases are separated by a blank line.OutputFor each test case print Yes if one can rearrange the corresponding array b so that a_i + b_i \leq x holds for each i (1 \le i \le n) or No otherwise.Each character can be printed in any case.ExampleInput 4 3 4 1 2 3 1 1 2 2 6 1 4 2 5 4 4 1 2 3 4 1 2 3 4 1 5 5 5 Output Yes Yes No No NoteIn the first test case, one can rearrange b so it'll look like [1, 2, 1]. In this case, 1 + 1 \leq 4; 2 + 2 \leq 4; 3 + 1 \leq 4.In the second test case, one can set b to [5, 2], then 1 + 5 \leq 6; 4 + 2 \leq 6.In the third test case, no matter how one shuffles array b, a_4 + b_4 = 4 + b_4 > 4.In the fourth test case, there is only one rearrangement of array b and it doesn't satisfy the condition since 5 + 5 > 5.
4 3 4 1 2 3 1 1 2 2 6 1 4 2 5 4 4 1 2 3 4 1 2 3 4 1 5 5 5
Yes Yes No No
1 second
512 megabytes
['greedy', 'sortings', '*800']
E. Finding the Vertextime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.You are given a tree — connected undirected graph without cycles. One vertex of the tree is special, and you have to find which one. You can ask questions in the following form: given an edge of the tree, which endpoint is closer to the special vertex, meaning which endpoint's shortest path to the special vertex contains fewer edges. You have to find the special vertex by asking the minimum number of questions in the worst case for a given tree.Please note that the special vertex might not be fixed by the interactor in advance: it might change the vertex to any other one, with the requirement of being consistent with the previously given answers.InputYou are given an integer n (2 \le n \le 100) — the number of vertices in a tree.The folloiwing n-1 lines contain two integers each, u and v (1 \le u, v \le n), that denote an edge in the tree connecting u and v. It is guaranteed that the given edges form a tree.InteractionAfter reading the input data, one can start making queries. There are two possible queries: "? u v" — to ask for an edge (u, v) (1 \le u, v \le n) which of the endpoints is closer to the special vertex. The answer to this query is one of the endpoints. Note that, u and v must be connected by an edge, and hence they can not have the same distance to the special vertex. "! u" — to indicate that you found the special vertex. After the program does that, it must immediately terminate. Do not forget to output the end of line and flush the output. Otherwise you will get Idleness limit exceeded verdict. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; sys.stdout.flush() in Python; see documentation for other languages. In case you ask more queries than needed in the worst case for a given tree, you will get verdict Wrong answer.ExamplesInput 5 1 2 2 3 3 4 4 5 3 2 1 Output ? 3 4 ? 2 3 ? 1 2 ! 1 Input 5 2 1 3 1 4 1 5 1 1 1 4 Output ? 1 2 ? 1 3 ? 1 4 ! 4 NoteHacks are forbidden in this task.
5 1 2 2 3 3 4 4 5 3 2 1
? 3 4 ? 2 3 ? 1 2 ! 1
1 second
512 megabytes
['brute force', 'dfs and similar', 'dp', 'interactive', 'trees', '*3500']
D. Rectangular Polylinetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputOne drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersections, which means that in case any two segments shared a common point, that point was an endpoint for both of them (please consult the examples in the notes section).Unfortunately, the polyline was erased, and you only know the lengths of the horizonal and vertical segments. Please construct any polyline matching the description with such segments, or determine that it does not exist.InputThe first line contains one integer t (1 \leq t \leq 200) —the number of test cases.The first line of each test case contains one integer h (1 \leq h \leq 1000) — the number of horizontal segments. The following line contains h integers l_1, l_2, \dots, l_h (1 \leq l_i \leq 1000) — lengths of the horizontal segments of the polyline, in arbitrary order.The following line contains an integer v (1 \leq v \leq 1000) — the number of vertical segments, which is followed by a line containing v integers p_1, p_2, \dots, p_v (1 \leq p_i \leq 1000) — lengths of the vertical segments of the polyline, in arbitrary order.Test cases are separated by a blank line, and the sum of values h + v over all test cases does not exceed 1000.OutputFor each test case output Yes, if there exists at least one polyline satisfying the requirements, or No otherwise. If it does exist, in the following n lines print the coordinates of the polyline vertices, in order of the polyline traversal: the i-th line should contain two integers x_i and y_i — coordinates of the i-th vertex.Note that, each polyline segment must be either horizontal or vertical, and the segments should alternate between horizontal and vertical. The coordinates should not exceed 10^9 by their absolute value.ExamplesInput 2 2 1 1 2 1 1 2 1 2 2 3 3 Output Yes 1 0 1 1 0 1 0 0 No Input 2 4 1 1 1 1 4 1 1 1 1 3 2 1 1 3 2 1 1 Output Yes 1 0 1 1 2 1 2 2 1 2 1 1 0 1 0 0 Yes 0 -2 2 -2 2 -1 1 -1 1 0 0 0 Input 2 4 1 4 1 2 4 3 4 5 12 4 1 2 3 6 2 1 3 Output Yes 2 0 2 3 3 3 3 7 4 7 4 12 0 12 0 0 No NoteIn the first test case of the first example, the answer is Yes — for example, the following picture illustrates a square that satisfies the requirements: In the first test case of the second example, the desired polyline also exists. Note that, the polyline contains self-intersections, but only in the endpoints: In the second test case of the second example, the desired polyline could be like the one below: Note that the following polyline is not a valid one, since it contains self-intersections that are not endpoints for some of the segments:
2 2 1 1 2 1 1 2 1 2 2 3 3
Yes 1 0 1 1 0 1 0 0 No
2 seconds
512 megabytes
['constructive algorithms', 'dp', 'geometry', '*2900']
C. Team-Buildingtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe new academic year has started, and Berland's university has n first-year students. They are divided into k academic groups, however, some of the groups might be empty. Among the students, there are m pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty).InputThe first line contains three integers n, m and k (1 \le n \le 500\,000; 0 \le m \le 500\,000; 2 \le k \le 500\,000) — the number of students, the number of pairs of acquaintances and the number of groups respectively.The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le k), where c_i equals to the group number of the i-th student.Next m lines follow. The i-th of them contains two integers a_i and b_i (1 \le a_i, b_i \le n), denoting that students a_i and b_i are acquaintances. It's guaranteed, that a_i \neq b_i, and that no (unordered) pair is mentioned more than once.OutputPrint a single integer — the number of ways to choose two different groups such that it's possible to select two teams to play the game.ExamplesInput 6 8 3 1 1 2 2 3 3 1 3 1 5 1 6 2 5 2 6 3 4 3 5 5 6 Output 2 Input 4 3 3 1 1 2 2 1 2 2 3 3 4 Output 3 Input 4 4 2 1 1 1 2 1 2 2 3 3 1 1 4 Output 0 Input 5 5 2 1 2 1 2 1 1 2 2 3 3 4 4 5 5 1 Output 0 NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students 1 and 4, while other team can be formed from students 2 and 3. Select the second and the third group. For instance, one team can be formed 3 and 6, while other team can be formed from students 4 and 5. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game.
6 8 3 1 1 2 2 3 3 1 3 1 5 1 6 2 5 2 6 3 4 3 5 5 6
2
3 seconds
512 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', '*2500']
B. Divide and Sumtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = \sum_{i = 1}^n |x_i - y_i|.Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.InputThe first line contains a single integer n (1 \leq n \leq 150\,000).The second line contains 2n integers a_1, a_2, \ldots, a_{2n} (1 \leq a_i \leq 10^9) — elements of array a.OutputPrint one integer — the answer to the problem, modulo 998244353.ExamplesInput 1 1 4 Output 6Input 2 2 1 2 1 Output 12Input 3 2 2 2 2 2 2 Output 0Input 5 13 8 35 94 9284 34 54 69 123 846 Output 2588544NoteTwo partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.In the first example, there are two correct partitions of the array a: p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3; p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3. In the second example, there are six valid partitions of the array a: p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p); p = [2, 2], q = [1, 1]; p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p); p = [1, 2], q = [2, 1]; p = [1, 1], q = [2, 2]; p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
1 1 4
6
2 seconds
512 megabytes
['combinatorics', 'math', 'sortings', '*1900']
A. Divisiontime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputOleg's favorite subjects are History and Math, and his favorite branch of mathematics is division.To improve his division skills, Oleg came up with t pairs of integers p_i and q_i and for each pair decided to find the greatest integer x_i, such that: p_i is divisible by x_i; x_i is not divisible by q_i. Oleg is really good at division and managed to find all the answers quickly, how about you?InputThe first line contains an integer t (1 \le t \le 50) — the number of pairs.Each of the following t lines contains two integers p_i and q_i (1 \le p_i \le 10^{18}; 2 \le q_i \le 10^{9}) — the i-th pair of integers.OutputPrint t integers: the i-th integer is the largest x_i such that p_i is divisible by x_i, but x_i is not divisible by q_i.One can show that there is always at least one value of x_i satisfying the divisibility conditions for the given constraints.ExampleInput 3 10 4 12 6 179 822 Output 10 4 179 NoteFor the first pair, where p_1 = 10 and q_1 = 4, the answer is x_1 = 10, since it is the greatest divisor of 10 and 10 is not divisible by 4.For the second pair, where p_2 = 12 and q_2 = 6, note that 12 is not a valid x_2, since 12 is divisible by q_2 = 6; 6 is not valid x_2 as well: 6 is also divisible by q_2 = 6. The next available divisor of p_2 = 12 is 4, which is the answer, since 4 is not divisible by 6.
3 10 4 12 6 179 822
10 4 179
1 second
512 megabytes
['brute force', 'math', 'number theory', '*1500']
E. Long Permutationtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA permutation is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] — are permutations, and [1, 1], [4, 3, 1], [2, 3, 4] — no.Permutation a is lexicographically smaller than permutation b (they have the same length n), if in the first index i in which they differ, a[i] < b[i]. For example, the permutation [1, 3, 2, 4] is lexicographically smaller than the permutation [1, 3, 4, 2], because the first two elements are equal, and the third element in the first permutation is smaller than in the second.The next permutation for a permutation a of length n — is the lexicographically smallest permutation b of length n that lexicographically larger than a. For example: for permutation [2, 1, 4, 3] the next permutation is [2, 3, 1, 4]; for permutation [1, 2, 3] the next permutation is [1, 3, 2]; for permutation [2, 1] next permutation does not exist. You are given the number n — the length of the initial permutation. The initial permutation has the form a = [1, 2, \ldots, n]. In other words, a[i] = i (1 \le i \le n).You need to process q queries of two types: 1 l r: query for the sum of all elements on the segment [l, r]. More formally, you need to find a[l] + a[l + 1] + \ldots + a[r]. 2 x: x times replace the current permutation with the next permutation. For example, if x=2 and the current permutation has the form [1, 3, 4, 2], then we should perform such a chain of replacements [1, 3, 4, 2] \rightarrow [1, 4, 2, 3] \rightarrow [1, 4, 3, 2]. For each query of the 1-st type output the required sum.InputThe first line contains two integers n (2 \le n \le 2 \cdot 10^5) and q (1 \le q \le 2 \cdot 10^5), where n — the length of the initial permutation, and q — the number of queries.The next q lines contain a single query of the 1-st or 2-nd type. The 1-st type query consists of three integers 1, l and r (1 \le l \le r \le n), the 2-nd type query consists of two integers 2 and x (1 \le x \le 10^5).It is guaranteed that all requests of the 2-nd type are possible to process.OutputFor each query of the 1-st type, output on a separate line one integer — the required sum.ExampleInput 4 4 1 2 4 2 3 1 1 2 1 3 4 Output 9 4 6 NoteInitially, the permutation has the form [1, 2, 3, 4]. Queries processing is as follows: 2 + 3 + 4 = 9; [1, 2, 3, 4] \rightarrow [1, 2, 4, 3] \rightarrow [1, 3, 2, 4] \rightarrow [1, 3, 4, 2]; 1 + 3 = 4; 4 + 2 = 6
4 4 1 2 4 2 3 1 1 2 1 3 4
9 4 6
4 seconds
256 megabytes
['brute force', 'math', 'two pointers', '*2400']
C. The Delivery Dilemmatime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is preparing for his birthday. He decided that there would be n different dishes on the dinner table, numbered from 1 to n. Since Petya doesn't like to cook, he wants to order these dishes in restaurants.Unfortunately, all dishes are prepared in different restaurants and therefore Petya needs to pick up his orders from n different places. To speed up this process, he wants to order courier delivery at some restaurants. Thus, for each dish, there are two options for Petya how he can get it: the dish will be delivered by a courier from the restaurant i, in this case the courier will arrive in a_i minutes, Petya goes to the restaurant i on his own and picks up the dish, he will spend b_i minutes on this. Each restaurant has its own couriers and they start delivering the order at the moment Petya leaves the house. In other words, all couriers work in parallel. Petya must visit all restaurants in which he has not chosen delivery, he does this consistently.For example, if Petya wants to order n = 4 dishes and a = [3, 7, 4, 5], and b = [2, 1, 2, 4], then he can order delivery from the first and the fourth restaurant, and go to the second and third on your own. Then the courier of the first restaurant will bring the order in 3 minutes, the courier of the fourth restaurant will bring the order in 5 minutes, and Petya will pick up the remaining dishes in 1 + 2 = 3 minutes. Thus, in 5 minutes all the dishes will be at Petya's house.Find the minimum time after which all the dishes can be at Petya's home.InputThe first line contains one positive integer t (1 \le t \le 2 \cdot 10^5) — the number of test cases. Then t test cases follow.Each test case begins with a line containing one integer n (1 \le n \le 2 \cdot 10^5) — the number of dishes that Petya wants to order.The second line of each test case contains n integers a_1 \ldots a_n (1 \le a_i \le 10^9) — the time of courier delivery of the dish with the number i.The third line of each test case contains n integers b_1 \ldots b_n (1 \le b_i \le 10^9) — the time during which Petya will pick up the dish with the number i.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output one integer — the minimum time after which all dishes can be at Petya's home.ExampleInput 4 4 3 7 4 5 2 1 2 4 4 1 2 3 4 3 3 3 3 2 1 2 10 10 2 10 10 1 2 Output 5 3 2 3
4 4 3 7 4 5 2 1 2 4 4 1 2 3 4 3 3 3 3 2 1 2 10 10 2 10 10 1 2
5 3 2 3
2 seconds
256 megabytes
['binary search', 'greedy', 'sortings', '*1400']
B. Saving the Citytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBertown is a city with n buildings in a straight line.The city's security service discovered that some buildings were mined. A map was compiled, which is a string of length n, where the i-th character is "1" if there is a mine under the building number i and "0" otherwise.Bertown's best sapper knows how to activate mines so that the buildings above them are not damaged. When a mine under the building numbered x is activated, it explodes and activates two adjacent mines under the buildings numbered x-1 and x+1 (if there were no mines under the building, then nothing happens). Thus, it is enough to activate any one mine on a continuous segment of mines to activate all the mines of this segment. For manual activation of one mine, the sapper takes a coins. He can repeat this operation as many times as you want.Also, a sapper can place a mine under a building if it wasn't there. For such an operation, he takes b coins. He can also repeat this operation as many times as you want.The sapper can carry out operations in any order.You want to blow up all the mines in the city to make it safe. Find the minimum number of coins that the sapper will have to pay so that after his actions there are no mines left in the city.InputThe first line contains one positive integer t (1 \le t \le 10^5) — the number of test cases. Then t test cases follow.Each test case begins with a line containing two integers a and b (1 \le a, b \le 1000) — the cost of activating and placing one mine, respectively.The next line contains a map of mines in the city — a string consisting of zeros and ones.The sum of the string lengths for all test cases does not exceed 10^5.OutputFor each test case, output one integer — the minimum number of coins that the sapper will have to pay.ExampleInput 2 1 1 01000010 5 1 01101110 Output 2 6 NoteIn the second test case, if we place a mine under the fourth building and then activate it, then all mines on the field are activated. The cost of such operations is six, b=1 coin for placing a mine and a=5 coins for activating.
2 1 1 01000010 5 1 01101110
2 6
2 seconds
256 megabytes
['dp', 'greedy', 'math', 'sortings', '*1300']
A. Kids Seatingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday the kindergarten has a new group of n kids who need to be seated at the dinner table. The chairs at the table are numbered from 1 to 4n. Two kids can't sit on the same chair. It is known that two kids who sit on chairs with numbers a and b (a \neq b) will indulge if: gcd(a, b) = 1 or, a divides b or b divides a. gcd(a, b) — the maximum number x such that a is divisible by x and b is divisible by x.For example, if n=3 and the kids sit on chairs with numbers 2, 3, 4, then they will indulge since 4 is divided by 2 and gcd(2, 3) = 1. If kids sit on chairs with numbers 4, 6, 10, then they will not indulge.The teacher really doesn't want the mess at the table, so she wants to seat the kids so there are no 2 of the kid that can indulge. More formally, she wants no pair of chairs a and b that the kids occupy to fulfill the condition above.Since the teacher is very busy with the entertainment of the kids, she asked you to solve this problem.InputThe first line contains one integer t (1 \leq t \leq 100) — the number of test cases. Then t test cases follow.Each test case consists of one line containing an integer n (1 \leq n \leq 100) — the number of kids.OutputOutput t lines, which contain n distinct integers from 1 to 4n — the numbers of chairs that the kids should occupy in the corresponding test case. If there are multiple answers, print any of them. You can print n numbers in any order.ExampleInput 3 2 3 4 Output 6 4 4 6 10 14 10 12 8
3 2 3 4
6 4 4 6 10 14 10 12 8
2 seconds
256 megabytes
['constructive algorithms', 'math', '*800']
F. Differentiating Gamestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problemGinny is taking an exam on game theory. The professor is tired of hearing the same answers over and over again, so he offered Ginny to play a game instead of a standard exam. As known from the course, a combinatorial game on a graph with multiple starting positions is a game with a directed graph and multiple starting vertices holding a token each. Two players take turns moving one of the tokens along the graph edges on each turn. The player who can't make a move loses the game. If both players can play an infinitely long game without losing, a draw is called.For the exam, the professor drew an acyclic directed graph and chose one of its vertices. Ginny needs to guess the vertex the professor chose. To do so, Ginny can choose a multiset of vertices S several times and ask the professor: "If I put one token in each vertex of the given graph for each occurrence of the vertex in the multiset S, and then one more in the selected vertex, what would be the result of the combinatorial game?". Having given the task, the professor left the room to give Ginny some time to prepare for the game. Ginny thinks that she's being tricked because the problem is impossible to solve. Therefore, while the professor is away, she wants to add or remove several edges from the graph. Even though the original graph was acyclic, edges could be added to the graph to make cycles appear.InteractionIn this task, interaction consists of several phases.In the first phase, the interactor gives as an input to your program three integers N (1 \le N \le 1000), M (0 \le M \le 100\,000), T (1 \le T \le 2000): the number of vertices and edges in the initial graph, and the number of times Ginny has to guess the chosen vertex. The next M lines contain pairs of vertices a_i b_i (1 \le a_i, b_i \le N): beginning and end of corresponding graph edges. The graph is guaranteed to be acyclic and all of its edges to be distinct.The solution should print an integer K (0 \le K \le 4242): the number of edges to change in the graph. The next K lines should contain either "+ a_i b_i" or "- a_i b_i": the beginning and the end of an edge that Ginny has to add or remove accordingly. You are allowed to add preexisting edges to the graph. Operations are performed in the order of appearance, so Ginny is allowed to remove an edge added by the solution. You can only remove an existing edge. The operations can create cycles in the graph. The next T phases are dedicated to guessing the chosen vertices. In each phase, the solution can make at most 20 queries and then print the answer. To query a multiset S, the solution should print "? |S|~S_1~S_2~\dots~S_{|S|}". The total size of all multisets in a single phase should not exceed 20. The interactor will reply with one of the following words: "Win", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the first player. "Lose", if the winner of a combinatorial game with tokens in multiset S and the selected vertex is the second player. "Draw", if a combinatorial game with tokens in multiset S and selected vertex ends in a draw. "Slow", if the solution made a 21-st request, or the total size of all multisets in a single phase exceeded 20. In this case, the solution should terminate and receive Wrong Answer verdict. As soon as the selected vertex is guessed, that solution should print "! v". If the chosen vertex is guessed correctly, the interactor will print Correct and the solution should either move on to the next phase of guessing or finish its execution if it's the last phase. Otherwise, the interactor will print Wrong, which means that the solution should terminate and will receive the Wrong Answer verdict. The interactor can change the chosen vertex based on graph changes and solution actions, but at every given moment of time, at least one vertex that corresponds to all given interactor answers will exist. Hack formatHacks have the following extra limitations: T = 1 you need to specify a single vertex, chosen by the interactor. Hack test format. The first line of input contains three integers N~M~1. The next M lines on input contain edge description in the same format as in the input. The next line contains a single integer v: the number of the chosen vertex. The hack will be successful even if the solution guesses the vertex right, but the vertex will not be the single one to match all performed queries.ExampleInput 3 2 3 1 2 2 3 Lose Correct Win Correct Draw CorrectOutput 6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2NoteIn the sample test, the empty lines represent waiting for the input by the other side of the interaction. The real interactor will not print empty lines, and the solution should not print them either. The image above illustrates the sample test. Added edges are coloured in red, and the removed edges are drawn with a dotted line. Three guessing phases denote different ways of getting the answer. If the solution will query just the chosen vertex, the interactor will return the result of the game in that vertex. The first player loses only if the chosen vertex has the number 1. If we add a single vertex 2 to the chosen vertex, then if the chosen vertex is either 1 or 2, the game should end in a draw. If vertex number 3 is chosen, then the first player wins. If we place three tokens in vertex 1 and two tokens in vertex 3, then the game will end in a draw only if vertex 2 is chosen. If the professor chose vertex 3, the first player will win, if the professor chose vertex 1, then the second player will win. In the first test, the interactor will behave as if the chosen vertices are the same as those in the example above. However, if you will try to guess the answer before it limits the options to one single vertex, the solution will get "Wrong Answer", even if you print the same answers. That's because the interactor is allowed to change the chosen vertex if it's consistent with the previous query answers.
3 2 3 1 2 2 3 Lose Correct Win Correct Draw Correct
6 + 2 2 - 1 2 + 2 3 - 2 2 + 3 1 + 2 2 ? 0 ! 1 ? 1 2 ! 3 ? 5 1 3 1 3 1 ! 2
2 seconds
512 megabytes
['games', 'interactive', '*3400']
E. Black, White and Grey Treetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree with each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.What is the minimum number of removals necessary to remove all vertices from the tree?InputEach test contains multiple test cases. The first line contains an integer t (1 \le t \le 100\,000), denoting the number of test cases, followed by a description of the test cases.The first line of each test case contains an integer n (1 \le n \le 200\,000): the number of vertices in the tree.The second line of each test case contains n integers a_v (0 \le a_v \le 2): colours of vertices. Gray vertices have a_v=0, white have a_v=1, black have a_v=2.Each of the next n-1 lines contains two integers u, v (1 \le u, v \le n): tree edges.The sum of all n throughout the test is guaranteed to not exceed 200\,000.OutputFor each test case, print one integer: the minimum number of operations to solve the problem.ExampleInput 4 2 1 1 1 2 4 1 2 1 2 1 2 2 3 3 4 5 1 1 0 1 2 1 2 2 3 3 4 3 5 8 1 2 1 2 2 2 1 2 1 3 2 3 3 4 4 5 5 6 5 7 5 8 Output 1 3 2 3 NoteIn the first test case, both vertices are white, so you can remove them at the same time.In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.
4 2 1 1 1 2 4 1 2 1 2 1 2 2 3 3 4 5 1 1 0 1 2 1 2 2 3 3 4 3 5 8 1 2 1 2 2 2 1 2 1 3 2 3 3 4 4 5 5 6 5 7 5 8
1 3 2 3
2 seconds
512 megabytes
['binary search', 'constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*3000']
D. Sumtime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n non-decreasing arrays of non-negative numbers. Vasya repeats the following operation k times: Selects a non-empty array. Puts the first element of the selected array in his pocket. Removes the first element from the selected array. Vasya wants to maximize the sum of the elements in his pocket.InputThe first line contains two integers n and k (1 \le n, k \le 3\,000): the number of arrays and operations.Each of the next n lines contain an array. The first integer in each line is t_i (1 \le t_i \le 10^6): the size of the i-th array. The following t_i integers a_{i, j} (0 \le a_{i, 1} \le \ldots \le a_{i, t_i} \le 10^8) are the elements of the i-th array.It is guaranteed that k \le \sum\limits_{i=1}^n t_i \le 10^6.OutputPrint one integer: the maximum possible sum of all elements in Vasya's pocket after k operations.ExampleInput 3 3 2 5 10 3 1 2 3 2 1 20 Output 26
3 3 2 5 10 3 1 2 3 2 1 20
26
1.5 seconds
512 megabytes
['data structures', 'divide and conquer', 'dp', 'greedy', '*2800']
C. Graph Transpositionstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1.The following actions are allowed: Token movement. To move the token from vertex u to vertex v if there is an edge u \to v in the graph. This action takes 1 second. Graph transposition. To transpose all the edges in the graph: replace each edge u \to v by an edge v \to u. This action takes increasingly more time: k-th transposition takes 2^{k-1} seconds, i.e. the first transposition takes 1 second, the second one takes 2 seconds, the third one takes 4 seconds, and so on. The goal is to move the token from vertex 1 to vertex n in the shortest possible time. Print this time modulo 998\,244\,353.InputThe first line of input contains two integers n, m (1 \le n, m \le 200\,000).The next m lines contain two integers each: u, v (1 \le u, v \le n; u \ne v), which represent the edges of the graph. It is guaranteed that all ordered pairs (u, v) are distinct.It is guaranteed that it is possible to move the token from vertex 1 to vertex n using the actions above.OutputPrint one integer: the minimum required time modulo 998\,244\,353.ExamplesInput 4 4 1 2 2 3 3 4 4 1 Output 2 Input 4 3 2 1 2 3 4 3 Output 10 NoteThe first example can be solved by transposing the graph and moving the token to vertex 4, taking 2 seconds.The best way to solve the second example is the following: transpose the graph, move the token to vertex 2, transpose the graph again, move the token to vertex 3, transpose the graph once more and move the token to vertex 4.
4 4 1 2 2 3 3 4 4 1
2
3 seconds
512 megabytes
['dfs and similar', 'graphs', 'greedy', 'shortest paths', '*2400']
B. Identify the Operationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe start with a permutation a_1, a_2, \ldots, a_n and with an empty array b. We apply the following operation k times.On the i-th iteration, we select an index t_i (1 \le t_i \le n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, \ldots, a_n to the left in order to fill in the empty space.You are given the initial permutation a_1, a_2, \ldots, a_n and the resulting array b_1, b_2, \ldots, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, \ldots, t_k modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains an integer t (1 \le t \le 100\,000), denoting the number of test cases, followed by a description of the test cases.The first line of each test case contains two integers n, k (1 \le k < n \le 200\,000): sizes of arrays 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 n): elements of a. All elements of a are distinct.The third line of each test case contains k integers b_1, b_2, \ldots, b_k (1 \le b_i \le n): elements of b. All elements of b are distinct.The sum of all n among all test cases is guaranteed to not exceed 200\,000.OutputFor each test case print one integer: the number of possible sequences modulo 998\,244\,353.ExampleInput 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note\require{cancel}Let's denote as a_1 a_2 \ldots \cancel{a_i} \underline{a_{i+1}} \ldots a_n \rightarrow a_1 a_2 \ldots a_{i-1} a_{i+1} \ldots a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b.In the first example test, the following two options can be used to produce the given array b: 1 2 \underline{3} \cancel{4} 5 \rightarrow 1 \underline{2} \cancel{3} 5 \rightarrow 1 \cancel{2} \underline{5} \rightarrow 1 2; (t_1, t_2, t_3) = (4, 3, 2); 1 2 \underline{3} \cancel{4} 5 \rightarrow \cancel{1} \underline{2} 3 5 \rightarrow 2 \cancel{3} \underline{5} \rightarrow 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step.In the third example test, there are four options to achieve the given array b: 1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 3 2 5 \rightarrow 4 3 \cancel{2} \underline{5} \rightarrow 4 3 5; 1 4 \cancel{7} \underline{3} 6 2 5 \rightarrow 1 4 3 \cancel{6} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{3} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5; 1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow \cancel{1} \underline{4} 7 2 5 \rightarrow 4 7 \cancel{2} \underline{5} \rightarrow 4 7 5; 1 4 7 \underline{3} \cancel{6} 2 5 \rightarrow 1 4 7 \cancel{3} \underline{2} 5 \rightarrow 1 \underline{4} \cancel{7} 2 5 \rightarrow 1 4 \cancel{2} \underline{5} \rightarrow 1 4 5;
3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5
2 0 4
2 seconds
512 megabytes
['combinatorics', 'data structures', 'dsu', 'greedy', 'implementation', '*1800']
A. Extreme Subtractiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n positive integers.You can use the following operation as many times as you like: select any integer 1 \le k \le n and do one of two things: decrement by one k of the first elements of the array. decrement by one k of the last elements of the array. For example, if n=5 and a=[3,2,2,1,4], then you can apply one of the following operations to it (not all possible options are listed below): decrement from the first two elements of the array. After this operation a=[2, 1, 2, 1, 4]; decrement from the last three elements of the array. After this operation a=[3, 2, 1, 0, 3]; decrement from the first five elements of the array. After this operation a=[2, 1, 1, 0, 3]; Determine if it is possible to make all the elements of the array equal to zero by applying a certain number of operations.InputThe first line contains one positive integer t (1 \le t \le 30000) — the number of test cases. Then t test cases follow.Each test case begins with a line containing one integer n (1 \le n \le 30000) — the number of elements in the array.The second line of each test case contains n integers a_1 \ldots a_n (1 \le a_i \le 10^6).The sum of n over all test cases does not exceed 30000.OutputFor each test case, output on a separate line: YES, if it is possible to make all elements of the array equal to zero by applying a certain number of operations. NO, otherwise. The letters in the words YES and NO can be outputed in any case.ExampleInput 4 3 1 2 1 5 11 7 9 6 8 5 1 3 1 3 1 4 5 2 1 10 Output YES YES NO YES
4 3 1 2 1 5 11 7 9 6 8 5 1 3 1 3 1 4 5 2 1 10
YES YES NO YES
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1800']
B. Sum of Medianstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA median of an array of integers of length n is the number standing on the \lceil {\frac{n}{2}} \rceil (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting with 1. For example, a median of the array [2, 6, 4, 1, 3, 5] is equal to 3. There exist some other definitions of the median, but in this problem, we will use the described one.Given two integers n and k and non-decreasing array of nk integers. Divide all numbers into k arrays of size n, such that each number belongs to exactly one array.You want the sum of medians of all k arrays to be the maximum possible. Find this maximum possible sum.InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. The next 2t lines contain descriptions of test cases.The first line of the description of each test case contains two integers n, k (1 \leq n, k \leq 1000).The second line of the description of each test case contains nk integers a_1, a_2, \ldots, a_{nk} (0 \leq a_i \leq 10^9) — given array. It is guaranteed that the array is non-decreasing: a_1 \leq a_2 \leq \ldots \leq a_{nk}.It is guaranteed that the sum of nk for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print a single integer — the maximum possible sum of medians of all k arrays.ExampleInput 6 2 4 0 24 34 58 62 64 69 78 2 2 27 61 81 91 4 3 2 4 16 18 21 27 36 53 82 91 92 95 3 4 3 11 12 22 33 35 38 67 69 71 94 99 2 1 11 41 3 3 1 1 1 1 1 1 1 1 1 Output 165 108 145 234 11 3 NoteThe examples of possible divisions into arrays for all test cases of the first test:Test case 1: [0, 24], [34, 58], [62, 64], [69, 78]. The medians are 0, 34, 62, 69. Their sum is 165.Test case 2: [27, 61], [81, 91]. The medians are 27, 81. Their sum is 108.Test case 3: [2, 91, 92, 95], [4, 36, 53, 82], [16, 18, 21, 27]. The medians are 91, 36, 18. Their sum is 145.Test case 4: [3, 33, 35], [11, 94, 99], [12, 38, 67], [22, 69, 71]. The medians are 33, 94, 38, 69. Their sum is 234.Test case 5: [11, 41]. The median is 11. The sum of the only median is 11.Test case 6: [1, 1, 1], [1, 1, 1], [1, 1, 1]. The medians are 1, 1, 1. Their sum is 3.
6 2 4 0 24 34 58 62 64 69 78 2 2 27 61 81 91 4 3 2 4 16 18 21 27 36 53 82 91 92 95 3 4 3 11 12 22 33 35 38 67 69 71 94 99 2 1 11 41 3 3 1 1 1 1 1 1 1 1 1
165 108 145 234 11 3
1 second
256 megabytes
['greedy', 'math', '*900']
A. Buy the Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four integers n, c_0, c_1 and h and a binary string s of length n.A binary string is a string consisting of characters 0 and 1.You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change.After some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character 0 you should pay c_0 coins, to buy the character 1 you should pay c_1 coins.Find the minimum number of coins needed to buy the string.InputThe first line contains a single integer t (1 \leq t \leq 10) — the number of test cases. Next 2t lines contain descriptions of test cases.The first line of the description of each test case contains four integers n, c_{0}, c_{1}, h (1 \leq n, c_{0}, c_{1}, h \leq 1000).The second line of the description of each test case contains the binary string s of length n.OutputFor each test case print a single integer — the minimum number of coins needed to buy the string.ExampleInput 6 3 1 1 1 100 5 10 100 1 01010 5 10 1 1 11111 5 1 10 1 11111 12 2 1 10 101110110101 2 100 1 10 00 Output 3 52 5 10 16 22 NoteIn the first test case, you can buy all characters and pay 3 coins, because both characters 0 and 1 costs 1 coin.In the second test case, you can firstly change 2-nd and 4-th symbols of the string from 1 to 0 and pay 2 coins for that. Your string will be 00000. After that, you can buy the string and pay 5 \cdot 10 = 50 coins for that. The total number of coins paid will be 2 + 50 = 52.
6 3 1 1 1 100 5 10 100 1 01010 5 10 1 1 11111 5 1 10 1 11111 12 2 1 10 101110110101 2 100 1 10 00
3 52 5 10 16 22
1 second
256 megabytes
['implementation', 'math', '*800']
E. Cheat and Wintime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's consider a (10^9+1) \times (10^9+1) field. The rows are numbered with integers from 0 to 10^9 and the columns are numbered with integers from 0 to 10^9. Let's define as (x, y) the cell located in the x-th row and y-th column.Let's call a cell (x, y) good if x \& y = 0, there \& is the bitwise and operation.Let's build a graph where vertices will be all good cells of the field and we will make an edge between all pairs of adjacent by side good cells. It can be proved that this graph will be a tree — connected graph without cycles. Let's hang this tree on vertex (0, 0), so we will have a rooted tree with root (0, 0).Two players will play the game. Initially, some good cells are black and others are white. Each player on his turn chooses a black good cell and a subset of its ancestors (possibly empty) and inverts their colors (from white to black and vice versa). The player who can't move (because all good cells are white) loses. It can be proved that the game is always finite.Initially, all cells are white. You are given m pairs of cells. For each pair color all cells in a simple path between them as black. Note that we do not invert their colors, we paint them black.Sohrab and Mashtali are going to play this game. Sohrab is the first player and Mashtali is the second.Mashtali wants to win and decided to cheat. He can make the following operation multiple times before the game starts: choose a cell and invert colors of all vertices on the path between it and the root of the tree.Mammad who was watching them wondered: "what is the minimum number of operations Mashtali should do to have a winning strategy?".Find the answer to this question for the initial painting of the tree. It can be proved that at least one possible way to cheat always exists.InputThe first line contains one integer m (1 \leq m \leq 10^5).Each of the next m lines contains four integers x_{1}, y_{1}, x_{2}, y_{2} (0 \leq x_i, y_i \leq 10^9, x_i \& y_i = 0). You should color all cells on the path between vertices (x_1, y_1) and (x_2, y_2) as black.OutputPrint a single integer — the minimum number of cheating operations the second player can do.ExamplesInput 1 7 0 0 7 Output 1 Input 3 1 2 3 4 3 4 1 2 2 1 3 4 Output 3 Input 2 0 1 0 8 1 0 8 0 Output 0 NoteIn the first test, you can make one cheating operation with the root of the tree. After that, the second player can win because he can use a symmetric strategy.In the second test, you can make cheating operations with cells (0, 2), (0, 0), (3, 4).In the third test, the second player already has the winning strategy and doesn't need to make any cheating operations.
1 7 0 0 7
1
3 seconds
256 megabytes
['bitmasks', 'data structures', 'games', 'trees', '*3500']
D. INOI Final Conteststime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday is the final contest of INOI (Iranian National Olympiad in Informatics). The contest room is a row with n computers. All computers are numbered with integers from 1 to n from left to right. There are m participants, numbered with integers from 1 to m.We have an array a of length m where a_{i} (1 \leq a_i \leq n) is the computer behind which the i-th participant wants to sit.Also, we have another array b of length m consisting of characters 'L' and 'R'. b_i is the side from which the i-th participant enters the room. 'L' means the participant enters from the left of computer 1 and goes from left to right, and 'R' means the participant enters from the right of computer n and goes from right to left.The participants in the order from 1 to m enter the room one by one. The i-th of them enters the contest room in the direction b_i and goes to sit behind the a_i-th computer. If it is occupied he keeps walking in his direction until he reaches the first unoccupied computer. After that, he sits behind it. If he doesn't find any computer he gets upset and gives up on the contest.The madness of the i-th participant is the distance between his assigned computer (a_i) and the computer he ends up sitting behind. The distance between computers i and j is equal to |i - j|.The values in the array a can be equal. There exist n^m \cdot 2^m possible pairs of arrays (a, b).Consider all pairs of arrays (a, b) such that no person becomes upset. For each of them let's calculate the sum of participants madnesses. Find the sum of all these values.You will be given some prime modulo p. Find this sum by modulo p.InputThe only line contains three integers n, m, p (1 \leq m \leq n \leq 500, 10^8 \leq p \leq 10 ^ 9 + 9).It is guaranteed, that the number p is prime.OutputPrint only one integer — the required sum by modulo p.ExamplesInput 3 1 1000000007 Output 0 Input 2 2 1000000009 Output 4 Input 3 2 998244353 Output 8 Input 20 10 1000000009 Output 352081045 NoteIn the first test, there are three possible arrays a: \{1\}, \{2\}, and \{3\} and two possible arrays b: \{\mathtt{L}\} and \{\mathtt{R}\}. For all six pairs of arrays (a, b), the only participant will sit behind the computer a_1, so his madness will be 0. So the total sum of madnesses will be 0.In the second test, all possible pairs of arrays (a, b), such that no person becomes upset are: (\{1, 1\}, \{\mathtt{L}, \mathtt{L}\}), the sum of madnesses is 1; (\{1, 1\}, \{\mathtt{R}, \mathtt{L}\}), the sum of madnesses is 1; (\{2, 2\}, \{\mathtt{R}, \mathtt{R}\}), the sum of madnesses is 1; (\{2, 2\}, \{\mathtt{L}, \mathtt{R}\}), the sum of madnesses is 1; all possible pairs of a \in \{\{1, 2\}, \{2, 1\}\} and b \in \{\{\mathtt{L}, \mathtt{L}\}, \{\mathtt{R}, \mathtt{L}\}, \{\mathtt{L}, \mathtt{R}\}, \{\mathtt{R}, \mathtt{R}\}\}, the sum of madnesses is 0. So, the answer is 1 + 1 + 1 + 1 + 0 \ldots = 4.
3 1 1000000007
0
3 seconds
256 megabytes
['combinatorics', 'dp', 'fft', '*3100']
C. Greedy Shoppingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n of integers. This array is non-increasing.Let's consider a line with n shops. The shops are numbered with integers from 1 to n from left to right. The cost of a meal in the i-th shop is equal to a_i.You should process q queries of two types: 1 x y: for each shop 1 \leq i \leq x set a_{i} = max(a_{i}, y). 2 x y: let's consider a hungry man with y money. He visits the shops from x-th shop to n-th and if he can buy a meal in the current shop he buys one item of it. Find how many meals he will purchase. The man can buy a meal in the shop i if he has at least a_i money, and after it his money decreases by a_i. InputThe first line contains two integers n, q (1 \leq n, q \leq 2 \cdot 10^5).The second line contains n integers a_{1},a_{2}, \ldots, a_{n} (1 \leq a_{i} \leq 10^9) — the costs of the meals. It is guaranteed, that a_1 \geq a_2 \geq \ldots \geq a_n.Each of the next q lines contains three integers t, x, y (1 \leq t \leq 2, 1\leq x \leq n, 1 \leq y \leq 10^9), each describing the next query.It is guaranteed that there exists at least one query of type 2.OutputFor each query of type 2 output the answer on the new line.ExampleInput 10 6 10 10 10 6 6 5 5 5 3 1 2 3 50 2 4 10 1 3 10 2 2 36 1 4 7 2 2 17 Output 8 3 6 2 NoteIn the first query a hungry man will buy meals in all shops from 3 to 10.In the second query a hungry man will buy meals in shops 4, 9, and 10.After the third query the array a_1, a_2, \ldots, a_n of costs won't change and will be \{10, 10, 10, 6, 6, 5, 5, 5, 3, 1\}.In the fourth query a hungry man will buy meals in shops 2, 3, 4, 5, 9, and 10.After the fifth query the array a of costs will be \{10, 10, 10, 7, 6, 5, 5, 5, 3, 1\}.In the sixth query a hungry man will buy meals in shops 2 and 4.
10 6 10 10 10 6 6 5 5 5 3 1 2 3 50 2 4 10 1 3 10 2 2 36 1 4 7 2 2 17
8 3 6 2
3 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'greedy', 'implementation', '*2600']
B. Graph Subset Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected graph with n vertices and m edges. Also, you are given an integer k.Find either a clique of size k or a non-empty subset of vertices such that each vertex of this subset has at least k neighbors in the subset. If there are no such cliques and subsets report about it.A subset of vertices is called a clique of size k if its size is k and there exists an edge between every two vertices from the subset. A vertex is called a neighbor of the other vertex if there exists an edge between them.InputThe first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The next lines contain descriptions of test cases.The first line of the description of each test case contains three integers n, m, k (1 \leq n, m, k \leq 10^5, k \leq n).Each of the next m lines contains two integers u, v (1 \leq u, v \leq n, u \neq v), denoting an edge between vertices u and v.It is guaranteed that there are no self-loops or multiple edges. It is guaranteed that the sum of n for all test cases and the sum of m for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case: If you found a subset of vertices such that each vertex of this subset has at least k neighbors in the subset in the first line output 1 and the size of the subset. On the second line output the vertices of the subset in any order.If you found a clique of size k then in the first line output 2 and in the second line output the vertices of the clique in any order.If there are no required subsets and cliques print -1.If there exists multiple possible answers you can print any of them.ExampleInput 3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3 Output 2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1 NoteIn the first test case: the subset \{1, 2, 3, 4\} is a clique of size 4.In the second test case: degree of each vertex in the original graph is at least 3. So the set of all vertices is a correct answer.In the third test case: there are no cliques of size 4 or required subsets, so the answer is -1.
3 5 9 4 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 10 15 3 1 2 2 3 3 4 4 5 5 1 1 7 2 8 3 9 4 10 5 6 7 10 10 8 8 6 6 9 9 7 4 5 4 1 2 2 3 3 4 4 1 1 3
2 4 1 2 3 1 10 1 2 3 4 5 6 7 8 9 10 -1
1 second
256 megabytes
['constructive algorithms', 'data structures', 'graphs', '*2600']
A2. Binary Table (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size n \times m. This table consists of symbols 0 and 1.You can make such operation: select 3 different cells that belong to one 2 \times 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).Your task is to make all symbols in the table equal to 0. You are allowed to make at most nm operations. You don't need to minimize the number of operations.It can be proved, that it is always possible.InputThe first line contains a single integer t (1 \leq t \leq 5000) — the number of test cases. The next lines contain descriptions of test cases.The first line of the description of each test case contains two integers n, m (2 \leq n, m \leq 100).Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.It is guaranteed, that the sum of nm for all test cases does not exceed 20000.OutputFor each test case print the integer k (0 \leq k \leq nm) — the number of operations.In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong to some 2 \times 2 square.ExampleInput 5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101 Output 1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2 NoteIn the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.In the second test case: operation with cells (2, 1), (3, 1), (3, 2). After it the table will be: 011001000 operation with cells (1, 2), (1, 3), (2, 3). After it the table will be: 000000000 In the fifth test case: operation with cells (1, 3), (2, 2), (2, 3). After it the table will be: 010110 operation with cells (1, 2), (2, 1), (2, 2). After it the table will be: 000000
5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101
1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2
1 second
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'implementation', '*1900']
A1. Binary Table (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.You are given a binary table of size n \times m. This table consists of symbols 0 and 1.You can make such operation: select 3 different cells that belong to one 2 \times 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0).Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations.It can be proved that it is always possible.InputThe first line contains a single integer t (1 \leq t \leq 5000) — the number of test cases. The next lines contain descriptions of test cases.The first line of the description of each test case contains two integers n, m (2 \leq n, m \leq 100).Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table.It is guaranteed that the sum of nm for all test cases does not exceed 20000.OutputFor each test case print the integer k (0 \leq k \leq 3nm) — the number of operations.In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 \leq x_1, x_2, x_3 \leq n, 1 \leq y_1, y_2, y_3 \leq m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 \times 2 square.ExampleInput 5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101 Output 1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2 NoteIn the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0.In the second test case: operation with cells (2, 1), (3, 1), (3, 2). After it the table will be: 011001000 operation with cells (1, 2), (1, 3), (2, 3). After it the table will be: 000000000 In the fifth test case: operation with cells (1, 3), (2, 2), (2, 3). After it the table will be: 010110 operation with cells (1, 2), (2, 1), (2, 2). After it the table will be: 000000
5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101
1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2
1 second
256 megabytes
['constructive algorithms', 'implementation', '*1500']
F. Olha and Igortime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Igor wants to find the key to Olha's heart. The problem is, that it's at the root of a binary tree.There is a perfect binary tree of height h consisting of n = 2^{h} - 1 nodes. The nodes have been assigned distinct labels from 1 to n. However, Igor only knows h and does not know which label corresponds to which node. To find key to Olha's heart he needs to find the label assigned to the root by making queries of the following type at most n+420 times: Select three distinct labels u, v and w (1 \leq u,v,w \leq n). In response, Olha (the grader) will tell him the label of the lowest common ancestor of nodes labelled u and v, if the tree was rooted at the node labelled w instead. Help Igor to find the root!Note: the grader is not adaptive: the labels are fixed before any queries are made.InputThe first and only line contains a single integer h (3 \le h \le 18) — the height of the tree.InteractionYou begin the interaction by reading h.To make a query for labels u, v, w, in a separate line output "? u v w".Numbers in the query have to satisfy 1 \le u, v, w \le n. Additionally, u \ne v, u \ne w, and v \ne w.In response, you will receive 1 \le x \le n, the label of the lowest common ancestor of u and v, if the tree was rooted at w. In case your query is invalid or you asked more than n+420 queries, program will print -1 and will finish interaction. You will receive Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you determine the label assigned to the root, output "! r", where r is the label of the root. After printing a query 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 documentation for other languages.Hack FormatTo hack, use the following format.The first line should contain a single integer h (height of the binary tree).On the next line, output a permutation p of size n = 2^h - 1. This represents a binary tree where the root is labelled p_1 and for 1 < i \le n, the parent of p_i is p_{ \lfloor{\frac{i}{2}}\rfloor }.ExampleInput 3 2 7 4Output ? 7 3 5 ? 1 6 4 ? 1 5 4 ! 4NoteThe labels corresponding to the tree in the example are [4,7,2,6,1,5,3], meaning the root is labelled 4, and for 1 < i \le n, the parent of p_i is p_{ \lfloor{\frac{i}{2}}\rfloor }.
3 2 7 4
? 7 3 5 ? 1 6 4 ? 1 5 4 ! 4
4 seconds
256 megabytes
['interactive', 'probabilities', 'trees', '*3000']
E. Yurii Can Do Everythingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYurii is sure he can do everything. Can he solve this task, though?He has an array a consisting of n positive integers. Let's call a subarray a[l...r] good if the following conditions are simultaneously satisfied: l+1 \leq r-1, i. e. the subarray has length at least 3; (a_l \oplus a_r) = (a_{l+1}+a_{l+2}+\ldots+a_{r-2}+a_{r-1}), where \oplus denotes the bitwise XOR operation. In other words, a subarray is good if the bitwise XOR of the two border elements is equal to the sum of the rest of the elements. Yurii wants to calculate the total number of good subarrays. What is it equal to?An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputThe first line contains a single integer n (3 \leq n \leq 2\cdot 10^5) — the length of a. The second line contains n integers a_1,a_2,\ldots,a_n (1 \leq a_i \lt 2^{30}) — elements of a. OutputOutput a single integer — the number of good subarrays. ExamplesInput 8 3 1 2 3 1 2 3 15 Output 6Input 10 997230370 58052053 240970544 715275815 250707702 156801523 44100666 64791577 43523002 480196854 Output 2NoteThere are 6 good subarrays in the example: [3,1,2] (twice) because (3 \oplus 2) = 1; [1,2,3] (twice) because (1 \oplus 3) = 2; [2,3,1] because (2 \oplus 1) = 3; [3,1,2,3,1,2,3,15] because (3 \oplus 15) = (1+2+3+1+2+3).
8 3 1 2 3 1 2 3 15
6
1 second
256 megabytes
['binary search', 'bitmasks', 'brute force', 'constructive algorithms', 'divide and conquer', 'two pointers', '*2500']
D. Powerful Kseniatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKsenia has an array a consisting of n positive integers a_1, a_2, \ldots, a_n. In one operation she can do the following: choose three distinct indices i, j, k, and then change all of a_i, a_j, a_k to a_i \oplus a_j \oplus a_k simultaneously, where \oplus denotes the bitwise XOR operation. She wants to make all a_i equal in at most n operations, or to determine that it is impossible to do so. She wouldn't ask for your help, but please, help her!InputThe first line contains one integer n (3 \leq n \leq 10^5) — the length of a.The second line contains n integers, a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — elements of a.OutputPrint YES or NO in the first line depending on whether it is possible to make all elements equal in at most n operations.If it is possible, print an integer m (0 \leq m \leq n), which denotes the number of operations you do.In each of the next m lines, print three distinct integers i, j, k, representing one operation. If there are many such operation sequences possible, print any. Note that you do not have to minimize the number of operations.ExamplesInput 5 4 2 1 7 2 Output YES 1 1 3 4Input 4 10 4 49 22 Output NO NoteIn the first example, the array becomes [4 \oplus 1 \oplus 7, 2, 4 \oplus 1 \oplus 7, 4 \oplus 1 \oplus 7, 2] = [2, 2, 2, 2, 2].
5 4 2 1 7 2
YES 1 1 3 4
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'math', '*2200']
C. Engineer Artemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArtem is building a new robot. He has a matrix a consisting of n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{i,j} written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side. Artem wants to increment the values in some cells by one to make a good.More formally, find a good matrix b that satisfies the following condition — For all valid (i,j), either b_{i,j} = a_{i,j} or b_{i,j} = a_{i,j}+1. For the constraints of this problem, it can be shown that such a matrix b always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). Description of the test cases follows.The first line of each test case contains two integers n, m (1 \le n \le 100, 1 \le m \le 100)  — the number of rows and columns, respectively.The following n lines each contain m integers. The j-th integer in the i-th line is a_{i,j} (1 \leq a_{i,j} \leq 10^9).OutputFor each case, output n lines each containing m integers. The j-th integer in the i-th line is b_{i,j}.ExampleInput 3 3 2 1 2 4 5 7 8 2 2 1 1 3 3 2 2 1 3 2 2 Output 1 2 5 6 7 8 2 1 4 3 2 4 3 2 NoteIn all the cases, you can verify that no two adjacent cells have the same value and that b is the same as a with some values incremented by one.
3 3 2 1 2 4 5 7 8 2 2 1 1 3 3 2 2 1 3 2 2
1 2 5 6 7 8 2 1 4 3 2 4 3 2
1 second
256 megabytes
['2-sat', 'chinese remainder theorem', 'constructive algorithms', 'fft', 'flows', '*2000']
B. Valerii Against Everyonetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array b of length n. Let's define another array a, also of length n, for which a_i = 2^{b_i} (1 \leq i \leq n). Valerii says that every two non-intersecting subarrays of a have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers l_1,r_1,l_2,r_2 that satisfy the following conditions: 1 \leq l_1 \leq r_1 \lt l_2 \leq r_2 \leq n; a_{l_1}+a_{l_1+1}+\ldots+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+\ldots+a_{r_2-1}+a_{r_2}. If such four integers exist, you will prove Valerii wrong. Do they exist?An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first line of every test case contains a single integer n (2 \le n \le 1000).The second line of every test case contains n integers b_1,b_2,\ldots,b_n (0 \le b_i \le 10^9). OutputFor every test case, if there exist two non-intersecting subarrays in a that have the same sum, output YES on a separate line. Otherwise, output NO on a separate line. Also, note that each letter can be in any case. ExampleInput 2 6 4 3 0 1 2 0 2 2 5 Output YES NO NoteIn the first case, a = [16,8,1,2,4,1]. Choosing l_1 = 1, r_1 = 1, l_2 = 2 and r_2 = 6 works because 16 = (8+1+2+4+1).In the second case, you can verify that there is no way to select to such subarrays.
2 6 4 3 0 1 2 0 2 2 5
YES NO
1 second
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'sortings', '*1000']
A. Specific Tastes of Andre time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements — 6 — is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't divisible by 4. Andre calls an array a of length n perfect if the following conditions hold: Every nonempty subarray of this array is good. For every i (1 \le i \le n), 1 \leq a_i \leq 100. Given a positive integer n, output any perfect array of length n. We can show that for the given constraints such an array always exists.An array c is a subarray of an array d if c can be obtained from d by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). Description of the test cases follows.The first and only line of every test case contains a single integer n (1 \le n \le 100).OutputFor every test, output any perfect array of length n on a separate line. ExampleInput 3 1 2 4 Output 24 19 33 7 37 79 49 NoteArray [19, 33] is perfect as all 3 its subarrays: [19], [33], [19, 33], have sums divisible by their lengths, and therefore are good.
3 1 2 4
24 19 33 7 37 79 49
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
G. Death DBMStime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor the simplicity, let's say that the "Death Note" is a notebook that kills a person when their name is written in it.It's easy to kill with it, but it's pretty hard to keep track of people you haven't killed and still plan to. You decided to make a "Death Database Management System" — a computer program that provides the easy access to the database of possible victims. Let me describe its specifications to you.Let's define a victim entity: a victim has a name (not necessarily unique) that consists only of lowercase Latin letters and an integer suspicion value.At the start of the program the user enters a list of n victim names into a database, each suspicion value is set to 0.Then the user makes queries of two types: 1~i~x — set the suspicion value of the i-th victim to x; 2~q — given a string q find the maximum suspicion value of a victim whose name is a contiguous substring of q. Just to remind you, this program doesn't kill people, it only helps to search for the names to write down in an actual notebook. Thus, the list of the victims in the database doesn't change throughout the queries.What are you waiting for? Write that program now!InputThe first line contains two integers n and m (1 \le n, m \le 3 \cdot 10^5) — the number of victims and the number of queries, respectively.Each of the next n lines contains a single string s_i — the name of the i-th victim. Each name consists only of lowercase Latin letters.Each of the next m lines contains a query of one of two types: 1~i~x (1 \le i \le n, 0 \le x \le 10^9) — change the suspicion value of the i-th victim to x; 2~q — given a string q consisting only of lowercase Latin letters find the maximum suspicion value of a victim whose name is a contiguous substring of q. There is at least one query of the second type. The total length of the strings s_i doesn't exceed 3 \cdot 10^5. The total length of the strings q doesn't exceed 3 \cdot 10^5. OutputFor each query of the second type print an integer value. If there is no victim name that is a contiguous substring of q, then print -1. Otherwise, print the maximum suspicion value of a victim whose name is a contiguous substring of q.ExamplesInput 5 8 kurou takuo takeshi naomi shingo 2 nakiraomi 2 abanaomicaba 1 3 943 2 takuotakeshishingo 1 5 135832 2 shingotakeshi 1 5 0 2 shingotakeshi Output -1 0 943 135832 943 Input 6 15 a ab ba b a ba 2 aa 1 4 4 2 bbb 1 2 1 1 2 18 2 b 2 c 1 6 10 2 aba 2 abbbba 1 2 12 2 bbaaab 1 1 11 1 5 5 2 baa Output 0 4 4 -1 18 18 12 11
5 8 kurou takuo takeshi naomi shingo 2 nakiraomi 2 abanaomicaba 1 3 943 2 takuotakeshishingo 1 5 135832 2 shingotakeshi 1 5 0 2 shingotakeshi
-1 0 943 135832 943
2 seconds
512 megabytes
['data structures', 'string suffix structures', 'strings', 'trees', '*2600']
F. Emotional Fishermentime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputn fishermen have just returned from a fishing vacation. The i-th fisherman has caught a fish of weight a_i.Fishermen are going to show off the fish they caught to each other. To do so, they firstly choose an order in which they show their fish (each fisherman shows his fish exactly once, so, formally, the order of showing fish is a permutation of integers from 1 to n). Then they show the fish they caught according to the chosen order. When a fisherman shows his fish, he might either become happy, become sad, or stay content.Suppose a fisherman shows a fish of weight x, and the maximum weight of a previously shown fish is y (y = 0 if that fisherman is the first to show his fish). Then: if x \ge 2y, the fisherman becomes happy; if 2x \le y, the fisherman becomes sad; if none of these two conditions is met, the fisherman stays content. Let's call an order in which the fishermen show their fish emotional if, after all fishermen show their fish according to this order, each fisherman becomes either happy or sad. Calculate the number of emotional orders modulo 998244353.InputThe first line contains one integer n (2 \le n \le 5000).The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9).OutputPrint one integer — the number of emotional orders, taken modulo 998244353.ExamplesInput 4 1 1 4 9 Output 20 Input 4 4 3 2 1 Output 0 Input 3 4 2 1 Output 6 Input 8 42 1337 13 37 420 666 616 97 Output 19200
4 1 1 4 9
20
4 seconds
1024 megabytes
['combinatorics', 'dp', 'math', 'two pointers', '*2600']
E. Make It Increasingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.In one operation, you may choose two integers i and x (1 \le i \le n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.Calculate the minimum number of operations you should perform so the array a is increasing (that is, a_1 < a_2 < a_3 < \dots < a_n), or report that it is impossible.InputThe first line contains two integers n and k (1 \le n \le 5 \cdot 10^5, 0 \le k \le n) — the size of the array a and the set b, respectively.The second line contains n integers a_1, a_2, ..., a_n (1 \le a_i \le 10^9).Then, if k \ne 0, the third line follows, containing k integers b_1, b_2, ..., b_k (1 \le b_1 < b_2 < \dots < b_k \le n). If k = 0, this line is skipped.OutputIf it is impossible to make the array a increasing using the given operations, print -1.Otherwise, print one integer — the minimum number of operations you have to perform.ExamplesInput 7 2 1 2 1 1 3 5 1 3 5 Output 4 Input 3 3 1 3 2 1 2 3 Output -1 Input 5 0 4 3 1 2 3 Output 2 Input 10 3 1 3 5 6 12 9 8 10 13 15 2 4 9 Output 3
7 2 1 2 1 1 3 5 1 3 5
4
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'dp', 'implementation', '*2200']
D. Minimal Height Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty(): k = q.pop() # retrieve the first vertex from the queue a.append(k) # append k to the end of the sequence in which vertices were visited for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order a, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex 1 is 0, since it's the root, and the depth of all root's children are 1.Help Monocarp to find any tree with given visiting order a and minimum height.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le n; a_i \neq a_j; a_1 = 1) — the order in which the vertices were visited by the BFS algorithm.It's guaranteed that the total sum of n over test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case print the minimum possible height of a tree with the given visiting order a.ExampleInput 3 4 1 4 3 2 2 1 2 3 1 2 3 Output 3 1 1 NoteIn the first test case, there is only one tree with the given visiting order: In the second test case, there is only one tree with the given visiting order as well: In the third test case, an optimal tree with the given visiting order is shown below:
3 4 1 4 3 2 2 1 2 3 1 2 3
3 1 1
2 seconds
256 megabytes
['graphs', 'greedy', 'shortest paths', 'trees', '*1600']
C. Chef Monocarptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes.At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| — the absolute difference between T and t_i. Once the dish is out of the oven, it can't go back in.Monocarp should put all the dishes out of the oven. What is the minimum total unpleasant value Monocarp can obtain?InputThe first line contains a single integer q (1 \le q \le 200) — the number of testcases.Then q testcases follow.The first line of the testcase contains a single integer n (1 \le n \le 200) — the number of dishes in the oven.The second line of the testcase contains n integers t_1, t_2, \dots, t_n (1 \le t_i \le n) — the optimal cooking time for each dish.The sum of n over all q testcases doesn't exceed 200.OutputPrint a single integer for each testcase — the minimum total unpleasant value Monocarp can obtain when he puts out all the dishes out of the oven. Remember that Monocarp can only put the dishes out at positive integer minutes and no more than one dish at any minute.ExampleInput 6 6 4 2 4 4 5 2 7 7 7 7 7 7 7 7 1 1 5 5 1 2 4 3 4 1 4 4 4 21 21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13 Output 4 12 0 0 2 21 NoteIn the first example Monocarp can put out the dishes at minutes 3, 1, 5, 4, 6, 2. That way the total unpleasant value will be |4 - 3| + |2 - 1| + |4 - 5| + |4 - 4| + |6 - 5| + |2 - 2| = 4.In the second example Monocarp can put out the dishes at minutes 4, 5, 6, 7, 8, 9, 10.In the third example Monocarp can put out the dish at minute 1.In the fourth example Monocarp can put out the dishes at minutes 5, 1, 2, 4, 3.In the fifth example Monocarp can put out the dishes at minutes 1, 3, 4, 5.
6 6 4 2 4 4 5 2 7 7 7 7 7 7 7 7 1 1 5 5 1 2 4 3 4 1 4 4 4 21 21 8 1 4 1 5 21 1 8 21 11 21 11 3 12 8 19 15 9 11 13
4 12 0 0 2 21
2 seconds
256 megabytes
['dp', 'flows', 'graph matchings', 'greedy', 'math', 'sortings', '*1800']
B. Reverse Binary Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's.String s has exactly \frac{n}{2} zeroes and \frac{n}{2} ones (n is even).In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.What is the minimum number of operations you need to make string s alternating? A string is alternating if s_i \neq s_{i + 1} for all i. There are two types of alternating strings in general: 01010101... or 10101010...InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^5; n is even) — the length of string s.The second line of each test case contains a binary string s of length n (s_i \in {0, 1}). String s has exactly \frac{n}{2} zeroes and \frac{n}{2} ones.It's guaranteed that the total sum of n over test cases doesn't exceed 10^5.OutputFor each test case, print the minimum number of operations to make s alternating.ExampleInput 3 2 10 4 0110 8 11101000 Output 0 1 2 NoteIn the first test case, string 10 is already alternating.In the second test case, we can, for example, reverse the last two elements of s and get: 0110 \rightarrow 0101.In the third test case, we can, for example, make the following two operations: 11101000 \rightarrow 10101100; 10101100 \rightarrow 10101010.
3 2 10 4 0110 8 11101000
0 1 2
2 seconds
256 megabytes
['constructive algorithms', 'greedy', '*1200']
A. Marketing Schemetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts. Suppose you decided to sell packs with a cans in a pack with a discount and some customer wants to buy x cans of cat food. Then he follows a greedy strategy: he buys \left\lfloor \frac{x}{a} \right\rfloor packs with a discount; then he wants to buy the remaining (x \bmod a) cans one by one. \left\lfloor \frac{x}{a} \right\rfloor is x divided by a rounded down, x \bmod a is the remainer of x divided by a.But customers are greedy in general, so if the customer wants to buy (x \bmod a) cans one by one and it happens that (x \bmod a) \ge \frac{a}{2} he decides to buy the whole pack of a cans (instead of buying (x \bmod a) cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.You know that each of the customers that come to your shop can buy any number of cans from l to r inclusive. Can you choose such size of pack a that each customer buys more cans than they wanted initially?InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first and only line of each test case contains two integers l and r (1 \le l \le r \le 10^9) — the range of the number of cans customers can buy.OutputFor each test case, print YES if you can choose such size of pack a that each customer buys more cans than they wanted initially. Otherwise, print NO.You can print each character in any case.ExampleInput 3 3 4 1 2 120 150 Output YES NO YES NoteIn the first test case, you can take, for example, a = 5 as the size of the pack. Then if a customer wants to buy 3 cans, he'll buy 5 instead (3 \bmod 5 = 3, \frac{5}{2} = 2.5). The one who wants 4 cans will also buy 5 cans.In the second test case, there is no way to choose a.In the third test case, you can take, for example, a = 80.
3 3 4 1 2 120 150
YES NO YES
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', '*800']
F. Sum Over Subsetstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a multiset S. Over all pairs of subsets A and B, such that: B \subset A; |B| = |A| - 1; greatest common divisor of all elements in A is equal to one; find the sum of \sum_{x \in A}{x} \cdot \sum_{x \in B}{x}, modulo 998\,244\,353.InputThe first line contains one integer m (1 \le m \le 10^5): the number of different values in the multiset S.Each of the next m lines contains two integers a_i, freq_i (1 \le a_i \le 10^5, 1 \le freq_i \le 10^9). Element a_i appears in the multiset S freq_i times. All a_i are different.OutputPrint the required sum, modulo 998\,244\,353.ExamplesInput 2 1 1 2 1 Output 9 Input 4 1 1 2 1 3 1 6 1 Output 1207 Input 1 1 5 Output 560 NoteA multiset is a set where elements are allowed to coincide. |X| is the cardinality of a set X, the number of elements in it.A \subset B: Set A is a subset of a set B.In the first example B=\{1\}, A=\{1,2\} and B=\{2\}, A=\{1, 2\} have a product equal to 1\cdot3 + 2\cdot3=9. Other pairs of A and B don't satisfy the given constraints.
2 1 1 2 1
9
1 second
256 megabytes
['combinatorics', 'math', 'number theory', '*2800']
E. Complicated Computationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem MEX of a certain array is the smallest positive integer not contained in this array.Everyone knows this definition, including Lesha. But Lesha loves MEX, so he comes up with a new problem involving MEX every day, including today.You are given an array a of length n. Lesha considers all the non-empty subarrays of the initial array and computes MEX for each of them. Then Lesha computes MEX of the obtained numbers.An array b is a subarray of an array a, if b can be obtained from a by deletion of several (possible none or all) elements from the beginning and several (possibly none or all) elements from the end. In particular, an array is a subarray of itself.Lesha understands that the problem is very interesting this time, but he doesn't know how to solve it. Help him and find the MEX of MEXes of all the subarrays!InputThe first line contains a single integer n (1 \le n \le 10^5) — the length of the array. The next line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of the array.OutputPrint a single integer — the MEX of MEXes of all subarrays.ExamplesInput 3 1 3 2 Output 3 Input 5 1 4 3 1 2 Output 6
3 1 3 2
3
1 second
256 megabytes
['binary search', 'data structures', 'two pointers', '*2400']
D. Bandit in a Citytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBandits appeared in the city! One of them is trying to catch as many citizens as he can.The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square.After Sunday walk all the roads were changed to one-way roads in such a way that it is possible to reach any square from the main square.At the moment when the bandit appeared on the main square there were a_i citizens on the i-th square. Now the following process will begin. First, each citizen that is currently on a square with some outgoing one-way roads chooses one of such roads and moves along it to another square. Then the bandit chooses one of the one-way roads outgoing from the square he is located and moves along it. The process is repeated until the bandit is located on a square with no outgoing roads. The bandit catches all the citizens on that square.The bandit wants to catch as many citizens as possible; the citizens want to minimize the number of caught people. The bandit and the citizens know positions of all citizens at any time, the citizens can cooperate. If both sides act optimally, how many citizens will be caught?InputThe first line contains a single integer n — the number of squares in the city (2 \le n \le 2\cdot10^5).The second line contains n-1 integers p_2, p_3 \dots p_n meaning that there is a one-way road from the square p_i to the square i (1 \le p_i < i). The third line contains n integers a_1, a_2, \dots, a_n — the number of citizens on each square initially (0 \le a_i \le 10^9).OutputPrint a single integer — the number of citizens the bandit will catch if both sides act optimally.ExamplesInput 3 1 1 3 1 2 Output 3 Input 3 1 1 3 1 3 Output 4 NoteIn the first example the citizens on the square 1 can split into two groups 2 + 1, so that the second and on the third squares will have 3 citizens each.In the second example no matter how citizens act the bandit can catch at least 4 citizens.
3 1 1 3 1 2
3
1 second
256 megabytes
['binary search', 'dfs and similar', 'graphs', 'greedy', 'trees', '*1900']
C. Binary Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down).Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x!Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order.Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7.InputThe only line of input contains integers n, x and pos (1 \le x \le n \le 1000, 0 \le pos \le n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively.OutputPrint a single number — the remainder of the division of the number of valid permutations by 10^9+7.ExamplesInput 4 1 2 Output 6 Input 123 42 24 Output 824071958 NoteAll possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
4 1 2
6
1 second
256 megabytes
['binary search', 'combinatorics', '*1500']
B. Prime Squaretime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n \times n is called prime if the following three conditions are held simultaneously: all numbers on the square are non-negative integers not exceeding 10^5; there are no prime numbers in the square; sums of integers in each row and each column are prime numbers. Sasha has an integer n. He asks you to find any prime square of size n \times n. Sasha is absolutely sure such squares exist, so just help him!InputThe first line contains a single integer t (1 \le t \le 10) — the number of test cases.Each of the next t lines contains a single integer n (2 \le n \le 100) — the required size of a square.OutputFor each test case print n lines, each containing n integers — the prime square you built. If there are multiple answers, print any.ExampleInput 2 4 2 Output 4 6 8 1 4 9 9 9 4 10 10 65 1 4 4 4 1 1 1 1
2 4 2
4 6 8 1 4 9 9 9 4 10 10 65 1 4 4 4 1 1 1 1
1.5 seconds
256 megabytes
['constructive algorithms', 'math', '*900']