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
E. Split Into Two Setstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp was recently given a set of n (number n — even) dominoes. Each domino contains two integers from 1 to n.Can he divide all the dominoes into two sets so that all the numbers on the dominoes of each set are different? Each domino must go into exactly one of the two sets.For example, if he has 4 dominoes: \{1, 4\}, \{1, 3\}, \{3, 2\} and \{4, 2\}, then Polycarp will be able to divide them into two sets in the required way. The first set can include the first and third dominoes (\{1, 4\} and \{3, 2\}), and the second set — the second and fourth ones (\{1, 3\} and \{4, 2\}).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The descriptions of the test cases follow.The first line of each test case contains a single even integer n (2 \le n \le 2 \cdot 10^5) — the number of dominoes.The next n lines contain pairs of numbers a_i and b_i (1 \le a_i, b_i \le n) describing the numbers on the i-th domino.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case print: YES, if it is possible to divide n dominoes into two sets so that the numbers on the dominoes of each set are different; NO if this is not possible. You can print YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).ExampleInput 641 24 32 13 461 24 51 34 62 35 621 12 221 22 182 11 24 34 35 65 78 67 881 22 14 35 35 46 78 67 8Output YES NO NO YES YES NO NoteIn the first test case, the dominoes can be divided as follows: First set of dominoes: [\{1, 2\}, \{4, 3\}] Second set of dominoes: [\{2, 1\}, \{3, 4\}] In other words, in the first set we take dominoes with numbers 1 and 2, and in the second set we take dominoes with numbers 3 and 4.In the second test case, there's no way to divide dominoes into 2 sets, at least one of them will contain repeated number.
641 24 32 13 461 24 51 34 62 35 621 12 221 22 182 11 24 34 35 65 78 67 881 22 14 35 35 46 78 67 8
YES NO NO YES YES NO
2 seconds
256 megabytes
['dfs and similar', 'dsu', 'graphs', '*1600']
D. Not a Cheap Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet s be a string of lowercase Latin letters. Its price is the sum of the indices of letters (an integer between 1 and 26) that are included in it. For example, the price of the string abca is 1+2+3+1=7.The string w and the integer p are given. Remove the minimal number of letters from w so that its price becomes less than or equal to p and print the resulting string. Note that the resulting string may be empty. You can delete arbitrary letters, they do not have to go in a row. If the price of a given string w is less than or equal to p, then nothing needs to be deleted and w must be output.Note that when you delete a letter from w, the order of the remaining letters is preserved. For example, if you delete the letter e from the string test, you get tst.InputThe first line of input contains an integer t (1 \le t \le 10^4) — the number of test cases in the test. The following are descriptions of t test cases.Each case consists of two lines.The first of them is the string w, it is non-empty and consists of lowercase Latin letters. Its length does not exceed 2\cdot10^5.The second line contains an integer p (1 \le p \le 5\,200\,000).It is guaranteed that the sum of string lengths w over all test cases does not exceed 2 \cdot 10^5.OutputOutput exactly t rows, the i-th of them should contain the answer to the i-th set of input data. Print the longest string that is obtained from w by deleting letters such that its price is less or equal to p. If there are several answers, then output any of them.Note that the empty string  — is one of the possible answers. In this case, just output an empty string.ExampleInput 5abca2abca6codeforces1codeforces10codeforces100Output aa abc cdc codeforces
5abca2abca6codeforces1codeforces10codeforces100
aa abc cdc codeforces
2 seconds
256 megabytes
['greedy', '*1000']
C. Train and Queriestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlong the railroad there are stations indexed from 1 to 10^9. An express train always travels along a route consisting of n stations with indices u_1, u_2, \dots, u_n, where (1 \le u_i \le 10^9). The train travels along the route from left to right. It starts at station u_1, then stops at station u_2, then at u_3, and so on. Station u_n — the terminus.It is possible that the train will visit the same station more than once. That is, there may be duplicates among the values u_1, u_2, \dots, u_n.You are given k queries, each containing two different integers a_j and b_j (1 \le a_j, b_j \le 10^9). For each query, determine whether it is possible to travel by train from the station with index a_j to the station with index b_j.For example, let the train route consist of 6 of stations with indices [3, 7, 1, 5, 1, 4] and give 3 of the following queries: a_1 = 3, b_1 = 5It is possible to travel from station 3 to station 5 by taking a section of the route consisting of stations [3, 7, 1, 5]. Answer: YES. a_2 = 1, b_2 = 7You cannot travel from station 1 to station 7 because the train cannot travel in the opposite direction. Answer: NO. a_3 = 3, b_3 = 10It is not possible to travel from station 3 to station 10 because station 10 is not part of the train's route. Answer: NO. InputThe first line of the input contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case is empty.The second line of each test case contains two integers: n and k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5) —the number of stations the train route consists of and the number of queries.The third line of each test case contains exactly n integers u_1, u_2, \dots, u_n (1 \le u_i \le 10^9). The values u_1, u_2, \dots, u_n are not necessarily different.The following k lines contain two different integers a_j and b_j (1 \le a_j, b_j \le 10^9) describing the query with index j.It is guaranteed that the sum of n values over all test cases in the test does not exceed 2 \cdot 10^5. Similarly, it is guaranteed that the sum of k values over all test cases in the test also does not exceed 2 \cdot 10^5OutputFor each test case, output on a separate line: YES, if you can travel by train from the station with index a_j to the station with index b_j NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput 36 33 7 1 5 1 43 51 73 103 31 2 12 11 24 57 52 1 1 1 2 4 41 31 42 14 11 2Output YES NO NO YES YES NO NO YES YES NO YES NoteThe first test case is explained in the problem statement.
36 33 7 1 5 1 43 51 73 103 31 2 12 11 24 57 52 1 1 1 2 4 41 31 42 14 11 2
YES NO NO YES YES NO NO YES YES NO YES
3 seconds
256 megabytes
['data structures', 'greedy', '*1100']
B. Polycarp Writes a String from Memorytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a poor memory. Each day he can remember no more than 3 of different letters. Polycarp wants to write a non-empty string of s consisting of lowercase Latin letters, taking minimum number of days. In how many days will he be able to do it?Polycarp initially has an empty string and can only add characters to the end of that string.For example, if Polycarp wants to write the string lollipops, he will do it in 2 days: on the first day Polycarp will memorize the letters l, o, i and write lolli; On the second day Polycarp will remember the letters p, o, s, add pops to the resulting line and get the line lollipops. If Polycarp wants to write the string stringology, he will do it in 4 days: in the first day will be written part str; on day two will be written part ing; on the third day, part of olog will be written; on the fourth day, part of y will be written. For a given string s, print the minimum number of days it will take Polycarp to write it.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of a non-empty string s consisting of lowercase Latin letters (the length of the string s does not exceed 2 \cdot 10^5) — the string Polycarp wants to construct.It is guaranteed that the sum of string lengths s over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single number — minimum number of days it will take Polycarp to write the string s from memory.ExampleInput 6lollipopsstringologyabracadabracodeforcestestfOutput 2 4 3 4 1 1
6lollipopsstringologyabracadabracodeforcestestf
2 4 3 4 1 1
2 seconds
256 megabytes
['greedy', '*800']
A. Round Down the Pricetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAt the store, the salespeople want to make all prices round. In this problem, a number that is a power of 10 is called a round number. For example, the numbers 10^0 = 1, 10^1 = 10, 10^2 = 100 are round numbers, but 20, 110 and 256 are not round numbers. So, if an item is worth m bourles (the value of the item is not greater than 10^9), the sellers want to change its value to the nearest round number that is not greater than m. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly 10^k bourles, where the value of k — is the maximum possible (k — any non-negative integer).For example, let the item have a value of 178-bourles. Then the new price of the item will be 100, and the answer will be 178-100=78.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases .Each test case is a string containing a single integer m (1 \le m \le 10^9) — the price of the item.OutputFor each test case, output on a separate line a single integer d (0 \le d < m) such that if you reduce the cost of the item by d bourles, the cost of the item will be the maximal possible round number. More formally: m - d = 10^k, where k — the maximum possible non-negative integer.ExampleInput 712178209999999999000987654321Output 0 1 78 10 899999999 8000 887654321 NoteIn the example: 1 - 0 = 10^0, 2 - 1 = 10^0, 178 - 78 = 10^2, 20 - 10 = 10^1, 999999999 - 899999999 = 10^8, 9000 - 8000 = 10^3, 987654321 - 887654321 = 10^8. Note that in each test case, we get the maximum possible round number.
712178209999999999000987654321
0 1 78 10 899999999 8000 887654321
1 second
256 megabytes
['constructive algorithms', '*800']
F. Pointstime limit per test6.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA triple of points i, j and k on a coordinate line is called beautiful if i < j < k and k - i \le d.You are given a set of points on a coordinate line, initially empty. You have to process queries of three types: add a point; remove a point; calculate the number of beautiful triples consisting of points belonging to the set. InputThe first line contains two integers q and d (1 \le q, d \le 2 \cdot 10^5) — the number of queries and the parameter for defining if a triple is beautiful, respectively.The second line contains q integers a_1, a_2, \dots, a_q (1 \le a_i \le 2 \cdot 10^5) denoting the queries. The integer a_i denotes the i-th query in the following way: if the point a_i belongs to the set, remove it; otherwise, add it; after adding or removing the point, print the number of beautiful triples. OutputFor each query, print one integer — the number of beautiful triples after processing the respective query.ExampleInput 7 5 8 5 3 2 1 5 6 Output 0 0 1 2 5 1 5
7 5 8 5 3 2 1 5 6
0 0 1 2 5 1 5
6.5 seconds
512 megabytes
['combinatorics', 'data structures', 'implementation', 'math', 'matrices', '*2500']
E. Text Editortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou wanted to write a text t consisting of m lowercase Latin letters. But instead, you have written a text s consisting of n lowercase Latin letters, and now you want to fix it by obtaining the text t from the text s.Initially, the cursor of your text editor is at the end of the text s (after its last character). In one move, you can do one of the following actions: press the "left" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i. e. before its first character); press the "right" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i. e. after its last character); press the "home" button, so the cursor is moved to the beginning of the text (before the first character of the text); press the "end" button, so the cursor is moved to the end of the text (after the last character of the text); press the "backspace" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens). Your task is to calculate the minimum number of moves required to obtain the text t from the text s using the given set of actions, or determine it is impossible to obtain the text t from the text s.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 first line of the test case contains two integers n and m (1 \le m \le n \le 5000) — the length of s and the length of t, respectively.The second line of the test case contains the string s consisting of n lowercase Latin letters.The third line of the test case contains the string t consisting of m lowercase Latin letters.It is guaranteed that the sum of n over all test cases does not exceed 5000 (\sum n \le 5000).OutputFor each test case, print one integer — the minimum number of moves required to obtain the text t from the text s using the given set of actions, or -1 if it is impossible to obtain the text t from the text s in the given test case.ExampleInput 69 4aaaaaaaaaaaaa7 3abacabaaaa5 4aabcdabcd4 2abbabb6 4barakabaka8 7questionproblemOutput 5 6 3 4 4 -1
69 4aaaaaaaaaaaaa7 3abacabaaaa5 4aabcdabcd4 2abbabb6 4barakabaka8 7questionproblem
5 6 3 4 4 -1
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'strings', '*2500']
D. Permutation Restorationtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp had a permutation a of n integers 1, 2, ..., n (a permutation is an array where each element from 1 to n occurs exactly once).Then Monocarp calculated an array of integers b of size n, where b_i = \left\lfloor \frac{i}{a_i} \right\rfloor. For example, if the permutation a is [2, 1, 4, 3], then the array b is equal to \left[ \left\lfloor \frac{1}{2} \right\rfloor, \left\lfloor \frac{2}{1} \right\rfloor, \left\lfloor \frac{3}{4} \right\rfloor, \left\lfloor \frac{4}{3} \right\rfloor \right] = [0, 2, 0, 1].Unfortunately, the Monocarp has lost his permutation, so he wants to restore it. Your task is to find a permutation a that corresponds to the given array b. If there are multiple possible permutations, then print any of them. The tests are constructed in such a way that least one suitable permutation exists.InputThe first line contains a single integer t (1 \le t \le 10^5) — number of test cases.The first line of each test case contains a single integer n (1 \le n \le 5 \cdot 10^5).The second line contains n integers b_1, b_2, \dots, b_n (0 \le b_i \le n).Additional constrains on the input: the sum of n over test cases does not exceed 5 \cdot 10^5; there exists at least one permutation a that would yield this array b. OutputFor each test case, print n integers — a permutation a that corresponds to the given array b. If there are multiple possible permutations, then print any of them.ExampleInput 440 2 0 121 150 0 1 4 130 1 3Output 2 1 4 3 1 2 3 4 2 1 5 3 2 1
440 2 0 121 150 0 1 4 130 1 3
2 1 4 3 1 2 3 4 2 1 5 3 2 1
4 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'math', 'sortings', 'two pointers', '*1900']
C. Schedule Managementtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n workers and m tasks. The workers are numbered from 1 to n. Each task i has a value a_i — the index of worker who is proficient in this task.Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in 1 hour. Otherwise, it takes them 2 hours.The workers work in parallel, independently of each other. Each worker can only work on one task at once.Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time 0. What's the minimum time all tasks can be completed by?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers n and m (1 \le n \le m \le 2 \cdot 10^5) — the number of workers and the number of tasks.The second line contains m integers a_1, a_2, \dots, a_m (1 \le a_i \le n) — the index of the worker proficient in the i-th task.The sum of m over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the minimum time all tasks can be completed by.ExampleInput 42 41 2 1 22 41 1 1 15 55 1 3 2 41 11Output 2 3 1 1 NoteIn the first testcase, the first worker works on tasks 1 and 3, and the second worker works on tasks 2 and 4. Since they both are proficient in the corresponding tasks, they take 1 hour on each. Both of them complete 2 tasks in 2 hours. Thus, all tasks are completed by 2 hours.In the second testcase, it's optimal to assign the first worker to tasks 1, 2 and 3 and the second worker to task 4. The first worker spends 3 hours, the second worker spends 2 hours (since they are not proficient in the taken task).In the third example, each worker can be assigned to the task they are proficient at. Thus, each of them complete their task in 1 hour.
42 41 2 1 22 41 1 1 15 55 1 3 2 41 11
2 3 1 1
2 seconds
256 megabytes
['binary search', 'greedy', 'implementation', 'two pointers', '*1400']
B. Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that a permutation of length n is an array where each element from 1 to n occurs exactly once.For a fixed positive integer d, let's define the cost of the permutation p of length n as the number of indices i (1 \le i < n) such that p_i \cdot d = p_{i + 1}.For example, if d = 3 and p = [5, 2, 6, 7, 1, 3, 4], then the cost of such a permutation is 2, because p_2 \cdot 3 = p_3 and p_5 \cdot 3 = p_6.Your task is the following one: for a given value n, find the permutation of length n and the value d with maximum possible cost (over all ways to choose the permutation and d). If there are multiple answers, then print any of them.InputThe first line contains a single integer t (1 \le t \le 500) — the number of test cases.The single line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5).The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the value d in the first line, and n integers in the second line — the permutation itself. If there are multiple answers, then print any of them.ExampleInput 223Output 2 1 2 3 2 1 3
223
2 1 2 3 2 1 3
2 seconds
256 megabytes
['greedy', '*800']
A. Grass Fieldtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a field of size 2 \times 2. Each cell of this field can either contain grass or be empty. The value a_{i, j} is 1 if the cell (i, j) contains grass, or 0 otherwise.In one move, you can choose one row and one column and cut all the grass in this row and this column. In other words, you choose the row x and the column y, then you cut the grass in all cells a_{x, i} and all cells a_{i, y} for all i from 1 to 2. After you cut the grass from a cell, it becomes empty (i. e. its value is replaced by 0).Your task is to find the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all a_{i, j} zeros).You have to answer t independent test cases.InputThe first line of the input contains one integer t (1 \le t \le 16) — the number of test cases. Then t test cases follow.The test case consists of two lines, each of these lines contains two integers. The j-th integer in the i-th row is a_{i, j}. If a_{i, j} = 0 then the cell (i, j) is empty, and if a_{i, j} = 1 the cell (i, j) contains grass.OutputFor each test case, print one integer — the minimum number of moves required to cut the grass in all non-empty cells of the field (i. e. make all a_{i, j} zeros) in the corresponding test case.ExampleInput 30 00 01 00 11 11 1Output 0 1 2
30 00 01 00 11 11 1
0 1 2
1 second
256 megabytes
['implementation', '*800']
F. Puzzletime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPupils Alice and Ibragim are best friends. It's Ibragim's birthday soon, so Alice decided to gift him a new puzzle. The puzzle can be represented as a matrix with 2 rows and n columns, every element of which is either 0 or 1. In one move you can swap two values in neighboring cells.More formally, let's number rows 1 to 2 from top to bottom, and columns 1 to n from left to right. Also, let's denote a cell in row x and column y as (x, y). We consider cells (x_1, y_1) and (x_2, y_2) neighboring if |x_1 - x_2| + |y_1 - y_2| = 1.Alice doesn't like the way in which the cells are currently arranged, so she came up with her own arrangement, with which she wants to gift the puzzle to Ibragim. Since you are her smartest friend, she asked you to help her find the minimal possible number of operations in which she can get the desired arrangement. Find this number, or determine that it's not possible to get the new arrangement.InputThe first line contains an integer n (1 \leq n \leq 200\,000) — the number of columns in the puzzle.Following two lines describe the current arrangement on the puzzle. Each line contains n integers, every one of which is either 0 or 1.The last two lines describe Alice's desired arrangement in the same format.OutputIf it is possible to get the desired arrangement, print the minimal possible number of steps, otherwise print -1.ExamplesInput 5 0 1 0 1 0 1 1 0 0 1 1 0 1 0 1 0 0 1 1 0 Output 5 Input 3 1 0 0 0 0 0 0 0 0 0 0 0 Output -1 NoteIn the first example the following sequence of swaps will suffice: (2, 1), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (1, 4), (1, 5), (2, 5), (2, 4). It can be shown that 5 is the minimal possible answer in this case.In the second example no matter what swaps you do, you won't get the desired arrangement, so the answer is -1.
5 0 1 0 1 0 1 1 0 0 1 1 0 1 0 1 0 0 1 1 0
5
1 second
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*2600']
E. Serega the Piratetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle pirate Serega robbed a ship with puzzles of different kinds. Among all kinds, he liked only one, the hardest.A puzzle is a table of n rows and m columns, whose cells contain each number from 1 to n \cdot m exactly once.To solve a puzzle, you have to find a sequence of cells in the table, such that any two consecutive cells are adjacent by the side in the table. The sequence can have arbitrary length and should visit each cell one or more times. For a cell containing the number i, denote the position of the first occurrence of this cell in the sequence as t_i. The sequence solves the puzzle, if t_1 < t_2 < \dots < t_{nm}. In other words, the cell with number x should be first visited before the cell with number x + 1 for each x.Let's call a puzzle solvable, if there exists at least one suitable sequence.In one move Serega can choose two arbitrary cells in the table (not necessarily adjacent by the side) and swap their numbers. He would like to know the minimum number of moves to make his puzzle solvable, but he is too impatient. Thus, please tell if the minimum number of moves is 0, 1, or at least 2. In the case, where 1 move is required, please also find the number of suitable cell pairs to swap.InputIn the first line there are two whole positive numbers n, m (1 \leq n\cdot m \leq 400\,000) — table dimensions.In the next n lines there are m integer numbers a_{i1}, a_{i2}, \dots, a_{im} (1 \le a_{ij} \le nm). It is guaranteed that every number from 1 to nm occurs exactly once in the table.OutputLet a be the minimum number of moves to make the puzzle solvable.If a = 0, print 0.If a = 1, print 1 and the number of valid swaps.If a \ge 2, print 2. ExamplesInput 3 3 2 1 3 6 7 4 9 8 5 Output 0 Input 2 3 1 6 4 3 2 5 Output 1 3 Input 1 6 1 6 5 4 3 2 Output 2 NoteIn the first example the sequence (1, 2), (1, 1), (1, 2), (1, 3), (2, 3), (3, 3), (2, 3), (1, 3), (1, 2), (1, 1), (2, 1), (2, 2), (3, 2), (3, 1) solves the puzzle, so the answer is 0.The puzzle in the second example can't be solved, but it's solvable after any of three swaps of cells with values (1, 5), (1, 6), (2, 6). The puzzle from the third example requires at least two swaps, so the answer is 2.
3 3 2 1 3 6 7 4 9 8 5
0
2 seconds
256 megabytes
['brute force', 'constructive algorithms', '*2600']
D. River Lockstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently in Divanovo, a huge river locks system was built. There are now n locks, the i-th of them has the volume of v_i liters, so that it can contain any amount of water between 0 and v_i liters. Each lock has a pipe attached to it. When the pipe is open, 1 liter of water enters the lock every second.The locks system is built in a way to immediately transfer all water exceeding the volume of the lock i to the lock i + 1. If the lock i + 1 is also full, water will be transferred further. Water exceeding the volume of the last lock pours out to the river. The picture illustrates 5 locks with two open pipes at locks 1 and 3. Because locks 1, 3, and 4 are already filled, effectively the water goes to locks 2 and 5. Note that the volume of the i-th lock may be greater than the volume of the i + 1-th lock.To make all locks work, you need to completely fill each one of them. The mayor of Divanovo is interested in q independent queries. For each query, suppose that initially all locks are empty and all pipes are closed. Then, some pipes are opened simultaneously. For the j-th query the mayor asks you to calculate the minimum number of pipes to open so that all locks are filled no later than after t_j seconds.Please help the mayor to solve this tricky problem and answer his queries. InputThe first lines contains one integer n (1 \le n \le 200\,000) — the number of locks. The second lines contains n integers v_1, v_2, \dots, v_n (1 \le v_i \le 10^9)) — volumes of the locks. The third line contains one integer q (1 \le q \le 200\,000) — the number of queries. Each of the next q lines contains one integer t_j (1 \le t_j \le 10^9) — the number of seconds you have to fill all the locks in the query j. OutputPrint q integers. The j-th of them should be equal to the minimum number of pipes to turn on so that after t_j seconds all of the locks are filled. If it is impossible to fill all of the locks in given time, print -1. ExamplesInput 5 4 1 5 4 1 6 1 6 2 3 4 5 Output -1 3 -1 -1 4 3 Input 5 4 4 4 4 4 6 1 3 6 5 2 4 Output -1 -1 4 4 -1 5 NoteThere are 6 queries in the first example test. In the queries 1, 3, 4 the answer is -1. We need to wait 4 seconds to fill the first lock even if we open all the pipes. In the sixth query we can open pipes in locks 1, 3, and 4. After 4 seconds the locks 1 and 4 are full. In the following 1 second 1 liter of water is transferred to the locks 2 and 5. The lock 3 is filled by its own pipe. Similarly, in the second query one can open pipes in locks 1, 3, and 4.In the fifth query one can open pipes 1, 2, 3, 4.
5 4 1 5 4 1 6 1 6 2 3 4 5
-1 3 -1 -1 4 3
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', 'math', '*1900']
C. Helping the Naturetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLittle Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are n trees growing near the path, the current levels of moisture of each tree are denoted by the array a_1, a_2, \dots, a_n. Leon has learned three abilities which will help him to dry and water the soil. Choose a position i and decrease the level of moisture of the trees 1, 2, \dots, i by 1. Choose a position i and decrease the level of moisture of the trees i, i + 1, \dots, n by 1. Increase the level of moisture of all trees by 1. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to 0.InputThe first line contains a single integer t (1 \le t \le 2 \cdot 10^4)  — the number of test cases. The description of t test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 200\,000).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \leq a_i \leq 10^9) — the initial levels of trees moisture. It is guaranteed that the sum of n over all test cases doesn't exceed 200\,000.OutputFor each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.ExampleInput 4 3 -2 -2 -2 3 10 4 7 4 4 -4 4 -4 5 1 -2 3 -4 5 Output 2 13 36 33 NoteIn the first test case it's enough to apply the operation of adding 1 to the whole array 2 times. In the second test case you can apply the operation of decreasing 4 times on the prefix of length 3 and get an array 6, 0, 3. After that apply the operation of decreasing 6 times on the prefix of length 1 and 3 times on the suffix of length 1. In total, the number of actions will be 4 + 6 + 3 = 13. It can be shown that it's impossible to perform less actions to get the required array, so the answer is 13.
4 3 -2 -2 -2 3 10 4 7 4 4 -4 4 -4 5 1 -2 3 -4 5
2 13 36 33
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1700']
B. Palindromic Numbers time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDuring a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers 121, 66, 98989 are palindromes, and 103, 239, 1241 are not palindromes.Alina understands that a valid number always exist. Help her find one!InputThe first line of input data contains an integer t (1 \leq t \leq 100) — the number of test cases. Next, descriptions of t test cases follow.The first line of each test case contains a single integer n (2 \leq n \leq 100\,000) — the length of the number that is written on the ground.The second line of contains the positive n-digit integer without leading zeroes — the number itself.It is guaranteed that the sum of the values n over all test cases does not exceed 100\,000.OutputFor each of t test cases print an answer — a positive n-digit integer without leading zeros, such that the sum of the input integer and this number is a palindrome.We can show that at least one number satisfying the constraints exists. If there are multiple solutions, you can output any of them.ExampleInput 3 2 99 4 1023 3 385 Output 32 8646 604NoteIn the first test case 99 + 32 = 131 is a palindrome. Note that another answer is 12, because 99 + 12 = 111 is also a palindrome.In the second test case 1023 + 8646 = 9669.In the third test case 385 + 604 = 989.
3 2 99 4 1023 3 385
32 8646 604
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'math', '*1100']
A. Optimal Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a table a of size n \times m. We will consider the table rows numbered from top to bottom from 1 to n, and the columns numbered from left to right from 1 to m. We will denote a cell that is in the i-th row and in the j-th column as (i, j). In the cell (i, j) there is written a number (i - 1) \cdot m + j, that is a_{ij} = (i - 1) \cdot m + j.A turtle initially stands in the cell (1, 1) and it wants to come to the cell (n, m). From the cell (i, j) it can in one step go to one of the cells (i + 1, j) or (i, j + 1), if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path. For example, with n = 2 and m = 3 the table will look as shown above. The turtle can take the following path: (1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3). The cost of such way is equal to a_{11} + a_{12} + a_{13} + a_{23} = 12. On the other hand, the paths (1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1) and (1, 1) \rightarrow (1, 3) are incorrect, because in the first path the turtle can't make a step (2, 2) \rightarrow (2, 1), and in the second path it can't make a step (1, 1) \rightarrow (1, 3).You are asked to tell the turtle a minimal possible cost of a path from the cell (1, 1) to the cell (n, m). Please note that the cells (1, 1) and (n, m) are a part of the way.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of test cases follows.A single line of each test case contains two integers n and m (1 \leq n, m \leq 10^4) — the number of rows and columns of the table a respectively.OutputFor each test case output a single integer — a minimal possible cost of a path from the cell (1, 1) to the cell (n, m).ExampleInput 71 12 33 27 11 105 510000 10000Output 1 12 13 28 55 85 500099995000 NoteIn the first test case the only possible path consists of a single cell (1, 1).The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from (1, 1) to (n, m). Both paths visit every cell in the table.
71 12 33 27 11 105 510000 10000
1 12 13 28 55 85 500099995000
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*800']
E. Three Days Gracetime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIbti was thinking about a good title for this problem that would fit the round theme (numerus ternarium). He immediately thought about the third derivative, but that was pretty lame so he decided to include the best band in the world — Three Days Grace.You are given a multiset A with initial size n, whose elements are integers between 1 and m. In one operation, do the following: select a value x from the multiset A, then select two integers p and q such that p, q > 1 and p \cdot q = x. Insert p and q to A, delete x from A. Note that the size of the multiset A increases by 1 after each operation. We define the balance of the multiset A as \max(a_i) - \min(a_i). Find the minimum possible balance after performing any number (possible zero) of operations.InputThe first line of the input contains a single integer t (1 \le t \le 10^5) — the number of test cases.The second line of each test case contains two integers n and m (1 \le n \le 10^6, 1 \le m \le 5 \cdot 10^6) — the initial size of the multiset, and the maximum value of an element.The third line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le m) — the elements in the initial multiset.It is guaranteed that the sum of n across all test cases does not exceed 10^6 and the sum of m across all test cases does not exceed 5 \cdot 10^6.OutputFor each test case, print a single integer — the minimum possible balance.ExampleInput 45 102 4 2 4 23 5012 2 32 406 352 51 5Output 0 1 2 4 NoteIn the first test case, we can apply the operation on each of the 4s with (p,q) = (2,2) and make the multiset \{2,2,2,2,2,2,2\} with balance \max(\{2,2,2,2,2,2,2\}) - \min(\{2,2,2,2,2,2,2\}) = 0. It is obvious we cannot make this balance less than 0.In the second test case, we can apply an operation on 12 with (p,q) = (3,4). After this our multiset will be \{3,4,2,3\}. We can make one more operation on 4 with (p,q) = (2,2), making the multiset \{3,2,2,2,3\} with balance equal to 1.In the third test case, we can apply an operation on 35 with (p,q) = (5,7). The final multiset is \{6,5,7\} and has a balance equal to 7-5 = 2.In the forth test case, we cannot apply any operation, so the balance is 5 - 1 = 4.
45 102 4 2 4 23 5012 2 32 406 352 51 5
0 1 2 4
4 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'math', 'number theory', 'two pointers', '*2600']
D. Almost Triple Deletionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n and an array a_1,a_2,\ldots,a_n.In one operation, you can choose an index i (1 \le i \lt n) for which a_i \neq a_{i+1} and delete both a_i and a_{i+1} from the array. After deleting a_i and a_{i+1}, the remaining parts of the array are concatenated.For example, if a=[1,4,3,3,6,2], then after performing an operation with i=2, the resulting array will be [1,3,6,2].What is the maximum possible length of an array of equal elements obtainable from a by performing several (perhaps none) of the aforementioned operations?InputEach test contains multiple test cases. The first line of input contains one integer t (1 \le t \le 1000) — the number of test cases. The following lines contain the descriptions of the test cases.The first line of each test case contains a single integer n (1 \le n \le 5000) — the length of array a.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le n) — the elements of array a.It is guaranteed that the sum of n across all test cases does not exceed 10\,000.OutputFor each testcase, print a single integer, the maximum possible length of an array of equal elements obtainable from a by performing a sequence of operations.ExampleInput 571 2 3 2 1 3 31161 1 1 2 2 281 1 2 2 3 3 1 1121 5 2 3 3 3 4 4 4 4 3 3Output 3 1 0 4 2 NoteFor the first testcase, an optimal sequence of operations would be: [1,2,3,2,1,3,3] \rightarrow [3,2,1,3,3] \rightarrow [3,3,3].For the second testcase, all elements in the array are already equal.For the third testcase, the only possible sequence of operations is: [1,1,1,2,2,2] \rightarrow [1,1,2,2] \rightarrow [1,2] \rightarrow []. Note that, according to the statement, the elements deleted at each step must be different.For the fourth testcase, the optimal sequence of operations is: [1,1,2,2,3,3,1,1] \rightarrow [1,1,2,3,1,1] \rightarrow [1,1,1,1].For the fifth testcase, one possible reachable array of two equal elements is [4,4].
571 2 3 2 1 3 31161 1 1 2 2 281 1 2 2 3 3 1 1121 5 2 3 3 3 4 4 4 4 3 3
3 1 0 4 2
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', '*2300']
C. The Third Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a_1,a_2,\ldots,a_n of integers from 0 to n - 1. Your task is to find how many permutations b_1,b_2,\ldots,b_n are similar to permutation a. Two permutations a and b of size n are considered similar if for all intervals [l,r] (1 \le l \le r \le n), the following condition is satisfied: \operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]), where the \operatorname{MEX} of a collection of integers c_1,c_2,\ldots,c_k is defined as the smallest non-negative integer x which does not occur in collection c. For example, \operatorname{MEX}([1,2,3,4,5])=0, and \operatorname{MEX}([0,1,2,4,5])=3.Since the total number of such permutations can be very large, you will have to print its remainder modulo 10^9+7.In this problem, a permutation of size n is an array consisting of n distinct integers from 0 to n-1 in arbitrary order. For example, [1,0,2,4,3] is a permutation, while [0,1,1] is not, since 1 appears twice in the array. [0,1,3] is also not a permutation, since n=3 and there is a 3 in the array.InputEach test contains multiple test cases. The first line of input contains one integer t (1 \le t \le 10^4) — the number of test cases. The following lines contain the descriptions of the test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the size of permutation a.The second line of each test case contains n distinct integers a_1,a_2,\ldots,a_n (0 \le a_i \lt n) — the elements of permutation a.It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, print a single integer, the number of permutations similar to permutation a, taken modulo 10^9+7.ExampleInput 554 0 3 2 11040 1 2 361 2 4 0 5 381 3 7 2 5 0 6 4Output 2 1 1 4 72 NoteFor the first test case, the only permutations similar to a=[4,0,3,2,1] are [4,0,3,2,1] and [4,0,2,3,1].For the second and third test cases, the given permutations are only similar to themselves.For the fourth test case, there are 4 permutations similar to a=[1,2,4,0,5,3]: [1,2,4,0,5,3]; [1,2,5,0,4,3]; [1,4,2,0,5,3]; [1,5,2,0,4,3].
554 0 3 2 11040 1 2 361 2 4 0 5 381 3 7 2 5 0 6 4
2 1 1 4 72
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'math', '*1700']
B. Almost Ternary Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two even integers n and m. Your task is to find any binary matrix a with n rows and m columns where every cell (i,j) has exactly two neighbours with a different value than a_{i,j}.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell (x,y) are: (x-1,y), (x,y+1), (x+1,y) and (x,y-1).It can be proven that under the given constraints, an answer always exists.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 100) — the number of test cases. The following lines contain the descriptions of the test cases.The only line of each test case contains two even integers n and m (2 \le n,m \le 50) — the height and width of the binary matrix, respectively.OutputFor each test case, print n lines, each of which contains m numbers, equal to 0 or 1 — any binary matrix which satisfies the constraints described in the statement.It can be proven that under the given constraints, an answer always exists.ExampleInput 32 42 24 4Output 1 0 0 1 0 1 1 0 1 0 0 1 1 0 1 0 0 0 1 1 1 1 0 0 0 1 0 1NoteWhite means 0, black means 1. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case
32 42 24 4
1 0 0 1 0 1 1 0 1 0 0 1 1 0 1 0 0 0 1 1 1 1 0 0 0 1 0 1
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'matrices', '*900']
A. The Third Three Number Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer n. Your task is to find any three integers a, b and c (0 \le a, b, c \le 10^9) for which (a\oplus b)+(b\oplus c)+(a\oplus c)=n, or determine that there are no such integers.Here a \oplus b denotes the bitwise XOR of a and b. For example, 2 \oplus 4 = 6 and 3 \oplus 1=2.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The following lines contain the descriptions of the test cases.The only line of each test case contains a single integer n (1 \le n \le 10^9). OutputFor each test case, print any three integers a, b and c (0 \le a, b, c \le 10^9) for which (a\oplus b)+(b\oplus c)+(a\oplus c)=n. If no such integers exist, print -1.ExampleInput 541122046194723326Output 3 3 1 -1 2 4 6 69 420 666 12345678 87654321 100000000 NoteIn the first test case, a=3, b=3, c=1, so (3 \oplus 3)+(3 \oplus 1) + (3 \oplus 1)=0+2+2=4.In the second test case, there are no solutions.In the third test case, (2 \oplus 4)+(4 \oplus 6) + (2 \oplus 6)=6+2+4=12.
541122046194723326
3 3 1 -1 2 4 6 69 420 666 12345678 87654321 100000000
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
G. Long Binary Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a binary string t of length 10^{100}, and initally all of its bits are \texttt{0}. You are given a binary string s, and perform the following operation some times: Select some substring of t, and replace it with its XOR with s.^\dagger After several operations, the string t has exactly two bits \texttt{1}; that is, there are exactly two distinct indices p and q such that the p-th and q-th bits of t are \texttt{1}, and the rest of the bits are \texttt{0}. Find the lexicographically largest^\ddagger string t satisfying these constraints, or report that no such string exists.^\dagger Formally, choose an index i such that 0 \leq i \leq 10^{100}-|s|. For all 1 \leq j \leq |s|, if s_j = \texttt{1}, then toggle t_{i+j}. That is, if t_{i+j}=\texttt{0}, set t_{i+j}=\texttt{1}. Otherwise if t_{i+j}=\texttt{1}, set t_{i+j}=\texttt{0}.^\ddagger A binary string a is lexicographically larger than a binary string b of the same length if in the first position where a and b differ, the string a has a bit \texttt{1} and the corresponding bit in b is \texttt{0}.InputThe only line of each test contains a single binary string s (1 \leq |s| \leq 35).OutputIf no string t exists as described in the statement, output -1. Otherwise, output the integers p and q (1 \leq p < q \leq 10^{100}) such that the p-th and q-th bits of the lexicographically maximal t are \texttt{1}.ExamplesInput 1 Output 1 2 Input 001 Output 3 4 Input 1111 Output 1 5 Input 00000 Output -1 Input 00000111110000011111000001111101010 Output 6 37452687 NoteIn the first test, you can perform the following operations. \texttt{00000}\ldots \to \color{red}{\texttt{1}}\texttt{0000}\ldots \to \texttt{1}\color{red}{\texttt{1}}\texttt{000}\ldotsIn the second test, you can perform the following operations. \texttt{00000}\ldots \to \color{red}{\texttt{001}}\texttt{00}\ldots \to \texttt{0}\color{red}{\texttt{011}}\texttt{0}\ldotsIn the third test, you can perform the following operations. \texttt{00000}\ldots \to \color{red}{\texttt{1111}}\texttt{0}\ldots \to \texttt{1}\color{red}{\texttt{0001}}\ldotsIt can be proven that these strings t are the lexicographically largest ones.In the fourth test, you can't make a single bit \texttt{1}, so it is impossible.
1
1 2
2 seconds
256 megabytes
['bitmasks', 'math', 'matrices', 'meet-in-the-middle', 'number theory', '*2900']
F. Equal Reversaltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an array a of length n. You may perform the following operation on it: Choose two indices l and r where 1 \le l \le r \le n and a_l = a_r. Then, reverse the subsegment from the l-th to the r-th element, i. e. set [a_l, a_{l + 1}, \ldots, a_{r - 1}, a_r] to [a_r, a_{r-1}, \ldots, a_{l+1}, a_l]. You are also given another array b of length n which is a permutation of a. Find a sequence of at most n^2 operations that transforms array a into b, or report that no such sequence exists.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \le n \le 500) — the length of array a and b.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — elements of the array a.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n) — elements of the array b.It is guaranteed that b is a permutation of a.It is guaranteed that the sum of n over all test cases does not exceed 500.OutputFor each test case, output "NO" (without quotes) if it is impossible to turn a into b using at most n^2 operations.Otherwise, output "YES" (without quotes). Then output an integer k (0 \leq k \leq n^2) denoting the number of operations you will perform. Note that you don't have to minimize the number of operations.Afterwards, output k lines. The i-th line should contain two integers l_i and r_i (1 \leq l_i \leq r_i \leq n) — the left and right indices for the i-th operation.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).If there are multiple possible sequences of operations, you may output any of them.ExampleInput 581 2 4 3 1 2 1 11 1 3 4 2 1 2 171 2 3 1 3 2 31 3 2 3 1 2 331 1 21 2 121 22 1111Output YES 2 5 8 1 6 YES 2 1 4 3 6 NO NO YES 0 NoteIn the first test case, we can perform the following operations: [1,2,4,3,1,2,1,1] \xrightarrow[l=5,\,r=8]{} [1,2,4,3,1,1,2,1] \xrightarrow[l=1,\,r=6]{} [1,1,3,4,2,1,2,1].In the second test case, we can perform the following operations: [1,2,3,1,3,2,3] \xrightarrow[l=1,\,r=4]{} [1,3,2,1,3,2,3] \xrightarrow[l=3,\,r=6]{} [1,3,2,3,1,2,3].It can be proven that it is impossible to turn a into b in the third and fourth test cases.
581 2 4 3 1 2 1 11 1 3 4 2 1 2 171 2 3 1 3 2 31 3 2 3 1 2 331 1 21 2 121 22 1111
YES 2 5 8 1 6 YES 2 1 4 3 6 NO NO YES 0
1 second
256 megabytes
['constructive algorithms', 'graphs', 'implementation', 'math', '*2800']
E. PermutationForces IItime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation a of length n. Recall that permutation is an array consisting of n distinct integers from 1 to n in arbitrary order.You have a strength of s and perform n moves on the permutation a. The i-th move consists of the following: Pick two integers x and y such that i \leq x \leq y \leq \min(i+s,n), and swap the positions of the integers x and y in the permutation a. Note that you can select x=y in the operation, in which case no swap will occur. You want to turn a into another permutation b after n moves. However, some elements of b are missing and are replaced with -1 instead. Count the number of ways to replace each -1 in b with some integer from 1 to n so that b is a permutation and it is possible to turn a into b with a strength of s. Since the answer can be large, output it modulo 998\,244\,353.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and s (1 \leq n \leq 2 \cdot 10^5; 1 \leq s \leq n) — the size of the permutation and your strength, respectively.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of a. All elements of a are distinct.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n or b_i = -1) — the elements of b. All elements of b that are not equal to -1 are distinct.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of ways to fill up the permutation b so that it is possible to turn a into b using a strength of s, modulo 998\,244\,353.ExampleInput 63 12 1 33 -1 -13 22 1 33 -1 -14 11 4 3 24 3 1 26 44 2 6 3 1 56 1 5 -1 3 -17 41 3 6 2 7 4 52 5 -1 -1 -1 4 -114 141 2 3 4 5 6 7 8 9 10 11 12 13 14-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1Output 1 2 0 2 12 331032489 NoteIn the first test case, a=[2,1,3]. There are two possible ways to fill out the -1s in b to make it a permutation: [3,1,2] or [3,2,1]. We can make a into [3,1,2] with a strength of 1 as follows: [2,1,3] \xrightarrow[x=1,\,y=1]{} [2,1,3] \xrightarrow[x=2,\,y=3]{} [3,1,2] \xrightarrow[x=3,\,y=3]{} [3,1,2]. It can be proven that it is impossible to make [2,1,3] into [3,2,1] with a strength of 1. Thus only one permutation b satisfies the constraints, so the answer is 1.In the second test case, a and b the same as the previous test case, but we now have a strength of 2. We can make a into [3,2,1] with a strength of 2 as follows: [2,1,3] \xrightarrow[x=1,\,y=3]{} [2,3,1] \xrightarrow[x=2,\,y=3]{} [3,2,1] \xrightarrow[x=3,\,y=3]{} [3,2,1]. We can still make a into [3,1,2] using a strength of 1 as shown in the previous test case, so the answer is 2. In the third test case, there is only one permutation b. It can be shown that it is impossible to turn a into b, so the answer is 0.
63 12 1 33 -1 -13 22 1 33 -1 -14 11 4 3 24 3 1 26 44 2 6 3 1 56 1 5 -1 3 -17 41 3 6 2 7 4 52 5 -1 -1 -1 4 -114 141 2 3 4 5 6 7 8 9 10 11 12 13 14-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
1 2 0 2 12 331032489
1 second
256 megabytes
['brute force', 'combinatorics', 'greedy', 'sortings', 'trees', 'two pointers', '*2300']
D. Fixed Point Guessingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Initially, there is an array a = [1, 2, \ldots, n], where n is an odd positive integer. The jury has selected \frac{n-1}{2} disjoint pairs of elements, and then the elements in those pairs are swapped. For example, if a=[1,2,3,4,5], and the pairs 1 \leftrightarrow 4 and 3 \leftrightarrow 5 are swapped, then the resulting array is [4, 2, 5, 1, 3]. As a result of these swaps, exactly one element will not change position. You need to find this element.To do this, you can ask several queries. In each query, you can pick two integers l and r (1 \leq l \leq r \leq n). In return, you will be given the elements of the subarray [a_l, a_{l + 1}, \dots, a_r] sorted in increasing order. Find the element which did not change position. You can make at most \mathbf{15} queries.The array a is fixed before the interaction and does not change after your queries.Recall that an array b is a subarray of the array a if b can be obtained from a 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 an integer t (1 \leq t \leq 500) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (3 \leq n < 10^4; n is odd) — the length of the array a.After reading the first line of each test case, you should begin the interaction.It is guaranteed that the sum of n over all test cases does not exceed 10^4.InteractionFor each test case, begin the interaction by reading the integer n.To make a query, output "\texttt{?}\;l\;r" (1 \leq l \leq r \leq n) without quotes. Afterwards, you should read in r-l+1 integers — the integers a_l, a_{l + 1}, \dots, a_r, in increasing order. You can make at most 15 such queries in a single test case.If you receive the integer -1 instead of an answer or the integer n, it means your program has made an invalid query, has exceed the limit of queries, or has given incorrect answer on the previous test case. Your program must terminate immediately to receive a Wrong Answer verdict. Otherwise you can get an arbitrary verdict because your solution will continue to read from a closed stream.When you are ready to give the final answer, output "\texttt{!}\;x" (1 \leq x \leq n) without quotes — the element that did not change position. Giving this answer does not count towards the limit of 15 queries. Afterwards, your program must continue to solve the remaining test cases, or exit if all test cases have been solved.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. HacksTo make a hack, use the following format. The first line must contain an integer t (1 \leq t \leq 500) — the number of test cases. The description of the test cases follows.The first line of each test case must contain an integer n (3 \leq n < 10^4; n is odd) — the length of the array a.The second line of each test case must contain n space-separated integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of a. The array a should be the result of \frac{n-1}{2} disjoint swaps on the array [1,2,\dots,n].ExampleInput 2 5 1 2 4 5 1 3 5 3 1Output ? 1 4 ? 3 5 ! 2 ? 1 1 ! 1 NoteIn the first test, the interaction proceeds as follows. SolutionJuryExplanation\texttt{2}There are 2 test cases.\texttt{5}In the first test case, the hidden array is [4,2,5,1,3], with length 5.\texttt{? 1 4}\texttt{1 2 4 5}The solution requests the subarray [4,2,5,1] in increasing order, and the jury responds with [1,2,4,5].\texttt{? 3 5}\texttt{1 3 5}The solution requests the subarray [5,1,3] in increasing order, and the jury responds with [1,3,5].\texttt{! 2}The solution has somehow determined that a_2=2, and outputs it. Since the output is correct, the jury continues to the next test case.\texttt{3}In the second test case, the hidden array is [1,3,2], with length 3.\texttt{? 1 1}\texttt{1}The solution requests the number [1] only, and the jury responds with [1].\texttt{! 1}The solution has determined that a_1=1, and outputs it. Since the output is correct and there are no more test cases, the jury and the solution exit. Note that the line breaks in the example input and output are for the sake of clarity, and do not occur in the real interaction.
2 5 1 2 4 5 1 3 5 3 1
? 1 4 ? 3 5 ! 2 ? 1 1 ! 1
1 second
256 megabytes
['binary search', 'constructive algorithms', 'interactive', '*1600']
C. 3SUM Closuretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. The array is called 3SUM-closed if for all distinct indices i, j, k, the sum a_i + a_j + a_k is an element of the array. More formally, a is 3SUM-closed if for all integers 1 \leq i < j < k \leq n, there exists some integer 1 \leq l \leq n such that a_i + a_j + a_k = a_l.Determine if a is 3SUM-closed.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains an integer n (3 \leq n \leq 2 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-10^9 \leq a_i \leq 10^9) — the elements of the array.It is guaranteed that the sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" (without quotes) if a is 3SUM-closed and "NO" (without quotes) otherwise.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 43-1 0 151 -2 -2 1 -360 0 0 0 0 04-1 2 -3 4Output YES NO YES NO NoteIn the first test case, there is only one triple where i=1, j=2, k=3. In this case, a_1 + a_2 + a_3 = 0, which is an element of the array (a_2 = 0), so the array is 3SUM-closed.In the second test case, a_1 + a_4 + a_5 = -1, which is not an element of the array. Therefore, the array is not 3SUM-closed.In the third test case, a_i + a_j + a_k = 0 for all distinct i, j, k, and 0 is an element of the array, so the array is 3SUM-closed.
43-1 0 151 -2 -2 1 -360 0 0 0 0 04-1 2 -3 4
YES NO YES NO
1 second
256 megabytes
['brute force', 'data structures', '*1300']
B. Rising Sandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n piles of sand where the i-th pile has a_i blocks of sand. The i-th pile is called too tall if 1 < i < n and a_i > a_{i-1} + a_{i+1}. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer k. An operation consists of picking k consecutive piles of sand and adding one unit of sand to them all. Formally, pick 1 \leq l,r \leq n such that r-l+1=k. Then for all l \leq i \leq r, update a_i \gets a_i+1.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (3 \leq n \leq 2 \cdot 10^5; 1 \leq k \leq n) — the number of piles of sand and the size of the operation, respectively.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the sizes of the piles.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum number of piles that are simultaneously too tall after some (possibly zero) operations.ExampleInput 35 22 9 2 4 14 41 3 2 13 11 3 1Output 2 0 1 NoteIn the first test case, we can perform the following three operations: Add one unit of sand to piles 1 and 2: [\color{red}{3}, \color{red}{10}, 2, 4, 1]. Add one unit of sand to piles 4 and 5: [3, 10, 2, \color{red}{5}, \color{red}{2}]. Add one unit of sand to piles 3 and 4: [3, 10, \color{red}{3}, \color{red}{6}, 2]. Now piles 2 and 4 are too tall, so in this case the answer is 2. It can be shown that it is impossible to make more than 2 piles too tall.In the second test case, any operation will increase all piles by 1 unit, so the number of too tall piles will always be 0.In the third test case, we can increase any pile by 1 unit of sand. It can be shown that the maximum number of too tall piles is 1.
35 22 9 2 4 14 41 3 2 13 11 3 1
2 0 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*800']
A. XOR Mixuptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an array a with n-1 integers. Let x be the bitwise XOR of all elements of the array. The number x is added to the end of the array a (now it has length n), and then the elements are shuffled.You are given the newly formed array a. What is x? If there are multiple possible values of x, you can output any of them.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 100) — the number of integers in the resulting array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 127) — the elements of the newly formed array a.Additional constraint on the input: the array a is made by the process described in the statement; that is, some value of x exists.OutputFor each test case, output a single integer — the value of x, as described in the statement. If there are multiple possible values of x, output any of them.ExampleInput 444 3 2 556 1 10 7 1066 6 6 6 6 63100 100 0Output 3 7 6 0 NoteIn the first test case, one possible array a is a=[2, 5, 4]. Then x = 2 \oplus 5 \oplus 4 = 3 (\oplus denotes the bitwise XOR), so the new array is [2, 5, 4, 3]. Afterwards, the array is shuffled to form [4, 3, 2, 5].In the second test case, one possible array a is a=[1, 10, 6, 10]. Then x = 1 \oplus 10 \oplus 6 \oplus 10 = 7, so the new array is [1, 10, 6, 10, 7]. Afterwards, the array is shuffled to form [6, 1, 10, 7, 10].In the third test case, all elements of the array are equal to 6, so x=6.In the fourth test case, one possible array a is a=[100, 100]. Then x = 100 \oplus 100 = 0, so the new array is [100, 100, 0]. Afterwards, the array is shuffled to form [100, 100, 0]. (Note that after the shuffle, the array can remain the same.)
444 3 2 556 1 10 7 1066 6 6 6 6 63100 100 0
3 7 6 0
1 second
256 megabytes
['bitmasks', 'brute force', '*800']
F. Too Many Constraintstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are asked to build an array a, consisting of n integers, each element should be from 1 to k.The array should be non-decreasing (a_i \le a_{i+1} for all i from 1 to n-1). You are also given additional constraints on it. Each constraint is of one of three following types: 1~i~x: a_i should not be equal to x; 2~i~j~x: a_i + a_j should be less than or equal to x; 3~i~j~x: a_i + a_j should be greater than or equal to x. Build any non-decreasing array that satisfies all constraints or report that no such array exists.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains three integers n, m and k (2 \le n \le 2 \cdot 10^4; 0 \le m \le 2 \cdot 10^4; 2 \le k \le 10).The i-th of the next m lines contains a description of a constraint. Each constraint is of one of three following types: 1~i~x (1 \le i \le n; 1 \le x \le k): a_i should not be equal to x; 2~i~j~x (1 \le i < j \le n; 2 \le x \le 2 \cdot k): a_i + a_j should be less than or equal to x; 3~i~j~x (1 \le i < j \le n; 2 \le x \le 2 \cdot k): a_i + a_j should be greater than or equal to x. The sum of n over all testcases doesn't exceed 2 \cdot 10^4. The sum of m over all testcases doesn't exceed 2 \cdot 10^4.OutputFor each testcase, determine if there exists a non-decreasing array that satisfies all conditions. If there is no such array, then print -1. Otherwise, print any valid array — n integers from 1 to k.ExampleInput 4 4 0 4 2 2 3 3 1 2 3 1 2 2 3 3 2 1 1 1 2 2 3 2 3 2 3 2 5 5 5 3 2 5 7 2 4 5 10 3 4 5 6 3 3 4 7 2 1 5 7 Output 1 2 3 4 1 3 -1 1 2 2 5 5
4 4 0 4 2 2 3 3 1 2 3 1 2 2 3 3 2 1 1 1 2 2 3 2 3 2 3 2 5 5 5 3 2 5 7 2 4 5 10 3 4 5 6 3 3 4 7 2 1 5 7
1 2 3 4 1 3 -1 1 2 2 5 5
2 seconds
512 megabytes
['2-sat', 'constructive algorithms', 'graphs', 'implementation', '*2800']
E. Coloringtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n points on the plane, the coordinates of the i-th point are (x_i, y_i). No two points have the same coordinates.The distance between points i and j is defined as d(i,j) = |x_i - x_j| + |y_i - y_j|.For each point, you have to choose a color, represented by an integer from 1 to n. For every ordered triple of different points (a,b,c), the following constraints should be met: if a, b and c have the same color, then d(a,b) = d(a,c) = d(b,c); if a and b have the same color, and the color of c is different from the color of a, then d(a,b) < d(a,c) and d(a,b) < d(b,c). Calculate the number of different ways to choose the colors that meet these constraints.InputThe first line contains one integer n (2 \le n \le 100) — the number of points.Then n lines follow. The i-th of them contains two integers x_i and y_i (0 \le x_i, y_i \le 10^8).No two points have the same coordinates (i. e. if i \ne j, then either x_i \ne x_j or y_i \ne y_j).OutputPrint one integer — the number of ways to choose the colors for the points. Since it can be large, print it modulo 998244353.ExamplesInput 3 1 0 3 0 2 1 Output 9 Input 5 1 2 2 4 3 4 4 4 1 3 Output 240 Input 4 1 0 3 0 2 1 2 0 Output 24 NoteIn the first test, the following ways to choose the colors are suitable: [1, 1, 1]; [2, 2, 2]; [3, 3, 3]; [1, 2, 3]; [1, 3, 2]; [2, 1, 3]; [2, 3, 1]; [3, 1, 2]; [3, 2, 1].
3 1 0 3 0 2 1
9
3 seconds
512 megabytes
['brute force', 'combinatorics', 'constructive algorithms', 'dp', 'geometry', 'graphs', 'greedy', 'implementation', 'math', '*2400']
D. Guess The Stringtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury has chosen a string s consisting of n characters; each character of s is a lowercase Latin letter. Your task is to guess this string; initially, you know only its length.You may ask queries of two types: 1 i — the query of the first type, where i is an integer from 1 to n. In response to this query, the jury will tell you the character s_i; 2 l r — the query of the second type, where l and r are integers such that 1 \le l \le r \le n. In response to this query, the jury will tell you the number of different characters among s_l, s_{l+1}, \dots, s_r. You are allowed to ask no more than 26 queries of the first type, and no more than 6000 queries of the second type. Your task is to restore the string s.For each test in this problem, the string s is fixed beforehand, and will be the same for every submission.InputInitially, the jury program sends one integer n on a separate line — the size of s (1 \le n \le 1000).OutputTo give the answer, print one line ! s with a line break in the end, where s should be the string picked by the jury. After that, your program should flush the output and terminate gracefully.InteractionTo ask a query, you should send one line containing the query, in one of the following formats: ? 1 i — for a query of the first type (1 \le i \le n); ? 2 l r — for a query of the second type (1 \le l \le r \le n). Don't forget to flush the output after sending the query line.The answer to your query will be given on a separate line. For a query of the first type, the answer will be the character s_i. For a query of the second type, the answer will be an integer equal to the number of different characters among s_l, s_{l+1}, \dots, s_r.You are allowed to ask no more than 26 queries of the first type, and no more than 6000 queries of the second type.In case you ask too many queries, or the jury program fails to recognize your query format, the answer to your query will be one integer 0. After receiving 0 as the answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer".ExampleInput 5 4 u 2 g e s 1 Output ? 2 1 5 ? 1 2 ? 2 1 2 ? 1 1 ? 1 3 ? 1 4 ? 2 4 5 ! guess NoteLet's analyze the example of interaction.The string chosen by the jury is guess, so initially the jury sends one integer 5. the first query is ? 2 1 5, which means "count the number of different characters among s_1, s_2, \dots, s_5". The answer to it is 4. the second query is ? 1 2, which means "tell which character is s_2". The answer to it is u. the third query is ? 2 1 2, which means "count the number of different characters among s_1 and s_2". The answer to it is 2. the fourth query is ? 1 1, which means "tell which character is s_1". The answer to it is g. the fifth query is ? 1 3, which means "tell which character is s_3". The answer to it is e. the sixth query is ? 1 4, which means "tell which character is s_4". The answer to it is s. the seventh query is ? 2 4 5, which means "count the number of different characters among s_4 and s_5". The answer to it is 1, so it's possible to deduce that s_4 is the same as s_5.In the end, the answer is submitted as ! guess, and it is deduced correctly.
5 4 u 2 g e s 1
? 2 1 5 ? 1 2 ? 2 1 2 ? 1 1 ? 1 3 ? 1 4 ? 2 4 5 ! guess
4 seconds
512 megabytes
['binary search', 'constructive algorithms', 'interactive', '*1900']
C. awoo's Favorite Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings s and t, both of length n. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions: choose an occurrence of "ab" in s and replace it with "ba"; choose an occurrence of "bc" in s and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string s to make it equal to string t?InputThe first line contains a single integer q (1 \le q \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 10^5) — the length of strings s and t.The second line contains string s of length n. Each character is 'a', 'b' or 'c'.The third line contains string t of length n. Each character is 'a', 'b' or 'c'.The sum of n over all testcases doesn't exceed 10^5.OutputFor each testcase, print "YES" if you can change string s to make it equal to string t by performing an arbitrary amount of moves (possibly, zero). Otherwise, print "NO".ExampleInput 5 3 cab cab 1 a b 6 abbabc bbaacb 10 bcaabababc cbbababaac 2 ba ab Output YES NO YES YES NO
5 3 cab cab 1 a b 6 abbabc bbaacb 10 bcaabababc cbbababaac 2 ba ab
YES NO YES YES NO
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'implementation', 'strings', 'two pointers', '*1400']
B. Promotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe store sells n items, the price of the i-th item is p_i. The store's management is going to hold a promotion: if a customer purchases at least x items, y cheapest of them are free.The management has not yet decided on the exact values of x and y. Therefore, they ask you to process q queries: for the given values of x and y, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of items in the store and the number of queries, respectively.The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le 10^6), where p_i — the price of the i-th item.The following q lines contain two integers x_i and y_i each (1 \le y_i \le x_i \le n) — the values of the parameters x and y in the i-th query.OutputFor each query, print a single integer — the maximum total value of items received for free for one purchase.ExampleInput 5 3 5 3 1 5 2 3 2 1 1 5 3 Output 8 5 6 NoteIn the first query, a customer can buy three items worth 5, 3, 5, the two cheapest of them are 3 + 5 = 8.In the second query, a customer can buy two items worth 5 and 5, the cheapest of them is 5.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is 1 + 2 + 3 = 6.
5 3 5 3 1 5 2 3 2 1 1 5 3
8 5 6
2 seconds
256 megabytes
['greedy', 'sortings', '*900']
A. Parkway Walktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are walking through a parkway near your house. The parkway has n+1 benches in a row numbered from 1 to n+1 from left to right. The distance between the bench i and i+1 is a_i meters.Initially, you have m units of energy. To walk 1 meter of distance, you spend 1 unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed m.Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench n+1 from the bench 1 (and end your walk).You have to answer t independent test cases.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 first line of the test case contains two integers n and m (1 \le n \le 100; 1 \le m \le 10^4).The second line of the test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 100), where a_i is the distance between benches i and i+1.OutputFor each test case, print one integer — the minimum amount of energy you have to restore (by sitting on benches) to reach the bench n+1 from the bench 1 (and end your walk) in the corresponding test case.ExampleInput 3 3 1 1 2 1 4 5 3 3 5 2 5 16 1 2 3 4 5 Output 3 8 0 NoteIn the first test case of the example, you can walk to the bench 2, spending 1 unit of energy, then restore 2 units of energy on the second bench, walk to the bench 3, spending 2 units of energy, restore 1 unit of energy and go to the bench 4.In the third test case of the example, you have enough energy to just go to the bench 6 without sitting at all.
3 3 1 1 2 1 4 5 3 3 5 2 5 16 1 2 3 4 5
3 8 0
1 second
256 megabytes
['greedy', 'implementation', '*800']
H. Maximum Product?time limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a positive integer k. For a multiset of integers S, define f(S) as the following. If the number of elements in S is less than k, f(S)=0. Otherwise, define f(S) as the maximum product you can get by choosing exactly k integers from S. More formally, let |S| denote the number of elements in S. Then, If |S|<k, f(S)=0. Otherwise, f(S)=\max\limits_{T\subseteq S,|T|=k}\left(\prod\limits_{i\in T}i\right). You are given a multiset of integers, A. Compute \sum\limits_{B\subseteq A} f(B) modulo 10^9+7.Note that in this problem, we distinguish the elements by indices instead of values. That is, a multiset consisting of n elements always has 2^n distinct subsets regardless of whether some of its elements are equal.InputThe first line of input contains two integers n and k, where n is the number of elements in A (1\le k\le n\le 600).The second line of input contains n integers a_1,a_2,\dots,a_n, describing the elements in A (-10^9\le a_i\le 10^9).OutputOutput \sum\limits_{B\subseteq A} f(B) modulo 10^9+7.ExamplesInput 3 2 -1 2 4 Output 10Input 3 1 1 1 1 Output 7Input 10 4 -24 -41 9 -154 -56 14 18 53 -7 120 Output 225905161Input 15 5 0 0 2 -2 2 -2 3 -3 -3 4 5 -4 -4 4 5 Output 18119684NoteConsider the first sample. From the definitions we know that f(\varnothing)=0 f(\{-1\})=0 f(\{2\})=0 f(\{4\})=0 f(\{-1,2\})=-2 f(\{-1,4\})=-4 f(\{2,4\})=8 f(\{-1,2,4\})=8 So we should print (0+0+0+0-2-4+8+8)\bmod (10^9+7)=10.In the second example, note that although the multiset consists of three same values, it still has 8 distinct subsets: \varnothing,\{1\},\{1\},\{1\},\{1,1\},\{1,1\},\{1,1\},\{1,1,1\}.
3 2 -1 2 4
10
1.5 seconds
512 megabytes
['brute force', 'combinatorics', 'dp', 'greedy', 'implementation', 'math', 'two pointers', '*3500']
G. Fishingprince Plays With Array Againtime limit per test6 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputSuppose you are given a 1-indexed sequence a of non-negative integers, whose length is n, and two integers x, y. In consecutive t seconds (t can be any positive real number), you can do one of the following operations: Select 1\le i<n, decrease a_i by x\cdot t, and decrease a_{i+1} by y\cdot t. Select 1\le i<n, decrease a_i by y\cdot t, and decrease a_{i+1} by x\cdot t. Define the minimum amount of time (it might be a real number) required to make all elements in the sequence less than or equal to 0 as f(a).For example, when x=1, y=2, it takes 3 seconds to deal with the array [3,1,1,3]. We can: In the first 1.5 seconds do the second operation with i=1. In the next 1.5 seconds do the first operation with i=3. We can prove that it's not possible to make all elements less than or equal to 0 in less than 3 seconds, so f([3,1,1,3])=3.Now you are given a 1-indexed sequence b of positive integers, whose length is n. You are also given positive integers x, y. Process q queries of the following two types: 1 k v: change b_k to v. 2 l r: print f([b_l,b_{l+1},\dots,b_r]). InputThe first line of input contains two integers n and q (2\le n\le 2\cdot 10^5, 1\le q\le 2\cdot 10^5).The second line of input contains two integers x and y (1\le x,y\le 10^6).The third line of input contains n integers b_1,b_2,\ldots,b_n (1\le b_i\le 10^6).This is followed by q lines. Each of these q lines contains three integers. The first integer op is either 1 or 2. If it is 1, it is followed by two integers k, v (1\le k\le n, 1\le v\le 10^6). It means that you should change b_k to v. If it is 2, it is followed by two integers l, r (1\le l<r\le n). It means that you should print f([b_l,b_{l+1},\dots,b_r]). OutputFor each query of type 2, print one real number — the answer to the query. Your answer is considered correct if its absolute error or relative error does not exceed 10^{-9}.ExampleInput 4 3 1 2 3 1 1 4 2 1 4 1 1 1 2 1 3 Output 3.500000000000000 1.000000000000000 NoteLet's analyse the sample.In the first query, we are asked to compute f([3,1,1,4]). The answer is 3.5. One optimal sequence of operations is: In the first 1.5 seconds do the second operation with i=1. In the next 2 seconds do the first operation with i=3. In the third query, we are asked to compute f([1,1,1]). The answer is 1. One optimal sequence of operations is: In the first 0.5 seconds do the second operation with i=1. In the next 0.5 seconds do the first operation with i=2.
4 3 1 2 3 1 1 4 2 1 4 1 1 1 2 1 3
3.500000000000000 1.000000000000000
6 seconds
1024 megabytes
['brute force', 'data structures', 'geometry', 'math', '*3300']
F. Tree Recoverytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputFishingprince loves trees. A tree is a connected undirected graph without cycles.Fishingprince has a tree of n vertices. The vertices are numbered 1 through n. Let d(x,y) denote the shortest distance on the tree from vertex x to vertex y, assuming that the length of each edge is 1.However, the tree was lost in an accident. Fortunately, Fishingprince still remembers some information about the tree. More specifically, for every triple of integers x,y,z (1\le x<y\le n, 1\le z\le n) he remembers whether d(x,z)=d(y,z) or not.Help him recover the structure of the tree, or report that no tree satisfying the constraints exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 200). Description of the test cases follows.The first line of each test case contains an integer n (2\le n\le 100) — the number of vertices in the tree.Then n-1 lines follow. The i-th line of these n-1 lines contains n-i strings of length n consisting of 0 and 1. If the k-th character in the j-th string of the i-th line is 0, it means that d(i,k)\ne d(i+j,k); if the k-th character in the j-th string of the i-th line is 1, it means that d(i,k)=d(i+j,k).It is guaranteed that in one input file, there are at most 2 test cases that have n>50; there are at most 5 test cases that have n>20. OutputFor each test case: if no answer exists, output No; otherwise, on the first line output Yes. Then output n-1 lines. Each line should contain two integers x,y (1\le x,y\le n), denoting an edge between vertices x and y of the tree. If there are multiple solutions, print any. When printing Yes and No, you can print each letter in any case (upper or lower).ExampleInput 52002103001 0000003001 010000500000 01001 00000 0110000000 10000 0000000000 1101000000Output Yes 1 2 No Yes 1 3 2 3 No Yes 1 2 1 4 2 3 2 5
52002103001 0000003001 010000500000 01001 00000 0110000000 10000 0000000000 1101000000
Yes 1 2 No Yes 1 3 2 3 No Yes 1 2 1 4 2 3 2 5
1 second
512 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'trees', '*2600']
E. Placing Jinastime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWe say an infinite sequence a_{0}, a_{1}, a_2, \ldots is non-increasing if and only if for all i\ge 0, a_i \ge a_{i+1}.There is an infinite right and down grid. The upper-left cell has coordinates (0,0). Rows are numbered 0 to infinity from top to bottom, columns are numbered from 0 to infinity from left to right.There is also a non-increasing infinite sequence a_{0}, a_{1}, a_2, \ldots. You are given a_0, a_1, \ldots, a_n; for all i>n, a_i=0. For every pair of x, y, the cell with coordinates (x,y) (which is located at the intersection of x-th row and y-th column) is white if y<a_x and black otherwise.Initially there is one doll named Jina on (0,0). You can do the following operation. Select one doll on (x,y). Remove it and place a doll on (x,y+1) and place a doll on (x+1,y). Note that multiple dolls can be present at a cell at the same time; in one operation, you remove only one. Your goal is to make all white cells contain 0 dolls.What's the minimum number of operations needed to achieve the goal? Print the answer modulo 10^9+7.InputThe first line of input contains one integer n (1\le n\le 2\cdot 10^5).The second line of input contains n+1 integers a_0,a_1,\ldots,a_n (0\le a_i\le 2\cdot 10^5).It is guaranteed that the sequence a is non-increasing.OutputPrint one integer — the answer to the problem, modulo 10^9+7.ExamplesInput 2 2 2 0 Output 5Input 10 12 11 8 8 6 6 6 5 3 2 1 Output 2596NoteConsider the first example. In the given grid, cells (0,0),(0,1),(1,0),(1,1) are white, and all other cells are black. Let us use triples to describe the grid: triple (x,y,z) means that there are z dolls placed on cell (x,y). Initially the state of the grid is (0,0,1).One of the optimal sequence of operations is as follows: Do the operation with (0,0). Now the state of the grid is (1,0,1),(0,1,1). Do the operation with (0,1). Now the state of the grid is (1,0,1),(1,1,1),(0,2,1). Do the operation with (1,0). Now the state of the grid is (1,1,2),(0,2,1),(2,0,1). Do the operation with (1,1). Now the state of the grid is (1,1,1),(0,2,1),(2,0,1),(1,2,1),(2,1,1). Do the operation with (1,1). Now the state of the grid is (0,2,1),(2,0,1),(1,2,2),(2,1,2). Now all white cells contain 0 dolls, so we have achieved the goal with 5 operations.
2 2 2 0
5
2 seconds
512 megabytes
['combinatorics', 'math', '*2000']
D. Permutation Graphtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).You are given a permutation of 1,2,\dots,n, [a_1,a_2,\dots,a_n]. For integers i, j such that 1\le i<j\le n, define \operatorname{mn}(i,j) as \min\limits_{k=i}^j a_k, and define \operatorname{mx}(i,j) as \max\limits_{k=i}^j a_k.Let us build an undirected graph of n vertices, numbered 1 to n. For every pair of integers 1\le i<j\le n, if \operatorname{mn}(i,j)=a_i and \operatorname{mx}(i,j)=a_j both holds, or \operatorname{mn}(i,j)=a_j and \operatorname{mx}(i,j)=a_i both holds, add an undirected edge of length 1 between vertices i and j.In this graph, find the length of the shortest path from vertex 1 to vertex n. We can prove that 1 and n will always be connected via some path, so a shortest path always exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 5\cdot 10^4). Description of the test cases follows.The first line of each test case contains one integer n (1\le n\le 2.5\cdot 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1\le a_i\le n). It's guaranteed that a is a permutation of 1, 2, \dots, n.It is guaranteed that the sum of n over all test cases does not exceed 5\cdot 10^5.OutputFor each test case, print a single line containing one integer — the length of the shortest path from 1 to n.ExampleInput 51121 251 4 2 3 552 1 5 3 4107 4 8 1 6 10 3 5 2 9Output 0 1 1 4 6 NoteThe following are illustrations of constructed graphs in example test cases. the constructed graph in test case 1 the constructed graph in test case 2 the constructed graph in test case 3 the constructed graph in test case 4 the constructed graph in test case 5
51121 251 4 2 3 552 1 5 3 4107 4 8 1 6 10 3 5 2 9
0 1 1 4 6
2 seconds
512 megabytes
['binary search', 'constructive algorithms', 'data structures', 'divide and conquer', 'greedy', 'shortest paths', '*1900']
C. Fishingprince Plays With Arraytime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFishingprince is playing with an array [a_1,a_2,\dots,a_n]. He also has a magic number m.He can do the following two operations on it: Select 1\le i\le n such that a_i is divisible by m (that is, there exists an integer t such that m \cdot t = a_i). Replace a_i with m copies of \frac{a_i}{m}. The order of the other elements doesn't change. For example, when m=2 and a=[2,3] and i=1, a changes into [1,1,3]. Select 1\le i\le n-m+1 such that a_i=a_{i+1}=\dots=a_{i+m-1}. Replace these m elements with a single m \cdot a_i. The order of the other elements doesn't change. For example, when m=2 and a=[3,2,2,3] and i=2, a changes into [3,4,3]. Note that the array length might change during the process. The value of n above is defined as the current length of the array (might differ from the n in the input).Fishingprince has another array [b_1,b_2,\dots,b_k]. Please determine if he can turn a into b using any number (possibly zero) of operations.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 two integers n and m (1\le n\le 5\cdot 10^4, 2\le m\le 10^9).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1\le a_i\le 10^9).The third line of each test case contains one integer k (1\le k\le 5\cdot 10^4).The fourth line of each test case contains k integers b_1,b_2,\ldots,b_k (1\le b_i\le 10^9).It is guaranteed that the sum of n+k over all test cases does not exceed 2\cdot 10^5.OutputFor each testcase, print Yes if it is possible to turn a into b, and No otherwise. You can print each letter in any case (upper or lower).ExampleInput 55 21 2 2 4 241 4 4 26 21 2 2 8 2 221 168 33 3 3 3 3 3 3 346 6 6 68 33 9 6 3 12 12 36 12169 3 2 2 2 3 4 12 4 12 4 12 4 12 4 48 33 9 6 3 12 12 36 12712 2 4 3 4 12 56Output Yes Yes No Yes No NoteIn the first test case of the sample, we can do the second operation with i=2: [1,\color{red}{2,2},4,2]\to [1,\color{red}{4},4,2].In the second testcase of the sample, we can: do the second operation with i=2: [1,\color{red}{2,2},8,2,2]\to [1,\color{red}{4},8,2,2]. do the second operation with i=4: [1,4,8,\color{red}{2,2}]\to [1,4,8,\color{red}{4}]. do the first operation with i=3: [1,4,\color{red}{8},4]\to [1,4,\color{red}{4,4},4]. do the second operation with i=2: [1,\color{red}{4,4},4,4]\to [1,\color{red}{8},4,4]. do the second operation with i=3: [1,8,\color{red}{4,4}]\to [1,8,\color{red}{8}]. do the second operation with i=2: [1,\color{red}{8,8}]\to [1,\color{red}{16}].
55 21 2 2 4 241 4 4 26 21 2 2 8 2 221 168 33 3 3 3 3 3 3 346 6 6 68 33 9 6 3 12 12 36 12169 3 2 2 2 3 4 12 4 12 4 12 4 12 4 48 33 9 6 3 12 12 36 12712 2 4 3 4 12 56
Yes Yes No Yes No
2 seconds
512 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*1400']
B. NIT Destroys the Universetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor a collection of integers S, define \operatorname{mex}(S) as the smallest non-negative integer that does not appear in S.NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.The universe can be represented as a 1-indexed array a of length n. When NIT snaps his fingers, he does the following operation on the array: He selects positive integers l and r such that 1\le l\le r\le n. Let w=\operatorname{mex}(\{a_l,a_{l+1},\dots,a_r\}). Then, for all l\le i\le r, set a_i to w. We say the universe is destroyed if and only if for all 1\le i\le n, a_i=0 holds.Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to 0.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 one integer n (1\le n\le 10^5).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0\le a_i\le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print one integer — the answer to the problem.ExampleInput 440 0 0 050 1 2 3 470 2 3 0 1 2 011000000000Output 0 1 2 1 NoteIn the first test case, we do 0 operations and all elements in the array are already equal to 0.In the second test case, one optimal way is doing the operation with l=2, r=5.In the third test case, one optimal way is doing the operation twice, respectively with l=4, r=4 and l=2, r=6.In the fourth test case, one optimal way is doing the operation with l=1, r=1.
440 0 0 050 1 2 3 470 2 3 0 1 2 011000000000
0 1 2 1
2 seconds
512 megabytes
['greedy', '*900']
A. NIT orz!time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputNIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to \operatorname{or} z. Can you solve this problem too?You are given a 1-indexed array of n integers, a, and an integer z. You can do the following operation any number (possibly zero) of times: Select a positive integer i such that 1\le i\le n. Then, simutaneously set a_i to (a_i\operatorname{or} z) and set z to (a_i\operatorname{and} z). In other words, let x and y respectively be the current values of a_i and z. Then set a_i to (x\operatorname{or}y) and set z to (x\operatorname{and}y). Here \operatorname{or} and \operatorname{and} denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in a after any number (possibly zero) of 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 and z (1\le n\le 2000, 0\le z<2^{30}).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (0\le a_i<2^{30}).It is guaranteed that the sum of n over all test cases does not exceed 10^4.OutputFor each test case, print one integer — the answer to the problem.ExampleInput 52 33 45 50 2 4 6 81 9105 77 15 30 29 273 3954874310293834 10284344 13635445Output 7 13 11 31 48234367 NoteIn the first test case of the sample, one optimal sequence of operations is: Do the operation with i=1. Now a_1 becomes (3\operatorname{or}3)=3 and z becomes (3\operatorname{and}3)=3. Do the operation with i=2. Now a_2 becomes (4\operatorname{or}3)=7 and z becomes (4\operatorname{and}3)=0. Do the operation with i=1. Now a_1 becomes (3\operatorname{or}0)=3 and z becomes (3\operatorname{and}0)=0. After these operations, the sequence a becomes [3,7], and the maximum value in it is 7. We can prove that the maximum value in a can never exceed 7, so the answer is 7.In the fourth test case of the sample, one optimal sequence of operations is: Do the operation with i=1. Now a_1 becomes (7\operatorname{or}7)=7 and z becomes (7\operatorname{and}7)=7. Do the operation with i=3. Now a_3 becomes (30\operatorname{or}7)=31 and z becomes (30\operatorname{and}7)=6. Do the operation with i=5. Now a_5 becomes (27\operatorname{or}6)=31 and z becomes (27\operatorname{and}6)=2.
52 33 45 50 2 4 6 81 9105 77 15 30 29 273 3954874310293834 10284344 13635445
7 13 11 31 48234367
1 second
512 megabytes
['bitmasks', 'greedy', '*800']
E. Ambiguous Dominoestime limit per test8 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp and Monocarp are both solving the same puzzle with dominoes. They are given the same set of n dominoes, the i-th of which contains two numbers x_i and y_i. They are also both given the same m by k grid of values a_{ij} such that m\cdot k = 2n.The puzzle asks them to place the n dominoes on the grid in such a way that none of them overlap, and the values on each domino match the a_{ij} values that domino covers. Dominoes can be rotated arbitrarily before being placed on the grid, so the domino (x_i, y_i) is equivalent to the domino (y_i, x_i).They have both solved the puzzle, and compared their answers, but noticed that not only did their solutions not match, but none of the n dominoes were in the same location in both solutions! Formally, if two squares were covered by the same domino in Polycarp's solution, they were covered by different dominoes in Monocarp's solution. The diagram below shows one potential a grid, along with the two players' solutions. Polycarp and Monocarp remember the set of dominoes they started with, but they have lost the grid a. Help them reconstruct one possible grid a, along with both of their solutions, or determine that no such grid exists.InputThe first line contains a single integer n (1 \le n \le 3\cdot 10^5).The i-th of the next n lines contains two integers x_i and y_i (1 \le x_i, y_i \le 2n).OutputIf there is no solution, print a single integer -1.Otherwise, print m and k, the height and width of the puzzle grid, on the first line of output. These should satisfy m\cdot k = 2n.The i-th of the next m lines should contain k integers, the j-th of which is a_{ij}.The next m lines describe Polycarp's solution. Print m lines of k characters each. For each square, if it is covered by the upper half of a domino in Polycarp's solution, it should contain a "U". Similarly, if it is covered by the bottom, left, or right half of a domino, it should contain "D", "L", or "R", respectively.The next m lines should describe Monocarp's solution, in the same format as Polycarp's solution.If there are multiple answers, print any.ExamplesInput 1 1 2 Output -1 Input 2 1 1 1 2 Output 2 2 2 1 1 1 LR LR UU DD Input 10 1 3 1 1 2 1 3 4 1 5 1 5 3 1 2 4 3 3 4 1 Output 4 5 1 2 5 1 5 3 4 1 3 1 1 2 4 4 1 1 3 3 3 1 LRULR LRDLR ULRLR DLRLR UULRU DDUUD LRDDU LRLRD NoteExtra blank lines are added to the output for clarity, but are not required.The third sample case corresponds to the image from the statement.
1 1 2
-1
8 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', '*2700']
D2. Tree Queries (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and D1 is the bound on the size of the tree.You are given an unrooted tree with n vertices. There is some hidden vertex x in that tree that you are trying to find.To do this, you may ask k queries v_1, v_2, \ldots, v_k where the v_i are vertices in the tree. After you are finished asking all of the queries, you are given k numbers d_1, d_2, \ldots, d_k, where d_i is the number of edges on the shortest path between v_i and x. Note that you know which distance corresponds to which query.What is the minimum k such that there exists some queries v_1, v_2, \ldots, v_k that let you always uniquely identify x (no matter what x is).Note that you don't actually need to output these queries.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 a single integer n (1 \le n \le 2\cdot10^5)  — the number of vertices in the tree.Each of the next n-1 lines contains two integers x and y (1 \le x, y \le n), meaning there is an edges between vertices x and y in the tree.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case print a single nonnegative integer, the minimum number of queries you need, on its own line.ExampleInput 3 1 2 1 2 10 2 4 2 1 5 7 3 10 8 6 6 1 1 3 4 7 9 6 Output 0 1 2 NoteIn the first test case, there is only one vertex, so you don't need any queries.In the second test case, you can ask a single query about the node 1. Then, if x = 1, you will get 0, otherwise you will get 1.
3 1 2 1 2 10 2 4 2 1 5 7 3 10 8 6 6 1 1 3 4 7 9 6
0 1 2
2 seconds
256 megabytes
['constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*2300']
D1. Tree Queries (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and D2 is the bound on the size of the tree.You are given an unrooted tree with n vertices. There is some hidden vertex x in that tree that you are trying to find.To do this, you may ask k queries v_1, v_2, \ldots, v_k where the v_i are vertices in the tree. After you are finished asking all of the queries, you are given k numbers d_1, d_2, \ldots, d_k, where d_i is the number of edges on the shortest path between v_i and x. Note that you know which distance corresponds to which query.What is the minimum k such that there exists some queries v_1, v_2, \ldots, v_k that let you always uniquely identify x (no matter what x is).Note that you don't actually need to output these queries.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 a single integer n (1 \le n \le 2000)  — the number of vertices in the tree.Each of the next n-1 lines contains two integers x and y (1 \le x, y \le n), meaning there is an edges between vertices x and y in the tree.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case print a single nonnegative integer, the minimum number of queries you need, on its own line.ExampleInput 3 1 2 1 2 10 2 4 2 1 5 7 3 10 8 6 6 1 1 3 4 7 9 6 Output 0 1 2 NoteIn the first test case, there is only one vertex, so you don't need any queries.In the second test case, you can ask a single query about the node 1. Then, if x = 1, you will get 0, otherwise you will get 1.
3 1 2 1 2 10 2 4 2 1 5 7 3 10 8 6 6 1 1 3 4 7 9 6
0 1 2
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'dp', 'greedy', 'trees', '*2200']
C. Zero Pathtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a grid with n rows and m columns. We denote the square on the i-th (1\le i\le n) row and j-th (1\le j\le m) column by (i, j) and the number there by a_{ij}. All numbers are equal to 1 or to -1. You start from the square (1, 1) and can move one square down or one square to the right at a time. In the end, you want to end up at the square (n, m).Is it possible to move in such a way so that the sum of the values written in all the visited cells (including a_{11} and a_{nm}) is 0?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n, m \le 1000)  — the size of the grid.Each of the following n lines contains m integers. The j-th integer on the i-th line is a_{ij} (a_{ij} = 1 or -1)  — the element in the cell (i, j).It is guaranteed that the sum of n\cdot m over all test cases does not exceed 10^6.OutputFor each test case, print "YES" if there exists a path from the top left to the bottom right that adds up to 0, and "NO" otherwise. You can output each letter in any case.ExampleInput 5 1 1 1 1 2 1 -1 1 4 1 -1 1 -1 3 4 1 -1 -1 -1 -1 1 1 -1 1 1 1 -1 3 4 1 -1 1 1 -1 1 -1 1 1 -1 1 1 Output NO YES YES YES NO NoteOne possible path for the fourth test case is given in the picture in the statement.
5 1 1 1 1 2 1 -1 1 4 1 -1 1 -1 3 4 1 -1 -1 -1 -1 1 1 -1 1 1 1 -1 3 4 1 -1 1 1 -1 1 -1 1 1 -1 1 1
NO YES YES YES NO
2 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'graphs', 'greedy', 'shortest paths', '*1700']
B. Circle Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMike and Joe are playing a game with some stones. Specifically, they have n piles of stones of sizes a_1, a_2, \ldots, a_n. These piles are arranged in a circle.The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile 1. Formally, if a player removed stones from pile i on a turn, the other player removes stones from pile ((i\bmod n) + 1) on the next turn.If a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.If Mike and Joe play optimally, who will win?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 50)  — the number of piles.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9)  — the size of the piles.OutputFor each test case print the winner of the game, either "Mike" or "Joe" on its own line (without quotes).ExampleInput 2 1 37 2 100 100 Output Mike Joe NoteIn the first test case, Mike just takes all 37 stones on his first turn.In the second test case, Joe can just copy Mike's moves every time. Since Mike went first, he will hit 0 on the first pile one move before Joe does so on the second pile.
2 1 37 2 100 100
Mike Joe
1 second
256 megabytes
['games', 'greedy', '*1000']
A. Subrectangle Guesstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMichael and Joe are playing a game. The game is played on a grid with n rows and m columns, filled with distinct integers. We denote the square on the i-th (1\le i\le n) row and j-th (1\le j\le m) column by (i, j) and the number there by a_{ij}.Michael starts by saying two numbers h (1\le h \le n) and w (1\le w \le m). Then Joe picks any h\times w subrectangle of the board (without Michael seeing).Formally, an h\times w subrectangle starts at some square (a,b) where 1 \le a \le n-h+1 and 1 \le b \le m-w+1. It contains all squares (i,j) for a \le i \le a+h-1 and b \le j \le b+w-1. Possible move by Joe if Michael says 3\times 2 (with maximum of 15). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, h \cdot w), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose h, w for which he can ensure that he wins.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 20). Description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n, m \le 40)  — the size of the grid.Each of the following n lines contains m integers. The j-th integer on the i-th line is a_{ij} (-10^9 \le a_{ij} \le 10^9)  — the element in the cell (i, j).It is guaranteed that all the numbers are distinct (that is, if a_{i_1j_1} = a_{i_2j_2}, then i_1 = i_2, j_1 = j_2).OutputFor each test case print a single positive integer  — the minimum possible area the subrectangle can have while still ensuring that Michael can guarantee the victory.ExampleInput 3 1 1 3 4 4 2 12 6 10 3 15 16 4 1 13 8 11 14 7 9 5 2 3 -7 5 2 0 8 -3 Output 1 9 4 NoteIn the first test case, the grid is 1\times 1, so the only possible choice for h, w is h = 1, w = 1, giving an area of h\cdot w = 1.The grid from the second test case is drawn in the statement. It can be shown that with h = 3, w = 3 Michael can guarantee the victory and that any choice with h\cdot w \le 8 doesn't.
3 1 1 3 4 4 2 12 6 10 3 15 16 4 1 13 8 11 14 7 9 5 2 3 -7 5 2 0 8 -3
1 9 4
1 second
256 megabytes
['games', '*800']
B. Paranoid Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call a binary string T of length m indexed from 1 to m paranoid if we can obtain a string of length 1 by performing the following two kinds of operations m-1 times in any order : Select any substring of T that is equal to 01, and then replace it with 1. Select any substring of T that is equal to 10, and then replace it with 0.For example, if T = 001, we can select the substring [T_2T_3] and perform the first operation. So we obtain T = 01.You are given a binary string S of length n indexed from 1 to n. Find the number of pairs of integers (l, r) 1 \le l \le r \le n such that S[l \ldots r] (the substring of S from l to r) is a paranoid string. InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of S.The second line of each test case contains a binary string S of n characters S_1S_2 \ldots S_n. (S_i = 0 or S_i = 1 for each 1 \le i \le n)It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, output the number of pairs of integers (l, r) 1 \le l \le r \le n such that S[l \ldots r] (the substring of S from l to r) is a paranoid string. ExampleInput 5 1 1 2 01 3 100 4 1001 5 11111 Output 1 3 4 8 5 NoteIn the first sample, S already has length 1 and doesn't need any operations.In the second sample, all substrings of S are paranoid. For the entire string, it's enough to perform the first operation.In the third sample, all substrings of S are paranoid except [S_2S_3], because we can't perform any operations on it, and [S_1S_2S_3] (the entire string).
5 1 1 2 01 3 100 4 1001 5 11111
1 3 4 8 5
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1200']
A. Creeptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDefine the score of some binary string T as the absolute difference between the number of zeroes and ones in it. (for example, T= 010001 contains 4 zeroes and 2 ones, so the score of T is |4-2| = 2).Define the creepiness of some binary string S as the maximum score among all of its prefixes (for example, the creepiness of S= 01001 is equal to 2 because the score of the prefix S[1 \ldots 4] is 2 and the rest of the prefixes have a score of 2 or less).Given two integers a and b, construct a binary string consisting of a zeroes and b ones with the minimum possible creepiness.InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers a and b ( 1 \le a, b \le 100)  — the numbers of zeroes and ones correspondingly.OutputFor each test case, print a binary string consisting of a zeroes and b ones with the minimum possible creepiness. If there are multiple answers, print any of them.ExampleInput 5 1 1 1 2 5 2 4 5 3 7 Output 10 011 0011000 101010101 0001111111 NoteIn the first test case, the score of S[1 \ldots 1] is 1, and the score of S[1 \ldots 2] is 0.In the second test case, the minimum possible creepiness is 1 and one of the other answers is 101.In the third test case, the minimum possible creepiness is 3 and one of the other answers is 0001100.
5 1 1 1 2 5 2 4 5 3 7
10 011 0011000 101010101 0001111111
1 second
256 megabytes
['greedy', 'implementation', '*800']
F. I Might Be Wrongtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string S of length n indexed from 1 to n. You can perform the following operation any number of times (possibly zero):Choose two integers l and r (1 \le l \le r \le n). Let cnt_0 be the number of times 0 occurs in S[l \ldots r] and cnt_1 be the number of times 1 occurs in S[l \ldots r]. You can pay |cnt_0 - cnt_1| + 1 coins and sort the S[l \ldots r]. (by S[l \ldots r] we mean the substring of S starting at position l and ending at position r)For example if S = 11001, we can perform the operation on S[2 \ldots 4], paying |2 - 1| + 1 = 2 coins, and obtain S = 10011 as a new string.Find the minimum total number of coins required to sort S in increasing order.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of S.The second line of each test case contains a binary string S of n characters S_1S_2 \ldots S_n. (S_i = 0 or S_i = 1 for each 1 \le i \le n)It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, output the minimum total number of coins required to sort S in increasing order.ExampleInput 71121031014100051101061100002001000010001010011000Output 0 1 1 3 2 2 5 NoteIn the first test case, S is already sorted.In the second test case, it's enough to apply the operation with l = 1, r = 2.In the third test case, it's enough to apply the operation with l = 1, r = 2.
71121031014100051101061100002001000010001010011000
0 1 1 3 2 2 5
2 seconds
256 megabytes
['binary search', 'greedy', 'two pointers', '*3400']
E. Outermost Maximumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYeri has an array of n + 2 non-negative integers : a_0, a_1, ..., a_n, a_{n + 1}.We know that a_0 = a_{n + 1} = 0.She wants to make all the elements of a equal to zero in the minimum number of operations.In one operation she can do one of the following: Choose the leftmost maximum element and change it to the maximum of the elements on its left. Choose the rightmost maximum element and change it to the maximum of the elements on its right.Help her find the minimum number of operations needed to make all elements of a equal to zero.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n).OutputPrint a single integer  — the minimum number of operations needed to make all elements of a equal to zero.ExamplesInput 6 1 4 2 4 0 2 Output 7 Input 5 1 3 5 4 2 Output 9 Input 4 0 0 0 0 Output 0 NoteIn the first sample, you get \langle 1, \underline{1}, 2, 4, 0, 2 \rangle by performing the first operation and \langle 1, 4, 2, \underline{2}, 0, 2 \rangle by performing the second operation.One way to achieve our goal is shown below. (The underlines show the last change.) \langle 1, 4, 2, 4, 0, 2 \rangle \to \langle 1, 4, 2, \underline{2}, 0, 2 \rangle \to \langle 1, \underline{1}, 2, 2, 0, 2 \rangle \to \langle 1, 1, 2, 2, 0, \underline{0} \rangle \to \langle 1, 1, 2, \underline{0}, 0, 0 \rangle \to \langle 1, 1, \underline{0}, 0, 0, 0 \rangle \to \langle \underline{0}, 1, 0, 0, 0, 0 \rangle \to \langle 0, \underline{0}, 0, 0, 0, 0 \rangle In the third sample each element is already equal to zero so no operations are needed.
6 1 4 2 4 0 2
7
2 seconds
256 megabytes
['data structures', 'greedy', '*3400']
D. Decinc Dividingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an array a of m integers a_1, a_2, \ldots, a_m Decinc if a can be made increasing by removing a decreasing subsequence (possibly empty) from it. For example, if a = [3, 2, 4, 1, 5], we can remove the decreasing subsequence [a_1, a_4] from a and obtain a = [2, 4, 5], which is increasing.You are given a permutation p of numbers from 1 to n. Find the number of pairs of integers (l, r) with 1 \le l \le r \le n such that p[l \ldots r] (the subarray of p from l to r) is a Decinc array. InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5)  — the size of p.The second line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, all p_i are distinct)  — elements of the permutation.OutputOutput the number of pairs of integers (l, r) such that p[l \ldots r] (the subarray of p from l to r) is a Decinc array. (1 \le l \le r \le n)ExamplesInput 3 2 3 1 Output 6 Input 6 4 5 2 6 1 3 Output 19 Input 10 7 10 1 8 3 9 2 4 6 5 Output 39 NoteIn the first sample, all subarrays are Decinc.In the second sample, all subarrays except p[1 \ldots 6] and p[2 \ldots 6] are Decinc.
3 2 3 1
6
2 seconds
256 megabytes
['brute force', 'data structures', 'divide and conquer', 'dp', 'greedy', '*2800']
C. Keshi in Search of AmShZtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAmShZ has traveled to Italy from Iran for the Thom Yorke concert. There are n cities in Italy indexed from 1 to n and m directed roads indexed from 1 to m. Initially, Keshi is located in the city 1 and wants to go to AmShZ's house in the city n. Since Keshi doesn't know the map of Italy, AmShZ helps him to see each other as soon as possible.In the beginning of each day, AmShZ can send one of the following two messages to Keshi: AmShZ sends the index of one road to Keshi as a blocked road. Then Keshi will understand that he should never use that road and he will remain in his current city for the day. AmShZ tells Keshi to move. Then, Keshi will randomly choose one of the cities reachable from his current city and move there. (city B is reachable from city A if there's an out-going road from city A to city B which hasn't become blocked yet). If there are no such cities, Keshi will remain in his current city.Note that AmShZ always knows Keshi's current location. AmShZ and Keshi want to find the smallest possible integer d for which they can make sure that they will see each other after at most d days. Help them find d.InputThe first line of the input contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le 2 \cdot 10^5)  — the number of cities and roads correspondingly.The i-th line of the following m lines contains two integers v_i and u_i (1 \le v_i , u_i \le n,v_i \neq u_i), denoting a directed road going from city v_i to city u_i.It is guaranteed that there is at least one route from city 1 to city n. Note that there may be more than one road between a pair of cities in each direction.OutputOutput the smallest possible integer d to make sure that AmShZ and Keshi will see each other after at most d days.ExamplesInput 2 1 1 2 Output 1 Input 4 4 1 2 1 4 2 4 1 4 Output 2 Input 5 7 1 2 2 3 3 5 1 4 4 3 4 5 3 1 Output 4 NoteIn the first sample, it's enough for AmShZ to send the second type of message.In the second sample, on the first day, AmShZ blocks the first road. So the only reachable city from city 1 will be city 4. Hence on the second day, AmShZ can tell Keshi to move and Keshi will arrive at AmShZ's house.It's also possible for AmShZ to tell Keshi to move for two days.
2 1 1 2
1
2 seconds
256 megabytes
['graphs', 'greedy', 'shortest paths', '*2300']
B. Fake Plastic Treestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is the vertex 1 and the parent of the vertex v is p_v.There is a number written on each vertex, initially all numbers are equal to 0. Let's denote the number written on the vertex v as a_v.For each v, we want a_v to be between l_v and r_v (l_v \leq a_v \leq r_v).In a single operation we do the following: Choose some vertex v. Let b_1, b_2, \ldots, b_k be vertices on the path from the vertex 1 to vertex v (meaning b_1 = 1, b_k = v and b_i = p_{b_{i + 1}}). Choose a non-decreasing array c of length k of nonnegative integers: 0 \leq c_1 \leq c_2 \leq \ldots \leq c_k. For each i (1 \leq i \leq k), increase a_{b_i} by c_i. What's the minimum number of operations needed to achieve our goal?InputThe first line contains an integer t (1\le t\le 1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2\le n\le 2 \cdot 10^5)  — the number of the vertices in the tree.The second line of each test case contains n - 1 integers, p_2, p_3, \ldots, p_n (1 \leq p_i < i), where p_i denotes the parent of the vertex i.The i-th of the following n lines contains two integers l_i and r_i (1 \le l_i \le r_i \le 10^9).It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case output the minimum number of operations needed.ExampleInput 4 2 1 1 5 2 9 3 1 1 4 5 2 4 6 10 4 1 2 1 6 9 5 6 4 5 2 4 5 1 2 3 4 5 5 4 4 3 3 2 2 1 1 Output 1 2 2 5 NoteIn the first test case, we can achieve the goal with a single operation: choose v = 2 and c = [1, 2], resulting in a_1 = 1, a_2 = 2.In the second test case, we can achieve the goal with two operations: first, choose v = 2 and c = [3, 3], resulting in a_1 = 3, a_2 = 3, a_3 = 0. Then, choose v = 3, c = [2, 7], resulting in a_1 = 5, a_2 = 3, a_3 = 7.
4 2 1 1 5 2 9 3 1 1 4 5 2 4 6 10 4 1 2 1 6 9 5 6 4 5 2 4 5 1 2 3 4 5 5 4 4 3 3 2 2 1 1
1 2 2 5
1 second
256 megabytes
['dfs and similar', 'dp', 'greedy', 'trees', '*1700']
A. Directional Increasetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputWe have an array of length n. Initially, each element is equal to 0 and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by 1. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by 1. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array a. Determine whether it's possible to obtain a after some operations or not.InputThe first line contains a single integer t (1\le t\le 1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1\le n\le 2 \cdot 10^5)  — the size of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — elements of the array.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print "Yes" (without quotes) if it's possible to obtain a after some operations, and "No" (without quotes) otherwise.You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 7 2 1 0 4 2 -1 -1 0 4 1 -4 3 0 4 1 -1 1 -1 5 1 2 3 4 -10 7 2 -1 1 -2 0 0 0 1 0 Output No Yes No No Yes Yes Yes NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle
7 2 1 0 4 2 -1 -1 0 4 1 -4 3 0 4 1 -1 1 -1 5 1 2 3 4 -10 7 2 -1 1 -2 0 0 0 1 0
No Yes No No Yes Yes Yes
1 second
256 megabytes
['greedy', '*1300']
H. Gamblingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMarian is at a casino. The game at the casino works like this.Before each round, the player selects a number between 1 and 10^9. After that, a dice with 10^9 faces is rolled so that a random number between 1 and 10^9 appears. If the player guesses the number correctly their total money is doubled, else their total money is halved. Marian predicted the future and knows all the numbers x_1, x_2, \dots, x_n that the dice will show in the next n rounds. He will pick three integers a, l and r (l \leq r). He will play r-l+1 rounds (rounds between l and r inclusive). In each of these rounds, he will guess the same number a. At the start (before the round l) he has 1 dollar.Marian asks you to determine the integers a, l and r (1 \leq a \leq 10^9, 1 \leq l \leq r \leq n) such that he makes the most money at the end.Note that during halving and multiplying there is no rounding and there are no precision errors. So, for example during a game, Marian could have money equal to \dfrac{1}{1024}, \dfrac{1}{128}, \dfrac{1}{2}, 1, 2, 4, etc. (any value of 2^t, where t is an integer of any sign).InputThe first line contains a single integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 2\cdot 10^5) — the number of rounds.The second line of each test case contains n integers x_1, x_2, \dots, x_n (1 \leq x_i \leq 10^9), where x_i is the number that will fall on the dice in the i-th round.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output three integers a, l, and r such that Marian makes the most amount of money gambling with his strategy. If there are multiple answers, you may output any of them.ExampleInput 4 5 4 4 3 4 4 5 11 1 11 1 11 1 1000000000 10 8 8 8 9 9 6 6 9 6 6 Output 4 1 5 1 2 2 1000000000 1 1 6 6 10 NoteFor the first test case, the best choice is a=4, l=1, r=5, and the game would go as follows. Marian starts with one dollar. After the first round, he ends up with 2 dollars because the numbers coincide with the chosen one. After the second round, he ends up with 4 dollars because the numbers coincide again. After the third round, he ends up with 2 dollars because he guesses 4 even though 3 is the correct choice. After the fourth round, he ends up with 4 dollars again. In the final round, he ends up 8 dollars because he again guessed correctly. There are many possible answers for the second test case, but it can be proven that Marian will not end up with more than 2 dollars, so any choice with l = r with the appropriate a is acceptable.
4 5 4 4 3 4 4 5 11 1 11 1 11 1 1000000000 10 8 8 8 9 9 6 6 9 6 6
4 1 5 1 2 2 1000000000 1 1 6 6 10
2 seconds
256 megabytes
['data structures', 'dp', 'greedy', 'math', '*1700']
G. 2^Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n and an integer k, find the number of indices 1 \leq i \leq n - k such that the subarray [a_i, \dots, a_{i+k}] with length k+1 (not with length k) has the following property: If you multiply the first element by 2^0, the second element by 2^1, ..., and the (k+1)-st element by 2^k, then this subarray is sorted in strictly increasing order. More formally, count the number of indices 1 \leq i \leq n - k such that 2^0 \cdot a_i < 2^1 \cdot a_{i+1} < 2^2 \cdot a_{i+2} < \dots < 2^k \cdot a_{i+k}. InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains two integers n, k (3 \leq n \leq 2 \cdot 10^5, 1 \leq k < n) — the length of the array and the number of inequalities.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the elements of the array.The sum of n across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the number of indices satisfying the condition in the statement.ExampleInput 6 4 2 20 22 19 84 5 1 9 5 3 2 1 5 2 9 5 3 2 1 7 2 22 12 16 4 3 22 12 7 3 22 12 16 4 3 22 12 9 3 3 9 12 3 9 12 3 9 12 Output 2 3 2 3 1 0 NoteIn the first test case, both subarrays satisfy the condition: i=1: the subarray [a_1,a_2,a_3] = [20,22,19], and 1 \cdot 20 < 2 \cdot 22 < 4 \cdot 19. i=2: the subarray [a_2,a_3,a_4] = [22,19,84], and 1 \cdot 22 < 2 \cdot 19 < 4 \cdot 84. In the second test case, three subarrays satisfy the condition: i=1: the subarray [a_1,a_2] = [9,5], and 1 \cdot 9 < 2 \cdot 5. i=2: the subarray [a_2,a_3] = [5,3], and 1 \cdot 5 < 2 \cdot 3. i=3: the subarray [a_3,a_4] = [3,2], and 1 \cdot 3 < 2 \cdot 2. i=4: the subarray [a_4,a_5] = [2,1], but 1 \cdot 2 = 2 \cdot 1, so this subarray doesn't satisfy the condition.
6 4 2 20 22 19 84 5 1 9 5 3 2 1 5 2 9 5 3 2 1 7 2 22 12 16 4 3 22 12 7 3 22 12 16 4 3 22 12 9 3 3 9 12 3 9 12 3 9 12
2 3 2 3 1 0
1 second
256 megabytes
['data structures', 'dp', 'sortings', 'two pointers', '*1400']
F. 3SUMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of positive integers with length n, determine if there exist three distinct indices i, j, k such that a_i + a_j + a_k ends in the digit 3.InputThe first line contains an integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains an integer n (3 \leq n \leq 2 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the elements of the array.The sum of n across all test cases does not exceed 2 \cdot 10^5.OutputOutput t lines, each of which contains the answer to the corresponding test case. Output "YES" if there exist three distinct indices i, j, k satisfying the constraints in the statement, and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 6 4 20 22 19 84 4 1 11 1 2022 4 1100 1100 1100 1111 5 12 34 56 78 90 4 1 9 8 4 6 16 38 94 25 18 99 Output YES YES NO NO YES YES NoteIn the first test case, you can select i=1, j=4, k=3. Then a_1 + a_4 + a_3 = 20 + 84 + 19 = 123, which ends in the digit 3.In the second test case, you can select i=1, j=2, k=3. Then a_1 + a_2 + a_3 = 1 + 11 + 1 = 13, which ends in the digit 3.In the third test case, it can be proven that no such i, j, k exist. Note that i=4, j=4, k=4 is not a valid solution, since although a_4 + a_4 + a_4 = 1111 + 1111 + 1111 = 3333, which ends in the digit 3, the indices need to be distinct.In the fourth test case, it can be proven that no such i, j, k exist.In the fifth test case, you can select i=4, j=3, k=1. Then a_4 + a_3 + a_1 = 4 + 8 + 1 = 13, which ends in the digit 3.In the sixth test case, you can select i=1, j=2, k=6. Then a_1 + a_2 + a_6 = 16 + 38 + 99 = 153, which ends in the digit 3.
6 4 20 22 19 84 4 1 11 1 2022 4 1100 1100 1100 1111 5 12 34 56 78 90 4 1 9 8 4 6 16 38 94 25 18 99
YES YES NO NO YES YES
1 second
256 megabytes
['brute force', 'math', '*1300']
E. Binary Dequetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSlavic has an array of length n consisting only of zeroes and ones. In one operation, he removes either the first or the last element of the array. What is the minimum number of operations Slavic has to perform such that the total sum of the array is equal to s after performing all the operations? In case the sum s can't be obtained after any amount of operations, you should output -1.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains two integers n and s (1 \leq n, s \leq 2 \cdot 10^5) — the length of the array and the needed sum of elements.The second line of each test case contains n integers a_i (0 \leq a_i \leq 1) — the elements of the array.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum amount of operations required to have the total sum of the array equal to s, or -1 if obtaining an array with sum s isn't possible.ExampleInput 7 3 1 1 0 0 3 1 1 1 0 9 3 0 1 0 1 1 1 0 0 1 6 4 1 1 1 1 1 1 5 1 0 0 1 1 0 16 2 1 1 0 0 1 0 0 1 1 0 0 0 0 0 1 1 6 3 1 0 1 0 0 0 Output 0 1 3 2 2 7 -1 NoteIn the first test case, the sum of the whole array is 1 from the beginning, so we don't have to make any operations.In the second test case, the sum of the array is 2 and we want it to be equal to 1, so we should remove the first element. The array turns into [1, 0], which has a sum equal to 1.In the third test case, the sum of the array is 5 and we need it to be 3. We can obtain such a sum by removing the first two elements and the last element, doing a total of three operations. The array turns into [0, 1, 1, 1, 0, 0], which has a sum equal to 3.
7 3 1 1 0 0 3 1 1 1 0 9 3 0 1 0 1 1 1 0 0 1 6 4 1 1 1 1 1 1 5 1 0 0 1 1 0 16 2 1 1 0 0 1 0 0 1 1 0 0 0 0 0 1 1 6 3 1 0 1 0 0 0
0 1 3 2 2 7 -1
2 seconds
256 megabytes
['binary search', 'implementation', 'two pointers', '*1200']
D. The Clocktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVictor has a 24-hour clock that shows the time in the format "HH:MM" (00 \le HH \le 23, 00 \le MM \le 59). He looks at the clock every x minutes, and the clock is currently showing time s. How many different palindromes will Victor see in total after looking at the clock every x minutes, the first time being at time s?For example, if the clock starts out as 03:12 and Victor looks at the clock every 360 minutes (i.e. every 6 hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is 1.A palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.InputThe first line of the input contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of each test case follows.The only line of each test case contains a string s of length 5 with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59" (both "HH" and "MM" have exactly two digits) and an integer x (1 \leq x \leq 1440) — the number of minutes Victor takes to look again at the clock.OutputFor each test case, output a single integer — the number of different palindromes Victor will see if he looks at the clock every x minutes starting from time s.ExampleInput 6 03:12 360 00:00 1 13:22 2 15:15 10 11:11 1440 22:30 27 Output 1 16 10 0 1 1 NoteThe first test case is explained in the statement.
6 03:12 360 00:00 1 13:22 2 15:15 10 11:11 1440 22:30 27
1 16 10 0 1 1
1 second
256 megabytes
['brute force', 'implementation', '*1100']
C. Where's the Bishop?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMihai has an 8 \times 8 chessboard whose rows are numbered from 1 to 8 from top to bottom and whose columns are numbered from 1 to 8 from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between 2 and 7, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked. An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.InputThe first line of the input contains a single integer t (1 \leq t \leq 36) — the number of test cases. The description of test cases follows. There is an empty line before each test case.Each test case consists of 8 lines, each containing 8 characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.OutputFor each test case, output two integers r and c (2 \leq r, c \leq 7) — the row and column of the bishop. The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.ExampleInput 3 .....#.. #...#... .#.#.... ..#..... .#.#.... #...#... .....#.. ......#. #.#..... .#...... #.#..... ...#.... ....#... .....#.. ......#. .......# .#.....# ..#...#. ...#.#.. ....#... ...#.#.. ..#...#. .#.....# #....... Output 4 3 2 2 4 5 NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row 4 and column 3, the correct output is 4 3.
3 .....#.. #...#... .#.#.... ..#..... .#.#.... #...#... .....#.. ......#. #.#..... .#...... #.#..... ...#.... ....#... .....#.. ......#. .......# .#.....# ..#...#. ...#.#.. ....#... ...#.#.. ..#...#. .#.....# #.......
4 3 2 2 4 5
1 second
256 megabytes
['implementation', '*800']
B. All Distincttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSho has an array a consisting of n integers. An operation consists of choosing two distinct indices i and j and removing a_i and a_j from the array.For example, for the array [2, 3, 4, 2, 5], Sho can choose to remove indices 1 and 3. After this operation, the array becomes [3, 2, 5]. Note that after any operation, the length of the array is reduced by two.After he made some operations, Sho has an array that has only distinct elements. In addition, he made operations such that the resulting array is the longest possible. More formally, the array after Sho has made his operations respects these criteria: No pairs such that (i < j) and a_i = a_j exist. The length of a is maximized. Output the length of the final array.InputThe first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 50) — the length of the array.The second line of each test case contains n integers a_i (1 \leq a_i \leq 10^4) — the elements of the array.OutputFor each test case, output a single integer — the length of the final array. Remember that in the final array, all elements are different, and its length is maximum.ExampleInput 4 6 2 2 2 3 3 3 5 9 1 9 9 1 4 15 16 16 15 4 10 100 1000 10000 Output 2 1 2 4 NoteFor the first test case Sho can perform operations as follows: Choose indices 1 and 5 to remove. The array becomes [2, 2, 2, 3, 3, 3] \rightarrow [2, 2, 3, 3]. Choose indices 1 and 4 to remove. The array becomes [2, 2, 3, 3] \rightarrow [2, 3]. The final array has a length of 2, so the answer is 2. It can be proven that Sho cannot obtain an array with a longer length.For the second test case Sho can perform operations as follows: Choose indices 3 and 4 to remove. The array becomes [9, 1, 9, 9, 1] \rightarrow [9, 1, 1]. Choose indices 1 and 3 to remove. The array becomes [9, 1, 1] \rightarrow [1]. The final array has a length of 1, so the answer is 1. It can be proven that Sho cannot obtain an array with a longer length.
4 6 2 2 2 3 3 3 5 9 1 9 9 1 4 15 16 16 15 4 10 100 1000 10000
2 1 2 4
1 second
256 megabytes
['greedy', 'sortings', '*800']
A. Marathontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given four distinct integers a, b, c, d. Timur and three other people are running a marathon. The value a is the distance that Timur has run and b, c, d correspond to the distances the other three participants ran. Output the number of participants in front of Timur.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The description of each test case consists of four distinct integers a, b, c, d (0 \leq a, b, c, d \leq 10^4).OutputFor each test case, output a single integer — the number of participants in front of Timur.ExampleInput 4 2 3 4 1 10000 0 1 2 500 600 400 300 0 9999 10000 9998 Output 2 0 1 3 NoteFor the first test case, there are 2 people in front of Timur, specifically the participants who ran distances of 3 and 4. The other participant is not in front of Timur because he ran a shorter distance than Timur.For the second test case, no one is in front of Timur, since he ran a distance of 10000 while all others ran a distance of 0, 1, and 2 respectively.For the third test case, only the second person is in front of Timur, who ran a total distance of 600 while Timur ran a distance of 500.
4 2 3 4 1 10000 0 1 2 500 600 400 300 0 9999 10000 9998
2 0 1 3
1 second
256 megabytes
['implementation', '*800']
F. K-Set Treetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree G with n vertices and an integer k. The vertices of the tree are numbered from 1 to n.For a vertex r and a subset S of vertices of G, such that |S| = k, we define f(r, S) as the size of the smallest rooted subtree containing all vertices in S when the tree is rooted at r. A set of vertices T is called a rooted subtree, if all the vertices in T are connected, and for each vertex in T, all its descendants belong to T.You need to calculate the sum of f(r, S) over all possible distinct combinations of vertices r and subsets S, where |S| = k. Formally, compute the following: \sum_{r \in V} \sum_{S \subseteq V, |S| = k} f(r, S), where V is the set of vertices in G.Output the answer modulo 10^9 + 7.InputThe first line contains two integers n and k (3 \le n \le 2 \cdot 10^5, 1 \le k \le n).Each of the following n - 1 lines contains two integers x and y (1 \le x, y \le n), denoting an edge between vertex x and y.It is guaranteed that the given edges form a tree.OutputPrint the answer modulo 10^9 + 7.ExamplesInput 3 2 1 2 1 3 Output 25 Input 7 2 1 2 2 3 2 4 1 5 4 6 4 7 Output 849 NoteThe tree in the second example is given below: We have 21 subsets of size 2 in the given tree. Hence, S \in \left\{\{1, 2\}, \{1, 3\}, \{1, 4\}, \{1, 5\}, \{1, 6\}, \{1, 7\}, \{2, 3\}, \{2, 4\}, \{2, 5\}, \{2, 6\}, \{2, 7\}, \{3, 4\}, \{3, 5\}, \{3, 6\}, \{3, 7\}, \{4, 5\}, \{4, 6\}, \{4, 7\}, \{5, 6\}, \{5, 7\}, \{6, 7\} \right\}. And since we have 7 vertices, 1 \le r \le 7. We need to find the sum of f(r, S) over all possible pairs of r and S. Below we have listed the value of f(r, S) for some combinations of r and S. r = 1, S = \{3, 7\}. The value of f(r, S) is 5 and the corresponding subtree is \{2, 3, 4, 6, 7\}. r = 1, S = \{5, 4\}. The value of f(r, S) is 7 and the corresponding subtree is \{1, 2, 3, 4, 5, 6, 7\}. r = 1, S = \{4, 6\}. The value of f(r, S) is 3 and the corresponding subtree is \{4, 6, 7\}.
3 2 1 2 1 3
25
3 seconds
512 megabytes
['combinatorics', 'dfs and similar', 'dp', 'math', 'trees', '*2500']
E. Number of Groupstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n colored segments on the number line. Each segment is either colored red or blue. The i-th segment can be represented by a tuple (c_i, l_i, r_i). The segment contains all the points in the range [l_i, r_i], inclusive, and its color denoted by c_i: if c_i = 0, it is a red segment; if c_i = 1, it is a blue segment. We say that two segments of different colors are connected, if they share at least one common point. Two segments belong to the same group, if they are either connected directly, or through a sequence of directly connected segments. Find the number of groups of segments. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 10^5) — the number of segments. Each of the next n lines contains three integers c_i, l_i, r_i (0 \leq c_i \leq 1, 0 \leq l_i \leq r_i \leq 10^9), describing the i-th segment. It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single integer k, the number of groups of segments.ExampleInput 2 5 0 0 5 1 2 12 0 4 7 1 9 16 0 13 19 3 1 0 1 1 1 2 0 3 4 Output 2 3 NoteIn the first example there are 5 segments. The segments 1 and 2 are connected, because they are of different colors and share a point. Also, the segments 2 and 3 are connected, and so are segments 4 and 5. Thus, there are two groups: one containing segments \{1, 2, 3\}, and the other one containing segments \{4, 5\}.
2 5 0 0 5 1 2 12 0 4 7 1 9 16 0 13 19 3 1 0 1 1 1 2 0 3 4
2 3
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'sortings', '*2300']
D. Max GEQ Sumtime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. You are asked to find out if the inequality \max(a_i, a_{i + 1}, \ldots, a_{j - 1}, a_{j}) \geq a_i + a_{i + 1} + \dots + a_{j - 1} + a_{j} holds for all pairs of indices (i, j), where 1 \leq i \leq j \leq n.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5)  — the size of the array.The next line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, on a new line output "YES" if the condition is satisfied for the given array, and "NO" otherwise. You can print each letter in any case (upper or lower).ExampleInput 3 4 -1 1 -1 2 5 -1 2 -3 2 -1 3 2 3 -1 Output YES YES NO NoteIn test cases 1 and 2, the given condition is satisfied for all (i, j) pairs. In test case 3, the condition isn't satisfied for the pair (1, 2) as \max(2, 3) < 2 + 3.
3 4 -1 1 -1 2 5 -1 2 -3 2 -1 3 2 3 -1
YES YES NO
1.5 seconds
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'divide and conquer', 'implementation', 'two pointers', '*1800']
C. Sum of Substringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s of length n.Let's define d_i as the number whose decimal representation is s_i s_{i+1} (possibly, with a leading zero). We define f(s) to be the sum of all the valid d_i. In other words, f(s) = \sum\limits_{i=1}^{n-1} d_i.For example, for the string s = 1011: d_1 = 10 (ten); d_2 = 01 (one) d_3 = 11 (eleven); f(s) = 10 + 01 + 11 = 22. In one operation you can swap any two adjacent elements of the string. Find the minimum value of f(s) that can be achieved if at most k operations are allowed.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). Description of the test cases follows.First line of each test case contains two integers n and k (2 \le n \le 10^5, 0 \le k \le 10^9) — the length of the string and the maximum number of operations allowed.The second line of each test case contains the binary string s of length n, consisting of only zeros and ones.It is also given that sum of n over all the test cases doesn't exceed 10^5.OutputFor each test case, print the minimum value of f(s) you can obtain with at most k operations.ExampleInput 3 4 0 1010 7 1 0010100 5 2 00110 Output 21 22 12 Note For the first example, you can't do any operation so the optimal string is s itself. f(s) = f(1010) = 10 + 01 + 10 = 21. For the second example, one of the optimal strings you can obtain is "0011000". The string has an f value of 22. For the third example, one of the optimal strings you can obtain is "00011". The string has an f value of 12.
3 4 0 1010 7 1 0010100 5 2 00110
21 22 12
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', 'strings', '*1400']
B. Shoe Shufflingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are n students in the class, and you are given an array s in non-decreasing order, where s_i is the shoe size of the i-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation p of \{1,2,\ldots,n\} denoting a valid shuffling of shoes, where the i-th student gets the shoes of the p_i-th student (p_i \ne i). And output -1 if a valid shuffling does not exist.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (1\leq n\leq10^5) — the number of students.The second line of each test case contains n integers s_1, s_2,\ldots,s_n (1\leq s_i\leq10^9, and for all 1\le i<n, s_i\le s_{i+1}) — the shoe sizes of the students.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the answer in a single line using the following format.If a valid shuffling does not exist, print the number -1 as the answer.If a valid shuffling exists, print n space-separated integers — a permutation p of 1,2,\ldots,n denoting a valid shuffling of shoes where the i-th student gets the shoes of the p_i-th student. If there are multiple answers, then print any of them.ExampleInput 2 5 1 1 1 1 1 6 3 6 8 13 15 21 Output 5 1 2 3 4 -1 NoteIn the first test case, any permutation p of 1,\ldots,n where p_i\ne i would represent a valid shuffling since all students have equal shoe sizes, and thus anyone can wear anyone's shoes.In the second test case, it can be shown that no valid shuffling is possible.
2 5 1 1 1 1 1 6 3 6 8 13 15 21
5 1 2 3 4 -1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'two pointers', '*1000']
A. Beat The Oddstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a sequence a_1, a_2, \ldots, a_n, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every 2 consecutive elements is even.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2,\dots,a_n (1\leq a_i\leq10^9) — elements of the sequence.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print a single integer — the minimum number of elements to remove from the sequence such that the sum of every 2 consecutive elements is even.ExampleInput 2 5 2 4 3 6 8 6 3 5 9 7 1 3 Output 1 0 NoteIn the first test case, after removing 3, the sequence becomes [2,4,6,8]. The pairs of consecutive elements are \{[2, 4], [4, 6], [6, 8]\}. Each consecutive pair has an even sum now. Hence, we only need to remove 1 element to satisfy the condition asked.In the second test case, each consecutive pair already has an even sum so we need not remove any element.
2 5 2 4 3 6 8 6 3 5 9 7 1 3
1 0
1 second
256 megabytes
['brute force', 'greedy', 'math', '*800']
G. Count the Trainstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n of independent carriages on the rails. The carriages are numbered from left to right from 1 to n. The carriages are not connected to each other. The carriages move to the left, so that the carriage with number 1 moves ahead of all of them.The i-th carriage has its own engine, which can accelerate the carriage to a_i km/h, but the carriage cannot go faster than the carriage in front of it. See example for explanation.All carriages start moving to the left at the same time, and they naturally form trains. We will call trains — consecutive moving carriages having the same speed.For example, we have n=5 carriages and array a = [10, 13, 5, 2, 6]. Then the final speeds of the carriages will be [10, 10, 5, 2, 2]. Respectively, 3 of the train will be formed.There are also messages saying that some engine has been corrupted: message "k d" means that the speed of the k-th carriage has decreased by d (that is, there has been a change in the maximum speed of the carriage a_k = a_k - d). Messages arrive sequentially, the processing of the next message takes into account the changes from all previous messages.After each message determine the number of formed trains.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) —the number of input test cases.This is followed by descriptions of the test cases.The first line of each test case is empty.The second line of the test case contains two integers n and m (1 \le n,m \le 10^5) —the number of carriages and the number of messages to slow down the carriage, respectively.The third line contains n integers: a_1, a_2, \dots, a_n (0 \le a_i \le 10^9) — the number a_i means that the carriage with number i can reach a speed of a_i km/h. The next m lines contain two integers k_j and d_j (1 \le k_j \le n, 0 \le d_j \le a_{k_j}) —this is the message that the speed of the carriage with number k_j has decreased by d_j. In other words, there has been a change in its maximum speed a_{k_j} = a_{k_j} - d_j. Note that at any time the speed of each carriage is non-negative. In other words, a_i \ge s_i, where s_i —is the sum of such d_j that k_j=i.It is guaranteed that the sum of n over all test cases does not exceed 10^5. Similarly, it is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputPrint t lines. On each line print the answer for the corresponding test case.For each test case print m numbers: the number of trains formed after each message.ExampleInput 3 4 2 6 2 3 7 3 2 4 7 5 4 10 13 5 2 6 2 4 5 2 1 5 3 2 13 4 769 514 336 173 181 373 519 338 985 709 729 702 168 12 581 6 222 7 233 5 117 Output 3 4 4 4 2 3 5 6 6 5 NoteFor the first test case: Initially array a = [6, 2, 3, 7]. After the first message, the array a = [6, 2, 1, 7]. Accordingly, the speeds of the carriages are [6, 2, 1, 1] and will form 3 of the train. After the second message the array a = [6, 2, 1, 0]. Accordingly, the speeds of the carriages are [6, 2, 1, 0], and 4 of the train will be formed. For the second test case: Initially, the array a = [10, 13, 5, 2, 6]. After the first message, the array a = [10, 9, 5, 2, 6]. Accordingly, the speeds of the carriages are equal: [10, 9, 5, 2, 2], and 4 of the train will be formed. After the second message the array a = [10, 9, 5, 2, 4]. Accordingly, the speeds of the carriages are [10, 9, 5, 2, 2], and 4 of the train will be formed. After the third message the array a = [5, 9, 5, 2, 4]. Accordingly, the speeds of the carriages are [5, 5, 5, 2, 2], and 2 of the train will be formed. After the fourth message the array a = [5, 9, 3, 2, 4]. Accordingly, the speeds of the carriages are [5, 5, 3, 2, 2], and 3 of the train will be formed.
3 4 2 6 2 3 7 3 2 4 7 5 4 10 13 5 2 6 2 4 5 2 1 5 3 2 13 4 769 514 336 173 181 373 519 338 985 709 729 702 168 12 581 6 222 7 233 5 117
3 4 4 4 2 3 5 6 6 5
2 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'sortings', '*2000']
F. Shifting Stringtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp found the string s and the permutation p. Their lengths turned out to be the same and equal to n.A permutation of n elements — is an array of length n, in which every integer from 1 to n occurs exactly once. For example, [1, 2, 3] and [4, 3, 5, 1, 2] are permutations, but [1, 2, 4], [4, 3, 2, 1, 2] and [0, 1, 2] are not.In one operation he can multiply s by p, so he replaces s with string new, in which for any i from 1 to n it is true that new_i = s_{p_i}. For example, with s=wmbe and p = [3, 1, 4, 2], after operation the string will turn to s=s_3 s_1 s_4 s_2=bwem.Polycarp wondered after how many operations the string would become equal to its initial value for the first time. Since it may take too long, he asks for your help in this matter.It can be proved that the required number of operations always exists. It can be very large, so use a 64-bit integer type. InputThe first line of input contains one integer t (1 \le t \le 5000) — the number of test cases in input.The first line of each case contains single integer n (1 \le n \le 200) — the length of string and permutation.The second line of each case contains a string s of length n, containing lowercase Latin letters.The third line of each case contains n integers — permutation p (1 \le p_i \le n), all p_i are different.OutputOutput t lines, each of which contains the answer to the corresponding test case of input. As an answer output single integer — the minimum number of operations, after which the string s will become the same as it was before operations.ExampleInput 3 5 ababa 3 4 5 2 1 5 ababa 2 1 4 5 3 10 codeforces 8 6 1 7 5 2 9 3 10 4 Output 1 6 12 NoteIn the first sample operation doesn't change the string, so it will become the same as it was after 1 operations.In the second sample the string will change as follows: s = babaa s = abaab s = baaba s = abbaa s = baaab s = ababa
3 5 ababa 3 4 5 2 1 5 ababa 2 1 4 5 3 10 codeforces 8 6 1 7 5 2 9 3 10 4
1 6 12
3 seconds
256 megabytes
['graphs', 'math', 'number theory', 'strings', '*1700']
E. Price Maximizationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA batch of n goods (n — an even number) is brought to the store, i-th of which has weight a_i. Before selling the goods, they must be packed into packages. After packing, the following will be done: There will be \frac{n}{2} packages, each package contains exactly two goods; The weight of the package that contains goods with indices i and j (1 \le i, j \le n) is a_i + a_j. With this, the cost of a package of weight x is always \left \lfloor\frac{x}{k}\right\rfloor burles (rounded down), where k — a fixed and given value.Pack the goods to the packages so that the revenue from their sale is maximized. In other words, make such \frac{n}{2} pairs of given goods that the sum of the values \left \lfloor\frac{x_i}{k} \right \rfloor, where x_i is the weight of the package number i (1 \le i \le \frac{n}{2}), is maximal.For example, let n = 6, k = 3, weights of goods a = [3, 2, 7, 1, 4, 8]. Let's pack them into the following packages. In the first package we will put the third and sixth goods. Its weight will be a_3 + a_6 = 7 + 8 = 15. The cost of the package will be \left \lfloor\frac{15}{3}\right\rfloor = 5 burles. In the second package put the first and fifth goods, the weight is a_1 + a_5 = 3 + 4 = 7. The cost of the package is \left \lfloor\frac{7}{3}\right\rfloor = 2 burles. In the third package put the second and fourth goods, the weight is a_2 + a_4 = 2 + 1 = 3. The cost of the package is \left \lfloor\frac{3}{3}\right\rfloor = 1 burle. With this packing, the total cost of all packs would be 5 + 2 + 1 = 8 burles.InputThe first line of the input contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case contains two integers n (2 \le n \le 2\cdot10^5) and k (1 \le k \le 1000). The number n — is even.The second line of each test case contains exactly n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).It is guaranteed that the sum of n over all the test cases does not exceed 2\cdot10^5.OutputFor each test case, print on a separate line a single number — the maximum possible total cost of all the packages.ExampleInput 6 6 3 3 2 7 1 4 8 4 3 2 1 5 6 4 12 0 0 0 0 2 1 1 1 6 10 2 0 0 5 9 4 6 5 5 3 8 6 3 2 Output 8 4 0 2 1 5 NoteThe first test case is analyzed in the statement.In the second test case, you can get a total value equal to 4 if you put the first and second goods in the first package and the third and fourth goods in the second package.In the third test case, the cost of each item is 0, so the total cost will also be 0.
6 6 3 3 2 7 1 4 8 4 3 2 1 5 6 4 12 0 0 0 0 2 1 1 1 6 10 2 0 0 5 9 4 6 5 5 3 8 6 3 2
8 4 0 2 1 5
2 seconds
256 megabytes
['binary search', 'greedy', 'math', 'two pointers', '*1500']
D. Black and White Stripetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a stripe of checkered paper of length n. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of k consecutive black cells on the stripe?If the input data is such that a segment of k consecutive black cells already exists, then print 0. InputThe first line contains an integer t (1 \le t \le 10^4) — the number of test cases.Next, descriptions of t test cases follow.The first line of the input contains two integers n and k (1 \le k \le n \le 2\cdot10^5). The second line consists of the letters 'W' (white) and 'B' (black). The line length is n.It is guaranteed that the sum of values n does not exceed 2\cdot10^5.OutputFor each of t test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of k consecutive black cells.ExampleInput 4 5 3 BBWBW 5 5 BBWBW 5 1 BBWBW 1 1 W Output 1 2 0 1 NoteIn the first test case, s="BBWBW" and k=3. It is enough to recolor s_3 and get s="BBBBW". This string contains a segment of length k=3 consisting of the letters 'B'.In the second test case of the example s="BBWBW" and k=5. It is enough to recolor s_3 and s_5 and get s="BBBBB". This string contains a segment of length k=5 consisting of the letters 'B'.In the third test case of the example s="BBWBW" and k=1. The string s already contains a segment of length k=1 consisting of the letters 'B'.
4 5 3 BBWBW 5 5 BBWBW 5 1 BBWBW 1 1 W
1 2 0 1
2 seconds
256 megabytes
['implementation', 'two pointers', '*1000']
C. Restoring the Duration of Taskstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Polycarp completed n successive tasks.For each completed task, the time s_i is known when it was given, no two tasks were given at the same time. Also given is the time f_i when the task was completed. For each task, there is an unknown value d_i (d_i>0) — duration of task execution.It is known that the tasks were completed in the order in which they came. Polycarp performed the tasks as follows: As soon as the very first task came, Polycarp immediately began to carry it out. If a new task arrived before Polycarp finished the previous one, he put the new task at the end of the queue. When Polycarp finished executing the next task and the queue was not empty, he immediately took a new task from the head of the queue (if the queue is empty — he just waited for the next task). Find d_i (duration) of each task.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The descriptions of the input data sets follow.The first line of each test case contains one integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains exactly n integers s_1 < s_2 < \dots < s_n (0 \le s_i \le 10^9).The third line of each test case contains exactly n integers f_1 < f_2 < \dots < f_n (s_i < f_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each of t test cases print n positive integers d_1, d_2, \dots, d_n — the duration of each task.ExampleInput 4 3 0 3 7 2 10 11 2 10 15 11 16 9 12 16 90 195 1456 1569 3001 5237 19275 13 199 200 260 9100 10000 10914 91066 5735533 1 0 1000000000 Output 2 7 1 1 1 1 183 1 60 7644 900 914 80152 5644467 1000000000 NoteFirst test case:The queue is empty at the beginning: [ ]. And that's where the first task comes in. At time 2, Polycarp finishes doing the first task, so the duration of the first task is 2. The queue is empty so Polycarp is just waiting.At time 3, the second task arrives. And at time 7, the third task arrives, and now the queue looks like this: [7].At the time 10, Polycarp finishes doing the second task, as a result, the duration of the second task is 7.And at time 10, Polycarp immediately starts doing the third task and finishes at time 11. As a result, the duration of the third task is 1. An example of the first test case.
4 3 0 3 7 2 10 11 2 10 15 11 16 9 12 16 90 195 1456 1569 3001 5237 19275 13 199 200 260 9100 10000 10914 91066 5735533 1 0 1000000000
2 7 1 1 1 1 183 1 60 7644 900 914 80152 5644467 1000000000
2 seconds
256 megabytes
['data structures', 'greedy', 'implementation', '*800']
B. Array Decrementstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKristina has two arrays a and b, each containing n non-negative integers. She can perform the following operation on array a any number of times: apply a decrement to each non-zero element of the array, that is, replace the value of each element a_i such that a_i > 0 with the value a_i - 1 (1 \le i \le n). If a_i was 0, its value does not change. Determine whether Kristina can get an array b from an array a in some number of operations (probably zero). In other words, can she make a_i = b_i after some number of operations for each 1 \le i \le n?For example, let n = 4, a = [3, 5, 4, 1] and b = [1, 3, 2, 0]. In this case, she can apply the operation twice: after the first application of the operation she gets a = [2, 4, 3, 0]; after the second use of the operation she gets a = [1, 3, 2, 0]. Thus, in two operations, she can get an array b from an array a.InputThe first line of the input contains an integer t (1 \le t \le 10^4) —the number of test cases in the test.The descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \le n \le 5 \cdot 10^4).The second line of each test case contains exactly n non-negative integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).The third line of each test case contains exactly n non-negative integers b_1, b_2, \dots, b_n (0 \le b_i \le 10^9).It is guaranteed that the sum of n values over all test cases in the test does not exceed 2 \cdot 10^5.OutputFor each test case, output on a separate line: YES, if by doing some number of operations it is possible to get an array b from an array a; NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).ExampleInput 6 4 3 5 4 1 1 3 2 0 3 1 2 1 0 1 0 4 5 3 7 2 1 1 1 1 5 1 2 3 4 5 1 2 3 4 6 1 8 0 1 4 6 Output YES YES NO NO YES NO NoteThe first test case is analyzed in the statement.In the second test case, it is enough to apply the operation to array a once.In the third test case, it is impossible to get array b from array a.
6 4 3 5 4 1 1 3 2 0 3 1 2 1 0 1 0 4 5 3 7 2 1 1 1 1 5 1 2 3 4 5 1 2 3 4 6 1 8 0 1 4 6
YES YES NO NO YES NO
1 second
256 megabytes
['greedy', 'implementation', '*800']
A. Print a Pedestal (Codeforces logo?)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven the integer n — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of 3 platforms for 2-nd, 1-st and 3-rd places respectively. The platform for the 1-st place must be strictly higher than for the 2-nd place, and the platform for the 2-nd place must be strictly higher than for the 3-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block). Example pedestal of n=11 blocks: second place height equals 4 blocks, first place height equals 5 blocks, third place height equals 2 blocks.Among all possible pedestals of n blocks, deduce one such that the platform height for the 1-st place minimum as possible. If there are several of them, output any of them.InputThe first line of input data contains an integer t (1 \le t \le 10^4) — the number of test cases.Each test case contains a single integer n (6 \le n \le 10^5) — the total number of blocks for the pedestal. All n blocks must be used.It is guaranteed that the sum of n values over all test cases does not exceed 10^6.OutputFor each test case, output 3 numbers h_2, h_1, h_3 — the platform heights for 2-nd, 1-st and 3-rd places on a pedestal consisting of n blocks (h_1+h_2+h_3=n, 0 < h_3 < h_2 < h_1). Among all possible pedestals, output the one for which the value of h_1 minimal. If there are several of them, output any of them.ExampleInput 6 11 6 10 100000 7 8 Output 4 5 2 2 3 1 4 5 1 33334 33335 33331 2 4 1 3 4 1 NoteIn the first test case we can not get the height of the platform for the first place less than 5, because if the height of the platform for the first place is not more than 4, then we can use at most 4 + 3 + 2 = 9 blocks. And we should use 11 = 4 + 5 + 2 blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1.
6 11 6 10 100000 7 8
4 5 2 2 3 1 4 5 1 33334 33335 33331 2 4 1 3 4 1
1 second
256 megabytes
['constructive algorithms', 'greedy', '*800']
E. ANDfinitytime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBit Lightyear, to the ANDfinity and beyond!After graduating from computer sciences, Vlad has been awarded an array a_1,a_2,\ldots,a_n of n non-negative integers. As it is natural, he wanted to construct a graph consisting of n vertices, numbered 1, 2,\ldots, n. He decided to add an edge between i and j if and only if a_i \& a_j > 0, where \& denotes the bitwise AND operation.Vlad also wants the graph to be connected, which might not be the case initially. In order to satisfy that, he can do the following two types of operations on the array: Choose some element a_i and increment it by 1. Choose some element a_i and decrement it by 1 (possible only if a_i > 0). It can be proven that there exists a finite sequence of operations such that the graph will be connected. So, can you please help Vlad find the minimum possible number of operations to do that and also provide the way how to do that?InputThere are several test cases in the input data. The first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. This is followed by the test cases description.The first line of each test case contains an integer n (2\leq n \leq 2000). The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0\leq a_i < 2^{30}) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, print a single integer m in the first line — the minimum number of operations. In the second line print the array after a valid sequence of operations that have been done such that the graph from the task becomes connected. If there are multiple solutions, output any.ExampleInput 4 5 1 2 3 4 5 2 0 2 2 3 12 4 3 0 0 0 Output 0 1 2 3 4 5 2 2 2 1 3 11 3 3 1 1 1 NoteIn the first test case, the graph is already connected.In the second test case, we can increment 0 twice and end up with the array [2,2]. Since 2 \& 2 = 2 > 0, the graph is connected. It can be shown that one operation is not enough.In the third test case, we can decrement 12 once and we end up with an array [3,11]. 3 \& 11 = 3 > 0 hence the graph is connected. One operation has to be done since the graph is not connected at the beginning.
4 5 1 2 3 4 5 2 0 2 2 3 12 4 3 0 0 0
0 1 2 3 4 5 2 2 2 1 3 11 3 3 1 1 1
4 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'graphs', '*2500']
D. Lena and Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of n rows and m columns, and each cell is either black or white. The coordinates (i,j) denote the cell which belongs to the i-th row and j-th column for every 1\leq i \leq n and 1\leq j \leq m. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be k \ge 1 black cells in the matrix with coordinates (x_i,y_i) for every 1\leq i \leq k. Lena should choose a cell (a,b) that minimizes \max_{i=1}^{k}(|a-x_i|+|b-y_i|).As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose? InputThere are several test cases in the input data. The first line contains a single integer t (1\leq t\leq 10\,000) — the number of test cases. This is followed by the test cases description.The first line of each test case contains two integers n and m (2\leq n,m \leq 1000)  — the dimensions of the matrix. The following n lines contain m characters each, each character is either 'W' or 'B'. The j-th character in the i-th of these lines is 'W' if the cell (i,j) is white, and 'B' if the cell (i,j) is black. It is guaranteed that at least one black cell exists.It is guaranteed that the sum of n\cdot m does not exceed 10^6.OutputFor each test case, output the optimal cell (a,b) to choose. If multiple answers exist, output any.ExampleInput 5 3 2 BW WW WB 3 3 WWB WBW BWW 2 3 BBB BBB 5 5 BWBWB WBWBW BWBWB WBWBW BWBWB 9 9 WWWWWWWWW WWWWWWWWW BWWWWWWWW WWWWWWWWW WWWWBWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWB Output 2 1 2 2 1 2 3 3 6 5NoteIn the first test case the two black cells have coordinates (1,1) and (3,2). The four optimal cells are (1,2), (2,1), (2,2) and (3,1). It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell (2,2) with maximum Manhattan distance being 2.
5 3 2 BW WW WB 3 3 WWB WBW BWW 2 3 BBB BBB 5 5 BWBWB WBWBW BWBWB WBWBW BWBWB 9 9 WWWWWWWWW WWWWWWWWW BWWWWWWWW WWWWWWWWW WWWWBWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWW WWWWWWWWB
2 1 2 2 1 2 3 3 6 5
2 seconds
256 megabytes
['data structures', 'dp', 'geometry', 'shortest paths', '*1900']
C. Infected Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputByteland is a beautiful land known because of its beautiful trees.Misha has found a binary tree with n vertices, numbered from 1 to n. A binary tree is an acyclic connected bidirectional graph containing n vertices and n - 1 edges. Each vertex has a degree at most 3, whereas the root is the vertex with the number 1 and it has a degree at most 2.Unfortunately, the root got infected.The following process happens n times: Misha either chooses a non-infected (and not deleted) vertex and deletes it with all edges which have an end in this vertex or just does nothing. Then, the infection spreads to each vertex that is connected by an edge to an already infected vertex (all already infected vertices remain infected). As Misha does not have much time to think, please tell him what is the maximum number of vertices he can save from the infection (note that deleted vertices are not counted as saved).InputThere are several test cases in the input data. The first line contains a single integer t (1\leq t\leq 5000) — the number of test cases. This is followed by the test cases description.The first line of each test case contains one integer n (2\leq n\leq 3\cdot 10^5) — the number of vertices of the tree. The i-th of the following n-1 lines in the test case contains two positive integers u_i and v_i (1 \leq u_i, v_i \leq n), meaning that there exists an edge between them in the graph. It is guaranteed that the graph is a binary tree rooted at 1. It is also guaranteed that the sum of n over all test cases won't exceed 3\cdot 10^5.OutputFor each test case, output the maximum number of vertices Misha can save.ExampleInput 4 2 1 2 4 1 2 2 3 2 4 7 1 2 1 5 2 3 2 4 5 6 5 7 15 1 2 2 3 3 4 4 5 4 6 3 7 2 8 1 9 9 10 9 11 10 12 10 13 11 14 11 15 Output 0 2 2 10 NoteIn the first test case, the only possible action is to delete vertex 2, after which we save 0 vertices in total.In the second test case, if we delete vertex 2, we can save vertices 3 and 4.
4 2 1 2 4 1 2 2 3 2 4 7 1 2 1 5 2 3 2 4 5 6 5 7 15 1 2 2 3 3 4 4 5 4 6 3 7 2 8 1 9 9 10 9 11 10 12 10 13 11 14 11 15
0 2 2 10
3 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*1600']
B. Mystic Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is a little boy who lives in Byteland and he loves programming.Recently, he found a permutation of length n. He has to come up with a mystic permutation. It has to be a new permutation such that it differs from the old one in each position.More formally, if the old permutation is p_1,p_2,\ldots,p_n and the new one is q_1,q_2,\ldots,q_n it must hold that p_1\neq q_1, p_2\neq q_2, \ldots ,p_n\neq q_n.Monocarp is afraid of lexicographically large permutations. Can you please help him to find the lexicographically minimal mystic permutation?InputThere are several test cases in the input data. The first line contains a single integer t (1\leq t\leq 200) — the number of test cases. This is followed by the test cases description.The first line of each test case contains a positive integer n (1\leq n\leq 1000) — the length of the permutation.The second line of each test case contains n distinct positive integers p_1, p_2, \ldots, p_n (1 \leq p_i \leq n). It's guaranteed that p is a permutation, i. e. p_i \neq p_j for all i \neq j. It is guaranteed that the sum of n does not exceed 1000 over all test cases.OutputFor each test case, output n positive integers — the lexicographically minimal mystic permutations. If such a permutation does not exist, output -1 instead.ExampleInput 4 3 1 2 3 5 2 3 4 5 1 4 2 3 1 4 1 1 Output 2 3 1 1 2 3 4 5 1 2 4 3 -1 NoteIn the first test case possible permutations that are mystic are [2,3,1] and [3,1,2]. Lexicographically smaller of the two is [2,3,1].In the second test case, [1,2,3,4,5] is the lexicographically minimal permutation and it is also mystic.In third test case possible mystic permutations are [1,2,4,3], [1,4,2,3], [1,4,3,2], [3,1,4,2], [3,2,4,1], [3,4,2,1], [4,1,2,3], [4,1,3,2] and [4,3,2,1]. The smallest one is [1,2,4,3].
4 3 1 2 3 5 2 3 4 5 1 4 2 3 1 4 1 1
2 3 1 1 2 3 4 5 1 2 4 3 -1
2 seconds
256 megabytes
['data structures', 'greedy', '*900']
A. Lex Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, a and b, of lengths n and m respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string c be initially empty. Kuznecov can do the following two types of operations: Choose any character from the string a, remove it from a, and add it to the end of c. Choose any character from the string b, remove it from b, and add it to the end of c. But, he can not do more than k operations of the same type in a row. He must perform operations until either a or b becomes empty. What is the lexicographically smallest possible value of c after he finishes?A string x is lexicographically smaller than a string y if and only if one of the following holds: x is a prefix of y, but x \neq y; in the first position where x and y differ, the string x has a letter that appears earlier in the alphabet than the corresponding letter in y.InputThere are several test cases in the input data. The first line contains a single integer t (1 \leq t \leq 100) — the number of test cases. This is followed by the test cases description.The first line of each test case contains three integers n, m, and k (1\leq n,m,k \leq 100) — parameters from the statement.The second line of each test case contains the string a of length n.The third line of each test case contains the string b of length m. The strings contain only lowercase English letters. It is guaranteed that no symbol appears in a and b simultaneously.OutputIn each test case, output a single string c — the answer to the problem.ExampleInput 3 6 4 2 aaaaaa bbbb 5 9 3 caaca bedededeb 7 7 1 noskill wxhtzdy Output aabaabaa aaabbcc dihktlwlxnyoz NoteIn the first test case, it is optimal to take two 'a's from the string a and add them to the string c. Then it is forbidden to take more characters from a, hence one character 'b' from the string b has to be taken. Following that logic, we end up with c being 'aabaabaa' when string a is emptied.In the second test case it is optimal to take as many 'a's from string a as possible, then take as many 'b's as possible from string b. In the end, we take two 'c's from the string a emptying it.
3 6 4 2 aaaaaa bbbb 5 9 3 caaca bedededeb 7 7 1 noskill wxhtzdy
aabaabaa aaabbcc dihktlwlxnyoz
1 second
256 megabytes
['brute force', 'greedy', 'implementation', 'sortings', 'two pointers', '*800']
C. Manipulating Historytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.—Perfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string s of length 1 initially. To fix the chaos caused by Yukari, she needs to do the following operations n times, for the i-th time: She chooses a non-empty substring t_{2i-1} of s. She replaces t_{2i-1} with a non-empty string, t_{2i}. Note that the lengths of strings t_{2i-1} and t_{2i} can be different.Note that if t_{2i-1} occurs more than once in s, exactly one of them will be replaced.For example, let s="marisa", t_{2i-1}="a", and t_{2i}="z". After the operation, s becomes "mzrisa" or "marisz".After n operations, Keine got the final string and an operation sequence t of length 2n. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of t. Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string "abc" its substrings are: "ab", "c", "bc" and some others. But the following strings are not its substring: "ac", "cba", "acb".HacksYou cannot make hacks in this problem.InputEach test contains multiple test cases. The first line contains a single integer T (1 \leq T \leq 10^3) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n < 10 ^ 5) — the number of operations.The next 2n lines contains one non-empty string t_{i} — the i-th string of the shuffled sequence t.The next line contains one non-empty string s — the final string.It is guaranteed that the total length of given strings (including t_i and s) over all test cases does not exceed 2 \cdot 10 ^ 5. All given strings consist of lowercase English letters only.It is guaranteed that the initial string exists. It can be shown that the initial string is unique.OutputFor each test case, print the initial string in one line.ExampleInput 2 2 a ab b cd acd 3 z a a aa yakumo ran yakumoran Output a z NoteTest case 1:Initially s is "a". In the first operation, Keine chooses "a", and replaces it with "ab". s becomes "ab". In the second operation, Keine chooses "b", and replaces it with "cd". s becomes "acd".So the final string is "acd", and t=["a", "ab", "b", "cd"] before being shuffled.Test case 2:Initially s is "z". In the first operation, Keine chooses "z", and replaces it with "aa". s becomes "aa". In the second operation, Keine chooses "a", and replaces it with "ran". s becomes "aran". In the third operation, Keine chooses "a", and replaces it with "yakumo". s becomes "yakumoran".So the final string is "yakumoran", and t=["z", "aa", "a", "ran", "a", "yakumo"] before being shuffled.
2 2 a ab b cd acd 3 z a a aa yakumo ran yakumoran
a z
1 second
256 megabytes
['constructive algorithms', 'greedy', 'strings', '*1700']
B. Patchouli's Magical Talismantime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShe is skilled in all kinds of magics, and is keen on inventing new one.—Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has n magical tokens. Their magical power can be represented with positive integers a_1, a_2, \ldots, a_n. Patchouli may perform the following two operations on the tokens. Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens. Reduction: Patchouli chooses a token with an even value of magical power x, removes it and creates a new token with magical power equal to \frac{x}{2}. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^3) — the number of test cases. The description of the test cases follows.For each test case, the first line contains one integer n (1 \leq n\leq 2\cdot 10^5) — the initial number of tokens.The second line contains n intergers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^9) — the initial magical power of the n tokens.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power.It can be shown that under such restrictions the required sequence of operations exists. ExampleInput 4 2 1 9 3 1 1 2 3 2 4 8 3 1049600 33792 1280 Output 0 1 3 10 NoteTest case 1:a consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of 1 and 2 and perform Fusion. Now a=[1,3], both are odd numbers.Test case 3:Choose the tokens with magical power of 2 and 8 and perform Fusion. Now a=[4,10].Choose the token with magical power of 10 and perform Reduction. Now a=[4,5].Choose the tokens with magical power of 4 and 5 and perform Fusion. Now a=[9], and 9 is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than 3 moves, so the answer is 3.
4 2 1 9 3 1 1 2 3 2 4 8 3 1049600 33792 1280
0 1 3 10
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'greedy', 'sortings', '*800']
A. Cirno's Perfect Bitmasks Classroomtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEven if it's a really easy question, she won't be able to answer it— Perfect Memento in Strict SenseCirno's perfect bitmasks classroom has just started!Cirno gave her students a positive integer x. As an assignment, her students need to find the minimum positive integer y, which satisfies the following two conditions:x\ \texttt{and}\ y > 0 x\ \texttt{xor}\ y > 0Where \texttt{and} is the bitwise AND operation, and \texttt{xor} is the bitwise XOR operation.Among the students was Mystia, who was truly baffled by all these new operators. Please help her!InputThe first line of input contains a single integer t (1 \leq t \leq 10^3) — the number of input test cases.For each test case, the only line of input contains one integer x (1 \leq x \leq 2^{30}).OutputFor each test case, print a single integer — the minimum number of y.ExampleInput 7 1 2 5 9 16 114514 1000000 Output 3 3 1 1 17 2 64 NoteTest case 1: 1\; \texttt{and}\; 3=1>0, 1\; \texttt{xor}\; 3=2>0.Test case 2: 2\; \texttt{and}\; 3=2>0, 2\; \texttt{xor}\; 3=1>0.
7 1 2 5 9 16 114514 1000000
3 3 1 1 17 2 64
1 second
256 megabytes
['bitmasks', 'brute force', '*800']
F. Koishi's Unconscious Permutationtime limit per test12 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAs she closed the Satori's eye that could read minds, Koishi gained the ability to live in unconsciousness. Even she herself does not know what she is up to.— Subterranean AnimismKoishi is unconsciously permuting n numbers: 1, 2, \ldots, n.She thinks the permutation p is beautiful if s=\sum\limits_{i=1}^{n-1} [p_i+1=p_{i+1}]. [x] equals to 1 if x holds, or 0 otherwise.For each k\in[0,n-1], she wants to know the number of beautiful permutations of length n satisfying k=\sum\limits_{i=1}^{n-1}[p_i<p_{i+1}].InputThere is one line containing two intergers n (1 \leq n \leq 250\,000) and s (0 \leq s < n).OutputPrint one line with n intergers. The i-th integers represents the answer of k=i-1, modulo 998244353.ExamplesInput 2 0 Output 1 0 Input 4 1 Output 0 3 6 0 Input 8 3 Output 0 0 0 35 770 980 70 0 NoteLet f(p)=\sum\limits_{i=1}^{n-1}[p_i<p_{i+1}].Testcase 1:[2,1] is the only beautiful permutation. And f([2,1])=0.Testcase 2:Beautiful permutations:[1,2,4,3], [1,3,4,2], [1,4,2,3], [2,1,3,4], [2,3,1,4], [3,1,2,4], [3,4,2,1], [4,2,3,1], [4,3,1,2]. The first six of them satisfy f(p)=2, while others satisfy f(p)=1.
2 0
1 0
12 seconds
1024 megabytes
['fft', 'math', '*3500']
E. Become Big For Metime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCome, let's build a world where even the weak are not forgotten!—Kijin Seija, Double Dealing CharactersShinmyoumaru has a mallet that can turn objects bigger or smaller. She is testing it out on a sequence a and a number v whose initial value is 1. She wants to make v = \gcd\limits_{i\ne j}\{a_i\cdot a_j\} by no more than 10^5 operations (\gcd\limits_{i\ne j}\{a_i\cdot a_j\} denotes the \gcd of all products of two distinct elements of the sequence a). In each operation, she picks a subsequence b of a, and does one of the followings: Enlarge: v = v \cdot \mathrm{lcm}(b) Reduce: v = \frac{v}{\mathrm{lcm}(b)} Note that she does not need to guarantee that v is an integer, that is, v does not need to be a multiple of \mathrm{lcm}(b) when performing Reduce.Moreover, she wants to guarantee that the total length of b chosen over the operations does not exceed 10^6. Fine a possible operation sequence for her. You don't need to minimize anything.InputThe first line contains a single integer n (2\leq n\leq 10^5) — the size of sequence a.The second line contains n integers a_1,a_2,\cdots,a_n (1\leq a_i\leq 10^6) — the sequence a.It can be shown that the answer exists.OutputThe first line contains a non-negative integer k (0\leq k\leq 10^5) — the number of operations.The following k lines contains several integers. For each line, the first two integers f (f\in\{0,1\}) and p (1\le p\le n) stand for the option you choose (0 for Enlarge and 1 for Reduce) and the length of b. The other p integers of the line i_1,i_2,\ldots,i_p (1\le i_1<i_2<\ldots<i_p\le n) represents the indexes of the subsequence. Formally, b_j=a_{i_j}.ExamplesInput 3 6 10 15 Output 1 0 3 1 2 3 Input 4 2 4 8 16 Output 2 0 1 4 1 1 1 NoteTest case 1:\gcd\limits_{i\ne j}\{a_i\cdot a_j\}=\gcd\{60,90,150\}=30.Perform v = v\cdot \operatorname{lcm}\{a_1,a_2,a_3\}=30.Test case 2:\gcd\limits_{i\ne j}\{a_i\cdot a_j\}=8.Perform v = v\cdot \operatorname{lcm}\{a_4\}=16.Perform v = \frac{v}{\operatorname{lcm}\{a_1\}}=8.
3 6 10 15
1 0 3 1 2 3
3 seconds
512 megabytes
['combinatorics', 'constructive algorithms', 'greedy', 'math', 'number theory', '*3500']
D. Cute numbertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRan is especially skilled in computation and mathematics. It is said that she can do unimaginable calculation work in an instant.—Perfect Memento in Strict SenseRan Yakumo is a cute girl who loves creating cute Maths problems.Let f(x) be the minimal square number strictly greater than x, and g(x) be the maximal square number less than or equal to x. For example, f(1)=f(2)=g(4)=g(8)=4.A positive integer x is cute if x-g(x)<f(x)-x. For example, 1,5,11 are cute integers, while 3,8,15 are not. Ran gives you an array a of length n. She wants you to find the smallest non-negative integer k such that a_i + k is a cute number for any element of a.InputThe first line contains one integer n (1 \leq n \leq 10^6) — the length of a.The second line contains n intergers a_1,a_2,\ldots,a_n (1 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 2\cdot 10^6) — the array a.OutputPrint a single interger k — the answer.ExamplesInput 4 1 3 8 10 Output 1 Input 5 2 3 8 9 11 Output 8 Input 8 1 2 3 4 5 6 7 8 Output 48 NoteTest case 1:3 is not cute integer, so k\ne 0.2,4,9,11 are cute integers, so k=1.
4 1 3 8 10
1
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'dsu', 'implementation', 'math', '*2900']
C. Sanae and Giant Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIs it really?! The robot only existing in my imagination?! The Colossal Walking Robot?!!— Kochiya Sanae Sanae made a giant robot — Hisoutensoku, but something is wrong with it. To make matters worse, Sanae can not figure out how to stop it, and she is forced to fix it on-the-fly.The state of a robot can be represented by an array of integers of length n. Initially, the robot is at state a. She wishes to turn it into state b. As a great programmer, Sanae knows the art of copy-and-paste. In one operation, she can choose some segment from given segments, copy the segment from b and paste it into the same place of the robot, replacing the original state there. However, she has to ensure that the sum of a does not change after each copy operation in case the robot go haywire. Formally, Sanae can choose segment [l,r] and assign a_i = b_i (l\le i\le r) if \sum\limits_{i=1}^n a_i does not change after the operation.Determine whether it is possible for Sanae to successfully turn the robot from the initial state a to the desired state b with any (possibly, zero) operations.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 2\cdot 10^4) — the number of test cases. The descriptions of the test cases follow.The first line of each test case contains two integers n, m (2 \leq n\leq 2\cdot 10^5, 1 \leq m\leq 2\cdot 10^5) — the length of a, b and the number of segments.The second line contains n intergers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^9) — the initial state a.The third line contains n intergers b_1,b_2,\ldots,b_n (1 \leq b_i \leq 10^9) — the desired state b.Then m lines follow, the i-th line contains two intergers l_i,r_i (1 \leq l_i < r_i \leq n) — the segments that can be copy-pasted by Sanae.It is guaranteed that both the sum of n and the sum of m over all test cases does not exceed 2 \cdot 10 ^ 5.OutputFor each test case, print "YES" (without quotes) if a can be turned into b, or "NO" (without quotes) otherwise.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 2 5 2 1 5 4 2 3 3 2 5 4 1 1 3 2 5 5 2 1 5 4 2 3 3 2 4 5 1 1 2 2 4 Output YES NO NoteTest case 1:One possible way of turning a to b:First, select [1,3]. After the operation, a=[3,2,5,2,3].Then, select [2,5]. After the operation, a=[3,2,5,4,1]=b.Test case 2:It can be shown that it is impossible to turn a into b.
2 5 2 1 5 4 2 3 3 2 5 4 1 1 3 2 5 5 2 1 5 4 2 3 3 2 4 5 1 1 2 2 4
YES NO
1 second
256 megabytes
['binary search', 'brute force', 'data structures', 'dsu', 'greedy', 'sortings', '*2500']
B. Railway Systemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs for the technology in the outside world, it is really too advanced for Gensokyo to even look up to.—Yasaka Kanako, Symposium of Post-mysticismThis is an interactive problem.Under the direct supervision of Kanako and the Moriya Shrine, the railway system of Gensokyo is finally finished. GSKR (Gensokyo Railways) consists of n stations with m bidirectional tracks connecting them. The i-th track has length l_i (1\le l_i\le 10^6). Due to budget limits, the railway system may not be connected, though there may be more than one track between two stations.The value of a railway system is defined as the total length of its all tracks. The maximum (or minimum) capacity of a railway system is defined as the maximum (or minimum) value among all of the currently functional system's full spanning forest.In brief, full spanning forest of a graph is a spanning forest with the same connectivity as the given graph.Kanako has a simulator only able to process no more than 2m queries. The input of the simulator is a string s of length m, consisting of characters 0 and/or 1. The simulator will assume the i-th track functional if s_i= 1. The device will then tell Kanako the maximum capacity of the system in the simulated state.Kanako wants to know the the minimum capacity of the system with all tracks functional with the help of the simulator.The structure of the railway system is fixed in advance. In other words, the interactor is not adaptive.InputThe first and only line of input contains two integers n,m (2 \leq n \leq 200, 1\le m \le 500) — the number of stations and tracks.InteractionBegin the interaction by reading n,m.To make a query, print "? s" (without quotes, s is a string of length m, consisting of characters 0 and/or 1). Then you should read our response from standard input — the maximum capacity of the system in the simulated state.If your program has made an invalid query or has run out of tries, the interactor will terminate immediately and your program will get a verdict Wrong answer. To give the final answer, print "! L" (without the quotes, L is the minimum capacity of the system with all tracks functional). Note that giving this answer is not counted towards the limit of 2m queries.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. HacksThe first line of input must contain two integers n,m (2 \leq n \leq 200, 1\le m \le 500) — the number of stations and tracks.The next m lines of input must contain exactly 3 space-separated integers u_i, v_i, l_i (1\le u_i,v_i \le n, u_i\ne v_i, 1 \leq l_i \leq 10^6) — the endpoints and the length of the i-th track.ExampleInput 5 4 0 5 9 7 Output ? 0000 ? 1110 ? 1111 ? 1101 ! 7 NoteHere is the graph of the example, satisfying l_i=i.
5 4 0 5 9 7
? 0000 ? 1110 ? 1111 ? 1101 ! 7
1 second
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'interactive', 'sortings', '*1700']
A. The Enchanted Foresttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by n points on the X-axis numbered 1 through n. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by a_1,a_2,\ldots,a_n.Marisa can start out at any point in the forest on minute 0. Each minute, the followings happen in order: She moves from point x to y (|x-y|\le 1, possibly y=x). She collects all mushrooms on point y. A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute 0.Now, Marisa wants to know the maximum number of mushrooms she can pick after k minutes.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, k (1 \le n \le 2 \cdot 10 ^ 5, 1\le k \le 10^9) — the number of positions with mushrooms and the time Marisa has, respectively.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le 10^9) — the initial number of mushrooms on point 1,2,\ldots,n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10 ^ 5.OutputFor each test case, print the maximum number of mushrooms Marisa can pick after k minutes.ExampleInput 45 25 6 1 2 35 75 6 1 2 31 29999995 700001000000000 1000000000 1000000000 1000000000 1000000000Output 12 37 1000000 5000349985 NoteTest case 1:Marisa can start at x=2. In the first minute, she moves to x=1 and collect 5 mushrooms. The number of mushrooms will be [1,7,2,3,4]. In the second minute, she moves to x=2 and collects 7 mushrooms. The numbers of mushrooms will be [2,1,3,4,5]. After 2 minutes, Marisa collects 12 mushrooms.It can be shown that it is impossible to collect more than 12 mushrooms.Test case 2:This is one of her possible moving path:2 \rightarrow 3 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5It can be shown that it is impossible to collect more than 37 mushrooms.
45 25 6 1 2 35 75 6 1 2 31 29999995 700001000000000 1000000000 1000000000 1000000000 1000000000
12 37 1000000 5000349985
2 seconds
256 megabytes
['brute force', 'greedy', '*1600']
B. Odd Subarraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array [b_1, b_2, \ldots, b_m] define its number of inversions as the number of pairs (i, j) of integers such that 1 \le i < j \le m and b_i>b_j. Let's call array b odd if its number of inversions is odd. For example, array [4, 2, 7] is odd, as its number of inversions is 1, while array [2, 1, 4, 3] isn't, as its number of inversions is 2.You are given a permutation [p_1, p_2, \ldots, p_n] of integers from 1 to n (each of them appears exactly once in the permutation). You want to split it into several consecutive subarrays (maybe just one), so that the number of the odd subarrays among them is as large as possible. What largest number of these subarrays may be odd?InputThe first line of the input contains a single integer t (1 \le t \le 10^5)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5)  — the size of the permutation.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, all p_i are distinct)  — the elements of the permutation.The sum of n over all test cases doesn't exceed 2\cdot 10^5.OutputFor each test case output a single integer  — the largest possible number of odd subarrays that you can get after splitting the permutation into several consecutive subarrays.ExampleInput 531 2 344 3 2 121 222 164 5 6 1 2 3Output 0 2 0 1 1 NoteIn the first and third test cases, no matter how we split our permutation, there won't be any odd subarrays.In the second test case, we can split our permutation into subarrays [4, 3], [2, 1], both of which are odd since their numbers of inversions are 1.In the fourth test case, we can split our permutation into a single subarray [2, 1], which is odd.In the fifth test case, we can split our permutation into subarrays [4, 5], [6, 1, 2, 3]. The first subarray has 0 inversions, and the second has 3, so it is odd.
531 2 344 3 2 121 222 164 5 6 1 2 3
0 2 0 1 1
1 second
256 megabytes
['dp', 'greedy', '*800']
A. Everything Everywhere All But Onetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1, a_2, \ldots, a_n. After you watched the amazing film "Everything Everywhere All At Once", you came up with the following operation.In one operation, you choose n-1 elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array [1, 2, 3, 1] we can get the array [2, 2, 2, 1], if we choose the first three elements, or we can get the array [\frac{4}{3}, \frac{4}{3}, 3, \frac{4}{3}], if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?InputThe first line of the input contains a single integer t (1 \le t \le 200)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 50)  — the number of integers.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 100).OutputFor each test case, if it is possible to make all elements equal after some number of operations, output \texttt{YES}. Otherwise, output \texttt{NO}.You can output \texttt{YES} and \texttt{NO} in any case (for example, strings \texttt{yEs}, \texttt{yes}, \texttt{Yes} will be recognized as a positive response).ExampleInput 4 3 42 42 42 5 1 2 3 4 5 4 4 3 2 1 3 24 2 22 Output YES YES NO NO NoteIn the first test case, all elements are already equal.In the second test case, you can choose all elements except the third, their average is \frac{1 + 2 + 4 + 5}{4} = 3, so the array will become [3, 3, 3, 3, 3].It's possible to show that it's impossible to make all elements equal in the third and fourth test cases.
4 3 42 42 42 5 1 2 3 4 5 4 4 3 2 1 3 24 2 22
YES YES NO NO
1 second
256 megabytes
['greedy', '*800']
E. The Ultimate LIS Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt turns out that this is exactly the 100-th problem of mine that appears in some programming competition. So it has to be special! And what can be more special than another problem about LIS...You are given a permutation p_1, p_2, \ldots, p_{2n+1} of integers from 1 to 2n+1. You will have to process q updates, where the i-th update consists in swapping p_{u_i}, p_{v_i}.After each update, find any cyclic shift of p with LIS \le n, or determine that there is no such shift. (Refer to the output section for details).Here LIS(a) denotes the length of longest strictly increasing subsequence of a.Hacks are disabled in this problem. Don't ask why.InputThe first line of the input contains two integers n, q (2 \le n \le 10^5, 1 \le q \le 10^5).The second line of the input contains 2n+1 integers p_1, p_2, \ldots, p_{2n+1} (1 \le p_i \le 2n+1, all p_i are distinct)  — the elements of p.The i-th of the next q lines contains two integers u_i, v_i (1 \le u_i, v_i \le 2n+1, u_i \neq v_i)  — indicating that you have to swap elements p_{u_i}, p_{v_i} in the i-th update.OutputAfter each update, output any k (0 \le k \le 2n), such that the length of the longest increasing subsequence of (p_{k+1}, p_{k+2}, \ldots, p_{2n+1}, p_1, \ldots, p_k) doesn't exceed n, or -1, if there is no such k.ExampleInput 2 6 1 2 3 4 5 1 5 1 5 4 5 5 4 1 4 2 5 Output -1 -1 2 -1 4 0 NoteAfter the first update, our permutation becomes (5, 2, 3, 4, 1). We can show that all its cyclic shifts have LIS \ge 3.After the second update, our permutation becomes (1, 2, 3, 4, 5). We can show that all its cyclic shifts have LIS \ge 3.After the third update, our permutation becomes (1, 2, 3, 5, 4). Its shift by 2 is (3, 5, 4, 1, 2), and its LIS = 2.After the fourth update, our permutation becomes (1, 2, 3, 4, 5). We can show that all its cyclic shifts have LIS \ge 3.After the fifth update, our permutation becomes (4, 2, 3, 1, 5). Its shift by 4 is (5, 4, 2, 3, 1), and its LIS = 2.After the fifth update, our permutation becomes (4, 5, 3, 1, 2). Its shift by 0 is (4, 5, 3, 1, 2), and its LIS = 2.
2 6 1 2 3 4 5 1 5 1 5 4 5 5 4 1 4 2 5
-1 -1 2 -1 4 0
2 seconds
256 megabytes
['data structures', 'greedy', '*3500']
D2. Permutation Weight (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The difference between the easy and hard versions is that in this version, you have to output the lexicographically smallest permutation with the smallest weight.You are given a permutation p_1, p_2, \ldots, p_n of integers from 1 to n.Let's define the weight of the permutation q_1, q_2, \ldots, q_n of integers from 1 to n as |q_1 - p_{q_{2}}| + |q_2 - p_{q_{3}}| + \ldots + |q_{n-1} - p_{q_{n}}| + |q_n - p_{q_{1}}|You want your permutation to be as lightweight as possible. Among the permutations q with the smallest possible weight, find the lexicographically smallest.Permutation a_1, a_2, \ldots, a_n is lexicographically smaller than permutation b_1, b_2, \ldots, b_n, if there exists some 1 \le i \le n such that a_j = b_j for all 1 \le j < i and a_i<b_i.InputThe first line of the input contains a single integer t (1 \le t \le 100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 200)  — the size of the permutation.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, all p_i are distinct)  — the elements of the permutation.The sum of n over all test cases doesn't exceed 400.OutputFor each test case, output n integers q_1, q_2, \ldots, q_n (1 \le q_i \le n, all q_i are distinct)  — the lexicographically smallest permutation with the smallest weight.ExampleInput 322 142 3 1 455 4 3 2 1Output 1 2 1 3 4 2 1 3 4 2 5 NoteIn the first test case, there are two permutations of length 2: (1, 2) and (2, 1). Permutation (1, 2) has weight |1 - p_2| + |2 - p_1| = 0, and the permutation (2, 1) has the same weight: |2 - p_1| + |1 - p_2| = 0. In this version, you have to output the lexicographically smaller of them  — (1, 2).In the second test case, the weight of the permutation (1, 3, 4, 2) is |1 - p_3| + |3 - p_4| + |4 - p_2| + |2 - p_1| = |1 - 1| + |3 - 4| + |4 - 3| + |2 - 2| = 2. There are no permutations with smaller weights.In the third test case, the weight of the permutation (1, 3, 4, 2, 5) is |1 - p_3| + |3 - p_4| + |4 - p_2| + |2 - p_5| + |5 - p_1| = |1 - 3| + |3 - 2| + |4 - 4| + |2 - 1| + |5 - 5| = 4. There are no permutations with smaller weights.
322 142 3 1 455 4 3 2 1
1 2 1 3 4 2 1 3 4 2 5
1 second
256 megabytes
['constructive algorithms', 'greedy', '*3500']
D1. Permutation Weight (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The difference between the easy and hard versions is that in this version, you can output any permutation with the smallest weight.You are given a permutation p_1, p_2, \ldots, p_n of integers from 1 to n.Let's define the weight of the permutation q_1, q_2, \ldots, q_n of integers from 1 to n as |q_1 - p_{q_{2}}| + |q_2 - p_{q_{3}}| + \ldots + |q_{n-1} - p_{q_{n}}| + |q_n - p_{q_{1}}|You want your permutation to be as lightweight as possible. Find any permutation q with the smallest possible weight.InputThe first line of the input contains a single integer t (1 \le t \le 100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 200)  — the size of the permutation.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, all p_i are distinct)  — the elements of the permutation.The sum of n over all test cases doesn't exceed 400.OutputFor each test case, output n integers q_1, q_2, \ldots, q_n (1 \le q_i \le n, all q_i are distinct)  — one of the permutations with the smallest weight.ExampleInput 322 142 3 1 455 4 3 2 1Output 1 2 1 3 4 2 1 4 2 3 5 NoteIn the first test case, there are two permutations of length 2: (1, 2) and (2, 1). Permutation (1, 2) has weight |1 - p_2| + |2 - p_1| = 0, and permutation (2, 1) has the same weight: |2 - p_1| + |1 - p_2| = 0. You can output any of these permutations in this version.In the second test case, the weight of the permutation (1, 3, 4, 2) is |1 - p_3| + |3 - p_4| + |4 - p_2| + |2 - p_1| = |1 - 1| + |3 - 4| + |4 - 3| + |2 - 2| = 2. There are no permutations with smaller weights.In the third test case, the weight of the permutation (1, 4, 2, 3, 5) is |1 - p_4| + |4 - p_2| + |2 - p_3| + |3 - p_5| + |5 - p_1| = |1 - 2| + |4 - 4| + |2 - 3| + |3 - 1| + |5 - 5| = 4. There are no permutations with smaller weights.
322 142 3 1 455 4 3 2 1
1 2 1 3 4 2 1 4 2 3 5
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'dsu', '*2800']
C. Bring Balancetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlina has a bracket sequence s of length 2n, consisting of n opening brackets '(' and n closing brackets ')'. As she likes balance, she wants to turn this bracket sequence into a balanced bracket sequence.In one operation, she can reverse any substring of s.What's the smallest number of operations that she needs to turn s into a balanced bracket sequence? It can be shown that it's always possible in at most n operations.As a reminder, a sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), and (()(())) are balanced, while )(, ((), and (()))( are not.InputThe first line of the input contains a single integer t (1 \le t \le 2 \cdot 10^4)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains a string s of length 2n, consisting of n opening and n closing brackets.The sum of n over all test cases doesn't exceed 2\cdot 10^5.OutputFor each test case, in the first line output a single integer k (0 \le k \le n)  — the smallest number of operations required.The i-th of the next k lines should contain two integers l_i, r_i (1 \le l_i \le r_i \le 2n), indicating that in the i-th operation, Alina will reverse the substring s_ls_{l+1} \ldots s_{r-1}s_r. Here the numeration starts from 1.If there are multiple sequences of operations with the smallest length which transform the sequence into a balanced one, you can output any of them.ExampleInput 32(())5())((()))(6())((()))(()Output 0 2 3 4 9 10 1 2 11NoteIn the first test case, the string is already balanced.In the second test case, the string will be transformed as follows: ())((()))( \to ()()(()))( \to ()()(())(), where the last string is balanced.In the third test case, the string will be transformed to ((()))((())), which is balanced.
32(())5())((()))(6())((()))(()
0 2 3 4 9 10 1 2 11
1 second
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*2600']
B. Linguisticstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlina has discovered a weird language, which contains only 4 words: \texttt{A}, \texttt{B}, \texttt{AB}, \texttt{BA}. It also turned out that there are no spaces in this language: a sentence is written by just concatenating its words into a single string.Alina has found one such sentence s and she is curious: is it possible that it consists of precisely a words \texttt{A}, b words \texttt{B}, c words \texttt{AB}, and d words \texttt{BA}?In other words, determine, if it's possible to concatenate these a+b+c+d words in some order so that the resulting string is s. Each of the a+b+c+d words must be used exactly once in the concatenation, but you can choose the order in which they are concatenated.InputThe first line of the input contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains four integers a, b, c, d (0\le a,b,c,d\le 2\cdot 10^5) — the number of times that words \texttt{A}, \texttt{B}, \texttt{AB}, \texttt{BA} respectively must be used in the sentence.The second line contains the string s (s consists only of the characters \texttt{A} and \texttt{B}, 1\le |s| \le 2\cdot 10^5, |s|=a+b+2c+2d)  — the sentence. Notice that the condition |s|=a+b+2c+2d (here |s| denotes the length of the string s) is equivalent to the fact that s is as long as the concatenation of the a+b+c+d words.The sum of the lengths of s over all test cases doesn't exceed 2\cdot 10^5.OutputFor each test case output \texttt{YES} if it is possible that the sentence s consists of precisely a words \texttt{A}, b words \texttt{B}, c words \texttt{AB}, and d words \texttt{BA}, and \texttt{NO} otherwise. You can output each letter in any case.ExampleInput 8 1 0 0 0 B 0 0 1 0 AB 1 1 0 1 ABAB 1 0 1 1 ABAAB 1 1 2 2 BAABBABBAA 1 1 2 3 ABABABBAABAB 2 3 5 4 AABAABBABAAABABBABBBABB 1 3 3 10 BBABABABABBBABABABABABABAABABA Output NO YES YES YES YES YES NO YES NoteIn the first test case, the sentence s is \texttt{B}. Clearly, it can't consist of a single word \texttt{A}, so the answer is \texttt{NO}.In the second test case, the sentence s is \texttt{AB}, and it's possible that it consists of a single word \texttt{AB}, so the answer is \texttt{YES}.In the third test case, the sentence s is \texttt{ABAB}, and it's possible that it consists of one word \texttt{A}, one word \texttt{B}, and one word \texttt{BA}, as \texttt{A} + \texttt{BA} + \texttt{B} = \texttt{ABAB}.In the fourth test case, the sentence s is \texttt{ABAAB}, and it's possible that it consists of one word \texttt{A}, one word \texttt{AB}, and one word \texttt{BA}, as \texttt{A} + \texttt{BA} + \texttt{AB} = \texttt{ABAAB}. In the fifth test case, the sentence s is \texttt{BAABBABBAA}, and it's possible that it consists of one word \texttt{A}, one word \texttt{B}, two words \texttt{AB}, and two words \texttt{BA}, as \texttt{BA} + \texttt{AB} + \texttt{B} + \texttt{AB} + \texttt{BA} + \texttt{A}= \texttt{BAABBABBAA}.
8 1 0 0 0 B 0 0 1 0 AB 1 1 0 1 ABAB 1 0 1 1 ABAAB 1 1 2 2 BAABBABBAA 1 1 2 3 ABABABBAABAB 2 3 5 4 AABAABBABAAABABBABBBABB 1 3 3 10 BBABABABABBBABABABABABABAABABA
NO YES YES YES YES YES NO YES
1 second
256 megabytes
['greedy', 'implementation', 'sortings', 'strings', '*2000']
A. Circular Local MiniMaxtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n integers a_1, a_2, \ldots, a_n. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?In other words, check if there exists a rearrangement b_1, b_2, \ldots, b_n of the integers a_1, a_2, \ldots, a_n such that for each i from 1 to n at least one of the following conditions holds: b_{i-1} < b_i > b_{i+1} b_{i-1} > b_i < b_{i+1}To make sense of the previous formulas for i=1 and i=n, one shall define b_0=b_n and b_{n+1}=b_1.InputThe first line of the input contains a single integer t (1 \le t \le 3\cdot 10^4)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 10^5)  — the number of integers.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9).The sum of n over all test cases doesn't exceed 2\cdot 10^5.OutputFor each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output \texttt{NO}. You can output each letter in any case.Otherwise, output \texttt{YES}. In the second line, output n integers b_1, b_2, \ldots, b_n, which are a rearrangement of a_1, a_2, \ldots, a_n and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them.ExampleInput 4 3 1 1 2 4 1 9 8 4 4 2 0 2 2 6 1 1 1 11 111 1111 Output NO YES 1 8 4 9 NO YES 1 11 1 111 1 1111 NoteIt can be shown that there are no valid arrangements for the first and the third test cases.In the second test case, the arrangement [1, 8, 4, 9] works. In this arrangement, 1 and 4 are both smaller than their neighbors, and 8, 9 are larger.In the fourth test case, the arrangement [1, 11, 1, 111, 1, 1111] works. In this arrangement, the three elements equal to 1 are smaller than their neighbors, while all other elements are larger than their neighbors.
4 3 1 1 2 4 1 9 8 4 4 2 0 2 2 6 1 1 1 11 111 1111
NO YES 1 8 4 9 NO YES 1 11 1 111 1 1111
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', '*1100']