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
B. Forming Trianglestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have n sticks, numbered from 1 to n. The length of the i-th stick is 2^{a_i}.You want to choose exactly 3 sticks out of the given n sticks, and form a non-degenerate triangle out of them, using the sticks as the sides of the triangle. A triangle is called non-degenerate if its area is strictly greater than 0.You have to calculate the number of ways to choose exactly 3 sticks so that a triangle can be formed out of them. Note that the order of choosing sticks does not matter (for example, choosing the 1-st, 2-nd and 4-th stick is the same as choosing the 2-nd, 4-th and 1-st stick). InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines: the first line contains one integer n (1 \le n \le 3 \cdot 10^5); the second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le n). Additional constraint on the input: the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print one integer — the number of ways to choose exactly 3 sticks so that a triangle can be formed out of them.ExampleInput 471 1 1 1 1 1 143 2 1 331 2 311Output 35 2 0 0 NoteIn the first test case of the example, any three sticks out of the given 7 can be chosen.In the second test case of the example, you can choose the 1-st, 2-nd and 4-th stick, or the 1-st, 3-rd and 4-th stick.In the third test case of the example, you cannot form a triangle out of the given sticks with lengths 2, 4 and 8.
471 1 1 1 1 1 143 2 1 331 2 311
35 2 0 0
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'math', 'sortings', '*1200']
A. Tricky Templatetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n and three strings a, b, c, each consisting of n lowercase Latin letters.Let a template be a string t consisting of n lowercase and/or uppercase Latin letters. The string s matches the template t if the following conditions hold for all i from 1 to n: if the i-th letter of the template is lowercase, then s_i must be the same as t_i; if the i-th letter of the template is uppercase, then s_i must be different from the lowercase version of t_i. For example, if there is a letter 'A' in the template, you cannot use the letter 'a' in the corresponding position of the string. Accordingly, the string doesn't match the template if the condition doesn't hold for at least one i.Determine whether there exists a template t such that the strings a and b match it, while the string c does not.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains an integer n (1 \le n \le 20) — the length of the given strings.The next three lines contain the strings a, b and c. Each string consists of exactly n lowercase Latin letters.OutputFor each testcase, print "YES" if there exists a template t such that the strings a and b match it, while the string c does not. Otherwise, print "NO".ExampleInput 41abc2aabbaa10mathforcesluckforcesadhoccoder3accabdabcOutput YES NO YES NO NoteIn the first test case, you can use the template "C". The first letter of strings a and b differ from 'c', so they match the template. The first letter of string c equals 'c', so it doesn't match.In the third test case, you can use the template "CODEforces".
41abc2aabbaa10mathforcesluckforcesadhoccoder3accabdabc
YES NO YES NO
2 seconds
256 megabytes
['constructive algorithms', 'implementation', 'strings', '*800']
G. Mischievous Shootertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOnce the mischievous and wayward shooter named Shel found himself on a rectangular field of size n \times m, divided into unit squares. Each cell either contains a target or not.Shel only had a lucky shotgun with him, with which he can shoot in one of the four directions: right-down, left-down, left-up, or right-up. When fired, the shotgun hits all targets in the chosen direction, the Manhattan distance to which does not exceed a fixed constant k. The Manhattan distance between two points (x_1, y_1) and (x_2, y_2) is equal to |x_1 - x_2| + |y_1 - y_2|. Possible hit areas for k = 3. Shel's goal is to hit as many targets as possible. Please help him find this value.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains field dimensions n, m, and the constant for the shotgun's power k (1 \le n, m, k \le 10^5, 1 \le n \cdot m \le 10^5).Each of the next n lines contains m characters — the description of the next field row, where the character '.' means the cell is empty, and the character '#' indicates the presence of a target. It is guaranteed that the sum of n \cdot m over all test cases does not exceed 10^5.OutputFor each test case, output a single integer on a separate line, which is equal to the maximum possible number of hit targets with one shot.ExampleInput 43 3 1.#.###.#.2 5 3###.....##4 4 2..#####.#..#####2 1 3##Output 3 4 5 2 NotePossible optimal shots for the examples in the statement:
43 3 1.#.###.#.2 5 3###.....##4 4 2..#####.#..#####2 1 3##
3 4 5 2
2 seconds
256 megabytes
['brute force', 'data structures', 'divide and conquer', 'dp', 'implementation', '*2200']
F. Sum of Progressiontime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given an array a of n numbers. There are also q queries of the form s, d, k.For each query q, find the sum of elements a_s + a_{s+d} \cdot 2 + \dots + a_{s + d \cdot (k - 1)} \cdot k. In other words, for each query, it is necessary to find the sum of k elements of the array with indices starting from the s-th, taking steps of size d, multiplying it by the serial number of the element in the resulting sequence.InputEach test consists of several testcases. The first line contains one integer t (1 \le t \le 10^4) — the number of testcases. Next lines contain descriptions of testcases.The first line of each testcase contains two numbers n, q (1 \le n \le 10^5, 1 \le q \le 2 \cdot 10^5) — the number of elements in the array a and the number of queries.The second line contains n integers a_1, ... a_n (-10^8 \le a_1, ..., a_n \le 10^8) — elements of the array a.The next q lines each contain three integers s, d, and k (1 \le s, d, k \le n, s + d\cdot (k - 1) \le n ).It is guaranteed that the sum of n over all testcases does not exceed 10^5, and that the sum of q over all testcases does not exceed 2 \cdot 10^5 .OutputFor each testcase, print q numbers in a separate line — the desired sums, separated with space.ExampleInput 53 31 1 21 2 22 2 11 1 23 1-100000000 -100000000 -1000000001 1 35 31 2 3 4 51 2 32 3 21 1 53 1100000000 100000000 1000000001 1 37 734 87 5 42 -44 66 -322 2 24 3 11 3 26 2 15 2 22 5 26 1 2Output 5 1 3 -600000000 22 12 55 600000000 171 42 118 66 -108 23 2
53 31 1 21 2 22 2 11 1 23 1-100000000 -100000000 -1000000001 1 35 31 2 3 4 51 2 32 3 21 1 53 1100000000 100000000 1000000001 1 37 734 87 5 42 -44 66 -322 2 24 3 11 3 26 2 15 2 22 5 26 1 2
5 1 3 -600000000 22 12 55 600000000 171 42 118 66 -108 23 2
2 seconds
1024 megabytes
['brute force', 'data structures', 'dp', 'implementation', 'math', '*1900']
E. Eat the Chiptime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game on a checkered board. The board has h rows, numbered from top to bottom, and w columns, numbered from left to right. Both players have a chip each. Initially, Alice's chip is located at the cell with coordinates (x_a, y_a) (row x_a, column y_a), and Bob's chip is located at (x_b, y_b). It is guaranteed that the initial positions of the chips do not coincide. Players take turns making moves, with Alice starting.On her turn, Alice can move her chip one cell down or one cell down-right or down-left (diagonally). Bob, on the other hand, moves his chip one cell up, up-right, or up-left. It is not allowed to make moves that go beyond the board boundaries.More formally, if at the beginning of Alice's turn she is in the cell with coordinates (x_a, y_a), then she can move her chip to one of the cells (x_a + 1, y_a), (x_a + 1, y_a - 1), or (x_a + 1, y_a + 1). Bob, on his turn, from the cell (x_b, y_b) can move to (x_b - 1, y_b), (x_b - 1, y_b - 1), or (x_b - 1, y_b + 1). The new chip coordinates (x', y') must satisfy the conditions 1 \le x' \le h and 1 \le y' \le w. Example game state. Alice plays with the white chip, Bob with the black one. Arrows indicate possible moves. A player immediately wins if they place their chip in a cell occupied by the other player's chip. If either player cannot make a move (Alice—if she is in the last row, i.e. x_a = h, Bob—if he is in the first row, i.e. x_b = 1), the game immediately ends in a draw.What will be the outcome of the game if both opponents play optimally?InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. This is followed by the description of the test cases.Each test case consists of a single line containing six integers h, w, x_a, y_a, x_b, y_b (1 \le x_a, x_b \le h \le 10^6, 1 \le y_a, y_b \le w \le 10^9) — the dimensions of the board and the initial positions of Alice's and Bob's chips. It is guaranteed that either x_a \ne x_b or y_a \ne y_b.It is guaranteed that the sum of h over all test cases does not exceed 10^6.OutputFor each test case, output "Alice" if Alice wins, "Bob" if Bob wins, and "Draw" if neither player can secure a victory. You can output each letter in any case (lowercase or uppercase). For example, the strings "bOb", "bob", "Bob", and "BOB" will be accepted as Bob's victory.ExampleInput 126 5 2 2 5 34 1 2 1 4 11 4 1 3 1 15 5 1 4 5 24 4 1 1 4 410 10 1 6 10 810 10 2 6 10 710 10 9 1 8 110 10 8 1 10 210 10 1 1 2 110 10 1 3 4 110 10 3 1 1 1Output Alice Bob Draw Draw Draw Alice Draw Draw Bob Alice Alice Draw
126 5 2 2 5 34 1 2 1 4 11 4 1 3 1 15 5 1 4 5 24 4 1 1 4 410 10 1 6 10 810 10 2 6 10 710 10 9 1 8 110 10 8 1 10 210 10 1 1 2 110 10 1 3 4 110 10 3 1 1 1
Alice Bob Draw Draw Draw Alice Draw Draw Bob Alice Alice Draw
1 second
256 megabytes
['brute force', 'games', 'greedy', 'math', '*1600']
D. Very Different Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya has an array a_i of n integers. His brother Vasya became envious and decided to make his own array of n integers.To do this, he found m integers b_i (m\ge n), and now he wants to choose some n integers of them and arrange them in a certain order to obtain an array c_i of length n.To avoid being similar to his brother, Vasya wants to make his array as different as possible from Petya's array. Specifically, he wants the total difference D = \sum_{i=1}^{n} |a_i - c_i| to be as large as possible.Help Vasya find the maximum difference D he can obtain.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. This is followed by a description of the test cases.The first line of each test case contains two integers n and m (1\le n\le m\le 2 \cdot 10^5).The second line of each test case contains n integers a_i (1\le a_i\le 10^9). The third line of each test case contains m integers b_i (1\le b_i\le 10^9).It is guaranteed that in a test, the sum of m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum total difference D that can be obtained.ExampleInput 94 66 1 2 43 5 1 7 2 33 41 1 11 1 1 15 51 2 3 4 51 2 3 4 52 65 88 7 5 8 2 102 24 19 64 68 10 6 43 10 6 1 8 93 56 5 21 7 9 7 25 59 10 6 3 75 9 2 3 91 632 7 10 1 1 5Output 16 0 12 11 10 23 15 25 7 NoteIn the first example, Vasya can, for example, create the array (1, 5, 7, 2). Then the total difference will be D = |6-1|+|1-5|+|2-7|+|4-2| = 5+4+5+2 = 16.In the second example, all the integers available to Vasya are equal to 1, so he can only create the array (1, 1, 1), for which the difference D = 0.In the third example, Vasya can, for example, create the array (5, 4, 3, 2, 1). Then the total difference will be D = |1-5|+|2-4|+|3-3|+|4-2|+|5-1| = 4+2+0+2+4 = 12.
94 66 1 2 43 5 1 7 2 33 41 1 11 1 1 15 51 2 3 4 51 2 3 4 52 65 88 7 5 8 2 102 24 19 64 68 10 6 43 10 6 1 8 93 56 5 21 7 9 7 25 59 10 6 3 75 9 2 3 91 632 7 10 1 1 5
16 0 12 11 10 23 15 25 7
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', 'two pointers', '*1100']
C. Sending Messagestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputStepan is a very busy person. Today he needs to send n messages at moments m_1, m_2, \dots m_n (m_i < m_{i + 1}). Unfortunately, by the moment 0, his phone only has f units of charge left. At the moment 0, the phone is turned on.The phone loses a units of charge for each unit of time it is on. Also, at any moment, Stepan can turn off the phone and turn it on later. This action consumes b units of energy each time. Consider turning on and off to be instantaneous, so you can turn it on at moment x and send a message at the same moment, and vice versa, send a message at moment x and turn off the phone at the same moment.If at any point the charge level drops to 0 (becomes \le 0), it is impossible to send a message at that moment.Since all messages are very important to Stepan, he wants to know if he can send all the messages without the possibility of charging the phone.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. This is followed by the descriptions of the test cases.The first line of each test case contains four integers n, f, a, and b (1 \le n \le 2 \cdot 10^5, 1 \le f, a, b \le 10^9) — the number of messages, the initial phone's charge, the charge consumption per unit of time, and the consumption when turned off and on sequentially.The second line of each test case contains n integers m_1, m_2, \dots, m_n (1 \le m_i \le 10^9, m_i < m_{i + 1}) — the moments at which messages need to be sent.It is guaranteed that in a test the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" if Stepan can send all the messages, and "NO" otherwise.You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be accepted as a positive answer.ExampleInput 61 3 1 537 21 1 34 6 10 13 17 20 265 10 1 21 2 3 4 51 1000000000 1000000000 100000000010000000003 11 9 66 8 1012 621526648 2585904 356629951789 61859 71998 73401 247675 298086 606959 663464 735972 806043 806459 919683Output NO YES YES NO NO YES NoteIn the first test case of the example, at moment 0, the phone's charge is 3. When sending a message at moment 3 without turning it off, (3 - 0) \cdot 1 = 3 units of charge will be spent. In this case, the charge will drop to 0 and Stepan will not be able to send the message. When turning off and on, the phone's charge will decrease by 5, so it will not be possible to send the message in this way.In the third test case of the example, at moment 0, the phone's charge is 10. The phone loses 1 unit of charge per unit of time, and when turned off and on, it loses 2 units of charge. To send all messages, the following actions can be taken: Turn off the phone at moment 0 and turn it on at moment 1, after which 10 - 2 = 8 units of charge will remain; send a message at moment 1; send a message at moment 2, after which 8 - (2 - 1) \cdot 1 = 7 units of charge will remain; Turn off the phone at moment 2 and turn it on at moment 3, after which 7 - 2 = 5 units of charge will remain; send a message at moment 3; Turn off the phone at moment 3 and turn it on at moment 4, after which 5 - 2 = 3 units of charge will remain; send a message at moment 4; Turn off the phone at moment 4 and turn it on at moment 5, after which 3 - 2 = 1 unit of charge will remain; send a message at moment 5. The last (sixth) test set of the example may fail if there is an integer overflow in your solution.
61 3 1 537 21 1 34 6 10 13 17 20 265 10 1 21 2 3 4 51 1000000000 1000000000 100000000010000000003 11 9 66 8 1012 621526648 2585904 356629951789 61859 71998 73401 247675 298086 606959 663464 735972 806043 806459 919683
NO YES YES NO NO YES
2 seconds
256 megabytes
['greedy', 'math', '*900']
B. Arranging Catstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn order to test the hypothesis about the cats, the scientists must arrange the cats in the boxes in a specific way. Of course, they would like to test the hypothesis and publish a sensational article as quickly as possible, because they are too engrossed in the next hypothesis about the phone's battery charge.Scientists have n boxes in which cats may or may not sit. Let the current state of the boxes be denoted by the sequence b_1, \dots, b_n: b_i = 1 if there is a cat in box number i, and b_i = 0 otherwise. Fortunately, the unlimited production of cats has already been established, so in one day, the scientists can perform one of the following operations: Take a new cat and place it in a box (for some i such that b_i = 0, assign b_i = 1). Remove a cat from a box and send it into retirement (for some i such that b_i = 1, assign b_i = 0). Move a cat from one box to another (for some i, j such that b_i = 1, b_j = 0, assign b_i = 0, b_j = 1). It has also been found that some boxes were immediately filled with cats. Therefore, the scientists know the initial position of the cats in the boxes s_1, \dots, s_n and the desired position f_1, \dots, f_n.Due to the large amount of paperwork, the scientists do not have time to solve this problem. Help them for the sake of science and indicate the minimum number of days required to test the hypothesis.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. This is followed by descriptions of the test cases.Each test case consists of three lines.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of boxes.The second line of each test case contains a string s of n characters, where the i-th character is '1' if there is a cat in the i-th box and '0' otherwise.The third line of each test case contains a string f of n characters, where the i-th character is '1' if there should be a cat in the i-th box and '0' otherwise.It is guaranteed that in a test the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single integer on a separate line — the minimum number of operations required to obtain the desired position from the initial position. It can be shown that a solution always exists.ExampleInput 6510010000011113000111401011010310010181001100111111110Output 2 0 3 2 1 4 NoteIn the first test case, you can first move the cat from the first box to the fifth, and then remove the cat from the fourth box.In the second test case, there is nothing to do — the only cat is already sitting in the correct box.In the third test case of input data, it takes three days to place a cat in each box.
6510010000011113000111401011010310010181001100111111110
2 0 3 2 1 4
2 seconds
512 megabytes
['greedy', 'implementation', '*800']
A. Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA square of positive (strictly greater than 0) area is located on the coordinate plane, with sides parallel to the coordinate axes. You are given the coordinates of its corners, in random order. Your task is to find the area of the square.InputEach test consists of several testcases. The first line contains one integer t (1 \le t \le 100) — the number of testcases. The following is a description of the testcases.Each testcase contains four lines, each line contains two integers x_i, y_i (-1000\le x_i, y_i\le 1000), coordinates of the corners of the square. It is guaranteed that there is a square with sides parallel to the coordinate axes, with positive (strictly greater than 0) area, with corners in given points.OutputFor each test case, print a single integer, the area of the square.ExampleInput 31 24 51 54 2-1 11 -11 1-1 -145 1145 3917 1117 39Output 9 4 784
31 24 51 54 2-1 11 -11 1-1 -145 1145 3917 1117 39
9 4 784
1 second
256 megabytes
['greedy', 'math', '*800']
F2. Smooth Sailing (Hard Version)time limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions of this problem is the constraint on q. You can make hacks only if both versions of the problem are solved.Thomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with n rows and m columns. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to m from left to right. The position of a cell at row r and column c can be represented as (r, c). Below is an example of a valid grid. Example of a valid grid There are three types of cells: island, ocean and underwater volcano. Cells representing the island are marked with a '#', cells representing the ocean are marked with a '.', and cells representing an underwater volcano are marked with a 'v'. It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is also guaranteed that the set of all island cells forms a single connected component^{\dagger} and the set of all ocean cells and underwater volcano cells forms a single connected component. Additionally, it is guaranteed that there are no island cells at the edge of the grid (that is, at row 1, at row n, at column 1, and at column m).Define a round trip starting from cell (x, y) as a path Thomas takes which satisfies the following conditions: The path starts and ends at (x, y). If Thomas is at cell (i, j), he can go to cells (i+1, j), (i-1, j), (i, j-1), and (i, j+1) as long as the destination cell is an ocean cell or an underwater volcano cell and is still inside the grid. Note that it is allowed for Thomas to visit the same cell multiple times in the same round trip. The path must go around the island and fully encircle it. Some path p fully encircles the island if it is impossible to go from an island cell to a cell on the grid border by only traveling to adjacent on a side or diagonal cells without visiting a cell on path p. In the image below, the path starting from (2, 2), going to (1, 3), and going back to (2, 2) the other way does not fully encircle the island and is not considered a round trip. Example of a path that does not fully encircle the island The safety of a round trip is the minimum Manhattan distance^{\ddagger} from a cell on the round trip to an underwater volcano (note that the presence of island cells does not impact this distance).You have q queries. A query can be represented as (x, y) and for every query, you want to find the maximum safety of a round trip starting from (x, y). It is guaranteed that (x, y) is an ocean cell or an underwater volcano cell.^{\dagger}A set of cells forms a single connected component if from any cell of this set it is possible to reach any other cell of this set by moving only through the cells of this set, each time going to a cell with a common side.^{\ddagger}Manhattan distance between cells (r_1, c_1) and (r_2, c_2) is equal to |r_1 - r_2| + |c_1 - c_2|.InputThe first line contains three integers n, m, and q (3 \leq n, m \leq 10^5, 9 \leq n \cdot m \leq 3 \cdot 10^5, 1 \leq q \leq 3 \cdot 10^5) — the number of rows and columns of the grid and the number of queries. Each of the following n lines contains m characters describing the cells of the grid. The character '#' denotes an island cell, '.' denotes an ocean cell, and 'v' denotes an underwater volcano cell.It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is guaranteed that the set of all island cells forms a single connected component and the set of all ocean cells and underwater volcano cells forms a single connected component. Also, it is guaranteed that there are no island cells at the edge of the grid (that is, at the row 1, at the row n, at the column 1, and at the column m).The following q lines describe the queries. Each of these lines contains two integers x and y (1 \leq x \leq n, 1 \leq y \leq m) denoting a round trip starting from (x, y).It is guaranteed that (x, y) is an ocean cell or an underwater volcano cell.OutputFor each query, output a single integer — the maximum safety of a round trip starting from the specified position.ExamplesInput 9 9 3 ......... ......... ....###.. ...v#.... ..###.... ...##...v ...##.... ......... v........ 1 1 9 1 5 7 Output 3 0 3 Input 3 3 5 ..v .#. ... 1 2 1 3 2 3 2 1 3 2 Output 0 0 0 0 0 Input 14 13 5 ............. ............. ............. ...vvvvvvv... ...v.....v... ...v.###.v... ...v.#.#.v... ...v..v..v... ...v..v..v... ....v...v.... .....vvv..... ............. ............. ............. 1 1 7 7 5 6 4 10 13 6 Output 3 0 1 0 2 Input 10 11 4 ........... ..#######.. ..#..#..#.. ..#.....#.. ..#..v..#.. ..#.###.#.. ..#.#.#.#.. ..#...#.#.. ..#####.#.. ........... 7 6 3 7 6 8 1 1 Output 1 2 3 4 NoteFor the first example, the image below shows an optimal round trip starting from (1, 1). The round trip has a safety of 3 as the minimum Manhattan distance from a cell on the round trip to an underwater volcano is 3. Example of an optimal round trip For the fourth example, remember that it is allowed for Thomas to visit the same cell multiple times in the same round trip. For example, doing so is necessary for the round trip starting from (7, 6).
9 9 3 ......... ......... ....###.. ...v#.... ..###.... ...##...v ...##.... ......... v........ 1 1 9 1 5 7
3 0 3
5 seconds
1024 megabytes
['binary search', 'data structures', 'dsu', 'geometry', 'graphs', 'trees', '*3000']
F1. Smooth Sailing (Easy Version)time limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe only difference between the two versions of this problem is the constraint on q. You can make hacks only if both versions of the problem are solved.Thomas is sailing around an island surrounded by the ocean. The ocean and island can be represented by a grid with n rows and m columns. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to m from left to right. The position of a cell at row r and column c can be represented as (r, c). Below is an example of a valid grid. Example of a valid grid There are three types of cells: island, ocean and underwater volcano. Cells representing the island are marked with a '#', cells representing the ocean are marked with a '.', and cells representing an underwater volcano are marked with a 'v'. It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is also guaranteed that the set of all island cells forms a single connected component^{\dagger} and the set of all ocean cells and underwater volcano cells forms a single connected component. Additionally, it is guaranteed that there are no island cells at the edge of the grid (that is, at row 1, at row n, at column 1, and at column m).Define a round trip starting from cell (x, y) as a path Thomas takes which satisfies the following conditions: The path starts and ends at (x, y). If Thomas is at cell (i, j), he can go to cells (i+1, j), (i-1, j), (i, j-1), and (i, j+1) as long as the destination cell is an ocean cell or an underwater volcano cell and is still inside the grid. Note that it is allowed for Thomas to visit the same cell multiple times in the same round trip. The path must go around the island and fully encircle it. Some path p fully encircles the island if it is impossible to go from an island cell to a cell on the grid border by only traveling to adjacent on a side or diagonal cells without visiting a cell on path p. In the image below, the path starting from (2, 2), going to (1, 3), and going back to (2, 2) the other way does not fully encircle the island and is not considered a round trip. Example of a path that does not fully encircle the island The safety of a round trip is the minimum Manhattan distance^{\ddagger} from a cell on the round trip to an underwater volcano (note that the presence of island cells does not impact this distance).You have q queries. A query can be represented as (x, y) and for every query, you want to find the maximum safety of a round trip starting from (x, y). It is guaranteed that (x, y) is an ocean cell or an underwater volcano cell.^{\dagger}A set of cells forms a single connected component if from any cell of this set it is possible to reach any other cell of this set by moving only through the cells of this set, each time going to a cell with a common side.^{\ddagger}Manhattan distance between cells (r_1, c_1) and (r_2, c_2) is equal to |r_1 - r_2| + |c_1 - c_2|.InputThe first line contains three integers n, m, and q (3 \leq n, m \leq 10^5, 9 \leq n \cdot m \leq 3 \cdot 10^5, 1 \leq q \leq 5) — the number of rows and columns of the grid and the number of queries. Each of the following n lines contains m characters describing the cells of the grid. The character '#' denotes an island cell, '.' denotes an ocean cell, and 'v' denotes an underwater volcano cell.It is guaranteed that there is at least one island cell and at least one underwater volcano cell. It is guaranteed that the set of all island cells forms a single connected component and the set of all ocean cells and underwater volcano cells forms a single connected component. Also, it is guaranteed that there are no island cells at the edge of the grid (that is, at the row 1, at the row n, at the column 1, and at the column m).The following q lines describe the queries. Each of these lines contains two integers x and y (1 \leq x \leq n, 1 \leq y \leq m) denoting a round trip starting from (x, y).It is guaranteed that (x, y) is an ocean cell or an underwater volcano cell.OutputFor each query, output a single integer — the maximum safety of a round trip starting from the specified position.ExamplesInput 9 9 3 ......... ......... ....###.. ...v#.... ..###.... ...##...v ...##.... ......... v........ 1 1 9 1 5 7 Output 3 0 3 Input 3 3 5 ..v .#. ... 1 2 1 3 2 3 2 1 3 2 Output 0 0 0 0 0 Input 14 13 5 ............. ............. ............. ...vvvvvvv... ...v.....v... ...v.###.v... ...v.#.#.v... ...v..v..v... ...v..v..v... ....v...v.... .....vvv..... ............. ............. ............. 1 1 7 7 5 6 4 10 13 6 Output 3 0 1 0 2 Input 10 11 4 ........... ..#######.. ..#..#..#.. ..#.....#.. ..#..v..#.. ..#.###.#.. ..#.#.#.#.. ..#...#.#.. ..#####.#.. ........... 7 6 3 7 6 8 1 1 Output 1 2 3 4 NoteFor the first example, the image below shows an optimal round trip starting from (1, 1). The round trip has a safety of 3 as the minimum Manhattan distance from a cell on the round trip to an underwater volcano is 3. Example of an optimal round trip For the fourth example, remember that it is allowed for Thomas to visit the same cell multiple times in the same round trip. For example, doing so is necessary for the round trip starting from (7, 6).
9 9 3 ......... ......... ....###.. ...v#.... ..###.... ...##...v ...##.... ......... v........ 1 1 9 1 5 7
3 0 3
5 seconds
1024 megabytes
['binary search', 'brute force', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'shortest paths', '*2500']
E. Counting Binary Stringstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPatrick calls a substring^\dagger of a binary string^\ddagger good if this substring contains exactly one 1. Help Patrick count the number of binary strings s such that s contains exactly n good substrings and has no good substring of length strictly greater than k. Note that substrings are differentiated by their location in the string, so if s = 1010 you should count both occurrences of 10.^\dagger A string a is a substring of a string b if a can be obtained from b by the deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.^\ddagger A binary string is a string that only contains the characters 0 and 1.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 2500) — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers n and k (1 \leq n \leq 2500, 1 \leq k \leq n) — the number of required good substrings and the maximum allowed length of a good substring. It is guaranteed that the sum of n over all test cases does not exceed 2500. OutputFor each test case, output a single integer — the number of binary strings s such that s contains exactly n good substrings and has no good substring of length strictly greater than k. Since this integer can be too large, output it modulo 998\,244\,353.ExampleInput 61 13 24 25 46 22450 2391Output 1 3 5 12 9 259280854 NoteIn the first test case, the only suitable binary string is 1. String 01 is not suitable because it contains a substring 01 with length 2 > 1.In the second test case, suitable binary strings are 011, 110 and 111.In the third test case, suitable binary strings are 101, 0110, 0111, 1110, and 1111.
61 13 24 25 46 22450 2391
1 3 5 12 9 259280854
2 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*2100']
D. Array Repetitiontime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputJayden has an array a which is initially empty. There are n operations of two types he must perform in the given order. Jayden appends an integer x (1 \leq x \leq n) to the end of array a. Jayden appends x copies of array a to the end of array a. In other words, array a becomes [a,\underbrace{a,\ldots,a}_{x}]. It is guaranteed that he has done at least one operation of the first type before this. Jayden has q queries. For each query, you must tell him the k-th element of array a. The elements of the array are numbered from 1.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 5000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and q (1 \leq n, q \leq 10^5) — the number of operations and the number of queries.The following n lines describe the operations. Each line contains two integers b and x (b \in \{1, 2\}), where b denotes the type of operation. If b=1, then x (1 \leq x \leq n) is the integer Jayden appends to the end of the array. If b=2, then x (1 \leq x \leq 10^9) is the number of copies Jayden appends to the end of the array. The next line of each test case contains q integers k_1, k_2, \ldots, k_q (1 \leq k_i \leq \min(10^{18}, c)), which denote the queries, where c is the size of the array after finishing all n operations.It is guaranteed that the sum of n and the sum of q over all test cases does not exceed 10^5. OutputFor each test case, output q integers — answers to Jayden's queries.ExampleInput 45 101 11 22 11 32 31 2 3 4 5 6 14 15 16 2010 101 31 82 151 61 91 12 61 12 122 1032752 25178 3198 3199 2460 2461 31450 33260 9016 499612 51 61 112 3921303341 42 7448117501 101 52 2093737802 1789289841 32 6583264642 1000000000914576963034536490 640707385283752918 636773368365261971 584126563607944922 10000000000000000002 21 11 21 2Output 1 2 1 2 3 1 2 3 1 3 9 8 1 3 1 3 6 3 8 8 11 11 11 10 11 1 2 NoteIn the first test case: After the first operation a = [1]; After the second operation a = [1, 2]; After the third operation a = [1, 2, 1, 2]; After the fourth operation a = [1, 2, 1, 2, 3]; After the fifth operation a = [1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 1, 2, 3].In the fourth test case, after all operations a = [1, 2].
45 101 11 22 11 32 31 2 3 4 5 6 14 15 16 2010 101 31 82 151 61 91 12 61 12 122 1032752 25178 3198 3199 2460 2461 31450 33260 9016 499612 51 61 112 3921303341 42 7448117501 101 52 2093737802 1789289841 32 6583264642 1000000000914576963034536490 640707385283752918 636773368365261971 584126563607944922 10000000000000000002 21 11 21 2
1 2 1 2 3 1 2 3 1 3 9 8 1 3 1 3 6 3 8 8 11 11 11 10 11 1 2
4 seconds
256 megabytes
['binary search', 'brute force', 'dsu', 'implementation', 'math', '*1900']
C. Partitioning the Arraytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAllen has an array a_1, a_2,\ldots,a_n. For every positive integer k that is a divisor of n, Allen does the following: He partitions the array into \frac{n}{k} disjoint subarrays of length k. In other words, he partitions the array into the following subarrays: [a_1,a_2,\ldots,a_k],[a_{k+1}, a_{k+2},\ldots,a_{2k}],\ldots,[a_{n-k+1},a_{n-k+2},\ldots,a_{n}] Allen earns one point if there exists some positive integer m (m \geq 2) such that if he replaces every element in the array with its remainder when divided by m, then all subarrays will be identical. Help Allen find the number of points he will earn.InputEach test consists of 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 a single integer n (1 \leq n \leq 2\cdot10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2,\ldots, a_n (1 \leq a_i \leq n) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, output a single integer — the number of points Allen will earn.ExampleInput 841 2 1 431 2 351 1 1 1 161 3 1 1 3 166 2 6 2 2 262 6 3 6 6 6101 7 5 1 4 3 1 3 1 411Output 2 1 2 4 4 1 2 1 NoteIn the first test case, k=2 earns a point since Allen can pick m = 2 and both subarrays will be equal to [1, 0]. k=4 also earns a point, since no matter what m Allen chooses, there will be only one subarray and thus all subarrays are equal.In the second test case, Allen earns 1 point for k=3, where his choice for m does not matter.
841 2 1 431 2 351 1 1 1 161 3 1 1 3 166 2 6 2 2 262 6 3 6 6 6101 7 5 1 4 3 1 3 1 411
2 1 2 4 4 1 2 1
3 seconds
256 megabytes
['brute force', 'math', 'number theory', '*1600']
B. Summation Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They have an array a_1, a_2,\ldots,a_n. The game consists of two steps: First, Alice will remove at most k elements from the array. Second, Bob will multiply at most x elements of the array by -1. Alice wants to maximize the sum of elements of the array while Bob wants to minimize it. Find the sum of elements of the array after the game if both players play optimally.InputEach test consists of 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 three integers n, k, and x (1 \leq n \leq 2 \cdot 10^5, 1 \leq x,k \leq n) — the number of elements in the array, the limit on the number of elements of the array that Alice can remove, and the limit on the number of elements of the array that Bob can multiply -1 to.The second line of each test case contains n integers a_1, a_2,\ldots, a_n (1 \leq a_i \leq 1000) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, output a single integer — the sum of elements of the array after the game if both players play optimally.ExampleInput 81 1 114 1 13 1 2 46 6 31 4 3 2 5 66 6 13 7 3 3 32 158 5 35 5 3 3 3 2 9 910 6 41 8 2 9 3 3 4 5 3 2002 2 14 32 1 21 3Output 0 2 0 3 -5 -9 0 -1 NoteIn the first test case, it is optimal for Alice to remove the only element of the array. Then, the sum of elements of the array is 0 after the game is over.In the second test case, it is optimal for Alice to not remove any elements. Bob will then multiply 4 by -1. So the final sum of elements of the array is 3+1+2-4=2.In the fifth test case, it is optimal for Alice to remove 9, 9. Bob will then multiply 5, 5, 3 by -1. So the final sum of elements of the array is -5-5-3+3+3+2=-5.
81 1 114 1 13 1 2 46 6 31 4 3 2 5 66 6 13 7 3 3 32 158 5 35 5 3 3 3 2 9 910 6 41 8 2 9 3 3 4 5 3 2002 2 14 32 1 21 3
0 2 0 3 -5 -9 0 -1
1 second
256 megabytes
['games', 'greedy', 'math', 'sortings', '*1100']
A. Satisfying Constraintstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex is solving a problem. He has n constraints on what the integer k can be. There are three types of constraints: k must be greater than or equal to some integer x; k must be less than or equal to some integer x; k must be not equal to some integer x. Help Alex find the number of integers k that satisfy all n constraints. It is guaranteed that the answer is finite (there exists at least one constraint of type 1 and at least one constraint of type 2). Also, it is guaranteed that no two constraints are the exact same.InputEach test consists of multiple test cases. The first line contains a single 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 a single integer n (2 \leq n \leq 100) — the number of constraints.The following n lines describe the constraints. Each line contains two integers a and x (a \in \{1,2,3\}, \, 1 \leq x \leq 10^9). a denotes the type of constraint. If a=1, k must be greater than or equal to x. If a=2, k must be less than or equal to x. If a=3, k must be not equal to x.It is guaranteed that there is a finite amount of integers satisfying all n constraints (there exists at least one constraint of type 1 and at least one constraint of type 2). It is also guaranteed that no two constraints are the exact same (in other words, all pairs (a, x) are distinct).OutputFor each test case, output a single integer — the number of integers k that satisfy all n constraints.ExampleInput 641 32 103 13 521 52 4103 63 71 21 73 1003 442 1002 981 33 9961 52 101 92 23 23 951 12 23 13 23 361 100002 9000000003 5000000001 1000000003 100003 900000001Output 7 0 90 0 0 800000000 NoteIn the first test case, k \geq 3 and k \leq 10. Furthermore, k \neq 1 and k \neq 5. The possible integers k that satisfy the constraints are 3,4,6,7,8,9,10. So the answer is 7.In the second test case, k \ge 5 and k \le 4, which is impossible. So the answer is 0.
641 32 103 13 521 52 4103 63 71 21 73 1003 442 1002 981 33 9961 52 101 92 23 23 951 12 23 13 23 361 100002 9000000003 5000000001 1000000003 100003 900000001
7 0 90 0 0 800000000
1 second
256 megabytes
['brute force', 'greedy', 'math', '*800']
H. Tree Diametertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a hidden tree with n vertices. The n-1 edges of the tree are numbered from 1 to n-1. You can ask the following queries of two types: Give the grader an array a with n - 1 positive integers. For each edge from 1 to n - 1, the weight of edge i is set to a_i. Then, the grader will return the length of the diameter^\dagger. Give the grader two indices 1 \le a, b \le n - 1. The grader will return the number of edges between edges a and b. In other words, if edge a connects u_a and v_a while edge b connects u_b and v_b, the grader will return \min(\text{dist}(u_a, u_b), \text{dist}(v_a, u_b), \text{dist}(u_a, v_b), \text{dist}(v_a, v_b)), where \text{dist}(u, v) represents the number of edges on the path between vertices u and v. Find any tree isomorphic^\ddagger to the hidden tree after at most n queries of type 1 and n queries of type 2 in any order.^\dagger The distance between two vertices is the sum of the weights on the unique simple path that connects them. The diameter is the largest of all those distances.^\ddagger Two trees, consisting of n vertices each, are called isomorphic if there exists a permutation p containing integers from 1 to n such that edge (u, v) is present in the first tree if and only if the edge (p_u, p_v) is present in the second tree.InputThe first and only line of input contains a single integer n (3 \le n \le 1000) — the number of vertices in the tree.InteractionBegin the interaction by reading n.You are allowed to make queries in the following way: "\mathtt{?}\,1\,a_1\,a_2 \ldots a_{n-1}" (1 \le a_i \le 10^9). Then, you should read an integer k which represents the length of the diameter. You are only allowed to ask this query at most n times. "\mathtt{?}\,2\,a\,b" (1 \le a, b \le n - 1). Then, you should read an integer k which represents the number of edges between edges a and b. You are only allowed to ask this query at most n times. In case your query is invalid. the program will terminate immediately and you will receive Wrong answer verdict.To give the final answer, print "!" on a single line, followed by n - 1 lines where line i contains "u_i\,v_i" (1 \le u_i, v_i \le n) which represents that for each i from 1 to n-1, there is an edge between u_i and v_i.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 contains a single integer n (3 \le n \le 1000) — the number of vertices in the tree.The next n - 1 lines contain two integers each u_i, v_i (1 \le u_i, v_i \le n) — the edges of the tree.ExampleInput 5 3 1 9 0Output ? 1 1 1 1 1 ? 2 1 3 ? 1 4 3 2 1 ? 2 4 2 ! 3 1 4 2 1 2 2 5 NoteThe hidden tree in the example is shown above. The number on the vertices represents the vertex number while the number on the edges represents the edge number.In the first query, all the edges are set to weight 1, so the diameter has length 3 as shown in the diagram.In the second query, there is 1 edge between edges 1 and 3.In the third query, the diameter is 9 by taking edges 1, 2 and 3.In the fourth query, there are no edges between edges 4 and 2.The answer given in the example is shown in the above diagram. Since it is isomorphic to the hidden tree, it is accepted as a correct answer. Note that the edges can be printed in any order.
5 3 1 9 0
? 1 1 1 1 1 ? 2 1 3 ? 1 4 3 2 1 ? 2 4 2 ! 3 1 4 2 1 2 2 5
2 seconds
256 megabytes
['interactive', 'trees', '*2000']
G. Tree LGMtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn TreeWorld, there is a popular two-player game played on a tree with n vertices labelled from 1 to n. In this game, the tournament leaders first choose a vertex to be the root of the tree and choose another vertex (possibly the same vertex as the root) to place a coin on. Then, each player will take turns moving the coin to any child^\dagger of the vertex that the coin is currently on. The first player who is unable to make a move loses.Alice wants to be a tree LGM, so she spends a lot of time studying the game. She wrote down an n by n matrix s, where s_{i,j} = \mathtt{1} if the first player can win with the root of the tree chosen to be vertex i, and the coin was initially placed on vertex j. Otherwise, s_{i, j} = \mathtt{0}. Alice is a perfectionist, so she assumes that both players play perfectly in the game.However, she accidentally knocked her head on the way to the tournament and forgot what the tree looked like. Determine whether there exists a tree that satisfies the winning and losing states represented by matrix s, and if it exists, construct a valid tree.^\dagger A vertex c is a child of vertex u if there is an edge between c and u, and c does not lie on the unique simple path from the root to vertex u.InputThe first line contains a single integer n (1 \le n \le 5000) — the number of vertices in the tree.Each of the next n lines contains a string with n characters, the j-th character of the i-th line representing s_{i, j} (s_{i, j} \in \{\mathtt{0}, \mathtt{1}\}) — the winning and losing states of the tree.OutputIf there is no tree satisfying the winning and losing states represented by matrix s, print a single line containing "NO".Otherwise, if there exists a tree satisfying matrix s, print "YES" on the first line, followed by n - 1 lines each containing two integers u and v (1 \le u, v \le n) representing that the tree has an edge between vertices u and v.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.If there are multiple trees satisfying the winning and losing states represented by matrix s, print any of them.ExamplesInput 41100010100110101Output YES 4 1 3 2 2 4 Input 3001010100Output NO NoteIn the first test case, the line graph 1\!-\!4\!-\!2\!-\!3 satisfies the winning and losing states represented by matrix s. For example, s_{3,3} = 1 as the first player can move the coin from 3\rightarrow 2, then the second player moves the coin from 2\rightarrow 4, and finally, the first player moves the coin from 4\rightarrow 1. At this point, 1 has no children, so the second player is unable to make a move and loses. On the other hand, s_{1,3} = 0 as if 1 is the root, then 3 has no children so the first player is unable to make the first move and loses.In the second test case, it is possible to prove that no tree satisfies the winning and losing states represented by matrix s.
41100010100110101
YES 4 1 3 2 2 4
3 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'games', 'trees', '*3500']
F2. Wine Factory (Hard Version)time limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the two versions is the constraint on c_i and z. You can make hacks only if both versions of the problem are solved.There are three arrays a, b and c. a and b have length n and c has length n-1. Let W(a,b,c) denote the liters of wine created from the following process.Create n water towers. The i-th water tower initially has a_i liters of water and has a wizard with power b_i in front of it. Furthermore, for each 1 \le i \le n - 1, there is a valve connecting water tower i to i + 1 with capacity c_i.For each i from 1 to n in this order, the following happens: The wizard in front of water tower i removes at most b_i liters of water from the tower and turns the removed water into wine. If i \neq n, at most c_i liters of the remaining water left in water tower i flows through the valve into water tower i + 1. There are q updates. In each update, you will be given integers p, x, y and z and you will update a_p := x, b_p := y and c_p := z. After each update, find the value of W(a,b,c). Note that previous updates to arrays a, b and c persist throughout future updates.InputThe first line contains two integers n and q (2 \le n \le 5\cdot 10^5, 1 \le q \le 5\cdot 10^5) — the number of water towers and the number of updates.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the number of liters of water in water tower i.The third line contains n integers b_1, b_2, \ldots, b_n (0 \le b_i \le 10^9) — the power of the wizard in front of water tower i.The fourth line contains n - 1 integers c_1, c_2, \ldots, c_{n - 1} (0 \le c_i \color{red}{\le} 10^{18}) — the capacity of the pipe connecting water tower i to i + 1.Each of the next q lines contains four integers p, x, y and z (1 \le p \le n, 0 \le x, y \le 10^9, 0 \le z \color{red}{\le} 10^{18}) — the updates done to arrays a, b and c.Note that c_n does not exist, so the value of z does not matter when p = n.OutputPrint q lines, each line containing a single integer representing W(a, b, c) after each update.ExamplesInput 4 33 3 3 31 4 2 85 2 14 3 8 10000000002 5 1 13 0 0 0Output 11 8 5 Input 5 510 3 8 9 23 4 10 8 16 5 9 25 4 9 11 1 1 12 7 4 84 1 1 11 8 3 3Output 31 25 29 21 23 NoteThe first update does not make any modifications to the arrays. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 5 liters of water in tower 2 and 4 liters of water is turned into wine. The remaining 1 liter of water flows into tower 3. When i = 3, there are 4 liters of water in tower 3 and 2 liters of water is turned into wine. Even though there are 2 liters of water remaining, only 1 liter of water can flow into tower 4. When i = 4, there are 4 liters of water in tower 4. All 4 liters of water are turned into wine. Hence, W(a,b,c)=1 + 4 + 2 + 4 = 11 after the first update.The second update modifies the arrays to a = [3, 5, 3, 3], b = [1, 1, 2, 8], and c = [5, 1, 1]. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 7 liters of water in tower 2 and 1 liter of water is turned into wine. Even though there are 6 liters of water remaining, only 1 liter of water can flow to tower 3. When i = 3, there are 4 liters of water in tower 3 and 2 liters of water is turned into wine. Even though there are 2 liters of water remaining, only 1 liter of water can flow into tower 4. When i = 4, there are 4 liters of water in tower 4. All 4 liters of water are turned into wine. Hence, W(a,b,c)=1 + 1 + 2 + 4 = 8 after the second update.The third update modifies the arrays to a = [3, 5, 0, 3], b = [1, 1, 0, 8], and c = [5, 1, 0]. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 7 liters of water in tower 2 and 1 liter of water is turned into wine. Even though there are 6 liters of water remaining, only 1 liter of water can flow to tower 3. When i = 3, there is 1 liter of water in tower 3 and 0 liters of water is turned into wine. Even though there is 1 liter of water remaining, no water can flow to tower 4. When i = 4, there are 3 liters of water in tower 4. All 3 liters of water are turned into wine. Hence, W(a,b,c)=1 + 1 + 0 + 3 = 5 after the third update.
4 33 3 3 31 4 2 85 2 14 3 8 10000000002 5 1 13 0 0 0
11 8 5
5 seconds
512 megabytes
['data structures', 'dp', 'flows', 'greedy', 'matrices', '*2800']
F1. Wine Factory (Easy Version)time limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on c_i and z. You can make hacks only if both versions of the problem are solved.There are three arrays a, b and c. a and b have length n and c has length n-1. Let W(a,b,c) denote the liters of wine created from the following process.Create n water towers. The i-th water tower initially has a_i liters of water and has a wizard with power b_i in front of it. Furthermore, for each 1 \le i \le n - 1, there is a valve connecting water tower i to i + 1 with capacity c_i.For each i from 1 to n in this order, the following happens: The wizard in front of water tower i removes at most b_i liters of water from the tower and turns the removed water into wine. If i \neq n, at most c_i liters of the remaining water left in water tower i flows through the valve into water tower i + 1. There are q updates. In each update, you will be given integers p, x, y and z and you will update a_p := x, b_p := y and c_p := z. After each update, find the value of W(a,b,c). Note that previous updates to arrays a, b and c persist throughout future updates.InputThe first line contains two integers n and q (2 \le n \le 5\cdot 10^5, 1 \le q \le 5\cdot 10^5) — the number of water towers and the number of updates.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the number of liters of water in water tower i.The third line contains n integers b_1, b_2, \ldots, b_n (0 \le b_i \le 10^9) — the power of the wizard in front of water tower i.The fourth line contains n - 1 integers c_1, c_2, \ldots, c_{n - 1} (c_i \color{red}{=} 10^{18}) — the capacity of the pipe connecting water tower i to i + 1.Each of the next q lines contains four integers p, x, y and z (1 \le p \le n, 0 \le x, y \le 10^9, z \color{red}{=} 10^{18}) — the updates done to arrays a, b and c.Note that c_n does not exist, so the value of z does not matter when p = n.OutputPrint q lines, each line containing a single integer representing W(a, b, c) after each update.ExamplesInput 4 33 3 3 31 4 2 81000000000000000000 1000000000000000000 10000000000000000004 3 8 10000000000000000002 5 1 10000000000000000003 0 0 1000000000000000000Output 12 12 10 Input 5 510 3 8 9 23 4 10 8 11000000000000000000 1000000000000000000 1000000000000000000 10000000000000000005 4 9 10000000000000000001 1 1 10000000000000000002 7 4 10000000000000000004 1 1 10000000000000000001 8 3 1000000000000000000Output 34 25 29 21 27 NoteThe first update does not make any modifications to the arrays. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 5 liters of water in tower 2 and 4 liters of water is turned into wine. The remaining 1 liter of water flows into tower 3. When i = 3, there are 4 liters of water in tower 3 and 2 liters of water is turned into wine. The remaining 2 liters of water flows into tower 4. When i = 4, there are 5 liters of water in tower 4. All 5 liters of water are turned into wine. Hence, W(a,b,c)=1 + 4 + 2 + 5 = 12 after the first update.The second update modifies the arrays to a = [3, 5, 3, 3], b = [1, 1, 2, 8], and c = [10^{18}, 10^{18}, 10^{18}]. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 7 liters of water in tower 2 and 1 liter of water is turned into wine. The remaining 6 liters of water flow into tower 3. When i = 3, there are 9 liters of water in tower 3 and 2 liters of water is turned into wine. The remaining 7 liters of water flow into tower 4. When i = 4, there are 10 liters of water in tower 4. Only 8 liters of water is turned into wine. Hence, W(a,b,c)=1 + 1 + 2 + 8 = 12 after the second update.The third update modifies the arrays to a = [3, 5, 0, 3], b = [1, 1, 0, 8], and c = [10^{18}, 10^{18}, 10^{18}]. When i = 1, there are 3 liters of water in tower 1 and 1 liter of water is turned into wine. The remaining 2 liters of water flow into tower 2. When i = 2, there are 7 liters of water in tower 2 and 1 liter of water is turned into wine. The remaining 6 liters of water flow into tower 3. When i = 3, there are 6 liters of water in tower 3 and 0 liters of water is turned into wine. The remaining 6 liters of water flow into tower 4. When i = 4, there are 9 liters of water in tower 4. Only 8 liters of water is turned into wine. Hence, W(a,b,c)=1 + 1 + 0 + 8 = 10 after the third update.
4 33 3 3 31 4 2 81000000000000000000 1000000000000000000 10000000000000000004 3 8 10000000000000000002 5 1 10000000000000000003 0 0 1000000000000000000
12 12 10
5 seconds
512 megabytes
['data structures', 'greedy', '*2300']
E. Counting Prefixestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a hidden array a of size n consisting of only 1 and -1. Let p be the prefix sums of array a. More formally, p is an array of length n defined as p_i = a_1 + a_2 + \ldots + a_i. Afterwards, array p is sorted in non-decreasing order. For example, if a = [1, -1, -1, 1, 1], then p = [1, 0, -1, 0, 1] before sorting and p = [-1, 0, 0, 1, 1] after sorting.You are given the prefix sum array p after sorting, but you do not know what array a is. Your task is to count the number of initial arrays a such that the above process results in the given sorted prefix sum array p. As this number can be large, you are only required to find it modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains a single 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 a single integer n (1 \le n \le 5000) — the size of the hidden array a.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (|p_i| \le n) — the n prefix sums of a sorted in non-decreasing order.It is guaranteed that p_1 \le p_2 \le \ldots \le p_n.It is guaranteed that the sum of n over all test cases does not exceed 5000.OutputFor each test case, output the answer modulo 998\,244\,353.ExampleInput 510113-1 1 25-1 0 0 1 15-4 -3 -3 -2 -1Output 0 1 0 3 1 NoteIn the first two test cases, the only possible arrays a for n = 1 are a = [1] and a = [-1]. Their respective sorted prefix sum arrays p are p = [1] and p = [-1]. Hence, there is no array a that can result in the sorted prefix sum array p = [0] and there is exactly 1 array a that can result in the sorted prefix sum array p = [1].In the third test case, it can be proven that there is no array a that could result in the sorted prefix sum array p = [-1, 1, 2].In the fourth test case, the 3 possible arrays a that could result in the sorted prefix sum array p = [-1, 0, 0, 1, 1] are: a = [1, -1, 1, -1, -1]. The prefix sum array before sorting is p = [1, 0, 1, 0, -1], which after sorting gives p = [-1, 0, 0, 1, 1]. a = [1, -1, -1, 1, 1]. The prefix sum array before sorting is p = [1, 0, -1, 0, 1], which after sorting gives p = [-1, 0, 0, 1, 1]. a = [-1, 1, 1, -1, 1]. The prefix sum array before sorting is p = [-1, 0, 1, 0, 1], which after sorting gives p = [-1, 0, 0, 1, 1]. For the fifth test case, the only possible array a that could result in the sorted prefix sum array p = [-4, -3, -3, -2, -1] is a = [-1, -1, -1, -1, 1].
510113-1 1 25-1 0 0 1 15-4 -3 -3 -2 -1
0 1 0 3 1
1 second
256 megabytes
['combinatorics', 'constructive algorithms', 'dp', 'implementation', 'math', '*2600']
D. 01 Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an edge-weighted complete binary tree with n leaves. A complete binary tree is defined as a tree where every non-leaf vertex has exactly 2 children. For each non-leaf vertex, we label one of its children as the left child and the other as the right child.The binary tree has a very strange property. For every non-leaf vertex, one of the edges to its children has weight 0 while the other edge has weight 1. Note that the edge with weight 0 can be connected to either its left or right child.You forgot what the tree looks like, but luckily, you still remember some information about the leaves in the form of an array a of size n. For each i from 1 to n, a_i represents the distance^\dagger from the root to the i-th leaf in dfs order^\ddagger. Determine whether there exists a complete binary tree which satisfies array a. Note that you do not need to reconstruct the tree.^\dagger The distance from vertex u to vertex v is defined as the sum of weights of the edges on the path from vertex u to vertex v.^\ddagger The dfs order of the leaves is found by calling the following \texttt{dfs} function on the root of the binary tree. dfs_order = []function dfs(v): if v is leaf: append v to the back of dfs_order else: dfs(left child of v) dfs(right child of v)dfs(root)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 a single integer n (2 \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 (0 \le a_i \le n - 1) — the distance from the root to the i-th leaf.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 there exists a complete binary tree which satisfies array a and "NO" otherwise.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).ExampleInput 252 1 0 1 151 0 2 1 3Output YES NO NoteIn the first test case, the following tree satisfies the array.In the second test case, it can be proven that there is no complete binary tree that satisfies the array.
252 1 0 1 151 0 2 1 3
YES NO
1 second
256 megabytes
['constructive algorithms', 'data structures', 'dsu', 'greedy', 'sortings', 'trees', '*2100']
C. Grouping Increasestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of size n. You will do the following process to calculate your penalty: Split array a into two (possibly empty) subsequences^\dagger s and t such that every element of a is either in s or t^\ddagger. For an array b of size m, define the penalty p(b) of an array b as the number of indices i between 1 and m - 1 where b_i < b_{i + 1}. The total penalty you will receive is p(s) + p(t). If you perform the above process optimally, find the minimum possible penalty you will receive.^\dagger A sequence x is a subsequence of a sequence y if x can be obtained from y by the deletion of several (possibly, zero or all) elements.^\ddagger Some valid ways to split array a=[3,1,4,1,5] into (s,t) are ([3,4,1,5],[1]), ([1,1],[3,4,5]) and ([\,],[3,1,4,1,5]) while some invalid ways to split a are ([3,4,5],[1]), ([3,1,4,1],[1,5]) and ([1,3,4],[5,1]).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 a single integer n (1\le n\le 2\cdot 10^5) — the size of the array a.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of the array a.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 representing the minimum possible penalty you will receive.ExampleInput 551 2 3 4 588 2 3 1 1 7 4 353 3 3 3 31122 1Output 3 1 0 0 0 NoteIn the first test case, a possible way to split a is s=[2,4,5] and t=[1,3]. The penalty is p(s)+p(t)=2 + 1 =3.In the second test case, a possible way to split a is s=[8,3,1] and t=[2,1,7,4,3]. The penalty is p(s)+p(t)=0 + 1 =1.In the third test case, a possible way to split a is s=[\,] and t=[3,3,3,3,3]. The penalty is p(s)+p(t)=0 + 0 =0.
551 2 3 4 588 2 3 1 1 7 4 353 3 3 3 31122 1
3 1 0 0 0
1 second
256 megabytes
['data structures', 'dp', 'greedy', '*1400']
B. Plus-Minus Splittime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of characters "+" and "-". s represents an array a of length n defined by a_i=1 if s_i= "+" and a_i=-1 if s_i= "-".You will do the following process to calculate your penalty: Split a into non-empty arrays b_1,b_2,\ldots,b_k such that b_1+b_2+\ldots+b_k=a^\dagger, where + denotes array concatenation. The penalty of a single array is the absolute value of its sum multiplied by its length. In other words, for some array c of length m, its penalty is calculated as p(c)=|c_1+c_2+\ldots+c_m| \cdot m. The total penalty that you will receive is p(b_1)+p(b_2)+\ldots+p(b_k). If you perform the above process optimally, find the minimum possible penalty you will receive.^\dagger Some valid ways to split a=[3,1,4,1,5] into (b_1,b_2,\ldots,b_k) are ([3],[1],[4],[1],[5]), ([3,1],[4,1,5]) and ([3,1,4,1,5]) while some invalid ways to split a are ([3,1],[1,5]), ([3],[\,],[1,4],[1,5]) and ([3,4],[5,1,1]).InputEach test contains multiple test cases. The first line contains a single 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 a single integer n (1 \le n \le 5000) — the length of string s.The second line of each test case contains string s (s_i \in \{ \mathtt{+}, \mathtt{-} \}, |s| = n).Note that there are no constraints on the sum of n over all test cases.OutputFor each test case, output a single integer representing the minimum possible penalty you will receive.ExampleInput 51+5-----6+-+-+-10--+++++++-20+---++++-+++++---++-Output 1 5 0 4 4 NoteIn the first test case, we have a=[1]. We can split array a into ([1]). Then, the sum of penalties of the subarrays is p([1]) = 1.In the second test case, we have a=[-1,-1,-1,-1,-1]. We can split array a into ([-1],[-1],[-1],[-1],[-1]). Then, the sum of penalties of the subarrays is p([-1]) + p([-1]) + p([-1]) + p([-1]) + p([-1]) = 1 + 1 + 1 + 1 + 1 = 5.In the third test case, we have a=[1,-1,1,-1,1,-1]. We can split array a into ([1,-1,1,-1],[1,-1]). Then, the sum of penalties of the subarrays is p([1,-1,1,-1]) + p([1,-1]) = 0 + 0 = 0.
51+5-----6+-+-+-10--+++++++-20+---++++-+++++---++-
1 5 0 4 4
1 second
256 megabytes
['greedy', '*800']
A. Wallet Exchangetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are bored, so they decide to play a game with their wallets. Alice has a coins in her wallet, while Bob has b coins in his wallet.Both players take turns playing, with Alice making the first move. In each turn, the player will perform the following steps in order: Choose to exchange wallets with their opponent, or to keep their current wallets. Remove 1 coin from the player's current wallet. The current wallet cannot have 0 coins before performing this step. The player who cannot make a valid move on their turn loses. If both Alice and Bob play optimally, determine who will win the game.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first and only line of each test case contains two integers a and b (1 \le a, b \le 10^9) — the number of coins in Alice's and Bob's wallets, respectively.OutputFor each test case, output "Alice" if Alice will win the game, and "Bob" if Bob will win the game.ExampleInput 101 11 45 34 511 983 911032 9307839204 72811000000000 100000000053110 2024Output Bob Alice Bob Alice Bob Bob Alice Alice Bob Bob NoteIn the first test case, an example of the game is shown below: Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=1. Since Alice's wallet is empty, Bob must choose to not swap their wallets in step 1 of his move. Now, a=0 and b=0. Since both Alice's and Bob's wallets are empty, Alice is unable to make a move. Hence, Bob wins. In the second test case, an example of the game is shown below: Alice chooses to swap wallets with Bob in step 1 of her move. Now, a=3 and b=1. Bob chooses to swap wallets with Alice in step 1 of his move. Now, a=1 and b=2. Alice chooses to not swap wallets with Bob in step 1 of her move. Now, a=0 and b=2. Since Alice's wallet is empty, Bob can only choose to not swap wallets with Alice in step 1 of his move. Now, a=0 and b=1. Since Alice's wallet is empty, Alice can only choose to swap wallets with Bob in step 1 of her move. Now, a=0 and b=0. Since both Alice's wallet and Bob's wallet are empty, Bob is unable to make a move. Hence, Alice wins.
101 11 45 34 511 983 911032 9307839204 72811000000000 100000000053110 2024
Bob Alice Bob Alice Bob Bob Alice Alice Bob Bob
1 second
256 megabytes
['games', 'math', '*800']
G. Permutation of Giventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou were given only one number, n. It didn't seem interesting to you, so you wondered if it's possible to come up with an array of length n consisting of non-zero integers, such that if each element of the array is replaced by the sum of its neighbors (the elements on the ends are replaced by their only neighbors), you obtain a permutation of the numbers in the original array.InputEach test case contains only one number, n (2 \leq n \leq 10^6).OutputIf a solution exists, output "YES" (without quotes), followed by an array a (-10^9 \leq a_i \leq 10^9, a_i \neq 0) that satisfies the condition of the problem. If there are multiple possible answers, output any of them.If there is no suitable array, output "NO" (without quotes).The words "YES" and "NO" can be output in any case, for example, "YES", "Yes", "yEs", and so on.ExamplesInput 4Output YES 1 2 -2 -1Input 5Output NO NoteIn the first test, the array [1, 2, -2, -1] is suitable, because if each element is replaced by the sum of its neighbors, the resulting array is [2, -1, 1, -2], which is a permutation of the original array.In the second test, it can be shown that there is no solution.
4
YES 1 2 -2 -1
1 second
256 megabytes
['constructive algorithms', 'math', '*2700']
F. Caterpillar on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe caterpillar decided to visit every node of the tree. Initially, it is sitting at the root.The tree is represented as a rooted tree with the root at the node 1. Each crawl to a neighboring node takes 1 minute for the caterpillar. And there is a trampoline under the tree. If the caterpillar detaches from the tree and falls onto the trampoline, it will end up at the root of the tree in 0 seconds. But the trampoline is old and can withstand no more than k caterpillar's falls.What is the minimum time the caterpillar can take to visit all the nodes of the tree?More formally, we need to find the minimum time required to visit all the nodes of the tree, if the caterpillar starts at the root (node 1) and moves using two methods. Crawl along an edge to one of the neighboring nodes: takes 1 minute. Teleport to the root: takes no time, no new nodes become visited. The second method (teleportation) can be used at most k times. The caterpillar can finish the journey at any node.InputThe first line of the input contains two integers: n (2 \le n \le 2\cdot 10^5) — the number of nodes in the tree, and k (0 \le k \le 10^9) — the maximum number of teleports to the root.The second line contains n-1 integers p_2, p_3, ..., p_n (1 \le p_i \le n) — the ancestors in the tree for nodes 2, 3, \ldots, n; node 1 is the root.OutputPrint a single number in a single line — the minimum number of minutes required to visit all the nodes of the tree.ExamplesInput 8 1 1 1 2 2 4 3 3 Output 9 Input 4 0 4 4 1 Output 4 NoteThe figure shows one of the ways to traverse the tree from the first test in 9 minutes.
8 1 1 1 2 2 4 3 3
9
2 seconds
256 megabytes
['dfs and similar', 'graphs', 'greedy', 'implementation', 'sortings', 'trees', '*2500']
E. ace5 and Task Ordertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!In the new round, there were n tasks with difficulties from 1 to n. The coordinator, who decided to have the first round with tasks in unsorted order of difficulty, rearranged the tasks, resulting in a permutation of difficulties from 1 to n. After that, the coordinator challenged ace5 to guess the permutation in the following way.Initially, the coordinator chooses a number x from 1 to n.ace5 can make queries of the form: ?\ i. The answer will be: >, if a_i > x, after which x increases by 1. <, if a_i < x, after which x decreases by 1. =, if a_i = x, after which x remains unchanged. The task for ace5 is to guess the permutation in no more than 40n queries. Since ace5 is too busy writing the announcement, he has entrusted this task to you.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.InteractionThe interaction between your program and the jury's program begins with reading a positive integer n (1 \leq n \leq 2000) — the length of the hidden permutation.To make a query, output a line in the format "? i", where 1 \leq i \leq n.As an answer, you will receive: ">", if a_i > x, after which x will increase by 1. "<", if a_i < x, after which x will decrease by 1. "=", if a_i = x, after which x will remain unchanged. You can make no more than 40n queries. To output the answer, you need to print "! a_1 a_2 ... a_n", where 1 \leq a_i \leq n, and all of them are distinct. Outputting the answer does not count as a query.If your program makes more than 40n queries for one test case, or makes an invalid query, then the response to the query will be -1. After receiving such a response, your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, it may receive any other verdict.After outputting a query, do not forget to print a newline and flush the output buffer. Otherwise, you will receive the verdict Presentation Error. To flush the buffer, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.It is guaranteed that the sum of n over all test cases does not exceed 2000. The interactor in this problem is not adaptive.Hacks:To make a hack, use the following format:The first line contains a single integer t — the number of test cases.The description of each test case should consist of two lines. The first line contains the numbers n and x (1 \leq x \leq n \leq 2000) — the length of the hidden permutation and the initial value of the number x. The second line contains n distinct numbers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — the permutation that the jury should choose in this test case.Sum of n over all test cases should not exceed 2000.ExampleInput 2 5 > = < = < < 2 >Output ? 4 ? 2 ? 1 ? 5 ? 1 ? 3 ! 2 4 1 5 3 ? 1 ! 2 1 NoteIn the first test, the hidden permutation is a = [2,4,1,5,3], and the initial value of x is 3.In the second test, the hidden permutation is a = [2,1], and the initial value of x is 1.
2 5 > = < = < < 2 >
? 4 ? 2 ? 1 ? 5 ? 1 ? 3 ! 2 4 1 5 3 ? 1 ! 2 1
2 seconds
256 megabytes
['constructive algorithms', 'divide and conquer', 'implementation', 'interactive', 'probabilities', 'sortings', '*2200']
D. Blocking Elementstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of numbers a_1, a_2, \ldots, a_n. Your task is to block some elements of the array in order to minimize its cost. Suppose you block the elements with indices 1 \leq b_1 < b_2 < \ldots < b_m \leq n. Then the cost of the array is calculated as the maximum of: the sum of the blocked elements, i.e., a_{b_1} + a_{b_2} + \ldots + a_{b_m}. the maximum sum of the segments into which the array is divided when the blocked elements are removed. That is, the maximum sum of the following (m + 1) subarrays: [1, b_1 − 1], [b_1 + 1, b_2 − 1], [\ldots], [b_{m−1} + 1, b_m - 1], [b_m + 1, n] (the sum of numbers in a subarray of the form [x,x − 1] is considered to be 0). For example, if n = 6, the original array is [1, 4, 5, 3, 3, 2], and you block the elements at positions 2 and 5, then the cost of the array will be the maximum of the sum of the blocked elements (4 + 3 = 7) and the sums of the subarrays (1, 5 + 3 = 8, 2), which is \max(7,1,8,2) = 8. You need to output the minimum cost of the array after blocking.InputThe first line of the input contains a single integer t (1 \leq t \leq 30\,000) — the number of queries.Each test case consists of two lines. The first line contains an integer n (1 \leq n \leq 10^5) — the length of the array a. The second line contains n elements a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the array a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single number — the minimum cost of blocking the array.ExampleInput 361 4 5 3 3 251 2 3 4 564 1 6 3 10 7Output 7 5 11 NoteThe first test case matches with the array from the statement. To obtain a cost of 7, you need to block the elements at positions 2 and 4. In this case, the cost of the array is calculated as the maximum of: the sum of the blocked elements, which is a_2 + a_4 = 7. the maximum sum of the segments into which the array is divided when the blocked elements are removed, i.e., the maximum of a_1, a_3, a_5 + a_6 = \max(1,5,5) = 5. So the cost is \max(7,5) = 7. In the second test case, you can block the elements at positions 1 and 4.In the third test case, to obtain the answer 11, you can block the elements at positions 2 and 5. There are other ways to get this answer, for example, blocking positions 4 and 6.
361 4 5 3 3 251 2 3 4 564 1 6 3 10 7
7 5 11
4 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'implementation', 'two pointers', '*1900']
C. XOR-distancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given integers a, b, r. Find the smallest value of |({a \oplus x}) - ({b \oplus x})| among all 0 \leq x \leq r.\oplus is the operation of bitwise XOR, and |y| is absolute value of y.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case contains integers a, b, r (0 \le a, b, r \le 10^{18}).OutputFor each test case, output a single number — the smallest possible value.ExampleInput 104 6 00 3 29 6 1092 256 23165 839 2011 14 52 7 296549 34359 13851853686404475946 283666553522252166 127929199446003072735268590557942972 916721749674600979 895150420120690183Output 2 1 1 164 542 5 3 37102 27934920819538516 104449824168870225 NoteIn the first test, when r = 0, then x is definitely equal to 0, so the answer is |{4 \oplus 0} - {6 \oplus 0}| = |4 - 6| = 2.In the second test: When x = 0, |{0 \oplus 0} - {3 \oplus 0}| = |0 - 3| = 3. When x = 1, |{0 \oplus 1} - {3 \oplus 1}| = |1 - 2| = 1. When x = 2, |{0 \oplus 2} - {3 \oplus 2}| = |2 - 1| = 1. Therefore, the answer is 1.In the third test, the minimum is achieved when x = 1.
104 6 00 3 29 6 1092 256 23165 839 2011 14 52 7 296549 34359 13851853686404475946 283666553522252166 127929199446003072735268590557942972 916721749674600979 895150420120690183
2 1 1 164 542 5 3 37102 27934920819538516 104449824168870225
2 seconds
256 megabytes
['bitmasks', 'greedy', 'implementation', 'math', '*1400']
B. Minimize Inversionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two permutations a and b of length n. A permutation is an array of n elements from 1 to n where all elements are distinct. For example, an array [2,1,3] is a permutation, but [0,1] and [1,3,1] aren't.You can (as many times as you want) choose two indices i and j, then swap a_i with a_j and b_i with b_j simultaneously. You hate inversions, so you want to minimize the total number of inversions in both permutations.An inversion in a permutation p is a pair of indices (i, j) such that i < j and p_i > p_j. For example, if p=[3,1,4,2,5] then there are 3 inversions in it (the pairs of indices are (1,2), (1,4) and (3,4)).InputThe first line contains an integer t (1 \leq t \leq 20\,000) — the number of test cases.Each test case consists of three lines. The first line contains an integer n (1 \leq n \leq 2\cdot10^5) — the length of the permutations a and b. The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — permutation a. The third line contains b in a similar format. It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output two permutations a' and b' (in the same format as in the input) — the permutations after all operations. The total number of inversions in a' and b' should be the minimum possible among all pairs of permutations that can be obtained using operations from the statement.If there are multiple solutions, print any of them.ExampleInput 351 2 3 4 55 4 3 2 133 1 23 1 262 5 6 1 3 41 5 3 6 2 4Output 3 2 5 1 4 3 4 1 5 2 1 2 3 1 2 3 2 3 4 6 5 1 1 2 4 3 5 6 NoteIn the first test case, the minimum possible number of inversions is 10.In the second test case, we can sort both permutations at the same time. For this, the following operations can be done: Swap the elements in the positions 1 and 3 in both permutations. After the operation, a = [2,1,3], b = [2,1,3]. Swap the elements in the positions 1 and 2. After the operations, a and b are sorted. In the third test case, the minimum possible number of inversions is 7.
351 2 3 4 55 4 3 2 133 1 23 1 262 5 6 1 3 41 5 3 6 2 4
3 2 5 1 4 3 4 1 5 2 1 2 3 1 2 3 2 3 4 6 5 1 1 2 4 3 5 6
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', 'implementation', 'sortings', '*900']
A. Brick Walltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA brick is a strip of size 1 \times k, placed horizontally or vertically, where k can be an arbitrary number that is at least 2 (k \ge 2).A brick wall of size n \times m is such a way to place several bricks inside a rectangle n \times m, that all bricks lie either horizontally or vertically in the cells, do not cross the border of the rectangle, and that each cell of the n \times m rectangle belongs to exactly one brick. Here n is the height of the rectangle n \times m and m is the width. Note that there can be bricks with different values of k in the same brick wall.The wall stability is the difference between the number of horizontal bricks and the number of vertical bricks. Note that if you used 0 horizontal bricks and 2 vertical ones, then the stability will be -2, not 2.What is the maximal possible stability of a wall of size n \times m?It is guaranteed that under restrictions in the statement at least one n \times m wall exists.InputThe first line of the input contains one integer t (1 \le t \le 10\,000), the number of test cases. The only line of each test case contains two integers n and m (2 \le n,\,m \le 10^4).OutputFor each test case, print one integer, the maximum stability of a wall of size n \times m.ExampleInput 52 27 816 93 510000 10000Output 2 28 64 6 50000000 NoteIn the 1st test case, the maximum stability of 2 is obtained by placing two horizontal bricks 1 \times 2 one on top of the other.In the 2nd test case, one can get the maximum stability of 28 by placing 4 horizontal bricks 1 \times 2 in each of the 7 rows.
52 27 816 93 510000 10000
2 28 64 6 50000000
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*800']
F. Construct Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers l_1, l_2, \dots, l_n and an integer d. Is it possible to construct a tree satisfying the following three conditions? The tree contains n + 1 nodes. The length of the i-th edge is equal to l_i. The (weighted) diameter of the tree is equal to d. InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 250) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, d (2 \leq n \leq 2000, 1 \leq d \leq 2000).The second line of each test case contains n integers l_1, l_2, \dots, l_n (1 \leq l_i \leq d).It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output \texttt{Yes} if it is possible to construct a tree that satisfies all the conditions, and \texttt{No} otherwise.You can print the letters in any case (upper or lower).ExampleInput 34 101 2 3 44 71 4 3 46 182 4 3 7 6 7Output Yes No Yes NoteBelow, you are given the illustrations of trees for the first and third test cases. One of the diameters is highlighted by coloring its edges in red.
34 101 2 3 44 71 4 3 46 182 4 3 7 6 7
Yes No Yes
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'trees', '*2500']
E. Construct Matrixtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an even integer n and an integer k. Your task is to construct a matrix of size n \times n consisting of numbers 0 and 1 in such a way that the following conditions are true, or report that it is impossible: the sum of all the numbers in the matrix is exactly k; the bitwise \texttt{XOR} of all the numbers in the row i is the same for each i; the bitwise \texttt{XOR} of all the numbers in the column j is the same for each j. InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 130) — the number of test cases. The description of the test cases follows.Each test case is described by a single line, which contains two integers n and k (2 \leq n \leq 1000, n is even, 0 \leq k \leq n^2).It is guaranteed that the sum of n over all test cases does not exceed 2000.OutputFor each test case, output \texttt{Yes} if it's possible to construct a matrix that satisfies all of the problem's conditions, and \texttt{No} otherwise.If it is possible to construct a matrix, the i-th of the next n lines should contain n integers representing the elements in the i-th row of the matrix.ExampleInput 5 4 0 6 6 6 5 4 2 6 36 Output Yes 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Yes 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 No No Yes 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1NoteIn the first example, all conditions are satisfied: the sum of all the numbers in the matrix is exactly 0; the bitwise \texttt{XOR} of all the numbers in the row i is 0 for each i; the bitwise \texttt{XOR} of all the numbers in the column j is 0 for each j. In the third example, it can be shown that it's impossible to find a matrix satisfying all the problem's conditions.
5 4 0 6 6 6 5 4 2 6 36
Yes 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Yes 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 No No Yes 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 second
256 megabytes
['constructive algorithms', 'math', '*2500']
D. Yet Another Inversions Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p_0, p_1, \ldots, p_{n-1} of odd integers from 1 to 2n-1 and a permutation q_0, q_1, \ldots, q_{k-1} of integers from 0 to k-1.An array a_0, a_1, \ldots, a_{nk-1} of length nk is defined as follows: a_{i \cdot k+j}=p_i \cdot 2^{q_j} for all 0 \le i < n and all 0 \le j < k For example, if p = [3, 5, 1] and q = [0, 1], then a = [3, 6, 5, 10, 1, 2].Note that all arrays in the statement are zero-indexed. Note that each element of the array a is uniquely determined.Find the number of inversions in the array a. Since this number can be very large, you should find only its remainder modulo 998\,244\,353.An inversion in array a is a pair (i, j) (0 \le i < j < nk) such that a_i > a_j.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n, k \le 2 \cdot 10^5) — the lengths of arrays p and q.The second line of each test case contains n distinct integers p_0, p_1, \ldots, p_{n-1} (1 \le p_i \le 2n-1, p_i is odd) — the array p.The third line of each test case contains k distinct integers q_0, q_1, \ldots, q_{k-1} (0 \le q_i < k) — the array q.It is guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5 and the sum of k over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, output one integer: the number of inversions in array a modulo 998\,244\,353.ExampleInput 43 23 5 10 13 41 3 53 2 0 11 510 1 2 3 48 35 1 7 11 15 3 9 132 0 1Output 9 25 0 104 NoteIn the first test case, array a is equal to [3, 6, 5, 10, 1, 2]. There are 9 inversions in it: (0, 4), (0, 5), (1, 2), (1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5). Note that these are pairs (i, j) such that i < j and a_i > a_j.In the second test case, array a is equal to [8, 4, 1, 2, 24, 12, 3, 6, 40, 20, 5, 10]. There are 25 inversions in it.In the third test case, array a is equal to [1, 2, 4, 8, 16]. There are no inversions in it.
43 23 5 10 13 41 3 53 2 0 11 510 1 2 3 48 35 1 7 11 15 3 9 132 0 1
9 25 0 104
2 seconds
256 megabytes
['combinatorics', 'data structures', 'dp', 'implementation', 'math', 'number theory', '*2300']
C. Watering an Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array of integers a_1, a_2, \ldots, a_n of length n. On the i-th of the next d days you are going to do exactly one of the following two actions: Add 1 to each of the first b_i elements of the array a (i.e., set a_j := a_j + 1 for each 1 \le j \le b_i). Count the elements which are equal to their position (i.e., the a_j = j). Denote the number of such elements as c. Then, you add c to your score, and reset the entire array a to a 0-array of length n (i.e., set [a_1, a_2, \ldots, a_n] := [0, 0, \ldots, 0]). Your score is equal to 0 in the beginning. Note that on each day you should perform exactly one of the actions above: you cannot skip a day or perform both actions on the same day.What is the maximum score you can achieve at the end?Since d can be quite large, the sequence b is given to you in the compressed format: You are given a sequence of integers v_1, v_2, \ldots, v_k. The sequence b is a concatenation of infinitely many copies of v: b = [v_1, v_2, \ldots, v_k, v_1, v_2, \ldots, v_k, \ldots]. InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases.The first line of each test case contains three integers n, k and d (1 \le n \le 2000, 1 \le k \le 10^5, k \le d \le 10^9) — the length of the array a, the length of the sequence v and the number of days you are going to perform operations on.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n) — the array a.The third line of each test case contains k integers v_1, v_2, \ldots, v_k (1 \le v_i \le n) — the sequence v.It is guaranteed that the sum of n over all test cases doesn't exceed 2000 and the sum of k over all test cases doesn't exceed 10^5.OutputFor each test case, output one integer: the maximum score you can achieve at the end of the d-th day.ExampleInput 53 4 41 2 31 3 2 36 2 36 1 2 4 1 56 65 1 10 5 0 5 051 1 1113 4 61 2 31 3 2 3Output 4 3 0 1 5 NoteIn the first test case, the sequence b is equal to [1, 3, 2, 3, 1, 3, 2, 3, \ldots] and one of the optimal solutions for this case is as follows: Perform the operation of the second type on the 1-st day: your score increases by 3 and array a becomes equal to [0, 0, 0]. Perform the operation of the first type on the 2-nd day: array a becomes equal to [1, 1, 1]. Perform the operation of the first type on the 3-rd day: array a becomes equal to [2, 2, 1]. Perform the operation of the second type on the 4-th day: your score increases by 1 and array a becomes equal to [0, 0, 0]. It can be shown that it is impossible to score more than 4, so the answer is 4.In the second test case, the sequence b is equal to [6, 6, 6, 6, \ldots]. One of the ways to score 3 is to perform operations of the first type on the 1-st and the 3-rd days and to perform an operation of the second type on the 2-nd day.
53 4 41 2 31 3 2 36 2 36 1 2 4 1 56 65 1 10 5 0 5 051 1 1113 4 61 2 31 3 2 3
4 3 0 1 5
2 seconds
256 megabytes
['brute force', 'greedy', 'implementation', 'math', '*1600']
B. Erase First or Second Lettertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n. Let's define two operations you can apply on the string: remove the first character of the string; remove the second character of the string. Your task is to find the number of distinct non-empty strings that can be generated by applying the given operations on the initial string any number of times (possibly zero), in any order.InputEach test consists of 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 n (1 \leq n \leq 10^5) — the length of the string.The second line of each test case contains the string s. It is guaranteed that the string only contains lowercase letters of the English alphabet.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 distinct non-empty strings you can get.ExampleInput 55aaaaa1z5ababa14bcdaaaabcdaaaa20abcdefghijklmnopqrstOutput 5 1 9 50 210 NoteIn the first test case, we can get the following strings: a, aa, aaa, aaaa, aaaaa.In the third test case, for example, the word ba can be reached in the following way: remove the first character of the current string ababa, getting baba; remove the second character of the current string baba, getting bba; remove the second character of the current string bba, getting ba.
55aaaaa1z5ababa14bcdaaaabcdaaaa20abcdefghijklmnopqrst
5 1 9 50 210
1 second
256 megabytes
['brute force', 'combinatorics', 'data structures', 'dp', 'strings', '*1100']
A. Least Producttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1, a_2, \dots, a_n. You can perform the following operation any number of times (possibly zero): Choose any element a_i from the array and change its value to any integer between 0 and a_i (inclusive). More formally, if a_i < 0, replace a_i with any integer in [a_i, 0], otherwise replace a_i with any integer in [0, a_i]. Let r be the minimum possible product of all the a_i after performing the operation any number of times.Find the minimum number of operations required to make the product equal to r. Also, print one such shortest sequence of operations. If there are multiple answers, you can print any of them.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 500) - the number of test cases. This is followed by their description.The first line of each test case contains the a single integer n (1 \leq n \leq 100) — the length of the array.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).OutputFor each test case: The first line must contain the minimum number of operations k (0 \leq k \leq n). The j-th of the next k lines must contain two integers i and x, which represent the j-th operation. That operation consists in replacing a_i with x. ExampleInput 4 1 155 4 2 8 -1 3 4 -1 0 -2 -5 4 -15 -75 -25 -30 Output 1 1 0 0 0 1 3 0 NoteIn the first test case, we can change the value of the first integer into 0 and the product will become 0, which is the minimum possible.In the second test case, initially, the product of integers is equal to 2 \cdot 8 \cdot (-1) \cdot 3 = -48 which is the minimum possible, so we should do nothing in this case.
4 1 155 4 2 8 -1 3 4 -1 0 -2 -5 4 -15 -75 -25 -30
1 1 0 0 0 1 3 0
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
H2. Matrix Rank (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only differences between the two versions of this problem are the constraints on k. You can make hacks only if all versions of the problem are solved.You are given integers n, p and k. p is guaranteed to be a prime number. For each r from 0 to k, find the number of n \times n matrices A of the field^\dagger of integers modulo p such that the rank^\ddagger of A is exactly r. Since these values are big, you are only required to output them modulo 998\,244\,353.^\dagger https://en.wikipedia.org/wiki/Field_(mathematics)^\ddagger https://en.wikipedia.org/wiki/Rank_(linear_algebra)InputThe first line of input contains three integers n, p and k (1 \leq n \leq 10^{18}, 2 \leq p < 998\,244\,353, 0 \leq k \leq 5 \cdot 10^5).It is guaranteed that p is a prime number.OutputOutput k+1 integers, the answers for each r from 0 to k.ExamplesInput 3 2 3Output 1 49 294 168 Input 1 51549919 2Output 1 51549918 0
3 2 3
1 49 294 168
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', 'matrices', 'string suffix structures', '*2700']
H1. Matrix Rank (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only differences between the two versions of this problem are the constraints on k. You can make hacks only if all versions of the problem are solved.You are given integers n, p and k. p is guaranteed to be a prime number. For each r from 0 to k, find the number of n \times n matrices A of the field^\dagger of integers modulo p such that the rank^\ddagger of A is exactly r. Since these values are big, you are only required to output them modulo 998\,244\,353.^\dagger https://en.wikipedia.org/wiki/Field_(mathematics)^\ddagger https://en.wikipedia.org/wiki/Rank_(linear_algebra)InputThe first line of input contains three integers n, p and k (1 \leq n \leq 10^{18}, 2 \leq p < 998\,244\,353, 0 \leq k \leq 5000).It is guaranteed that p is a prime number.OutputOutput k+1 integers, the answers for each r from 0 to k.ExamplesInput 3 2 3Output 1 49 294 168 Input 1 51549919 2Output 1 51549918 0
3 2 3
1 49 294 168
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'math', 'matrices', '*2700']
G. Optimizations From Chelsutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices, whose vertices are numbered from 1 to n. Each edge is labeled with some integer w_i.Define len(u, v) as the number of edges in the simple path between vertices u and v, and gcd(u, v) as the Greatest Common Divisor of all numbers written on the edges of the simple path between vertices u and v. For example, len(u, u) = 0 and gcd(u, u) = 0 for any 1 \leq u \leq n.You need to find the maximum value of len(u, v) \cdot gcd(u, v) over all pairs of vertices in the tree.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. This is followed by their description.The first line of each test case contains the number n (2 \leq n \leq 10^5) — the number of vertices in the tree.The next n-1 lines specify the edges in the format u, v, w (1 \leq u, v \leq n, 1 \leq w \leq 10^{12}).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single number equal to the maximum value of len(u, v) \cdot gcd(u, v) over all pairs of vertices in the tree.ExampleInput 421 2 100000000000043 2 62 1 102 4 681 2 122 3 93 4 94 5 65 6 126 7 47 8 9121 2 122 3 122 4 62 5 95 6 61 7 44 8 128 9 48 10 122 11 97 12 9Output 1000000000000 12 18 24
421 2 100000000000043 2 62 1 102 4 681 2 122 3 93 4 94 5 65 6 126 7 47 8 9121 2 122 3 122 4 62 5 95 6 61 7 44 8 128 9 48 10 122 11 97 12 9
1000000000000 12 18 24
2 seconds
256 megabytes
['divide and conquer', 'dp', 'number theory', 'trees', '*3500']
F. Group Divisiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the 31st lyceum, there were two groups of olympiad participants: computer science and mathematics. The number of computer scientists was n_1, and the number of mathematicians was n_2. It is not known for certain who belonged to which group, but it is known that there were friendly connections between some pairs of people (these connections could exist between a pair of people from the same group or from different groups).The connections were so strong that even if one person is removed along with all their friendly connections, any pair of people still remains acquainted either directly or through mutual friends.^{\dagger} More formally, two people (x, y) are acquainted in the following case: there are people a_1, a_2, \ldots,a_n (1 \le a_i \le n_1 + n_2) such that the following conditions are simultaneously met:\bullet Person x is directly acquainted with a_1.\bullet Person a_n is directly acquainted with y.\bullet Person a_i is directly acquainted with a_{i + 1} for any (1 \le i \le n - 1).The teachers were dissatisfied with the fact that computer scientists were friends with mathematicians and vice versa, so they decided to divide the students into two groups in such a way that the following two conditions are met:\bullet There were n_1 people in the computer science group, and n_2 people in the mathematics group.\bullet Any pair of computer scientists should be acquainted (acquaintance involving mutual friends, who must be from the same group as the people in the pair, is allowed), the same should be true for mathematicians.Help them solve this problem and find out who belongs to which group.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains three integers n_1, n_2, and m (1 \le n_1, n_2 \le 2000, 1 \le m \le 5000). n_1, n_2 are the sizes of the two groups described in the problem, and m is the number of friendly connections initially.The following m lines describe the friendly connections: in the i-th (1 \le i \le m) line, a pair of numbers (a, b) is given, which means that the person with number a is friends with the person with number b (and vice versa).It is guaranteed that for each test case, all friendly connections are distinct.It is guaranteed that the sum of n_1 + n_2 for all test cases does not exceed 2000, and the sum of m for all test cases does not exceed 5000.It is also guaranteed that for each test case, a solution exists.If there are several answers, print any of them.OutputFor each test case, output two lines.In the first line, output n_1 distinct numbers a_i (1 \le a_i \le n_1 + n_2) — the people belonging to the first group.In the second line, output n_2 distinct numbers b_i (1 \le b_i \le n_1 + n_2) — the people belonging to the second group.All numbers must be distinct.If there are several possible answers, print any one.ExampleInput 31 2 32 31 31 21 4 72 53 42 41 23 54 51 53 3 71 21 62 32 53 44 54 6Output 3 1 2 5 1 2 3 4 4 5 6 1 2 3 NoteConsider the third test case. The division into groups looks as follows: The students selected as computer scientists are colored in green, and those selected as mathematicians are colored in blue.Consider all pairs of computer scientists and how they are acquainted:Pairs (4, 5), (4, 6) are directly acquainted.Pair (5, 6) is acquainted through the computer scientist with number 4.Consider all pairs of mathematicians and how they are acquainted:Pairs (1, 2), (2, 3) are directly acquainted.Pair (1, 3) is acquainted through the mathematician with number 2.We conclude that any pair of people belonging to the same group is acquainted with each other, thus the division into two groups is correct.
31 2 32 31 31 21 4 72 53 42 41 23 54 51 53 3 71 21 62 32 53 44 54 6
3 1 2 5 1 2 3 4 4 5 6 1 2 3
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*2900']
E. Happy Life in Universitytime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputEgor and his friend Arseniy are finishing school this year and will soon enter university. And since they are very responsible guys, they have started preparing for admission already.First of all, they decided to take care of where they will live for the long four years of study, and after visiting the university's website, they found out that the university dormitory can be represented as a root tree with n vertices with the root at vertex 1. In the tree, each vertex represents a recreation with some type of activity a_i. The friends need to choose 2 recreations (not necessarily different) in which they will settle. The guys are convinced that the more the value of the following function f(u, v) = diff(u, lca(u, v)) \cdot diff(v, lca(u, v)), the more fun their life will be. Help Egor and Arseniy and find the maximum value of f(u, v) among all pairs of recreations!^{\dagger} diff(u, v) — the number of different activities listed on the simple path from vertex u to vertex v.^{\dagger} lca(u, v) — a vertex p such that it is at the maximum distance from the root and is a parent of both vertex u and vertex v.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains a single integer n (1 \le n \le 3 \cdot 10^{5}).The second line of each test case contains {n - 1} integers p_2, p_3, \ldots,p_n (1 \le p_i \le i - 1), where p_i — the parent of vertex i.The third line of each test case contains {n} integers a_1, a_2, \ldots,a_n (1 \le a_i \le n), where a_i — the number of the activity located at vertex i.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output the maximum value of f(u, v) for all pairs of recreations (u, v).ExampleInput 4211 271 1 2 2 3 36 5 2 3 6 5 6131 1 1 2 2 2 3 3 4 5 6 62 2 2 1 4 9 7 2 5 2 1 11 2121 1 1 2 2 3 4 4 7 7 611 2 1 11 12 8 5 8 8 5 11 7Output 2 9 9 12 NoteConsider the fourth test case. The tree has the following structure: All recreations are colored. The same colors mean that the activities in the recreations match. Consider the pair of vertices (11, 12), lca(11, 12) = 1. Write down all activities on the path from 11 to 1 — [11, 5, 1, 11], among them there are 3 different activities, so diff(11, 1) = 3. Also write down all activities on the path from 12 to 1 — [7, 8, 2, 11], among them there are 4 different activities, so diff(12, 1) = 4. We get that f(11, 12) = diff(12, 1) \cdot diff(11, 1) = 4 \cdot 3 = 12, which is the answer for this tree. It can be shown that a better answer is impossible to obtain.
4211 271 1 2 2 3 36 5 2 3 6 5 6131 1 1 2 2 2 3 3 4 5 6 62 2 2 1 4 9 7 2 5 2 1 11 2121 1 1 2 2 3 4 4 7 7 611 2 1 11 12 8 5 8 8 5 11 7
2 9 9 12
1 second
512 megabytes
['data structures', 'dfs and similar', 'greedy', 'trees', '*2300']
D. Mathematical Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe mathematicians of the 31st lyceum were given the following task:You are given an odd number n, and you need to find n different numbers that are squares of integers. But it's not that simple. Each number should have a length of n (and should not have leading zeros), and the multiset of digits of all the numbers should be the same. For example, for \mathtt{234} and \mathtt{432}, and \mathtt{11223} and \mathtt{32211}, the multisets of digits are the same, but for \mathtt{123} and \mathtt{112233}, they are not.The mathematicians couldn't solve this problem. Can you?InputThe first line contains an integer t (1 \leq t \leq 100) — the number of test cases.The following t lines contain one odd integer n (1 \leq n \leq 99) — the number of numbers to be found and their length.It is guaranteed that the solution exists within the given constraints.It is guaranteed that the sum of n^2 does not exceed 10^5.The numbers can be output in any order.OutputFor each test case, you need to output n numbers of length n — the answer to the problem.If there are several answers, print any of them.ExampleInput 3135Output 1 169 196 961 16384 31684 36481 38416 43681 NoteBelow are the squares of the numbers that are the answers for the second test case:\mathtt{169} = \mathtt{13}^2\mathtt{196} = \mathtt{14}^2\mathtt{961} = \mathtt{31}^2Below are the squares of the numbers that are the answers for the third test case:\mathtt{16384} = \mathtt{128}^2\mathtt{31684} = \mathtt{178}^2\mathtt{36481} = \mathtt{191}^2\mathtt{38416} = \mathtt{196}^2\mathtt{43681} = \mathtt{209}^2
3135
1 169 196 961 16384 31684 36481 38416 43681
1 second
256 megabytes
['brute force', 'constructive algorithms', 'geometry', 'math', '*1700']
C. Training Before the Olympiadtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha and Olya have an important team olympiad coming up soon. In honor of this, Masha, for warm-up, suggested playing a game with Olya:There is an array a of size n. Masha goes first, and the players take turns. Each move is described by the following sequence of actions:\bullet If the size of the array is 1, the game ends.\bullet The player who is currently playing chooses two different indices i, j (1 \le i, j \le |a|), and performs the following operation — removes a_i and a_j from the array and adds to the array a number equal to \lfloor \frac{a_i + a_j}{2} \rfloor \cdot 2. In other words, first divides the sum of the numbers a_i, a_j by 2 rounding down, and then multiplies the result by 2.Masha aims to maximize the final number, while Olya aims to minimize it.Masha and Olya decided to play on each non-empty prefix of the initial array a, and asked for your help.For each k = 1, 2, \ldots, n, answer the following question. Let only the first k elements of the array a be present in the game, with indices 1, 2, \ldots, k respectively. What number will remain at the end with optimal play by both players?InputThe first line contains an integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the size of the array.The second line contains n integers a_1,a_2, \ldots,a_n (1 \leq a_i \leq 10^9) — the array on which Masha and Olya play.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output n integers. The k-th of these numbers should be equal to the number that will remain at the end with optimal play by both players, on the array consisting of the first k elements of the array a.ExampleInput 413166 3 7 2 5 433 10 1157 13 11 19 1Output 31 6 8 16 18 22 26 3 12 24 7 20 30 48 50 NoteIn the third test case, for a prefix of length 1, the answer is 3. For a prefix of length 2, Masha has only one move, so the answer is 12. For a prefix of length 3, Masha has three possible moves: she chooses 3 and 10, then the final number is 22, 3 and 11, then the final number is 24, 10 and 11, then the final number is 22, so Masha will choose 3 and 11 and get 24.
413166 3 7 2 5 433 10 1157 13 11 19 1
31 6 8 16 18 22 26 3 12 24 7 20 30 48 50
1 second
256 megabytes
['constructive algorithms', 'games', 'greedy', 'implementation', 'math', '*1200']
B. Two Divisorstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA certain number 1 \le x \le 10^9 is chosen. You are given two integers a and b, which are the two largest divisors of the number x. At the same time, the condition 1 \le a < b < x is satisfied.For the given numbers a, b, you need to find the value of x.^{\dagger} The number y is a divisor of the number x if there is an integer k such that x = y \cdot k.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then follows the description of the test cases.The only line of each test cases contains two integers a, b (1 \le a < b \le 10^9).It is guaranteed that a, b are the two largest divisors for some number 1 \le x \le 10^9.OutputFor each test case, output the number x, such that a and b are the two largest divisors of the number x.If there are several answers, print any of them.ExampleInput 82 31 23 111 55 104 63 9250000000 500000000Output 6 4 33 25 20 12 27 1000000000 NoteFor the first test case, all divisors less than 6 are equal to [1, 2, 3], among them the two largest will be 2 and 3.For the third test case, all divisors less than 33 are equal to [1, 3, 11], among them the two largest will be 3 and 11.For the fifth test case, all divisors less than 20 are equal to [1, 2, 4, 5, 10], among them the two largest will be 5 and 10.For the sixth test case, all divisors less than 12 are equal to [1, 2, 3, 4, 6], among them the two largest will be 4 and 6.
82 31 23 111 55 104 63 9250000000 500000000
6 4 33 25 20 12 27 1000000000
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*1000']
A. 2023time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn a sequence a, whose product was equal to 2023, k numbers were removed, leaving a sequence b of length n. Given the resulting sequence b, find any suitable sequence a and output which k elements were removed from it, or state that such a sequence could not have existed.Notice that you are not guaranteed that such array exists.InputEach test consists of several test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. This is followed by a description of the test cases.The first line of each test case contains two integers n (1 \le n, k \le 5) — the size of sequence b and the number of numbers removed from sequence a.The second line contains n integers b_1,b_2, \ldots,b_n (1 \leq b_i \leq 2023) — the remaining sequence. The values of b_i might not be divisors of 2023.OutputFor each test case, output "YES" if the sequence a exists, and in the following line output k non-negative integers that were removed from the sequence a. If the sequence a does not exist, output "NO" in a single line.You can output the answer in any case (uppercase or lowercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive answers.ExampleInput 72 25 23 17 17 74 21 289 1 13 17 17 171 12891 120231 31Output NO NO YES 7 1 YES 1 YES 7 YES 1 YES 7 17 17 NoteIn third test case product is equal to 289 \cdot 7 = 2023.In fourth test case product is already equal to 2023.In seventh test case product is equal to 7 \cdot 17 \cdot 17 = 2023.
72 25 23 17 17 74 21 289 1 13 17 17 171 12891 120231 31
NO NO YES 7 1 YES 1 YES 7 YES 1 YES 7 17 17
1 second
256 megabytes
['constructive algorithms', 'implementation', 'math', 'number theory', '*800']
G. Bicyclestime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAll of Slavic's friends are planning to travel from the place where they live to a party using their bikes. And they all have a bike except Slavic. There are n cities through which they can travel. They all live in the city 1 and want to go to the party located in the city n. The map of cities can be seen as an undirected graph with n nodes and m edges. Edge i connects cities u_i and v_i and has a length of w_i.Slavic doesn't have a bike, but what he has is money. Every city has exactly one bike for sale. The bike in the i-th city has a slowness factor of s_{i}. Once Slavic buys a bike, he can use it whenever to travel from the city he is currently in to any neighboring city, by taking w_i \cdot s_j time, considering he is traversing edge i using a bike j he owns.Slavic can buy as many bikes as he wants as money isn't a problem for him. Since Slavic hates traveling by bike, he wants to get from his place to the party in the shortest amount of time possible. And, since his informatics skills are quite rusty, he asks you for help.What's the shortest amount of time required for Slavic to travel from city 1 to city n? Slavic can't travel without a bike. It is guaranteed that it is possible for Slavic to travel from city 1 to any other city.InputThe 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 two space-separated integers n and m (2 \leq n \leq 1000; n - 1 \leq m \leq 1000) — the number of cities and the number of roads, respectively.The i-th of the following m lines each contain three integers u_i, v_i, w_i (1 \le u_i, v_i \le n, u_i \neq v_i; 1 \leq w_i \leq 10^5), denoting that there is a road between cities u_i and v_i of length w_i. The same pair of cities can be connected by more than one road.The next line contains n integers s_1, \ldots, s_n (1 \leq s_i \leq 1000) — the slowness factor of each bike.The sum of n over all test cases does not exceed 1000, and the sum of m over all test cases does not exceed 1000.Additional constraint on the input: it is possible to travel from city 1 to any other city.OutputFor each test case, output a single integer denoting the shortest amount of time Slavic can reach city n starting from city 1.ExampleInput 35 51 2 23 2 12 4 52 5 74 5 15 2 1 3 35 101 2 51 3 51 4 41 5 82 3 62 4 32 5 23 4 13 5 84 5 27 2 8 4 17 103 2 82 1 42 5 72 6 47 1 24 3 56 4 26 7 16 7 44 5 97 6 5 4 3 2 1Output 19 36 14
35 51 2 23 2 12 4 52 5 74 5 15 2 1 3 35 101 2 51 3 51 4 41 5 82 3 62 4 32 5 23 4 13 5 84 5 27 2 8 4 17 103 2 82 1 42 5 72 6 47 1 24 3 56 4 26 7 16 7 44 5 97 6 5 4 3 2 1
19 36 14
4 seconds
256 megabytes
['graphs', 'greedy', 'implementation', 'shortest paths', 'sortings', '*1800']
F. Greetingstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n people on the number line; the i-th person is at point a_i and wants to go to point b_i. For each person, a_i < b_i, and the starting and ending points of all people are distinct. (That is, all of the 2n numbers a_1, a_2, \dots, a_n, b_1, b_2, \dots, b_n are distinct.) All the people will start moving simultaneously at a speed of 1 unit per second until they reach their final point b_i. When two people meet at the same point, they will greet each other once. How many greetings will there be?Note that a person can still greet other people even if they have reached their final point.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of people.Then n lines follow, the i-th of which contains two integers a_i and b_i (-10^9 \leq a_i < b_i \leq 10^9) — the starting and ending positions of each person.For each test case, all of the 2n numbers a_1, a_2, \dots, a_n, b_1, b_2, \dots, b_n are distinct.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer denoting the number of greetings that will happen.ExampleInput 522 31 462 63 94 51 87 10-2 1004-10 10-5 5-12 12-13 135-4 9-2 53 46 78 1041 23 45 67 8Output 1 9 6 4 0 NoteIn the first test case, the two people will meet at point 3 and greet each other.
522 31 462 63 94 51 87 10-2 1004-10 10-5 5-12 12-13 135-4 9-2 53 46 78 1041 23 45 67 8
1 9 6 4 0
5 seconds
256 megabytes
['data structures', 'divide and conquer', 'sortings', '*1500']
E. Romantic Glassestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIulia has n glasses arranged in a line. The i-th glass has a_i units of juice in it. Iulia drinks only from odd-numbered glasses, while her date drinks only from even-numbered glasses.To impress her date, Iulia wants to find a contiguous subarray of these glasses such that both Iulia and her date will have the same amount of juice in total if only the glasses in this subarray are considered. Please help her to do that.More formally, find out if there exists two indices l, r such that 1 \leq l \leq r \leq n, and a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r} = a_{l + 1} + a_{l + 3} + \dots + a_{r-1} if l and r have the same parity and a_l + a_{l + 2} + a_{l + 4} + \dots + a_{r - 1} = a_{l + 1} + a_{l + 3} + \dots + a_{r} otherwise.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 a single integer n (1 \leq n \leq 2 \cdot 10^5) — the total number of glasses.The second line of each test case contains n integers a_1, \ldots, a_n (1 \leq a_i \leq 10^9) — the amount of juice in each glass.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" if there exists a subarray satisfying the condition, 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 631 3 261 1 1 1 1 1101 6 9 8 55 3 14 2 7 281 2 11 4 1 5 1 262 6 1 5 7 892 5 10 4 4 9 6 7 8Output YES YES NO YES NO YES NoteIn the first test case, Iulia can pick l=1 and r=3. Then she drinks a_1+a_3=1+2=3 units and her date drinks a_2=3 units of juice.In the second test case, Iulia can pick l=2 and r=5. Then she drinks a_3+a_5=1+1=2 units and her date drinks a_2+a_4=1+1=2 units of juice.In the third test case no such contiguous subarray works.In the fourth test case, Iulia can pick l=2 and r=8. Then she drinks a_3+a_5+a_7=11+1+1=13 units and her date drinks a_2+a_4+a_6+a_8=2+4+5+2=13 units of juice.
631 3 261 1 1 1 1 1101 6 9 8 55 3 14 2 7 281 2 11 4 1 5 1 262 6 1 5 7 892 5 10 4 4 9 6 7 8
YES YES NO YES NO YES
1 second
256 megabytes
['data structures', 'greedy', 'math', '*1300']
D. Unnatural Language Processingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLura was bored and decided to make a simple language using the five letters \texttt{a}, \texttt{b}, \texttt{c}, \texttt{d}, \texttt{e}. There are two types of letters: vowels — the letters \texttt{a} and \texttt{e}. They are represented by \textsf{V}. consonants — the letters \texttt{b}, \texttt{c}, and \texttt{d}. They are represented by \textsf{C}. There are two types of syllables in the language: \textsf{CV} (consonant followed by vowel) or \textsf{CVC} (vowel with consonant before and after). For example, \texttt{ba}, \texttt{ced}, \texttt{bab} are syllables, but \texttt{aa}, \texttt{eda}, \texttt{baba} are not.A word in the language is a sequence of syllables. Lura has written a word in the language, but she doesn't know how to split it into syllables. Help her break the word into syllables.For example, given the word \texttt{bacedbab}, it would be split into syllables as \texttt{ba.ced.bab} (the dot \texttt{.} represents a syllable boundary).InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains an integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the word.The second line of each test case contains a string consisting of n lowercase Latin characters  — the word. All words given are valid words in the language; that is, they only use the letters \texttt{a}, \texttt{b}, \texttt{c}, \texttt{d}, \texttt{e}, and each word is made up of several syllables.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor test case, output a string denoting the word split into syllables by inserting a dot \texttt{.} between every pair of adjacent syllables.If there are multiple possible splittings, output any of them. The input is given in such a way that at least one possible splitting exists.ExampleInput 68bacedbab4baba13daddecabeddad3dac6dacdac22dababbabababbabbababbaOutput ba.ced.bab ba.ba dad.de.ca.bed.dad dac dac.dac da.bab.ba.ba.bab.bab.ba.bab.ba
68bacedbab4baba13daddecabeddad3dac6dacdac22dababbabababbabbababba
ba.ced.bab ba.ba dad.de.ca.bed.dad dac dac.dac da.bab.ba.ba.bab.bab.ba.bab.ba
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*900']
C. Can I Square?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCalin has n buckets, the i-th of which contains a_i wooden squares of side length 1.Can Calin build a square using all the given squares?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 a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of buckets.The second line of each test case contains n integers a_1, \ldots, a_n (1 \leq a_i \leq 10^9) — the number of squares in each bucket.The sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" if Calin can build a square using all of the given 1 \times 1 squares, 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 519214 271 2 3 4 5 6 761 3 5 7 9 1142 2 2 2Output YES YES NO YES NO NoteIn the first test case, Calin can build a 3 \times 3 square.In the second test case, Calin can build a 4 \times 4 square.In the third test case, Calin cannot build a square using all the given squares.
519214 271 2 3 4 5 6 761 3 5 7 9 1142 2 2 2
YES YES NO YES NO
1 second
256 megabytes
['binary search', 'implementation', '*800']
B. Not Quite Latin Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA Latin square is a 3 \times 3 grid made up of the letters \texttt{A}, \texttt{B}, and \texttt{C} such that: in each row, the letters \texttt{A}, \texttt{B}, and \texttt{C} each appear once, and in each column, the letters \texttt{A}, \texttt{B}, and \texttt{C} each appear once. For example, one possible Latin square is shown below. \begin{bmatrix} \texttt{A} & \texttt{B} & \texttt{C} \\ \texttt{C} & \texttt{A} & \texttt{B} \\ \texttt{B} & \texttt{C} & \texttt{A} \\ \end{bmatrix}You are given a Latin square, but one of the letters was replaced with a question mark \texttt{?}. Find the letter that was replaced.InputThe first line of the input contains a single integer t (1 \leq t \leq 108) — the number of testcases.Each test case contains three lines, each consisting of three characters, representing the Latin square. Each character is one of \texttt{A}, \texttt{B}, \texttt{C}, or \texttt{?}.Each test case is a Latin square with exactly one of the letters replaced with a question mark \texttt{?}.OutputFor each test case, output the letter that was replaced.ExampleInput 3ABCC?BBCABCACA?ABC?ABBCAABCOutput A B C NoteThe correct Latin squares for the three test cases are shown below:\begin{bmatrix} \texttt{A} & \texttt{B} & \texttt{C} \\ \texttt{C} & \color{red}{\texttt{A}} & \texttt{B} \\ \texttt{B} & \texttt{C} & \texttt{A} \\ \end{bmatrix} \quad \begin{bmatrix} \texttt{B} & \texttt{C} & \texttt{A} \\ \texttt{C} & \texttt{A} & \color{red}{\texttt{B}} \\ \texttt{A} & \texttt{B} & \texttt{C} \\ \end{bmatrix} \quad \begin{bmatrix} \color{red}{\texttt{C}} & \texttt{A} & \texttt{B} \\ \texttt{B} & \texttt{C} & \texttt{A} \\ \texttt{A} & \texttt{B} & \texttt{C} \\ \end{bmatrix}
3ABCC?BBCABCACA?ABC?ABBCAABC
A B C
1 second
256 megabytes
['bitmasks', 'brute force', 'implementation', '*800']
A. Odd One Outtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three digits a, b, c. Two of them are equal, but the third one is different from the other two. Find the value that occurs exactly once.InputThe first line contains a single integer t (1 \leq t \leq 270) — the number of test cases.The only line of each test case contains three digits a, b, c (0 \leq a, b, c \leq 9). Two of the digits are equal, but the third one is different from the other two.OutputFor each test case, output the value that occurs exactly once.ExampleInput 101 2 24 3 45 5 67 8 89 0 93 6 32 8 25 7 77 7 55 7 5Output 1 3 6 7 0 6 8 5 5 7
101 2 24 3 45 5 67 8 89 0 93 6 32 8 25 7 77 7 55 7 5
1 3 6 7 0 6 8 5 5 7
1 second
256 megabytes
['bitmasks', 'implementation', '*800']
G2. Light Bulbs (Hard Version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe easy and hard versions of this problem differ only in the constraints on n. In the hard version, the sum of values of n over all test cases does not exceed 2 \cdot 10^5. Furthermore, there are no additional constraints on the value of n in a single test case.There are 2n light bulbs arranged in a row. Each light bulb has a color from 1 to n (exactly two light bulbs for each color).Initially, all light bulbs are turned off. You choose a set of light bulbs S that you initially turn on. After that, you can perform the following operations in any order any number of times: choose two light bulbs i and j of the same color, exactly one of which is on, and turn on the second one; choose three light bulbs i, j, k, such that both light bulbs i and k are on and have the same color, and the light bulb j is between them (i < j < k), and turn on the light bulb j. You want to choose a set of light bulbs S that you initially turn on in such a way that by performing the described operations, you can ensure that all light bulbs are turned on.Calculate two numbers: the minimum size of the set S that you initially turn on; the number of sets S of minimum size (taken modulo 998244353). InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then follow the descriptions of the test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of pairs of light bulbs.The second line of each test case contains 2n integers c_1, c_2, \dots, c_{2n} (1 \le c_i \le n), where c_i is the color of the i-th light bulb. For each color from 1 to n, exactly two light bulbs have this color.Additional constraint on the input: the sum of values of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two integers: the minimum size of the set S that you initially turn on; the number of sets S of minimum size (taken modulo 998244353). ExampleInput 422 2 1 121 2 2 121 2 1 253 4 4 5 3 1 1 5 2 2Output 2 4 1 2 1 4 2 8
422 2 1 121 2 2 121 2 1 253 4 4 5 3 1 1 5 2 2
2 4 1 2 1 4 2 8
3 seconds
512 megabytes
['combinatorics', 'data structures', 'dfs and similar', 'dp', 'graphs', 'hashing', '*2300']
G1. Light Bulbs (Easy Version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe easy and hard versions of this problem differ only in the constraints on n. In the easy version, the sum of values of n^2 over all test cases does not exceed 10^6. Furthermore, n does not exceed 1000 in each test case.There are 2n light bulbs arranged in a row. Each light bulb has a color from 1 to n (exactly two light bulbs for each color).Initially, all light bulbs are turned off. You choose a set of light bulbs S that you initially turn on. After that, you can perform the following operations in any order any number of times: choose two light bulbs i and j of the same color, exactly one of which is on, and turn on the second one; choose three light bulbs i, j, k, such that both light bulbs i and k are on and have the same color, and the light bulb j is between them (i < j < k), and turn on the light bulb j. You want to choose a set of light bulbs S that you initially turn on in such a way that by performing the described operations, you can ensure that all light bulbs are turned on.Calculate two numbers: the minimum size of the set S that you initially turn on; the number of sets S of minimum size (taken modulo 998244353). InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then follow the descriptions of the test cases.The first line of each test case contains a single integer n (2 \le n \le 1000) — the number of pairs of light bulbs.The second line of each test case contains 2n integers c_1, c_2, \dots, c_{2n} (1 \le c_i \le n), where c_i is the color of the i-th light bulb. For each color from 1 to n, exactly two light bulbs have this color.Additional constraint on the input: the sum of values of n^2 over all test cases does not exceed 10^6.OutputFor each test case, output two integers: the minimum size of the set S that you initially turn on; the number of sets S of minimum size (taken modulo 998244353). ExampleInput 422 2 1 121 2 2 121 2 1 253 4 4 5 3 1 1 5 2 2Output 2 4 1 2 1 4 2 8
422 2 1 121 2 2 121 2 1 253 4 4 5 3 1 1 5 2 2
2 4 1 2 1 4 2 8
3 seconds
512 megabytes
['brute force', 'combinatorics', 'dfs and similar', 'dp', 'dsu', 'graphs', 'math', 'trees', '*2100']
F. Programming Competitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBerSoft is the biggest IT corporation in Berland. There are n employees at BerSoft company, numbered from 1 to n. The first employee is the head of the company, and he does not have any superiors. Every other employee i has exactly one direct superior p_i.Employee x is considered to be a superior (direct or indirect) of employee y if one of the following conditions holds: employee x is the direct superior of employee y; employee x is a superior of the direct superior of employee y. The structure of BerSoft is organized in such a way that the head of the company is superior of every employee.A programming competition is going to be held soon. Two-person teams should be created for this purpose. However, if one employee in a team is the superior of another, they are uncomfortable together. So, teams of two people should be created so that no one is the superior of the other. Note that no employee can participate in more than one team.Your task is to calculate the maximum possible number of teams according to the aforementioned rules.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of employees.The second line contains n-1 integers p_2, p_3, \dots, p_n (1 \le p_i \le n), where p_i is the index of the direct superior of the i-th employee.The sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum possible number of teams according to the aforementioned rules.ExampleInput 641 2 12155 5 5 171 2 1 1 3 371 1 3 2 2 471 2 1 1 1 3Output 1 0 1 3 3 3 NoteIn the first test case, team (3, 4) can be created.In the second test case, no team can be created, because there are only 2 employees and one is the superior of another.In the third test case, team (2, 3) can be created.In the fourth test case, teams (2, 4), (3, 5) and (6, 7) can be created.In the fifth test case, teams (2, 3), (6, 4) and (5, 7) can be created.
641 2 12155 5 5 171 2 1 1 3 371 1 3 2 2 471 2 1 1 1 3
1 0 1 3 3 3
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graph matchings', 'greedy', 'trees', '*1900']
E2. Game with Marbles (Hard Version)time limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe easy and hard versions of this problem differ only in the constraints on the number of test cases and n. In the hard version, the number of test cases does not exceed 10^4, and the sum of values of n over all test cases does not exceed 2 \cdot 10^5. Furthermore, there are no additional constraints on n in a single test case.Recently, Alice and Bob were given marbles of n different colors by their parents. Alice has received a_1 marbles of color 1, a_2 marbles of color 2,..., a_n marbles of color n. Bob has received b_1 marbles of color 1, b_2 marbles of color 2, ..., b_n marbles of color n. All a_i and b_i are between 1 and 10^9.After some discussion, Alice and Bob came up with the following game: players take turns, starting with Alice. On their turn, a player chooses a color i such that both players have at least one marble of that color. The player then discards one marble of color i, and their opponent discards all marbles of color i. The game ends when there is no color i such that both players have at least one marble of that color.The score in the game is the difference between the number of remaining marbles that Alice has and the number of remaining marbles that Bob has at the end of the game. In other words, the score in the game is equal to (A-B), where A is the number of marbles Alice has and B is the number of marbles Bob has at the end of the game. Alice wants to maximize the score, while Bob wants to minimize it.Calculate the score at the end of the game if both players play optimally.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of three lines: the first line contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of colors; the second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the number of marbles of the i-th color that Alice has; the third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9), where b_i is the number of marbles of the i-th color that Bob has. Additional constraint on the input: the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the score at the end of the game if both Alice and Bob act optimally.ExampleInput 534 2 11 2 441 20 1 20100 15 10 2051000000000 1000000000 1000000000 1000000000 10000000001 1 1 1 135 6 52 1 763 2 4 2 5 59 4 7 9 2 5Output 1 -9 2999999997 8 -6 NoteIn the first example, one way to achieve a score of 1 is as follows: Alice chooses color 1, discards 1 marble. Bob also discards 1 marble; Bob chooses color 3, discards 1 marble. Alice also discards 1 marble; Alice chooses color 2, discards 1 marble, and Bob discards 2 marble. As a result, Alice has a = [3, 1, 0] remaining, and Bob has b = [0, 0, 3] remaining. The score is 3 + 1 - 3 = 1.It can be shown that neither Alice nor Bob can achieve a better score if both play optimally.In the second example, Alice can first choose color 1, then Bob will choose color 4, after which Alice will choose color 2, and Bob will choose color 3. It can be shown that this is the optimal game.
534 2 11 2 441 20 1 20100 15 10 2051000000000 1000000000 1000000000 1000000000 10000000001 1 1 1 135 6 52 1 763 2 4 2 5 59 4 7 9 2 5
1 -9 2999999997 8 -6
3.5 seconds
256 megabytes
['games', 'greedy', 'sortings', '*1400']
E1. Game with Marbles (Easy Version)time limit per test3.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe easy and hard versions of this problem differ only in the constraints on the number of test cases and n. In the easy version, the number of test cases does not exceed 10^3, and n does not exceed 6.Recently, Alice and Bob were given marbles of n different colors by their parents. Alice has received a_1 marbles of color 1, a_2 marbles of color 2,..., a_n marbles of color n. Bob has received b_1 marbles of color 1, b_2 marbles of color 2, ..., b_n marbles of color n. All a_i and b_i are between 1 and 10^9.After some discussion, Alice and Bob came up with the following game: players take turns, starting with Alice. On their turn, a player chooses a color i such that both players have at least one marble of that color. The player then discards one marble of color i, and their opponent discards all marbles of color i. The game ends when there is no color i such that both players have at least one marble of that color.The score in the game is the difference between the number of remaining marbles that Alice has and the number of remaining marbles that Bob has at the end of the game. In other words, the score in the game is equal to (A-B), where A is the number of marbles Alice has and B is the number of marbles Bob has at the end of the game. Alice wants to maximize the score, while Bob wants to minimize it.Calculate the score at the end of the game if both players play optimally.InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases.Each test case consists of three lines: the first line contains a single integer n (2 \le n \le 6) — the number of colors; the second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9), where a_i is the number of marbles of the i-th color that Alice has; the third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^9), where b_i is the number of marbles of the i-th color that Bob has. OutputFor each test case, output a single integer — the score at the end of the game if both Alice and Bob act optimally.ExampleInput 534 2 11 2 441 20 1 20100 15 10 2051000000000 1000000000 1000000000 1000000000 10000000001 1 1 1 135 6 52 1 763 2 4 2 5 59 4 7 9 2 5Output 1 -9 2999999997 8 -6 NoteIn the first example, one way to achieve a score of 1 is as follows: Alice chooses color 1, discards 1 marble. Bob also discards 1 marble; Bob chooses color 3, discards 1 marble. Alice also discards 1 marble; Alice chooses color 2, discards 1 marble, and Bob discards 2 marble. As a result, Alice has a = [3, 1, 0] remaining, and Bob has b = [0, 0, 3] remaining. The score is 3 + 1 - 3 = 1.It can be shown that neither Alice nor Bob can achieve a better score if both play optimally.In the second example, Alice can first choose color 1, then Bob will choose color 4, after which Alice will choose color 2, and Bob will choose color 3. It can be shown that this is the optimal game.
534 2 11 2 441 20 1 20100 15 10 2051000000000 1000000000 1000000000 1000000000 10000000001 1 1 1 135 6 52 1 763 2 4 2 5 59 4 7 9 2 5
1 -9 2999999997 8 -6
3.5 seconds
256 megabytes
['brute force', 'games', 'greedy', 'sortings', '*1400']
D. Three Activitiestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWinter holidays are coming up. They are going to last for n days.During the holidays, Monocarp wants to try all of these activities exactly once with his friends: go skiing; watch a movie in a cinema; play board games. Monocarp knows that, on the i-th day, exactly a_i friends will join him for skiing, b_i friends will join him for a movie and c_i friends will join him for board games.Monocarp also knows that he can't try more than one activity in a single day.Thus, he asks you to help him choose three distinct days x, y, z in such a way that the total number of friends to join him for the activities (a_x + b_y + c_z) is maximized.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (3 \le n \le 10^5) — the duration of the winter holidays in days.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^8) — the number of friends that will join Monocarp for skiing on the i-th day.The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^8) — the number of friends that will join Monocarp for a movie on the i-th day.The fourth line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le 10^8) — the number of friends that will join Monocarp for board games on the i-th day.The sum of n over all testcases doesn't exceed 10^5.OutputFor each testcase, print a single integer — the maximum total number of friends that can join Monocarp for the activities on three distinct days.ExampleInput 431 10 110 1 11 1 10430 20 10 130 5 15 2030 25 10 10105 19 12 3 18 18 6 17 10 1315 17 19 11 16 3 11 17 17 171 17 18 10 15 8 17 3 13 121017 5 4 18 12 4 11 2 16 168 4 14 19 3 12 6 7 5 163 4 8 11 10 8 10 2 20 3Output 30 75 55 56 NoteIn the first testcase, Monocarp can choose day 2 for skiing, day 1 for a movie and day 3 for board games. This way, a_2 = 10 friends will join him for skiing, b_1 = 10 friends will join him for a movie and c_3 = 10 friends will join him for board games. The total number of friends is 30.In the second testcase, Monocarp can choose day 1 for skiing, day 4 for a movie and day 2 for board games. 30 + 20 + 25 = 75 friends in total. Note that Monocarp can't choose day 1 for all activities, because he can't try more than one activity in a single day.In the third testcase, Monocarp can choose day 2 for skiing, day 3 for a movie and day 7 for board games. 19 + 19 + 17 = 55 friends in total.In the fourth testcase, Monocarp can choose day 1 for skiing, day 4 for a movie and day 9 for board games. 17 + 19 + 20 = 56 friends in total.
431 10 110 1 11 1 10430 20 10 130 5 15 2030 25 10 10105 19 12 3 18 18 6 17 10 1315 17 19 11 16 3 11 17 17 171 17 18 10 15 8 17 3 13 121017 5 4 18 12 4 11 2 16 168 4 14 19 3 12 6 7 5 163 4 8 11 10 8 10 2 20 3
30 75 55 56
2 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'implementation', 'sortings', '*1200']
C. Queststime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a computer game. In order to level up his character, he can complete quests. There are n quests in the game, numbered from 1 to n.Monocarp can complete quests according to the following rules: the 1-st quest is always available for completion; the i-th quest is available for completion if all quests j < i have been completed at least once. Note that Monocarp can complete the same quest multiple times.For each completion, the character gets some amount of experience points: for the first completion of the i-th quest, he gets a_i experience points; for each subsequent completion of the i-th quest, he gets b_i experience points. Monocarp is a very busy person, so he has free time to complete no more than k quests. Your task is to calculate the maximum possible total experience Monocarp can get if he can complete no more than k quests.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 2 \cdot 10^5; 1 \le k \le 2 \cdot 10^5) — the number of quests and the maximum number of quests Monocarp can complete, respectively.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^3).The third line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^3).Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum possible total experience Monocarp can get if he can complete no more than k quests.ExampleInput 44 74 3 1 21 1 1 13 21 2 53 1 85 53 2 4 1 42 3 1 4 76 41 4 5 4 5 101 5 1 2 5 1Output 13 4 15 15 NoteIn the first test case, one of the possible quest completion sequences is as follows: 1, 1, 2, 3, 2, 4, 4; its total experience is equal to \underline{4} + 1 + \underline{3} + \underline{1} + 1 + \underline{2} + 1 = 13 (the underlined numbers correspond to the instances when we complete a quest for the first time).In the second test case, one of the possible quest completion sequences is as follows: 1, 1; its total experience is equal to \underline{1} + 3 = 4.In the third test case, one of the possible quest completion sequences is as follows: 1, 2, 2, 2, 3; its total experience is equal to \underline{3} + \underline{2} + 3 + 3 + \underline{4} = 15.
44 74 3 1 21 1 1 13 21 2 53 1 85 53 2 4 1 42 3 1 4 76 41 4 5 4 5 101 5 1 2 5 1
13 4 15 15
2.5 seconds
256 megabytes
['greedy', 'math', '*1100']
B. Preparing for the Contesttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is practicing for a big contest. He plans to solve n problems to make sure he's prepared. Each of these problems has a difficulty level: the first problem has a difficulty level of 1, the second problem has a difficulty level of 2, and so on, until the last (n-th) problem, which has a difficulty level of n.Monocarp will choose some order in which he is going to solve all n problems. Whenever he solves a problem which is more difficult than the last problem he solved, he gets excited because he feels like he's progressing. He doesn't get excited when he solves the first problem in his chosen order.For example, if Monocarp solves the problems in the order [3, \underline{5}, 4, 1, \underline{6}, 2], he gets excited twice (the corresponding problems are underlined).Monocarp wants to get excited exactly k times during his practicing session. Help him to choose the order in which he has to solve the problems!InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of one line containing two integers n and k (2 \le n \le 50; 0 \le k \le n - 1).OutputFor each test case, print n distinct integers from 1 to n, denoting the order in which Monocarp should solve the problems. If there are multiple answers, print any of them.It can be shown that under the constraints of the problem, the answer always exists.ExampleInput 36 25 45 0Output 3 5 4 1 6 2 1 2 3 4 5 5 4 3 2 1
36 25 45 0
3 5 4 1 6 2 1 2 3 4 5 5 4 3 2 1
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
A. Problemsolving Logtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is participating in a programming contest, which features 26 problems, named from 'A' to 'Z'. The problems are sorted by difficulty. Moreover, it's known that Monocarp can solve problem 'A' in 1 minute, problem 'B' in 2 minutes, ..., problem 'Z' in 26 minutes.After the contest, you discovered his contest log — a string, consisting of uppercase Latin letters, such that the i-th letter tells which problem Monocarp was solving during the i-th minute of the contest. If Monocarp had spent enough time in total on a problem to solve it, he solved it. Note that Monocarp could have been thinking about a problem after solving it.Given Monocarp's contest log, calculate the number of problems he solved during the contest.InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 500) — the duration of the contest, in minutes.The second line contains a string of length exactly n, consisting only of uppercase Latin letters, — Monocarp's contest log.OutputFor each testcase, print a single integer — the number of problems Monocarp solved during the contest.ExampleInput 36ACBCBC7AAAAFPC22FEADBBDFFEDFFFDHHHADCCOutput 3 1 4
36ACBCBC7AAAAFPC22FEADBBDFFEDFFFDHHHADCC
3 1 4
2 seconds
256 megabytes
['implementation', 'strings', '*800']
F. Palindromic Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n, consisting of lowercase Latin letters.You are allowed to replace at most one character in the string with an arbitrary lowercase Latin letter.Print the lexicographically minimal string that can be obtained from the original string and contains the maximum number of palindromes as substrings. Note that if a palindrome appears more than once as a substring, it is counted the same number of times it appears.The string a is lexicographically smaller than the string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b are different, the string a contains a letter that appears earlier in the alphabet than the corresponding letter in b. InputThe first line contains one integer n (1 \leq n \leq 3 \cdot 10^5) — the number of characters in the string.The second line contains the string s itself, consisting of exactly n lowercase Latin letters.OutputIn the first line, print one integer — the maximum number of palindromic substrings that can be obtained using the operation described in the statement at most once.In the second line, print the string that can be obtained from s and has the maximum possible number of palindromic substrings. If there are multiple answers, print the lexicographically smallest one.ExamplesInput 5aabaaOutput 15 aaaaa Input 5aaaaaOutput 15 aaaaa Input 4awooOutput 7 aooo
5aabaa
15 aaaaa
5 seconds
512 megabytes
['binary search', 'data structures', 'hashing', 'string suffix structures', 'strings', '*2800']
E. Matrix Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a matrix a, consisting of n rows by m columns. Each element of the matrix is equal to 0 or 1.You can perform the following operation any number of times (possibly zero): choose an element of the matrix and replace it with either 0 or 1.You are also given two arrays A and B (of length n and m respectively). After you perform the operations, the matrix should satisfy the following conditions: the number of ones in the i-th row of the matrix should be exactly A_i for every i \in [1, n]. the number of ones in the j-th column of the matrix should be exactly B_j for every j \in [1, m]. Calculate the minimum number of operations you have to perform.InputThe first line contains two integers n and m (2 \le n, m \le 50).Then n lines follow. The i-th of them contains m integers a_{i,1}, a_{i,2}, \dots, a_{i,m} (0 \le a_{i,j} \le 1).The next line contains n integers A_1, A_2, \dots, A_n (0\le A_i\le m).The next line contains m integers B_1, B_2, \dots, B_m (0\le B_i\le n).OutputPrint one integer — the minimum number of operations you have to perform, or -1 if it is impossible.ExamplesInput 3 30 0 00 0 00 0 01 1 11 1 1Output 3Input 3 31 1 11 1 11 1 13 2 11 2 3Output 3Input 2 20 00 01 20 1Output -1
3 30 0 00 0 00 0 01 1 11 1 1
3
1 second
256 megabytes
['flows', 'graphs', '*2400']
D. Array Collapsetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array [p_1, p_2, \dots, p_n], where all elements are distinct.You can perform several (possibly zero) operations with it. In one operation, you can choose a contiguous subsegment of p and remove all elements from that subsegment, except for the minimum element on that subsegment. For example, if p = [3, 1, 4, 7, 5, 2, 6] and you choose the subsegment from the 3-rd element to the 6-th element, the resulting array is [3, 1, 2, 6].An array a is called reachable if it can be obtained from p using several (maybe zero) aforementioned operations. Calculate the number of reachable arrays, and print it modulo 998244353.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. The first line contains one integer n (1 \le n \le 3 \cdot 10^5). The second line contains n distinct integers p_1, p_2, \dots, p_n (1 \le p_i \le 10^9).Additional constraint on the input: the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, print one integer — the number of reachable arrays, taken modulo 998244353.ExampleInput 322 142 4 1 3510 2 6 3 4Output 2 6 12
322 142 4 1 3510 2 6 3 4
2 6 12
2 seconds
256 megabytes
['data structures', 'divide and conquer', 'dp', 'trees', '*2100']
C. Game with Multisettime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem, you are initially given an empty multiset. You have to process two types of queries: ADD x — add an element equal to 2^{x} to the multiset; GET w — say whether it is possible to take the sum of some subset of the current multiset and get a value equal to w. InputThe first line contains one integer m (1 \le m \le 10^5) — the number of queries.Then m lines follow, each of which contains two integers t_i, v_i, denoting the i-th query. If t_i = 1, then the i-th query is ADD v_i (0 \le v_i \le 29). If t_i = 2, then the i-th query is GET v_i (0 \le v_i \le 10^9).OutputFor each GET query, print YES if it is possible to choose a subset with sum equal to w, or NO if it is impossible.ExamplesInput 51 01 01 02 32 4Output YES NO Input 71 01 11 21 102 42 62 7Output YES YES YES
51 01 01 02 32 4
YES NO
1.5 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'greedy', '*1300']
B. Swap and Deletetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s (a string consisting only of 0-s and 1-s).You can perform two types of operations on s: delete one character from s. This operation costs 1 coin; swap any pair of characters in s. This operation is free (costs 0 coins). You can perform these operations any number of times and in any order.Let's name a string you've got after performing operations above as t. The string t is good if for each i from 1 to |t| t_i \neq s_i (|t| is the length of the string t). The empty string is always good. Note that you are comparing the resulting string t with the initial string s.What is the minimum total cost to make the string t good?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then t test cases follow.The only line of each test case contains a binary string s (1 \le |s| \le 2 \cdot 10^5; s_i \in \{0, 1\}) — the initial string, consisting of characters 0 and/or 1.Additional constraint on the input: the total length of all strings s doesn't exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum total cost to make string t good.ExampleInput 400110101110001111100Output 1 1 0 4 NoteIn the first test case, you have to delete a character from s to get the empty string t. Only then t becomes good. One deletion costs 1 coin.In the second test case, you can, for example, delete the second character from s to get the string 01, and then swap the first and second characters to get the string t = 10. String t is good, since t_1 \neq s_1 and t_2 \neq s_2. The total cost is 1 coin.In the third test case, you can, for example, swap s_1 with s_2, swap s_3 with s_4, swap s_5 with s_7, s_6 with s_8 and s_9 with s_{10}. You'll get t = 1010001110. All swap operations are free, so the total cost is 0.
400110101110001111100
1 1 0 4
1 second
256 megabytes
['strings', '*1000']
A. Rating Increasetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is a great solver of adhoc problems. Recently, he participated in an Educational Codeforces Round, and gained rating!Monocarp knew that, before the round, his rating was a. After the round, it increased to b (b > a). He wrote both values one after another to not forget them.However, he wrote them so close to each other, that he can't tell now where the first value ends and the second value starts.Please, help him find some values a and b such that: neither of them has a leading zero; both of them are strictly greater than 0; b > a; they produce the given value ab when written one after another. If there are multiple answers, you can print any of them.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The only line of each testcase consists of a single string ab of length from 2 to 8 that: consists only of digits; doesn't start with a zero. OutputFor each testcase, determine if such values a and b exist. If they don't, print -1. Otherwise, print two integers a and b.If there are multiple answers, you can print any of them.ExampleInput 520002001391125200200200100012Output 2000 2001 39 1125 -1 200 1000 1 2 NoteIn the second testcase, printing 3 and 91125 is also valid.In the third testcase, 20 and 0200 is not valid, because b has a leading zero. 200 and 200 is not valid, because 200 is not strictly greater than 200.
520002001391125200200200100012
2000 2001 39 1125 -1 200 1000 1 2
2 seconds
256 megabytes
['implementation', '*800']
L. LOL Loverstime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere are n food items lying in a row on a long table. Each of these items is either a loaf of bread (denoted as a capital Latin letter 'L' with ASCII code 76) or an onion (denoted as a capital Latin letter 'O' with ASCII code 79). There is at least one loaf of bread and at least one onion on the table.You and your friend want to divide the food on the table: you will take a prefix of this row (several leftmost items), and the friend will take the rest. However, there are several restrictions: Each person should have at least one item. The number of your loaves should differ from the number of your friend's loaves. The number of your onions should differ from the number of your friend's onions. Find any correct division and print the number of items you take or report that there is no answer.InputThe first line contains one integer n (2 \le n \le 200) — the number of food items on the table. The second line contains a string of length n consisting of letters 'L' and 'O'. i-th symbol represents the type of the i-th food item on the table: 'L' stands for a loaf of bread, and 'O' stands for an onion. It is guaranteed that this string contains at least one letter 'L' and at least one letter 'O'.OutputPrint one integer — a number k such that, if you take k leftmost items and your friend takes the remaining n - k items, each of you and your friend get at least one item, your number of loaves is different from your friend's, and your number of onions is different from your friend's. If there are several possible answers, print any of them. If there are no possible answers, print the number -1.ExamplesInput 3LOLOutput -1 Input 2LOOutput 1 Input 4LLLOOutput 1 Input 4OLOLOutput -1 Input 10LLOOOOLLLOOutput 5NoteIn the first example, in any division the left and the right part contain one loaf of bread.In the second example, the division is 'L' and 'O', and in these two strings the number of loaves is different (1 and 0) and the number of onions is different (0 and 1).In the third example, any number 1, 2 or 3 is a correct answer.
3LOL
-1
3 seconds
1024 megabytes
['strings', '*800']
K. Kim's Questtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIn the long-forgotten halls of Kombinatoria's ancient academy, a gifted mathematician named Kim is faced with an unusual challenge. They found an old sequence of integers, which is believed to be a cryptic message from the legendary Kombinatoria's Oracle, and Kim wants to decipher its hidden meaning.Kim's mission is to find specific patterns within the sequence, known as Harmonious Subsequences. These are extraordinary subsequences where the sum of every three consecutive numbers is even, and each subsequence must be at least three numbers in length. Given a sequence a_i (1 \le i \le n) of length n, its subsequence of length m is equal to a_{b_1}, a_{b_2}, \ldots, a_{b_m} and is uniquely defined by a set of m indices b_j, such that 1 \le b_1 < b_2 < \ldots < b_m \le n. Subsequences given by different sets of indices b_j are considered different.There's a twist in Kim's quest: the number of these Harmonious Subsequences could be overwhelming. To report the findings effectively, Kim must calculate the total number of these subsequences, presenting the answer as a remainder after dividing by the number 998\,244\,353.InputThe first line contains a single integer n — the length of the sequence (3 \le n \le 2 \cdot 10^5).The second line contains n space-separated integers a_i — the elements of the sequence (1 \le a_i \le 2 \cdot 10^5).OutputOutput one number — the number of Harmonious Subsequences, modulo 998\,244\,353.ExamplesInput 31 2 3Output 1 Input 52 8 2 6 4Output 16 Input 55 7 1 3 5Output 0 Input 113 1 4 1 5 9 2 6 5 3 6Output 386 Input 54 2 1 1 1 1 2 1 2 2 2 2 1 1 1 2 1 1 2 2 1 2 2 2 2 2 2 2 1 1 1 2 2 1 1 1 1 2 2 1 1 2 2 2 2 2 1 1 1 2 2 1 2 1 1 Output 0 NoteIn the provided input data for the fifth sample, the sequence of numbers is split into three separate lines for clarity, but it should be understood that in the actual test data, the sequence is given in one line. The actual number of Harmonious Subsequences in this example is 4\,991\,221\,765 = 5 \times 998\,244\,353, hence the output is zero as a result of finding its remainder after dividing by the number 998\,244\,353.
31 2 3
1
3 seconds
1024 megabytes
['bitmasks', 'combinatorics', 'dp', '*1800']
H. Hypercatapult Commutetime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA revolutionary new transport system is currently operating in Byteland. This system requires neither roads nor sophisticated mechanisms, only giant catapults. The system works as follows. There are n cities in Byteland. In every city there is a catapult, right in the city center. People who want to travel are put in a special capsule, and a catapult throws this capsule to the center of some other city. Every catapult is powerful enough to throw the capsule to any other city, with any number of passengers inside the capsule. The only problem is that it takes a long time to charge the catapult, so it is only possible to use it once a day.The passenger may need to use the catapults multiple times. For example, if the passenger wants to travel from city A to city B, they can first use one catapult to move from A to C, and then transfer to another catapult to move from C to B.Today there are m passengers. Passenger i wants to travel from city a_i to city b_i. Your task is to find the way to deliver all the passengers to their destinations in a single day, using the minimal possible number of catapults, or say that it is impossible.InputThe first line of the input contains two integers n and m (1 \leq n \leq 1000, 0 \leq m \leq 10^5) — the number of cities and the number of passengers. The next m lines contain pairs of numbers a_i and b_i (1 \leq a_i, b_i \leq n, a_i \neq b_i).OutputIn the first line print the number k — the minimal number of catapults you need to use.In the next k lines, print descriptions of each catapult launch, in the order they need to be performed. Each description should consist of two integers c_i, d_i, the index of the city to launch from, and the index of destination city.Note that you don't need to print what passengers should be put into the capsule on each launch, but it should be possible for each passenger to reach their destination city using the plan you provide.If it is impossible to deliver all passengers, print the single number -1.ExamplesInput 5 61 31 22 34 21 55 1Output 5 5 1 1 2 4 2 2 3 3 5 Input 3 61 21 32 12 33 13 2Output -1
5 61 31 22 34 21 55 1
5 5 1 1 2 4 2 2 3 3 5
3 seconds
1024 megabytes
['graphs', '*2400']
F. Fugitive Frenzytime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe city of F. can be represented as a tree. A famous fugitive is hiding in it, and today a faithful police officer decided to catch him at all costs. The police officer is stronger than the fugitive, but the fugitive is much faster than the former. That is why the pursuit proceeds as follows. At the moment t = 0 the police officer appears at the vertex with number s, and the fugitive spawns at any other vertex of his choice. After that, they take turns, starting with the police officer. During the police officer's move, she selects any vertex adjacent to the one where she is currently located and moves there. The police officer spends one minute moving. Also, the police officer may decide to stand still instead, in which case she waits one minute at the vertex at which she started her move. If at the end of the turn the police officer ends up at the same vertex as the fugitive, she instantly catches him and the chase ends. The fugitive's move is as follows. Let him be at vertex b, and the police officer at vertex p. Then the fugitive chooses any vertex b' \ne p such that the path between the vertices b and b' does not contain vertex p and instantly moves there. In particular, he can always choose b' = b to stay where he is. The fugitive's move takes no time. Note that the fugitive managed to attach a radio bug to the police officer's badge a week ago, so the fugitive knows the location of the police officer at every moment (in particular, he knows the number s). On the contrary, the police officer knows nothing about the fugitive's movements and will only be able to detect him at the very moment she catches him.The police officer aims to catch the fugitive as fast as possible, and the fugitive aims to be caught as late as possible. Since the chase can be thought of as a game with incomplete information, participants can use mixed (probabilistic) strategies — thus, the police officer acts to minimize the expected duration of the chase, and the fugitive — to maximize it.Find the mathematical expectation of the duration of the chase with optimal actions of the police officer and the fugitive. It can be proven that it is always finite. In particular, with optimal strategies, the probability that the chase continues indefinitely is equal to zero.InputThe first line contains an integer n — the number of vertices in the tree (2 \le n \le 100). The next n - 1 lines describe the city of F.: each of them contains a pair of integers u_i, v_i — the numbers of the ends of an edge (1 \le u_i, v_i \le n). These edges are guaranteed to form a tree.The last line contains an integer s — the number of the vertex where the police officer initially appears (1 \le s \le n).OutputPrint one real number — the mathematical expectation of the duration of the chase with the optimal strategies of the police officer and the fugitive. Your answer will be accepted if its absolute or relative error does not exceed 10^{-6}; formally, if p is your answer, and j is the jury's answer, this should hold: \frac{|p - j|}{\max\{1, |j|\}} \le 10^{-6}.ExamplesInput 21 22Output 1Input 31 21 31Output 2Input 44 34 14 24Output 3.66667Input 71 44 55 24 66 77 33Output 8.3525NoteThe trees from the examples are depicted below.
21 22
1
5 seconds
1024 megabytes
['math', 'probabilities', '*3100']
E. Evaluate It and Back Againtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAidan and Nadia are long-time friends with a shared passion for mathematics. Each of them has a favorite number: Aidan's favorite number is p, and Nadia's is q. To commemorate their friendship, their friends want to make a present: a plaque with an arithmetic expression whose value is equal to their favorite numbers. At first glance, it sounds impossible, but the answer is simple: Aidan reads left-to-right, while Nadia reads right-to-left, so the same expression can have different values for them.For example, if 2023-12-13 is written on the plaque, then Aidan would calculate the result as 2023-12-13 = 1998, and Nadia would calculate it as 31-21-3202=-3192.Find an arithmetic expression that, when read left-to-right, evaluates to p, and, when read right-to-left, evaluates to q. Its length must be at most 1000 characters. It's guaranteed that such an expression exists for all valid inputs.InputThe first line of the input contains two integers p and q (-10^{18} \le p, q \le 10^{18}).OutputPrint the expression without spaces or line breaks. It can only contain digits 0 through 9, '+', '-', and '*' characters.The expression must contain at most 1000 characters. Leading zeros in numbers are not allowed (the only exception is the notation '0' representing the number 0) in both the expression and its reverse. Use of unary '+' or '-' is not allowed. The expression must be well-formed in both directions. The calculation uses the standard operator precedence. ExamplesInput 1998 -3192Output 2023-12-13Input 413 908Output 12*34+5
1998 -3192
2023-12-13
3 seconds
1024 megabytes
['constructive algorithms', 'implementation', 'math', '*2200']
D. Divisibility Testtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDaisy has recently learned divisibility rules for integers and she is fascinated by them. One of the tests she learned is a divisibility test by 3. You can find a sum of all digits of a decimal number and check if the resulting sum is divisible by 3. Moreover, the resulting sum of digits is congruent modulo 3 to the original number — the remainder modulo 3 is preserved. For example, 75 \equiv 7 + 5 \pmod 3. Daisy is specifically interested in such remainder preserving divisibility tests.There are more examples like that that she learned for decimal integers (integers base 10): To test divisibility modulo 11, find an alternating sum of digits. Counting digits from the last (least significant) digit, add digits on odd positions (the last, 3rd to the last, etc) and subtract digits on even positions (2nd to the last, 4th to the last, etc) to get the sum that is congruent modulo 11 to the original number. For example, 123 \equiv 1 - 2 + 3 \pmod {11}. To test divisibility modulo 4, keep the last two digits. Their value is congruent modulo 4 to the original number. For example, 876543 \equiv 43 \pmod 4. To test divisibility modulo 7, find an alternating sum of groups of three digits. For example, 4389328 \equiv 4 - 389 + 328 \pmod 7. Similar tests can be found in other bases. For example, to test divisibility modulo 5 for octal numbers (base 8), find an alternating sum of groups of two digits. For example, 1234_8 \equiv -12_8 + 34_8 \pmod 5.Daisy wants to find such rules for a given base b. She is interested in three kinds of divisibility rules: Kind 1 — take the last k digits of an integer in base b. Kind 2 — take a sum of groups of k digits of an integer in base b. Kind 3 — take an alternating sum of groups of k digits of an integer in base b. It is not always possible to find such a divisibility rule. For example, in base 10 there is no such test for divisibility modulo 6, even though different approaches to testing divisibility by 6 exist.Given base b and modulo n, Daisy wants to know the smallest group size k for which such a divisibility test exits.InputThere are several tests in the input. The first line of the input contains an integer t — the number of tests. The next t lines describe the tests.Each test consists of a line with two integers b and n — the base and the modulo (b, n \ge 2). The sum of all b values in the input does not exceed 10^6, and the sum of all n values in the input does not exceed 10^6.OutputWrite t lines — a line for each test in the input. On a line for a test write a single integer 0 if the divisibility test for a given b and n does not exist. Otherwise, write two integers a and k, where a is the kind of the divisibility test (1, 2, or 3) and k is the number of digits in a group for the test, such that k is the lowest among all possible divisiblity tests for the given b and n.ExampleInput 610 310 1110 410 78 510 6Output 2 1 3 1 1 2 3 3 3 2 0
610 310 1110 410 78 510 6
2 1 3 1 1 2 3 3 3 2 0
3 seconds
1024 megabytes
['math', '*1900']
B. Blueprint for Seatingtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAn aircraft manufacturing company wants to optimize their products for passenger airlines. The company's latest research shows that most of the delays happen because of slow boarding.Most of the medium-sized aircraft are designed with 3-3 seat layout, meaning each row has 6 seats: 3 seats on the left side, a single aisle, and 3 seats on the right side. At each of the left and right sides there is a window seat, a middle seat, and an aisle seat. A passenger that boards an aircraft assigned to an aisle seat takes significantly less time than a passenger assigned to a window seat even when there is no one else in the aircraft.The company decided to compute an inconvenience of a layout as the total sum of distances from each of the seats of a single row to the closest aisle. The distance from a seat to an aisle is the number of seats between them. For a 3-3 layout, a window seat has a distance of 2, a middle seat — 1, and an aisle seat — 0. The inconvenience of a 3-3 layout is (2+1+0)+(0+1+2)=6. The inconvenience of a 3-5-3 layout is (2+1+0)+(0+1+2+1+0)+(0+1+2)=10.Formally, a layout is a sequence of positive integers a_1, a_2, \ldots, a_{k+1} — group i having a_i seats, with k aisles between groups, the i-th aisle being between groups i and i+1. This means that in a layout each aisle must always be between two seats, so no aisle can be next to a window, and no two aisles can be next to each other.The company decided to design a layout with a row of n seats, k aisles and having the minimum inconvenience possible. Help them find the minimum inconvenience among all layouts of n seats and k aisles, and count the number of such layouts modulo 998\,244\,353.InputThe first line contains an integer t — the number of test cases you need to solve (1 \le t \le 10^5).For each of the test cases, there is a single line containing n and k — the number of seats, and the number of aisles in a row (2 \le n \le 10^9; 1 \le k \le 10^5; k < n).The total sum of k in all t given test cases does not exceed 10^6.OutputFor each test case print two integers — the minimum inconvenience among all possible layouts, and the number of layouts with the minimum inconvenience modulo 998\,244\,353.ExampleInput 84 13 24 25 26 16 21000000000 19 2Output 2 1 0 1 0 1 1 3 6 1 2 4 249999999500000000 1 6 3 NoteIn the last test case of 9 2 the possible layouts with the minimum inconvenience of 6 are 3-4-2, 2-4-3, and 2-5-2.
84 13 24 25 26 16 21000000000 19 2
2 1 0 1 0 1 1 3 6 1 2 4 249999999500000000 1 6 3
3 seconds
1024 megabytes
['combinatorics', 'divide and conquer', 'math', '*2100']
A. Accumulator Apextime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAllyn is playing a new strategy game called "Accumulator Apex". In this game, Allyn is given the initial value of an integer x, referred to as the accumulator, and k lists of integers. Allyn can make multiple turns. On each turn, Allyn can withdraw the leftmost element from any non-empty list and add it to the accumulator x if the resulting x is non-negative. Allyn can end the game at any moment. The goal of the game is to get the largest possible value of the accumulator x. Please help Allyn find the largest possible value of the accumulator x they can get in this game.InputThe first line of the input contains two integers x and k (0 \leq x \leq 10^9, 1 \leq k \leq 10^5) — the initial value of the accumulator x and the number of lists. The next k lines contain the description of lists: an integer l_i (l_i \ge 1) followed on the same line by l_i elements of the list in the order from left to right. Each element of lists does not exceed 10^9 by the absolute value, and the total size of all lists does not exceed 10^5.OutputThe sole line of the output should contain the largest value of the accumulator x Allyn can get.ExamplesInput 1 32 -1 22 -2 32 -3 4Output 4 Input 1 23 -1 -1 44 1 -3 -4 8Output 4 NoteIn the first input, we start with x = 1. Then, we can take the first integer from the first list and get x = 0 — adding the next integer 2 from the first list we get x = 2. After that, we can add the integers from the second list and obtain x = 3. Finally, we can add the integers from the third list and obtain x = 4.In the second input, we can add the first integer from the second list and get x = 2. Then, by adding the elements from the first list, we get x = 4. We cannot add more integers to increase x.
1 32 -1 22 -2 32 -3 4
4
3 seconds
1024 megabytes
['data structures', 'implementation', 'sortings', '*1900']
J. Two Colorstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. Some vertices of the tree are red, all other vertices are blue.Each edge of the tree has a positive weight. Let's define d(x, y) as the distance between the vertices x and y, i. e. the sum of weights of edges belonging to the simple path between x and y.For each vertex, you have to choose an integer v_i. These integers should meet the following constraint: for every blue vertex b and every red vertex r, d(b, r) \ge v_b + v_r. You have to maximize the value of \sum \limits_{i=1}^{n} v_i.Note that the values of v_i are not necessarily positive.InputThe first line contains one integer n (2 \le n \le 3 \cdot 10^5).The second line contains n integers c_1, c_2, \dots, c_n (0 \le c_i \le 1). If the i-th vertex is red, c_i = 1, otherwise c_i = 0.Then n-1 lines follow. Each line contains three integers x_i, y_i and w_i (1 \le x_i, y_i \le n; 1 \le w_i \le 10^6; x_i \ne y_i) denoting an edge between the vertices x_i and y_i which has weight w_i. These edges form a tree.OutputIf the value of \sum \limits_{i=1}^{n} v_i can be as big as possible, print Infinity. Otherwise, print one integer — the maximum possible value of \sum \limits_{i=1}^{n} v_i you can get.ExamplesInput 4 1 1 0 0 3 4 50 3 2 100 2 1 100 Output 350 Input 6 0 1 0 1 0 1 1 2 1 1 4 1 1 6 1 6 5 100 6 3 100 Output 203 Input 3 1 1 1 1 2 100 2 3 100 Output Infinity NoteIn the first example, you can assign v_1 = 120, v_2 = 20, v_3 = 80, v_4 = 130.
4 1 1 0 0 3 4 50 3 2 100 2 1 100
350
4 seconds
512 megabytes
['*special problem', '*2900']
I. Inverse Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputConsider the following problem.You are given a string s, consisting of n lowercase Latin letters, and an integer k (n is not divisible by k). Each letter is one of the first c letters of the alphabet.You apply the following operation until the length of the string is less than k: choose a contiguous substring of the string of length exactly k, remove it from the string and glue the resulting parts together without changing the order.Let the resulting string of length smaller than k be t. What is lexicographically smallest string t that can obtained?You are asked the inverse of this problem. Given two integers n and k (n is not divisible by k) and a string t, consisting of (n \bmod k) lowercase Latin letters, count the number of strings s that produce t as the lexicographically smallest solution.Print that number modulo 998\,244\,353.InputThe first line contains three integers n, k and c (1 \le n \le 10^6; 2 \le k \le 10^6; 1 \le c \le 26; n is not divisible by k) — the length of string s, the length of the substring that is being removed and the number of first letters from the alphabet.The second line contains string t, consisting of exactly (n \bmod k) lowercase Latin letters. Each letter is one of the first c letters of the alphabet.OutputPrint a single integer — the number of strings s that produce t as the lexicographically smallest solution.ExamplesInput 3 2 2 a Output 6 Input 5 3 3 bc Output 15 Input 34 12 26 codeforces Output 988024123 Input 5 3 1 aa Output 1 NoteThe strings s in the first example: "aaa", "aab", "aba", "abb", "baa", "bba".The strings s in the second example: "bcabc", "bcacc", "bcbbc", "bcbcc", "bccbc", "bcccc", "caabc", "cabbc", "cacbc", "cbabc", "cbbbc", "cbcbc", "ccabc", "ccbbc", "cccbc".
3 2 2 a
6
2 seconds
256 megabytes
['*special problem', 'combinatorics', 'dp', '*2700']
H. Sum of Digits of Sumstime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array [a_1, a_2, \dots, a_n], consisting of positive integers.For every i from 1 to n, calculate \sum \limits_{j=1}^{n} F(a_i + a_j), where F(x) is the sum of digits of x.InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i < 10^9).OutputPrint n integers. The i-th of them should be equal to \sum \limits_{j=1}^{n} F(a_i + a_j).ExamplesInput 4 1 3 3 7 Output 18 17 17 15 Input 3 42 1337 999 Output 38 53 47
4 1 3 3 7
18 17 17 15
6 seconds
512 megabytes
['*special problem', 'binary search', 'data structures', '*2400']
G. Pool Recordstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are swimming in the pool under the guidance of their instructor Monocarp.The pool can be represented as a segment on the OX-axis from 0 to 50. Both Alice and Bob started at moment 0 at point 0 with positive real speeds v_A and v_B correspondingly.Both Alice and Bob swim from 0 to point 50, then instantly turn back and swim from 50 to 0. At 0 they turn back again and swim to 50 and so on.Monocarp logged all valuable info about Alice and Bob, including moments of time when they met at the same point (Alice and Bob swim on parallel lanes, so they don't bother each other). Let's name that moments of time as sequence t_1, t_2, \dots, t_n.Due to some incident, Monocarp lost almost all data he recorded, and all he has now is array t. Monocarp remembers that Alice and Bob had distinct positive real swimming speeds v_A and v_B (v_A > 0; v_B > 0; v_A \neq v_B) and that sequence t contains the first n meeting moments.But looking at sequence t he noticed that all t_i are integer values, and now he doubts is sequence t valid or there are some errors in it. Help Monocarp to check array t!InputThe first line contains a single integer c (1 \le c \le 10^4) — the number of test cases. Then c cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of array t.The second line of each test case contains n integers t_1, t_2, \dots, t_n (1 \le t_1 < t_2 < \dots < t_n \le 10^9) — the meeting moments in the increasing order.It's guaranteed that the sum of n over all test cases doesn't exceed 2 \cdot 10^5.OutputFor each test case, print VALID if the array t is a valid array, or (in other words) exist such real values v_A and v_B (v_A, v_B > 0; v_A \neq v_B) that array t contains the first n meeting moments of Alice and Bob in the pool.Otherwise, print INVALID.You can output the answer in any case (upper or lower). For example, the strings "vALid", "valid", "Valid", and "VALID" will be recognized as positive responses.ExampleInput 714243 4 6 851 2 3 4 53999999998 999999999 100000000054 6 8 12 1646 11 12 14210 30Output VALID VALID VALID INVALID VALID INVALID INVALID NoteIn the first test case, imagine a situation: v_A = 1 and v_B = \frac{29}{21}. Then, at moment 42 Alice and Bob will be at point 42.In the second test case, imagine a situation: v_A = \frac{175}{6} and v_B = \frac{25}{6}. Then, at moment 3 Alice and Bob will meet at point 12.5, at 4 they'll meet at point \frac{50}{3}, at moment 6 they'll meet at 25 and at moment 8 — at point \frac{100}{3}. Since it's exactly the first 4 meeting moments. Array t may be valid.In the third test case, one of the possible situations is v_A = 25 and v_B = 75.
714243 4 6 851 2 3 4 53999999998 999999999 100000000054 6 8 12 1646 11 12 14210 30
VALID VALID VALID INVALID VALID INVALID INVALID
3 seconds
256 megabytes
['*special problem', 'greedy', '*2700']
F. Build Railway Stationstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is playing a computer game where he's controlling an empire. An empire consists of n cities, connected by n - 1 roads. The cities are numbered from 1 to n. It's possible to reach every city from every other one using the roads.Traversing every road takes 2 hours. However, that can be improved. Monocarp can build railway stations in no more than k cities. After they are built, all existing roads that connect two cities with railway stations get converted to railroads and become 1 hour to traverse.Let f(x, y) be the total time it takes to traverse the roads on the shortest path between cities x and y.Monocarp wants to build at most k railway stations in such a way that the following value is minimized: \sum \limits_{v=1}^{n} \sum \limits_{u=1}^{v-1} f(v, u) (the total time it takes to travel from every city to every other one). What the smallest value he can achieve?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains two integers n and k (2 \le k \le n \le 2 \cdot 10^5) — the number of cities and the maximum number of railway stations Monocarp can build.Each of the following n-1 lines contains two integers v and u (1 \le v, u \le n; v \neq u) — a road that connects cities v and u.It's possible to reach every city from every other one using the roads. The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest total time it takes to travel from every city to every other one that Monocarp can achieve after building at most k railway stations.ExampleInput 35 21 22 33 44 54 41 21 31 45 31 21 32 42 5Output 34 9 26
35 21 22 33 44 54 41 21 31 45 31 21 32 42 5
34 9 26
3 seconds
256 megabytes
['*special problem', 'greedy', 'trees', '*2000']
E. Maximum Sum Subarraystime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integer arrays a and b, both of length n.You can perform the following operation any number of times (possibly zero): swap a_i and b_i.Let f(c) be the maximum sum of a contiguous subarray of the array c (including the empty subsegment, which sum is 0).Your task is to calculate the maximum possible value of f(a) + f(b), using the aforementioned operation any number of times.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9).The third line contains n integers b_1, b_2, \dots, b_n (-10^9 \le b_i \le 10^9).The sum of n over all test case doesn't exceed 2 \cdot 10^5.OutputFor each test case, print a single integer — the maximum possible value of f(a) + f(b), using the aforementioned operation any number of times.ExampleInput 332 -1 3-4 0 164 2 -6 1 6 -4-6 -2 -3 7 -3 22-2 -50 -1Output 6 21 0
332 -1 3-4 0 164 2 -6 1 6 -4-6 -2 -3 7 -3 22-2 -50 -1
6 21 0
3 seconds
256 megabytes
['*special problem', 'dp', '*2100']
D. Remove and Addtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \dots, a_n, consisting of n integers.You goal is to make is strictly increasing. To achieve that, you perform each of the following operations exactly once: first, remove any element; second, select any number of elements (possibly, none or all n-1) and add 1 to them. Note that you are not allowed to rearrange the elements of the array.For the resulting array a', a'_1 < a'_2 < \dots < a'_{n-1} should hold. Determine if it's possible to achieve that.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of elements of the array.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^6).The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print YES if it's possible to remove one element and add 1 to some elements (possibly, none or all), so that the array becomes strictly increasing. Otherwise, print NO.ExampleInput 844 4 1 554 4 1 5 5210 531 2 332 1 141 1 1 141 3 1 251 1 3 3 1Output YES NO YES YES YES NO YES YES NoteIn the first testcase, you can remove the third element and add 1 to the second and the last element. a' will become [4, 5, 6], which is strictly increasing.In the second testcase, there is no way to perform the operations, so that the result is strictly increasing.In the third testcase, you can remove either of the elements.In the fourth testcase, you are already given a strictly increasing array, but you still have to remove an element. The result a' can be [1, 3], for example.
844 4 1 554 4 1 5 5210 531 2 332 1 141 1 1 141 3 1 251 1 3 3 1
YES NO YES YES YES NO YES YES
2 seconds
256 megabytes
['*special problem', 'greedy', '*1800']
C. Poisonous Swamptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe first location in the brand new critically acclaimed fantasy action RPG "Ancient Staff" is a poisonous swamp. The swamp has some lily pads growing in it. It can be represented as a 2 \times n grid (2 rows and n columns), where each cell is either empty or has a lily pad in it.There are exactly n lily pads in a swamp — one in each column. A frog is sitting on top of every lily pad. In one move, every frog must jump to an adjacent by a side cell.After the move, no frog can be outside the grid and no two frogs can share the same lily pad. Two frogs from adjacent cells can't jump towards each other (i.e. swap cells).If a frog jumps to a lily pad, it survives. Otherwise, it falls into a poisonous swamp and gets devoured by an eldritch creature living on its bottom.You can choose the direction each frogs jumps at. Determine the maximum number of frogs that can survive after one move.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of the testcase contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of columns in a swamp grid.Each of the following two lines contains a description of a row of a swamp — a string, consisting of exactly n characters. Each character is either a dot ('.'), denoting a swamp cell, or an asterisk ('*'), denoting a lily pad with a frog.In each column, there is exactly one dot and exactly one asterisk. The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the maximum number of frogs that can survive after one move, if you choose the direction each frogs jumps at.ExampleInput 35*..**.**..1*.3...***Output 2 0 2 NoteThe i-th frog is the frog on the lily pad in the i-th column.In the first testcase: the first frog can't survive because there's no adjacent lily pad; the second and the third frogs can jump right and up, respectively, — there's no way to save them both at the same time; the fourth and the fifth frogs can jump left and left, respectively, — there's no way to save them both at the same time; note, however, that the third and the fourth frogs will end up in the same cell in the swamp, which is not prohibited.
35*..**.**..1*.3...***
2 0 2
2 seconds
256 megabytes
['*special problem', '*special problem', 'implementation', 'implementation', '*1600']
B. Security Guardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is a security guard in Berland State University. Every day, he tracks how many people and at what time enter and leave the university. He writes this information down as follows: when someone enters the university, Monocarp writes a plus sign '+'; when someone leaves the university, Monocarp writes a minus sign '-'. At the beginning of the current day, there are no people at the university, except for Monocarp. During the day, Monocarp wrote out a sequence s. The characters in s are listed in the order Monocarp wrote them.Suddenly, Monocarp's boss decided to check his work. Unfortunately, Monocarp is a bit careless. So, the sequence s that he wrote might be impossible. For example, the sequence "+--" can't happen, since it represents a scenario when one person enters the university and two leave.Before his boss starts checking the sequence, Monocarp has the time to swap at most one pair of characters in it. Can he do it in such a way that the resulting sequence is plausible? Note that if the given sequence is already plausible, Monocarp doesn't have to swap anything.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The only line of each test case contains a single string s (1 \le |s| \le 3 \cdot 10^5), consisting only of characters '+' and/or '-'. A plus sign '+' represents a person entering the university. A minus sign '-' represents a person leaving the university.The sum of all |s| over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print an answer.If it's impossible to swap at most one pair of characters so that the resulting sequence is plausible, print -1.Otherwise, print two integers. If you swap one pair of characters, print two distinct integers from 1 to n — the indices of characters to swap. If you don't swap, print one integer from 1 to n twice — swap a character with itself.If there are multiple answers, print any of them.ExampleInput 6-++-+++----+++-Output 1 2 1 1 1 1 -1 1 1 -1
6-++-+++----+++-
1 2 1 1 1 1 -1 1 1 -1
2 seconds
256 megabytes
['*special problem', 'greedy', '*1600']
A. Usernametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the official website of Berland, each account has two parameters: username and ID.Username is a string consisting of lowercase Latin letters and/or digits, which contains at least one letter. For example, user0, 1fox1, zzzz are correct usernames, but 1337 and User22 are not. The ID of the account for a given username is generated as follows: a positive integer without leading zeroes is appended to the end of the username. For example, the ID user0125 can be generated by the following usernames: user012, user01, user0; but neither by user nor us.You are given a string s — a valid ID. Your task is to determine any valid username that can generate the given ID. If there are several correct usernames, you can print any of them.InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases.The only line of each test case contains a string s (2 \le |s| \le 50), consisting of lowercase Latin letters and/or digits.Additional constraint on input: there is at least one valid username that can generate the given ID.OutputFor each test case on a separate line, print a string — any valid username that can generate the given ID. If there are multiple correct usernames, you can print any of them.ExampleInput 4user0125a1kotlin9900001code0forces101Output user0 a kotlin9 1code0forces
4user0125a1kotlin9900001code0forces101
user0 a kotlin9 1code0forces
2 seconds
256 megabytes
['*special problem', 'implementation', '*1100']
I. Short Permutation Problemtime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputXomu - Last Dance⠀You are given an integer n.For each (m, k) such that 3 \leq m \leq n+1 and 0 \leq k \leq n-1, count the permutations of [1, 2, ..., n] such that p_i + p_{i+1} \geq m for exactly k indices i, modulo 998\,244\,353.InputThe input consists of a single line, which contains two integers n, x (2 \leq n \leq 4000, 1 \leq x < 1\,000\,000\,007).OutputLet a_{m,k} be the answer for the pair (m, k), modulo 998\,244\,353.Let \large S = \sum_{m=3}^{n+1} \sum_{k=0}^{n-1} a_{m,k}x^{mn+k}\phantom{0}.Output a single line with an integer: S modulo 1\,000\,000\,007.Note that using two different modulos is intentional. We want you to calculate all the a_{m,k} modulo 998\,244\,353, then treat them like integers in the range [0, 998\,244\,352], and hash them modulo 1\,000\,000\,007.ExamplesInput 3 2Output 77824 Input 4 1000000000Output 30984329 Input 8 327869541Output 85039220 Input 4000 1149333Output 584870166 NoteIn the first test case, the answers for all (m, k) are shown in the following table: k = 0k = 1k = 2m = 3006m = 4042 The answer for (m, k) = (3, 2) is 6, because for every permutation of length 3, a_i + a_{i+1} \geq 3 exactly 2 times. The answer for (m, k) = (4, 2) is 2. In fact, there are 2 permutations of length 3 such that a_i + a_{i+1} \geq 4 exactly 2 times: [1, 3, 2], [2, 3, 1]. Therefore, the value to print is 2^9 \cdot 0 + 2^{10} \cdot 0 + 2^{11} \cdot 6 + 2^{12} \cdot 0 + 2^{13} \cdot 4 + 2^{14} \cdot 2 \equiv 77\,824 \phantom{0} (\text{mod} \phantom{0} 1\,000\,000\,007).In the second test case, the answers for all (m, k) are shown in the following table: k = 0k = 1k = 2k = 3m = 300024m = 4001212m = 504164 The answer for (m, k) = (5, 1) is 4. In fact, there are 4 permutations of length 4 such that a_i + a_{i+1} \geq 5 exactly 1 time: [2, 1, 3, 4], [3, 1, 2, 4], [4, 2, 1, 3], [4, 3, 1, 2]. In the third test case, the answers for all (m, k) are shown in the following table: k = 0k = 1k = 2k = 3k = 4k = 5k = 6k = 7m = 3000000040320m = 40000001008030240m = 50000014401728021600m = 600004808640216009600m = 700096345616416168963456m = 80048216012960182406480432m = 901611529648186889648115216
3 2
77824
7 seconds
1024 megabytes
['combinatorics', 'dp', 'fft', 'math', '*1900']
H. Parallel Swaps Sorttime limit per test7 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDubmood - Keygen 8⠀You are given a permutation p_1, p_2, \dots, p_n of [1, 2, \dots, n]. You can perform the following operation some (possibly 0) times: choose a subarray [l, r] of even length; swap a_l, a_{l+1}; swap a_{l+2}, a_{l+3} (if l+3 \leq r); \dots swap a_{r-1}, a_r. Sort the permutation in at most 10^6 operations. You do not need to minimize the number of operations.InputThe first line contains a single integer n (2 \le n \le 3 \cdot 10^5) — the length of the permutation.The second line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, the p_i are distinct) — the permutation before performing the operations.OutputOutput your operations in the following format.The first line should contain an integer k (0 \le k \le 10^6) — the number of operations.The next k lines represent the k operations in order. Each of these k lines should contain two integers l and r (1 \leq l < r \leq n, r-l+1 must be even) — the corresponding operation consists in choosing the subarray [l, r] and swapping its elements according to the problem statement.After all the operations, a_i = i must be true for each i (1 \leq i \leq n).ExamplesInput 52 5 4 1 3Output 5 1 4 1 2 2 5 1 4 4 5 Input 91 2 3 4 5 6 7 8 9Output 0 Input 106 4 2 3 8 10 9 1 5 7Output 15 1 8 6 9 1 8 3 10 1 10 1 10 1 6 6 9 6 9 2 7 9 10 5 10 1 6 2 9 1 10 NoteIn the first test: At the beginning, p = [2, 5, 4, 1, 3]. In the first operation, you can choose [l, r] = [1, 4]. Then, (a_1, a_2) are swapped and (a_3, a_4) are swapped. The new permutation is p = [5, 2, 1, 4, 3]. In the second operation, you can choose [l, r] = [1, 2]. Then, (a_1, a_2) are swapped. The new permutation is p = [2, 5, 1, 4, 3]. In the third operation, you can choose [l, r] = [2, 5]. Then, (a_2, a_3) are swapped and (a_4, a_5) are swapped. The new permutation is p = [2, 1, 5, 3, 4]. In the fourth operation, you can choose [l, r] = [1, 4]. Then, (a_1, a_2) are swapped and (a_3, a_4) are swapped. The new permutation is p = [1, 2, 3, 5, 4]. In the fifth operation, you can choose [l, r] = [4, 5]. Then, (a_4, a_5) are swapped. The new permutation is p = [1, 2, 3, 4, 5], which is sorted. In the second test, the permutation is already sorted, so you do not need to perform any operation.
52 5 4 1 3
5 1 4 1 2 2 5 1 4 4 5
7 seconds
1024 megabytes
['constructive algorithms', 'data structures', '*3500']
G. Pumping Lemmatime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTanchiky & Siromaru - Crystal Gravity⠀You are given two strings s, t of length n, m, respectively. Both strings consist of lowercase letters of the English alphabet.Count the triples (x, y, z) of strings such that the following conditions are true: s = x+y+z (the symbol + represents the concatenation); t = x+\underbrace{ y+\dots+y }_{k \text{ times}} + z for some integer k. InputThe first line contains two integers n and m (1 \leq n < m \leq 10^7) — the length of the strings s and t, respectively.The second line contains the string s of length n, consisting of lowercase letters of the English alphabet.The third line contains the string t of length m, consisting of lowercase letters of the English alphabet.OutputOutput a single integer: the number of valid triples (x, y, z).ExamplesInput 4 8abcdabcbcbcdOutput 1 Input 3 5aaaaaaaaOutput 5 Input 12 16abbababacaababbababababacaabOutput 8 NoteIn the first test case, the only valid triple is (x, y, z) = (\texttt{"a"}, \texttt{"bc"}, \texttt{"d"}). In fact, \texttt{"abcd"} = \texttt{"a"} + \texttt{"bc"} + \texttt{"d"}; \texttt{"abcbcbcd"} = \texttt{"a"} + \texttt{"bc"} + \texttt{"bc"} + \texttt{"bc"} + \texttt{"d"}. In the second test case, there are 5 valid triples: (x, y, z) = (\texttt{""}, \texttt{"a"}, \texttt{"aa"}); (x, y, z) = (\texttt{""}, \texttt{"aa"}, \texttt{"a"}); (x, y, z) = (\texttt{"a"}, \texttt{"a"}, \texttt{"a"}); (x, y, z) = (\texttt{"a"}, \texttt{"aa"}, \texttt{""}); (x, y, z) = (\texttt{"aa"}, \texttt{"a"}, \texttt{""}). In the third test case, there are 8 valid triples: (x, y, z) = (\texttt{"ab"}, \texttt{"ba"}, \texttt{"babacaab"}); (x, y, z) = (\texttt{"abb"}, \texttt{"ab"}, \texttt{"abacaab"}); (x, y, z) = (\texttt{"abba"}, \texttt{"ba"}, \texttt{"bacaab"}); (x, y, z) = (\texttt{"ab"}, \texttt{"baba"}, \texttt{"bacaab"}); (x, y, z) = (\texttt{"abbab"}, \texttt{"ab"}, \texttt{"acaab"}); (x, y, z) = (\texttt{"abb"}, \texttt{"abab"}, \texttt{"acaab"}); (x, y, z) = (\texttt{"abbaba"}, \texttt{"ba"}, \texttt{"caab"}); (x, y, z) = (\texttt{"abba"}, \texttt{"baba"}, \texttt{"caab"}).
4 8abcdabcbcbcd
1
2 seconds
1024 megabytes
['hashing', 'strings', '*3000']
F2. Small Permutation Problem (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndy Tunstall - MiniBoss⠀In the easy version, the a_i are in the range [0, n]; in the hard version, the a_i are in the range [-1, n] and the definition of good permutation is slightly different. You can make hacks only if all versions of the problem are solved.You are given an integer n and an array a_1, a_2, \dots, a_n of integers in the range [-1, n].A permutation p_1, p_2, \dots, p_n of [1, 2, \dots, n] is good if, for each i, the following condition is true: if a_i \neq -1, the number of values \leq i in [p_1, p_2, \dots, p_i] is exactly a_i. Count the good permutations of [1, 2, \dots, n], modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-1 \le a_i \le n), which describe the conditions for a good permutation.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 line containing the number of good permutations, modulo 998\,244\,353.ExampleInput 105-1 -1 -1 -1 -151 2 3 4 560 2 2 2 -1 -16-1 -1 -1 -1 -1 56-1 -1 3 2 -1 -1150 0 -1 -1 -1 2 2 -1 -1 -1 -1 9 11 13 1560 2 2 2 4 660 1 3 4 5 561 2 3 2 4 6150 0 1 1 1 2 3 4 5 6 7 9 11 13 15Output 120 1 4 0 0 494403526 4 0 0 532305727 NoteIn the first test case, all the permutations of length 5 are good, so there are 120 good permutations.In the second test case, the only good permutation is [1, 2, 3, 4, 5].In the third test case, there are 4 good permutations: [2, 1, 5, 6, 3, 4], [2, 1, 5, 6, 4, 3], [2, 1, 6, 5, 3, 4], [2, 1, 6, 5, 4, 3]. For example, [2, 1, 5, 6, 3, 4] is good because: a_1 = 0, and there are 0 values \leq 1 in [p_1] = [2]; a_2 = 2, and there are 2 values \leq 2 in [p_1, p_2] = [2, 1]; a_3 = 2, and there are 2 values \leq 3 in [p_1, p_2, p_3] = [2, 1, 5]; a_4 = 2, and there are 2 values \leq 4 in [p_1, p_2, p_3, p_4] = [2, 1, 5, 6]; a_5 = -1, so there are no restrictions on [p_1, p_2, p_3, p_4, p_5]; a_6 = -1, so there are no restrictions on [p_1, p_2, p_3, p_4, p_5, p_6].
105-1 -1 -1 -1 -151 2 3 4 560 2 2 2 -1 -16-1 -1 -1 -1 -1 56-1 -1 3 2 -1 -1150 0 -1 -1 -1 2 2 -1 -1 -1 -1 9 11 13 1560 2 2 2 4 660 1 3 4 5 561 2 3 2 4 6150 0 1 1 1 2 3 4 5 6 7 9 11 13 15
120 1 4 0 0 494403526 4 0 0 532305727
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*2500']
F1. Small Permutation Problem (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndy Tunstall - MiniBoss⠀In the easy version, the a_i are in the range [0, n]; in the hard version, the a_i are in the range [-1, n] and the definition of good permutation is slightly different. You can make hacks only if all versions of the problem are solved.You are given an integer n and an array a_1, a_2 \dots, a_n of integers in the range [0, n].A permutation p_1, p_2, \dots, p_n of [1, 2, \dots, n] is good if, for each i, the following condition is true: the number of values \leq i in [p_1, p_2, \dots, p_i] is exactly a_i. Count the good permutations of [1, 2, \dots, n], modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le n), which describe the conditions for a good permutation.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 line containing the number of good permutations, modulo 998\,244\,353.ExampleInput 551 2 3 4 560 2 2 2 4 660 1 3 4 5 561 2 3 2 4 6150 0 1 1 1 2 3 4 5 6 7 9 11 13 15Output 1 4 0 0 532305727 NoteIn the first test case, the only good permutation is [1, 2, 3, 4, 5].In the second test case, there are 4 good permutations: [2, 1, 5, 6, 3, 4], [2, 1, 5, 6, 4, 3], [2, 1, 6, 5, 3, 4], [2, 1, 6, 5, 4, 3]. For example, [2, 1, 5, 6, 3, 4] is good because: a_1 = 0, and there are 0 values \leq 1 in [p_1] = [2]; a_2 = 2, and there are 2 values \leq 2 in [p_1, p_2] = [2, 1]; a_3 = 2, and there are 2 values \leq 3 in [p_1, p_2, p_3] = [2, 1, 5]; a_4 = 2, and there are 2 values \leq 4 in [p_1, p_2, p_3, p_4] = [2, 1, 5, 6]; a_5 = 4, and there are 4 values \leq 5 in [p_1, p_2, p_3, p_4, p_5] = [2, 1, 5, 6, 3]; a_6 = 6, and there are 6 values \leq 6 in [p_1, p_2, p_3, p_4, p_5, p_6] = [2, 1, 5, 6, 3, 4]. In the third test case, there are no good permutations, because there are no permutations with a_6 = 5 values \leq 6 in [p_1, p_2, p_3, p_4, p_5, p_6].
551 2 3 4 560 2 2 2 4 660 1 3 4 5 561 2 3 2 4 6150 0 1 1 1 2 3 4 5 6 7 9 11 13 15
1 4 0 0 532305727
2 seconds
256 megabytes
['brute force', 'combinatorics', 'dp', 'math', '*2200']
E. Multiple Lampstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKid2Will - Fire Aura⠀You have n lamps, numbered from 1 to n. Initially, all the lamps are turned off.You also have n buttons. The i-th button toggles all the lamps whose index is a multiple of i. When a lamp is toggled, if it was off it turns on, and if it was on it turns off.You have to press some buttons according to the following rules. You have to press at least one button. You cannot press the same button multiple times. You are given m pairs (u_i, v_i). If you press the button u_i, you also have to press the button v_i (at any moment, not necessarily after pressing the button u_i). Note that, if you press the button v_i, you don't need to press the button u_i. You don't want to waste too much electricity. Find a way to press buttons such that at the end at most \lfloor n/5 \rfloor lamps are on, or print -1 if it is impossible.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains two integers n and m (1 \leq n \leq 2 \cdot 10^5, 0 \leq m \leq 2 \cdot 10^5) — the number of lamps and the number of pairs, respectively.Each of the next m lines contains two integers u_i, v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i). If you press the button u_i, you also have to press the button v_i. It is guaranteed that the pairs (u_i, v_i) are distinct.It is guaranteed that the sum of n and the sum of m over all test cases do not exceed 2 \cdot 10^5.OutputFor each test case: If there is no choice of buttons that makes at most \lfloor n/5 \rfloor lamps on at the end, output a single line containing -1. Otherwise, output two lines. The first line should contain an integer k (1 \le k \le n) — the number of pressed buttons. The second line should contain k integers b_1, b_2, \dots, b_k (1 \le b_i \le n) — the indices of the pressed buttons (in any order). The b_i must be distinct, and at the end at most \lfloor n/5 \rfloor lamps must be turned on. ExampleInput 44 05 24 15 115 97 88 99 1010 911 112 213 314 415 55 41 22 33 44 5Output -1 4 3 5 1 2 3 8 9 10 1 5NoteIn the first test case, you need to turn at most \lfloor 4/5 \rfloor lamps on, which means that no lamp can be turned on. You can show that no choice of at least one button turns 0 lamps on.In the second test case, you can press buttons 3, 5, 1, 2. Initially, all the lamps are off; after pressing button 3, the lamps whose index is a multiple of 3 (i.e., 3) are toggled, so lamp 3 is turned on; after pressing button 5, the lamps whose index is a multiple of 5 (i.e., 5) are toggled, so lamps 3, 5 are turned on; after pressing button 1, the lamps whose index is a multiple of 1 (i.e., 1, 2, 3, 4, 5) are toggled, so lamps 1, 2, 4 are turned on; after pressing button 2, the lamps whose index is a multiple of 2 (i.e., 2, 4) are toggled, so lamp 1 is turned on. This is valid because you pressed at least one button; you pressed all the buttons at most once; you pressed button u_2 = 5, which means that you had to also press button v_2 = 1: in fact, button 1 has been pressed; at the end, only lamp 1 is on. In the third test case, pressing the buttons 8, 9, 10 turns only the lamps 8, 9, 10 on.
44 05 24 15 115 97 88 99 1010 911 112 213 314 415 55 41 22 33 44 5
-1 4 3 5 1 2 3 8 9 10 1 5
3 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'math', 'number theory', '*2400']
D. Split Plus Ktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputeliteLAQ - Desert Ruins⠀There are n positive integers a_1, a_2, \dots, a_n on a blackboard. You are also given a positive integer k. You can perform the following operation some (possibly 0) times: choose a number x on the blackboard; erase one occurrence of x; write two positive integers y, z such that y+z = x+k on the blackboard. Is it possible to make all the numbers on the blackboard equal? If yes, what is the minimum number of operations you need?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains two integers n, k (1 \le n \le 2 \cdot 10^5, 1 \leq k \leq 10^{12}) — the number of integers initially on the blackboard and the constant k.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{12}) — the initial state of the blackboard.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 line containing an integer: the minimum number of operations you need to make all the numbers on the blackboard equal, or -1 if it is impossible.ExampleInput 92 13 42 37 113 10100 40 1002 11 22 21 21 3278695413278695415 26250314066439986238782 581370817372 409476934981 287439719777 7376379831825 616753575719321037808624 222034505841 214063039282 441536506916 4640979418195 431813672576393004301966 405902283416 900951084746 672201172466 518769038906Output 3 1 4 -1 -1 0 3119 28999960732 -1 NoteIn the first test case, k = 1. You can make all the numbers on the blackboard equal to 2 with the following operations: Erase x = 4 and write (y, z) = (2, 3). Note that y+z=x+k. The blackboard now contains the multiset \{3, 2, 3\}. Erase x = 3 and write (y, z) = (2, 2). Note that y+z=x+k. The blackboard now contains \{2, 2, 2, 3\}. Erase x = 3 and write (y, z) = (2, 2). Note that y+z=x+k. The blackboard now contains \{2, 2, 2, 2, 2\}. This makes all the numbers equal in 3 operations. It can be shown that you cannot make all the numbers equal in less than 3 operations.In the second test case, k = 3. You can make all the numbers on the blackboard equal to 7 with the following operation: Erase x = 11 and write (y, z) = (7, 7). Note that y+z=x+k. The blackboard now contains \{7, 7, 7\}. In the third test case, k = 10. You can make all the numbers on the blackboard equal to 40 with the following operations: Erase x = 100 and write (y, z) = (70, 40). Note that y+z=x+k. The blackboard now contains \{70, 40, 40, 100\}. Erase x = 70 and write (y, z) = (40, 40). Note that y+z=x+k. The blackboard now contains \{40, 40, 40, 40, 100\}. Erase x = 100 and write (y, z) = (40, 70). Note that y+z=x+k. The blackboard now contains \{40, 40, 40, 40, 40, 70\}. Erase x = 70 and write (y, z) = (40, 40). Note that y+z=x+k. The blackboard now contains \{40, 40, 40, 40, 40, 40, 40\}. In the fourth and in the fifth test case, you can show that it is impossible to make all the numbers on the blackboard equal.
92 13 42 37 113 10100 40 1002 11 22 21 21 3278695413278695415 26250314066439986238782 581370817372 409476934981 287439719777 7376379831825 616753575719321037808624 222034505841 214063039282 441536506916 4640979418195 431813672576393004301966 405902283416 900951084746 672201172466 518769038906
3 1 4 -1 -1 0 3119 28999960732 -1
1 second
256 megabytes
['greedy', 'math', 'number theory', '*1900']
C. Heavy Intervalstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputShiki - Pure Ruby⠀You have n intervals [l_1, r_1], [l_2, r_2], \dots, [l_n, r_n], such that l_i < r_i for each i, and all the endpoints of the intervals are distinct.The i-th interval has weight c_i per unit length. Therefore, the weight of the i-th interval is c_i \cdot (r_i - l_i).You don't like large weights, so you want to make the sum of weights of the intervals as small as possible. It turns out you can perform all the following three operations: rearrange the elements in the array l in any order; rearrange the elements in the array r in any order; rearrange the elements in the array c in any order. However, after performing all of the operations, the intervals must still be valid (i.e., for each i, l_i < r_i must hold).What's the minimum possible sum of weights of the intervals after performing the operations?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5) — the number of intervals.The second line of each test case contains n integers l_1, l_2, \ldots, l_n (1 \le l_i \le 2 \cdot 10^5) — the left endpoints of the initial intervals.The third line of each test case contains n integers r_1, r_2, \ldots, r_n (l_i < r_i \le 2 \cdot 10^5) — the right endpoints of the initial intervals.It is guaranteed that \{l_1, l_2, \dots, l_n, r_1, r_2, \dots, r_n\} are all distinct.The fourth line of each test case contains n integers c_1, c_2, \ldots, c_n (1 \le c_i \le 10^7) — the initial weights of the intervals per unit length.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single integer: the minimum possible sum of weights of the intervals after your operations.ExampleInput 228 312 23100 100420 1 2 530 4 3 102 3 2 3Output 2400 42 NoteIn the first test case, you can make l = [8, 3]; r = [23, 12]; c = [100, 100]. In that case, there are two intervals: interval [8, 23] with weight 100 per unit length, and 100 \cdot (23-8) = 1500 in total; interval [3, 12] with weight 100 per unit length, and 100 \cdot (12-3) = 900 in total. The sum of the weights is 2400. It can be shown that there is no configuration of final intervals whose sum of weights is less than 2400.In the second test case, you can make l = [1, 2, 5, 20]; r = [3, 4, 10, 30]; c = [3, 3, 2, 2]. In that case, there are four intervals: interval [1, 3] with weight 3 per unit length, and 3 \cdot (3-1) = 6 in total; interval [2, 4] with weight 3 per unit length, and 3 \cdot (4-2) = 6 in total; interval [5, 10] with weight 2 per unit length, and 2 \cdot (10-5) = 10 in total; interval [20, 30] with weight 2 per unit length, and 2 \cdot (30-20) = 20 in total. The sum of the weights is 42. It can be shown that there is no configuration of final intervals whose sum of weights is less than 42.
228 312 23100 100420 1 2 530 4 3 102 3 2 3
2400 42
1 second
256 megabytes
['constructive algorithms', 'data structures', 'dsu', 'greedy', 'math', 'sortings', '*1400']
B. Make Almost Equal With Modtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputxi - Solar Storm⠀You are given an array a_1, a_2, \dots, a_n of distinct positive integers. You have to do the following operation exactly once: choose a positive integer k; for each i from 1 to n, replace a_i with a_i \text{ mod } k^\dagger. Find a value of k such that 1 \leq k \leq 10^{18} and the array a_1, a_2, \dots, a_n contains exactly 2 distinct values at the end of the operation. It can be shown that, under the constraints of the problem, at least one such k always exists. If there are multiple solutions, you can print any of them.^\dagger a \text{ mod } b denotes the remainder after dividing a by b. For example: 7 \text{ mod } 3=1 since 7 = 3 \cdot 2 + 1 15 \text{ mod } 4=3 since 15 = 4 \cdot 3 + 3 21 \text{ mod } 1=0 since 21 = 21 \cdot 1 + 0 InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 100) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{17}) — the initial state of the array. It is guaranteed that all the a_i are distinct.Note that there are no constraints on the sum of n over all test cases.OutputFor each test case, output a single integer: a value of k (1 \leq k \leq 10^{18}) such that the array a_1, a_2, \dots, a_n contains exactly 2 distinct values at the end of the operation.ExampleInput 548 15 22 30560 90 98 120 3086328 769 541 986 215 73451000 2000 7000 11000 1600022 1Output 7 30 3 5000 1000000000000000000NoteIn the first test case, you can choose k = 7. The array becomes [8 \text{ mod } 7, 15 \text{ mod } 7, 22 \text{ mod } 7, 30 \text{ mod } 7] = [1, 1, 1, 2], which contains exactly 2 distinct values (\{1, 2\}).In the second test case, you can choose k = 30. The array becomes [0, 0, 8, 0, 8], which contains exactly 2 distinct values (\{0, 8\}). Note that choosing k = 10 would also be a valid solution.In the last test case, you can choose k = 10^{18}. The array becomes [2, 1], which contains exactly 2 distinct values (\{1, 2\}). Note that choosing k = 10^{18} + 1 would not be valid, because 1 \leq k \leq 10^{18} must be true.
548 15 22 30560 90 98 120 3086328 769 541 986 215 73451000 2000 7000 11000 1600022 1
7 30 3 5000 1000000000000000000
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'math', 'number theory', '*1200']
A. Distinct Buttonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDeemo - Entrance⠀You are located at the point (0, 0) of an infinite Cartesian plane. You have a controller with 4 buttons which can perform one of the following operations: \texttt{U}: move from (x, y) to (x, y+1); \texttt{R}: move from (x, y) to (x+1, y); \texttt{D}: move from (x, y) to (x, y-1); \texttt{L}: move from (x, y) to (x-1, y). Unfortunately, the controller is broken. If you press all the 4 buttons (in any order), the controller stops working. It means that, during the whole trip, you can only press at most 3 distinct buttons (any number of times, in any order).There are n special points in the plane, with integer coordinates (x_i, y_i).Can you visit all the special points (in any order) without breaking the controller?InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the number of special points.Each of the next n lines contains two integers x_i, y_i (-100 \leq x_i, y_i \leq 100), which represent the special point (x_i, y_i).Note that there are no constraints on the sum of n over all test cases.OutputFor each test case, output "YES" (without quotes), if you can reach all the special points without breaking the controller, and "NO" (without quotes) otherwise.You may output each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).ExampleInput 631 -10 01 -14-3 -2-3 -1-3 0-3 141 1-1 -11 -1-1 16-4 14-9 -13-14 514 15-8 -419 9682 6439 913 4687 8374 217 251100 -100Output YES YES NO NO YES YES NoteIn the first test case, you can move as follows: you start from (0, 0); you visit the special point (x_2, y_2) = (0, 0); you press \texttt{R}, and you move from (0, 0) to (1, 0); you press \texttt{D}, and you move from (1, 0) to (1, -1); you visit the special point (x_1, y_1) = (1, -1); you visit the special point (x_3, y_3) = (1, -1). Therefore, you can visit all the special points using only the buttons \texttt{R}, \texttt{D}, so the controller does not break.Note that the special points may coincide.In the second test case, you can show that you can visit all the special points using only the buttons \texttt{U}, \texttt{D}, \texttt{L}.In the third test case, you can show that you must press all the buttons (\texttt{U}, \texttt{R}, \texttt{D}, \texttt{L}) to visit all the points, so the controller would break.
631 -10 01 -14-3 -2-3 -1-3 0-3 141 1-1 -11 -1-1 16-4 14-9 -13-14 514 15-8 -419 9682 6439 913 4687 8374 217 251100 -100
YES YES NO NO YES YES
1 second
256 megabytes
['implementation', 'math', '*800']
G. Lightstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn the end of the day, Anna needs to turn off the lights in the office. There are n lights and n light switches, but their operation scheme is really strange. The switch i changes the state of light i, but it also changes the state of some other light a_i (change the state means that if the light was on, it goes off and vice versa).Help Anna to turn all the lights off using minimal number of switches, or say it is impossible.InputThe first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Descriptions of test cases follow.The first line of each test case contains the integer n (2 \le n \le 10^5) — the number of lights. The second line of each test case contains the string of n characters, the initial state of the lights. Character "0" means that the corresponding light is off, and "1" means that it is on. The third line of each test case contains n integers a_i (1 \le a_i \le n, a_i \neq i) — the switch i changes the states of light i and light a_i.It is guaranteed that sum of n over all test cases does not exceed 2 \cdot 10^5OutputFor each test case output the integer k, the minimal number of switches to use, then in the separate line output the list of k switches.If it is impossible to turn off all the lights, output single integer -1.ExampleInput 85111014 3 4 2 22102 11000000000119 10 10 7 10 9 9 9 10 21010001111019 3 8 9 2 1 3 7 2 71000011010105 7 6 10 8 3 6 6 2 21001011000108 7 7 9 9 4 1 4 2 71010101110107 9 10 7 7 2 8 6 10 41011100000013 10 10 1 10 8 6 3 2 1Output 3 1 5 3 -1 1 9 5 5 6 10 2 3 6 4 9 5 10 8 7 3 5 4 9 6 1 3 5 9 7 8 2 2 1
85111014 3 4 2 22102 11000000000119 10 10 7 10 9 9 9 10 21010001111019 3 8 9 2 1 3 7 2 71000011010105 7 6 10 8 3 6 6 2 21001011000108 7 7 9 9 4 1 4 2 71010101110107 9 10 7 7 2 8 6 10 41011100000013 10 10 1 10 8 6 3 2 1
3 1 5 3 -1 1 9 5 5 6 10 2 3 6 4 9 5 10 8 7 3 5 4 9 6 1 3 5 9 7 8 2 2 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'implementation', '*2200']
F. Shift and Reversetime limit per test2.0 smemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array of integers a_1, a_2, \ldots, a_n. You can make two types of operations with this array: Shift: move the last element of array to the first place, and shift all other elements to the right, so you get the array a_n, a_1, a_2, \ldots, a_{n-1}. Reverse: reverse the whole array, so you get the array a_n, a_{n-1}, \ldots, a_1. Your task is to sort the array in non-decreasing order using the minimal number of operations, or say that it is impossible.InputThe first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Descriptions of test cases follow.The first line of each test case contains an integer n (1\le n \le 10^5) — size of the array. The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — elements of the array.It is guaranteed that sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output the number k, the minimal number of operations you need to sort the array. If it is impossible to sort the array using these operations, output -1.ExampleInput 1153 2 1 5 451 1 2 1 143 7 10 551 2 3 4 525 133 4 154 1 3 4 435 1 142 5 5 452 2 1 1 225 5Output 3 2 -1 0 1 1 3 1 2 2 0 NoteIn the first test case of the example, to sort the array [3, 2, 1, 5, 4] you need to perform 3 operations: Shift to obtain the array [4, 3, 2, 1, 5]; Shift to obtain the array [5, 4, 3, 2, 1]; Reverse to obtain the array [1, 2, 3, 4, 5]. In the third test case of the example, it can be shown that it is impossible to sort the array using the given operations.In the seventh test case of the example, to sort the array [4, 1, 3, 4, 4] you need to perform 3 operations: Reverse to obtain the array [4, 4, 3, 1, 4]; Shift to obtain the array [4, 4, 4, 3, 1]; Reverse to obtain the array [1, 3, 4, 4, 4].
1153 2 1 5 451 1 2 1 143 7 10 551 2 3 4 525 133 4 154 1 3 4 435 1 142 5 5 452 2 1 1 225 5
3 2 -1 0 1 1 3 1 2 2 0
2.0 s
256 megabytes
['greedy', 'sortings', '*1800']
E. Good Triplestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a non-negative integer number n (n \ge 0). Let's say a triple of non-negative integers (a, b, c) is good if a + b + c = n, and digsum(a) + digsum(b) + digsum(c) = digsum(n), where digsum(x) is the sum of digits of number x.For example, if n = 26, then the pair (4, 12, 10) is good, because 4 + 12 + 10 = 26, and (4) + (1 + 2) + (1 + 0) = (2 + 6).Your task is to find the number of good triples for the given number n. The order of the numbers in a triple matters. For example, the triples (4, 12, 10) and (10, 12, 4) are two different triples.InputThe first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Descriptions of test cases follow.The first and only line of the test case contains one integer n (0 \le n \le 10^7).OutputFor each test case output one integer, the number of good triples for the given integer n. Order of integers in a triple matters.ExampleInput 121101234531419992718999999910000000Output 9 1 3 6 10 15 21 1350 166375 29160 1522435234375 3 NoteIn the first example, the good triples are (0, 0, 11), (0, 1, 10), (0, 10, 1), (0, 11, 0), (1, 0, 10), (1, 10, 0), (10, 0, 1), (10, 1, 0), (11, 0, 0).In the second example, there is only one good triple (0, 0, 0).
121101234531419992718999999910000000
9 1 3 6 10 15 21 1350 166375 29160 1522435234375 3
2 seconds
256 megabytes
['brute force', 'combinatorics', 'number theory', '*1600']