problem_statement
stringlengths
147
8.53k
input
stringlengths
1
771
output
stringlengths
1
592
time_limit
stringclasses
32 values
memory_limit
stringclasses
21 values
tags
stringlengths
6
168
D. Jumping Through Segmentstime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is designing a level for a game. The level consists of n segments on the number line, where the i-th segment starts at the point with coordinate l_i and ends at the point with coordinate r_i.The player starts the level at the point with coordinate 0. In one move, they can move to any point that is within a distance of no more than k. After their i-th move, the player must land within the i-th segment, that is, at a coordinate x such that l_i \le x \le r_i. This means: After the first move, they must be inside the first segment (from l_1 to r_1); After the second move, they must be inside the second segment (from l_2 to r_2); ... After the n-th move, they must be inside the n-th segment (from l_n to r_n). The level is considered completed if the player reaches the n-th segment, following the rules described above. After some thought, Polycarp realized that it is impossible to complete the level with some values of k.Polycarp does not want the level to be too easy, so he asks you to determine the minimum integer k with which it is possible to complete the level.InputThe first line contains a single integer t (1 \le t \le 10^4)—the number of test cases. Descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5)—the number of segments in the level.The following n lines.The i-th line contain two integers l_i and r_i (0 \le l_i \le r_i \le 10^9)—the boundaries of the i-th segment. Segments may intersect.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer—the minimum value of k with which it is possible to complete the level.ExampleInput 451 53 45 68 100 130 20 10 333 810 186 11410 200 515 172 2Output 7 0 5 13 NoteIn the third example, the player can make the following moves: Move from point 0 to point 5 (3 \le 5 \le 8); Move from point 5 to point 10 (10 \le 10 \le 18); Move from point 10 to point 7 (6 \le 7 \le 11). Note that for the last move, the player could have chosen not to move and still complete the level.
451 53 45 68 100 130 20 10 333 810 186 11410 200 515 172 2
7 0 5 13
5 seconds
256 megabytes
['binary search', 'constructive algorithms', '*1400']
C. Removal of Unattractive Pairstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad found a string s consisting of n lowercase Latin letters, and he wants to make it as short as possible.To do this, he can remove any pair of adjacent characters from s any number of times, provided they are different. For example, if s=racoon, then by removing one pair of characters he can obtain the strings coon, roon, raon, and raco, but he cannot obtain racn (because the removed letters were the same) or rcon (because the removed letters were not adjacent).What is the minimum length Vlad can achieve by applying any number of deletions?InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line of each test case contains the string s consisting of n lowercase Latin letters.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 number—the minimum length of the string s, after removing pairs of adjacent characters with different values.ExampleInput 104aabc5abaca10avbvvcvvvd7abcdefg5dabbb8aacebeaa7bbbbacc6dacfcc6fdfcdc9dbdcfbbdcOutput 0 1 2 1 1 0 1 0 0 1 NoteIn the first test case of the example, you need to act as follows: "aabc" \rightarrow "ac" \rightarrow "". Note that with a different order of deletions, the string will not become empty.
104aabc5abaca10avbvvcvvvd7abcdefg5dabbb8aacebeaa7bbbbacc6dacfcc6fdfcdc9dbdcfbbdc
0 1 2 1 1 0 1 0 0 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', 'strings', '*1200']
B. YetnotherrokenKeoardtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a problem — his laptop keyboard is broken.Now, when he presses the 'b' key, it acts like an unusual backspace: it deletes the last (rightmost) lowercase letter in the typed string. If there are no lowercase letters in the typed string, then the press is completely ignored.Similarly, when he presses the 'B' key, it deletes the last (rightmost) uppercase letter in the typed string. If there are no uppercase letters in the typed string, then the press is completely ignored.In both cases, the letters 'b' and 'B' are not added to the typed string when these keys are pressed.Consider an example where the sequence of key presses was "ARaBbbitBaby". In this case, the typed string will change as follows: "" \xrightarrow{\texttt{A}} "A" \xrightarrow{\texttt{R}} "AR" \xrightarrow{\texttt{a}} "ARa" \xrightarrow{\texttt{B}} "Aa" \xrightarrow{\texttt{b}} "A" \xrightarrow{\texttt{b}} "A" \xrightarrow{\texttt{i}} "Ai" \xrightarrow{\texttt{t}} "Ait" \xrightarrow{\texttt{B}} "it" \xrightarrow{\texttt{a}} "ita" \xrightarrow{\texttt{b}} "it" \xrightarrow{\texttt{y}} "ity".Given a sequence of pressed keys, output the typed string after processing all key presses.InputThe first line of the input data contains an integer t (1 \le t \le 1000), the number of test cases in the test.The following contains t non-empty lines, which consist of lowercase and uppercase letters of the Latin alphabet.It is guaranteed that each line contains at least one letter and the sum of the lengths of the lines does not exceed 10^6.OutputFor each test case, output the result of processing the key presses on a separate line. If the typed string is empty, then output an empty line.ExampleInput 12ARaBbbitBabyYetAnotherBrokenKeyboardBubbleImprobableabbreviableBbBBBusyasaBeeinaBedofBloomingBlossomsCoDEBARbIEScodeforcesbobebobbesbTheBBlackbboardOutput ity YetnotherrokenKeoard le Imprle revile usyasaeeinaedofloominglossoms CDARIES codeforces es helaoard
12ARaBbbitBabyYetAnotherBrokenKeyboardBubbleImprobableabbreviableBbBBBusyasaBeeinaBedofBloomingBlossomsCoDEBARbIEScodeforcesbobebobbesbTheBBlackbboard
ity YetnotherrokenKeoard le Imprle revile usyasaeeinaedofloominglossoms CDARIES codeforces es helaoard
1 second
256 megabytes
['data structures', 'implementation', 'strings', '*1000']
A. Rooktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAs you probably know, chess is a game that is played on a board with 64 squares arranged in an 8\times 8 grid. Columns of this board are labeled with letters from a to h, and rows are labeled with digits from 1 to 8. Each square is described by the row and column it belongs to. The rook is a piece in the game of chess. During its turn, it may move any non-zero number of squares horizontally or vertically. Your task is to find all possible moves for a rook on an empty chessboard.InputThe first line of input contains single integer t (1 \le t \le 64) — the number of test cases. The descriptions of test cases follow.Each test case contains one string of two characters, description of the square where rook is positioned. The first character is a letter from a to h, the label of column, and the second character is a digit from 1 to 8, the label of row. The same position may occur in more than one test case.OutputFor each test case, output descriptions of all squares where the rook can move, in the same format as in the input. You can output squares in any order per test case.ExampleInput 1d5Output d1 d2 b5 g5 h5 d3 e5 f5 d8 a5 d6 d7 c5 d4
1d5
d1 d2 b5 g5 h5 d3 e5 f5 d8 a5 d6 d7 c5 d4
1 second
256 megabytes
['implementation', '*800']
M. Triangle Constructiontime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a regular N-sided polygon. Label one arbitrary side as side 1, then label the next sides in clockwise order as side 2, 3, \dots, N. There are A_i special points on side i. These points are positioned such that side i is divided into A_i + 1 segments with equal length.For instance, suppose that you have a regular 4-sided polygon, i.e., a square. The following illustration shows how the special points are located within each side when A = [3, 1, 4, 6]. The uppermost side is labelled as side 1. You want to create as many non-degenerate triangles as possible while satisfying the following requirements. Each triangle consists of 3 distinct special points (not necessarily from different sides) as its corners. Each special point can only become the corner of at most 1 triangle. All triangles must not intersect with each other.Determine the maximum number of non-degenerate triangles that you can create.A triangle is non-degenerate if it has a positive area.InputThe first line consists of an integer N (3 \leq N \leq 200\,000).The following line consists of N integers A_i (1 \leq A_i \leq 2 \cdot 10^9).OutputOutput a single integer representing the maximum number of non-degenerate triangles that you can create.ExamplesInput 4 3 1 4 6 Output 4 Input 6 1 2 1 2 1 2 Output 3 Input 3 1 1 1 Output 1 NoteExplanation for the sample input/output #1One possible construction which achieves maximum number of non-degenerate triangles can be seen in the following illustration. Explanation for the sample input/output #2One possible construction which achieves maximum number of non-degenerate triangles can be seen in the following illustration.
4 3 1 4 6
4
1 second
1024 megabytes
['greedy', 'math', '*1700']
L. Palindromic Parenthesestime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputConstruct a parentheses sequence consisting of N characters such that it is balanced and the length of its longest palindromic subsequence (LPS) is exactly K. Determine whether such a construction is possible. If there are several possible sequences, construct any of them.A parentheses sequence consists of only character ( and ). A parentheses sequence is balanced if each character ( has a corresponding character ) and the pairs of parentheses are properly nested. For example, (), (()), (())(), and ((())()) are balanced. However, )(, ((), and ()) are not balanced.A sequence is palindromic if it reads the same backwards as forwards. For example, ((, ), ())(, and (()(( are palindromic. However, (), )(, and (()) are not palindromic.A subsequence can be derived from another sequence by removing zero or more characters without changing the order of the remaining characters. For example, (, ))), ())(, and (())() are subsequence of (())(). However, )(( and ((())) are not subsequence of (())().The longest palindromic subsequence (LPS) of a sequence is a subsequence with the maximum number of characters, derived from that sequence and it is palindromic. For example, the LPS of sequence (())() is ())(, which can be obtained by removing the second and sixth characters. Therefore, the length of the LPS of (())() is 4.InputInput consists of two integers N K (2 \leq N \leq 2000; 1 \leq K \leq N). N is an even number.OutputIf there is no such parentheses sequence such that it is balanced and the length of its LPS is exactly K, then output -1.Otherwise, output a string of N characters, representing the parentheses sequence. If there are several possible answers, output any of them.ExamplesInput 6 4 Output (())()Input 6 3 Output (()())Input 4 1 Output -1Input 14 11 Output ()((())()())()NoteExplanation for the sample input/output #2The LPS of (()()) is either ((( by removing all ) characters, or ))) by removing all ( characters.The output ((())) also satisfies the requirements.Explanation for the sample input/output #3The only possible balanced parentheses sequences are (()) and ()(). The length of the LPS of (()) and ()() are 2 and 3, respectively.Explanation for the sample input/output #4The LPS of ()((())()())() is )())()())(), which can be obtained by removing the first, fourth, and fifth characters.
6 4
(())()
1 second
1024 megabytes
['constructive algorithms', '*2500']
K. Deck-Building Gametime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are playing a deck-building game with your friend. There are N cards, numbered from 1 to N. Card i has the value of A_i.You want to build two decks; one for you and one for your friend. A card cannot be inside both decks, and it is allowed to not use all N cards. It is also allowed for a deck to be empty, i.e. does not contain any cards.The power of a deck is represented as the bitwise XOR of the value of the cards in the deck. The power of an empty deck is 0.The game is balanced if both decks have the same power.Determine the number of ways to build two decks such that the game is balanced. Two ways are considered different if one of the decks contains at least one different card. Since the answer can be very large, calculate the answer modulo 998\,244\,353.InputThe first line consists of an integer N (2 \le N \le 100\,000).The following line consists of N integers A_i (1 \le A_i \le 100\,000).OutputOutput an integer representing the number of ways to build two decks such that the game is balanced. Output the answer modulo 998\,244\,353.ExamplesInput 4 16 12 4 8 Output 9 Input 4 1 2 4 8 Output 1 Input 2 1 1 Output 5 Input 6 1 1 1 2 2 2 Output 169 NoteExplanation for the sample input/output #1Denote S and T as the set of cards in your deck and your friend's deck, respectively. There are 9 ways to build the decks such that the game is balanced. S = \{\} and T = \{\}. Both decks have the power of 0. S = \{2, 3, 4\} and T = \{\}. Both decks have the power of 0. S = \{\} and T = \{2, 3, 4\}. Both decks have the power of 0. S = \{2, 4\} and T = \{3\}. Both decks have the power of 4. S = \{3\} and T = \{2, 4\}. Both decks have the power of 4. S = \{2, 3\} and T = \{4\}. Both decks have the power of 8. S = \{4\} and T = \{2, 3\}. Both decks have the power of 8. S = \{3, 4\} and T = \{2\}. Both decks have the power of 12. S = \{2\} and T = \{3, 4\}. Both decks have the power of 12. Explanation for the sample input/output #2The only way to make the game balanced is to have both decks empty.Explanation for the sample input/output #3There are 5 ways to build the decks such that the game is balanced. S = \{\} and T = \{\}. Both decks have the power of 0. S = \{1, 2\} and T = \{\}. Both decks have the power of 0. S = \{\} and T = \{1, 2\}. Both decks have the power of 0. S = \{1\} and T = \{2\}. Both decks have the power of 1. S = \{2\} and T = \{1\}. Both decks have the power of 1.
4 16 12 4 8
9
1 second
1024 megabytes
['divide and conquer', 'math', '*2500']
J. Count BFS Graphtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are currently researching a graph traversal algorithm called the Breadth First Search (BFS). Suppose you have an input graph of N nodes (numbered from 1 to N). The graph is represented by an adjacency matrix M, for which node u can traverse to node v if M_{u, v} is 1, otherwise it is 0. Your algorithm will output the order the nodes are visited in the BFS. The pseudocode of the algorithm is presented as follows. BFS(M[1..N][1..N]): let A be an empty array let Q be an empty queue append 1 to A push 1 to Q while Q is not empty: pop the front element of Q into u for v = 1 to N: if M[u][v] == 1 and v is not in A: append v to A push v to Q return ADuring your research, you are interested in the following problem. Given an array A such that A is a permutation of 1 to N and A_1 = 1. How many simple undirected graph with N nodes and adjacency matrix M such that \text{BFS}(M) = A? Since the answer can be very large, calculate the answer modulo 998\,244\,353.A simple graph has no self-loop (M_{i, i} = 0 for 1 \leq i \leq N) and there is at most one edge that connects a pair of nodes. In an undirected graph, if node u is adjacent to node v, then node v is also adjacent to node u; formally, M_{u, v} = M_{v, u} for 1 \leq u < v \leq N.Two graphs are considered different if there is an edge that exists in one graph but not the other. In other words, two graphs are considered different if their adjacency matrices are different.InputThe first line consists of an integer N (2 \leq N \leq 5000).The second line consists of N integers A_i. The array A is a permutation of 1 to N and A_1 = 1.OutputOutput an integer representing the number of simple undirected graphs with N nodes and adjacency matrix M such that \text{BFS}(M) = A. Since the answer can be very large, output the answer modulo 998\,244\,353.ExamplesInput 3 1 2 3 Output 3 Input 3 1 3 2 Output 1 Input 5 1 3 2 4 5 Output 17 Input 11 1 2 3 4 5 6 7 8 9 10 11 Output 379394847 NoteExplanation for the sample input/output #1The following illustration shows all graphs that satisfy the requirements. Explanation for the sample input/output #2The only graph that satisfies the requirements is a graph with two edges: one that connects nodes 1 and 3, and another one that connects nodes 3 and 2.
3 1 2 3
3
1 second
1024 megabytes
['combinatorics', 'dp', '*2100']
I. Contingency Plan 2time limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are working as a manager in The ICPC Company. In the company building, there are N computers (numbered from 1 to N). There are N - 1 cables, numbered from 1 to N - 1, that connect all the computers into a single network. Cable i connects computer U_i and V_i. Each cable can be set into emergency mode, where cable i only transfers data from computer U_i to computer V_i, but not the other way around. During a disaster, it is mandatory for all cables to be in emergency mode.Through your research, you discover a new way to determine the vulnerability of a network. You want to add zero or more new cables to the current network such that it is not vulnerable during a disaster. Your network is not vulnerable if and only if there is exactly one permutation of 1 to N such that u appears before v in the permutation for all cables that connect computer u and v. In other words, it should have exactly one topological order.The following illustration shows examples of not vulnerable networks and vulnerable networks. For the not vulnerable networks, the only permutation that satisfies the requirement for the networks on the left and on the right are [1, 2, 3] and [3, 1, 2], respectively. Meanwhile, for the vulnerable networks, there are 2 permutations that satisfy the requirement for the network on the left: [1, 2, 3] and [3, 1, 2]; while there is no permutation that satisfies the requirement for the network on the right.You are interested in the minimum number of new cables that should be added to the current network such that it is not vulnerable during a disaster. Furthermore, you want to know, which pairs of computers should be connected by using the minimum number of cables. If there are several ways to connect, you can connect in any way of your choice. Under the given constraints, it can be proven that there exists a way to make the network not vulnerable.InputThe first line consists of an integer N (2 \leq N \leq 100\,000).Each of the next N - 1 lines consists of two integers U_i V_i (1 \leq U_i, V_i \leq N). The input edges form a tree.OutputThe first line consists of an integer, representing the minimum number of new cables that should be added to the current network such that it is no longer vulnerable during a disaster. Denote this number as K and the new cables are numbered from 1 to K.If K is not 0, then output K lines. Each of the next K lines consists of two integers A_i B_i, representing the computers that are connected by the new cable i. During a disaster, new cable i only transfers data from computer A_i to computer B_i, but not the other way around. If there exist several solutions, you can output any of them.ExamplesInput 3 1 2 3 2 Output 1 3 1Input 3 1 2 2 3 Output 0Input 5 1 2 1 3 3 4 3 5 Output 2 2 3 4 5NoteExplanation for the sample input/output #3The following illustration shows the original network and the new network with the added cables during a disaster. The only permutation that satisfies the requirement is [1, 2, 3, 4, 5].
3 1 2 3 2
1 3 1
1 second
1024 megabytes
['graph matchings', '*2900']
H. Twin Friendstime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou meet two new friends who are twins. The name of the elder twin is A, which consists of N characters. While the name of the younger twin is B, which consists of M characters. It is known that N \leq M.You want to call each of them with a nickname. For the elder twin, you want to pick any permutation of A as the nickname. For the younger twin, you want to remove exactly M - N characters from any permutation of B. Denote the nicknames of the elder twin and the younger twin as A' and B', respectively.You want the nicknames to satisfy the following requirement. For each i that satisfies 1 \leq i \leq N, B'_i must be equal to either A'_i or the next letter that follows alphabetically after A'_i (if such a next letter exists).Determine the number of different pairs of nicknames (A', B') that satisfy the requirement. Two pairs of nicknames are considered different if at least one of the nicknames are different. As the result might be large, find the answer modulo 998\,244\,353.InputThe first line consists of two integers N M (1 \leq N \leq M \leq 200\,000).The second line consists of a string A of length N.The third line consists of a string B of length M.All strings consist of only upper-case letters.OutputOutput a single integer representing number of different pairs (A', B') that satisfy the requirement, modulo 998\,244\,353.ExamplesInput 3 4 AMA ANAB Output 9 Input 5 8 BINUS BINANUSA Output 120 Input 15 30 BINUSUNIVERSITY BINANUSANTARAUNIVERSITYJAKARTA Output 151362308 Input 4 4 UDIN ASEP Output 0 NoteExplanation for the sample input/output #1The 9 pairs are: (AAM, AAN), (AAM, ABN), (AAM, BAN), (AMA, ANA), (AMA, ANB), (AMA, BNA), (MAA, NAA), (MAA, NAB), and (MAA, NBA). Explanation for the sample input/output #2The 120 pairs are the pairs where A' is a permutation of BINUS and B' = A'.
3 4 AMA ANAB
9
1 second
1024 megabytes
['combinatorics', 'dp', '*2200']
G. Grid Game 2time limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are playing "Grid Game 2" with your friend. There is a grid with 10^9 rows (numbered from 1 to 10^9) and 10^9 columns (numbered from 1 to 10^9). The cell at row r and column c is denoted as (r, c).Each cell can have a colour of either black or white. Initially, there are exactly N black cells (numbered from 1 to N). Black cell i is located at (R_i, C_i). The rest of the cells are white.You and your friend will alternately take turn playing on this grid, and you are playing in the first turn. In one turn, a player will choose a black cell (r, c), then toggle cells (r - x, c - y) for all 0 \leq x, y < \min(r, c). If a cell is toggled, then the cell becomes black if it was a white cell, and the cell becomes white if it was a black cell.For example, the following illustration shows how the grid changes after a player chooses a black cell (5, 4) in their turn. A player who is unable to play on their turn, i.e. no remaining black cells, loses the game, and the opposing player wins the game. If you and your friend are playing optimally, determine who will win the game.InputThe first line consists of an integer N (1 \le N \le 200\,000).Each of the next N lines consists of two integers R_i C_i (1 \leq R_i, C_i \leq 10^9). For 1 \leq i < j \leq N, (R_i, C_i) \neq (R_j, C_j).OutputOutput FIRST if you will win the game, or SECOND otherwise.ExamplesInput 2 2 3 2 4 Output FIRST Input 1 2 2 Output SECOND Input 13 1 1 1 4 1 5 2 1 2 4 2 5 4 1 4 2 4 4 5 1 5 2 5 4 5 5 Output SECOND NoteExplanation for the sample input/output #1You can start your move by choosing (2, 4), whose effect was demonstrated in the following illustration. The remaining black cells are (1, 3) and (1, 4), each of which will only toggle itself when chosen. Whichever your friend chooses on the next move, the you can choose the remaining black cell.Explanation for the sample input/output #2You have only one cell to choose, and will toggle cells (1, 1), (1, 2), (2, 1), and (2, 2). Your friend and you will alternately choose the remaining black cells with your friend choosing the last black cell.
2 2 3 2 4
FIRST
1 second
1024 megabytes
['games', 'number theory', '*2900']
F. Maximize The Valuetime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a one-based array consisting of N integers: A_1, A_2, \cdots, A_N. Initially, the value of each element is set to 0.There are M operations (numbered from 1 to M). Operation i is represented by \langle L_i, R_i, X_i \rangle. If operation i is executed, all elements A_j for L_i \leq j \leq R_i will be increased by X_i.You have to answer Q independent queries. Each query is represented by \langle K, S, T \rangle which represents the following task. Choose a range [l, r] satisfying S \leq l \leq r \leq T, and execute operations l, l + 1, \dots, r. The answer to the query is the maximum value of A_K after the operations are executed among all possible choices of l and r.InputThe first line consists of two integers N M (1 \leq N, M \leq 100\,000).Each of the next M lines consists of three integers L_i R_i X_i (1 \leq L_i \leq R_i \leq N; -100\,000 \leq X_i \leq 100\,000).The following line consists of an integer Q (1 \leq Q \leq 100\,000).Each of the next Q lines consists of three integers K S T (1 \leq K \leq N; 1 \leq S \leq T \leq M).OutputFor each query, output in a single line, an integer which represent the answer of the query.ExamplesInput 2 6 1 1 -50 1 2 -20 2 2 -30 1 1 60 1 2 40 2 2 10 5 1 1 6 2 1 6 1 1 3 2 1 3 1 1 2 Output 100 50 0 0 -20 Input 5 3 1 3 3 2 4 -2 3 5 3 6 1 1 3 2 1 3 3 1 3 3 2 3 2 2 3 2 2 2 Output 3 3 4 3 0 -2 NoteExplanation for the sample input/output #1For query 1, one of the solutions is to execute operation 4 and 5.For query 2, one of the solutions is to execute operation 4, 5, and 6.For query 3, the only solution is to execute operation 3.For query 4, the only solution is to execute operation 1.For query 6, the only solution is to execute operation 2.
2 6 1 1 -50 1 2 -20 2 2 -30 1 1 60 1 2 40 2 2 10 5 1 1 6 2 1 6 1 1 3 2 1 3 1 1 2
100 50 0 0 -20
1 second
1024 megabytes
['data structures', 'sortings', '*2100']
E. Merge Not Sorttime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are currently researching the Merge Sort algorithm. Merge Sort is a sorting algorithm that is based on the principle of Divide and Conquer. It works by dividing an array into two subarrays of equal length, sorting each subarrays, then merging the sorted subarrays back together to form the final sorted array.You are particularly interested in the merging routine. Common merge implementation will combine two subarrays by iteratively comparing their first elements, and move the smaller one to a new merged array. More precisely, the merge algorithm can be presented by the following pseudocode. Merge(A[1..N], B[1..N]): C = [] i = 1 j = 1 while i <= N AND j <= N: if A[i] < B[j]: append A[i] to C i = i + 1 else: append B[j] to C j = j + 1 while i <= N: append A[i] to C i = i + 1 while j <= N: append B[j] to C j = j + 1 return CDuring your research, you are keen to understand the behaviour of the merge algorithm when arrays A and B are not necessarily sorted. For example, if A = [3, 1, 6] and B = [4, 5, 2], then \text{Merge}(A, B) = [3, 1, 4, 5, 2, 6].To further increase the understanding of the merge algorithm, you decided to work on the following problem. You are given an array C of length 2 \cdot N such that it is a permutation of 1 to 2 \cdot N. Construct any two arrays A and B of the same length N, such that \text{Merge}(A, B) = C, or determine if it is impossible to do so.InputThe first line consists of an integer N (1 \leq N \leq 1000).The following line consists of 2 \cdot N integers C_i. The array C is a permutation of 1 to 2 \cdot N.OutputIf it is impossible to construct two arrays A and B of length N such that \text{Merge}(A, B) = C, then output -1.Otherwise, output the arrays A and B in two lines. The first line consists of N integers A_i. The second line consists of N integers B_i. If there are several possible answers, output any of them.ExamplesInput 3 3 1 4 5 2 6 Output 3 1 6 4 5 2Input 4 1 2 3 4 5 6 7 8 Output 2 3 5 7 1 4 6 8Input 2 4 3 2 1 Output -1NoteExplanation for the sample input/output #1The solution A = [3, 1, 4] and B = [5, 2, 6] is also correct. Explanation for the sample input/output #2The solution A = [1, 2, 3, 4] and B = [5, 6, 7, 8] is also correct.
3 3 1 4 5 2 6
3 1 6 4 5 2
1 second
1024 megabytes
['constructive algorithms', 'dp', '*1900']
D. Spaceship Explorationtime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIn The ICPC Galaxy, there exists a zone filled with asteroids that is unsafe to enter. The map of the galaxy is represented in a 2D Cartesian coordinate system. The zone is in the shape of an N-sided convex polygon. Each corner is numbered from 1 to N; corner i is located at (X_i, Y_i). At any moment, you should not be inside this polygon; however, it is safe to touch the side of the polygon.There are Q scenarios (numbered from 1 to Q). In scenario j, you want to go from a starting point at (A_j, B_j) to an ending point at (C_j, D_j). You will be riding on a special spaceship that can only travel in a straight line. First, you set the direction of the spaceship, then the spaceship will start traveling in that direction. During the travel, you are only allowed to change direction at most once. Changing direction means you stop the spaceship, set a new direction, and then start traveling again in the new direction.For each scenario, determine the minimum distance required to travel without being inside of the zone at any moment, or report if it is impossible to reach the ending point.InputThe first line consists of an integer N (3 \leq N \leq 100\,000).Each of the next N lines consists of two integers X_i Y_i (-10^9 \leq X_i, Y_i \leq 10^9). The points form a convex polygon in counterclockwise order. There are no three points which are collinear.The following line consists of an integer Q (1 \leq Q \leq 100\,000).Each of the next Q lines consists of four integers A_j B_j C_j D_j (-10^9 \leq A_j, B_j, C_j, D_j \leq 10^9). There are no starting points and ending points inside the zone. However, it is possible for the starting point and the ending point to be at the side of the zone.All the coordinates in the input are integers.OutputFor each scenario, output the answer in a single line.If it is possible to reach the ending point without being inside the zone at any moment, then output the minimum distance required to travel. Otherwise, output -1.Your answer is considered correct if its absolute error or relative error does not exceed 10^{-6}. Namely, if your answer is a and the jury's answer is b, then your answer is accepted if \frac{|a - b|}{\max(1, |b|)} \leq 10^{-6}.ExamplesInput 5 0 2 2 0 4 0 4 4 2 4 5 6 1 6 3 2 5 0 0 3 5 3 -1 1 4 5 4 3 4 3 0 Output 2 5.6055512755 8.48528137422 4 -1Input 4 -10 -9 10 -9 10 9 -10 9 2 0 10 0 -10 -10 -10 -10 -10 Output 200.9975124224 0Input 8 -20 -10 10 -20 25 -15 35 -5 30 10 15 20 -25 15 -30 5 6 -15 -15 -15 20 -30 -5 30 15 25 20 -5 -20 -5 25 20 -20 -30 10 30 -10 -30 -50 50 0 Output 59.0857761929 103.2455532034 94.7213595500 101.5640991922 164.8528137424 94.3398113206NoteExplanation for the sample input/output #1This sample is depicted in the following illustration. During scenario 1 and 4, you can directly go to the ending point without changing the direction.During scenario 2, you can go to (0, 2), then change direction to the ending point.During scenario 3, you can go to (6, 2), then change direction to the ending point.During scenario 5, it can be shown that it is impossible to reach the ending point.
5 0 2 2 0 4 0 4 4 2 4 5 6 1 6 3 2 5 0 0 3 5 3 -1 1 4 5 4 3 4 3 0
2 5.6055512755 8.48528137422 4 -1
3 seconds
1024 megabytes
['binary search', 'geometry', '*2800']
B. Button Pressingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given N buttons (numbered from 1 to N) and N lamps (numbered from 1 to N). Each lamp can either be on or off. Initially, lamp i is on if A_i = 1, and off if A_i = 0.Button i is connected to lamp i - 1 (if i > 1) and lamp i + 1 (if i < N). In one move, you can press a button i only if lamp i is on. When a button is pressed, the state of the lamps connected to this button is toggled. Formally, the lamps will be on if it was off previously, and the lamps will be off if it was on previously. Note that lamp i is not connected to button i, thus, the state of lamp i does not change if button i is pressed.After zero or more moves, you want lamp i to be on if B_i = 1, and off if B_i = 0. Determine if it is possible to achieve this task.InputThis problem has multiple test cases. The first line consists of an integer T (1 \leq T \leq 1000), which represents the number of test cases. Each test case consists of three lines.The first line of each test case consists of an integer N (3 \le N \le 200\,000). The sum of N over all test cases does not exceed 200\,000.The second line of each test case consists of a string A of length N. Each character of A can either be 0 or 1. The i-th character represents the initial state of lamp i.The third line of each test case consists of a string A of length N. Each character of B can either be 0 or 1. The i-th character represents the desired final state of lamp i.OutputFor each test case, output YES in a single line if the final state of all lamps can be reached after zero or more moves, or NO otherwise.ExamplesInput 2 4 0101 0100 3 000 010 Output YES NO Input 5 7 0101011 1111010 5 11111 00000 4 1101 1101 6 101010 100100 3 000 000 Output NO NO YES YES YES NoteExplanation for the sample input/output #1For the first test case, by pressing the buttons 4, 2, 4, 3, 1, 2 in sequence, the condition of the buttons changes as: 0101 \rightarrow 0111 \rightarrow 1101 \rightarrow 1111 \rightarrow 1010 \rightarrow 1110 \rightarrow 0100.For the second test case, you are unable to press any button, hence it is impossible to reach the final state.
2 4 0101 0100 3 000 010
YES NO
1 second
1024 megabytes
['bitmasks', 'constructive algorithms', 'hashing', '*2600']
A. Easy As ABCtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are playing a word puzzle. The puzzle starts with a 3 by 3 grid, where each cell contains either the letter A, B, or C.The goal of this puzzle is to find the lexicographically smallest possible word of length 3. The word can be formed by choosing three different cells where the cell containing the first letter is adjacent to the cell containing the second letter, and the cell containing the second letter is adjacent to the cell containing the third letter.Two cells are adjacent to each other if they share a border or a corner, as shown in the following illustration. Formally, if (r, c) denotes the cell in the r-th row and c-th column, then cell (r, c) is adjacent to cell (r, c + 1), (r - 1, c + 1), (r - 1, c), (r - 1, c - 1), (r, c - 1), (r + 1, c - 1), (r + 1, c), and (r + 1, c + 1). Determine the lexicographically smallest possible word of length 3 that you can find within the grid.A string s of length n is lexicographically smaller than string t of the same length if there exists an integer 1 \leq i \leq n such that s_j = t_j for all 1 \leq j < i, and s_i < t_i in alphabetical order. The following illustration shows some examples on some grids and their the lexicographically smallest possible word of length 3 that you can find within the grids. InputInput consists of three lines, each containing three letters, representing the puzzle grid. Each letter in the grid can only be either A, B, or C.OutputOutput the lexicographically smallest possible word of length 3 that you can find within the grid.ExamplesInput BCB CAC BCB Output ABC Input BCB CCC CCA Output ACB Input ACA CBC ACA Output ABA Input ACA CAC ACA Output AAA Input CCC CBC CCC Output BCC
BCB CAC BCB
ABC
1 second
1024 megabytes
['brute force', '*1000']
F. Field Should Not Be Emptytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^{\dagger} p of length n.We call index x good if for all y < x it holds that p_y < p_x and for all y > x it holds that p_y > p_x. We call f(p) the number of good indices in p. You can perform the following operation: pick 2 distinct indices i and j and swap elements p_i and p_j. Find the maximum value of f(p) after applying the aforementioned operation exactly once.^{\dagger}A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test consists of multiple test cases. The first line of contains a single integer t (1 \le t \le 2 \cdot 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the length of the permutation p.The second line of each test case contain n distinct integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — the elements of the permutation p.It is guaranteed that sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum value of f(p) after performing the operation exactly once.ExampleInput 551 2 3 4 552 1 3 4 572 1 5 3 7 6 462 3 5 4 1 677 6 5 4 3 2 1Output 3 5 2 3 2 NoteIn the first test case, p = [1,2,3,4,5] and f(p)=5 which is already maximum possible. But must perform the operation anyway. We can get f(p)=3 by choosing i=1 and j=2 which makes p = [2,1,3,4,5].In the second test case, we can transform p into [1,2,3,4,5] by choosing i=1 and j=2. Thus f(p)=5.
551 2 3 4 552 1 3 4 572 1 5 3 7 6 462 3 5 4 1 677 6 5 4 3 2 1
3 5 2 3 2
2 seconds
256 megabytes
['brute force', 'data structures', 'divide and conquer', '*2600']
E. One-Xtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputIn this sad world full of imperfections, ugly segment trees exist.A segment tree is a tree where each node represents a segment and has its number. A segment tree for an array of n elements can be built in a recursive manner. Let's say function \operatorname{build}(v,l,r) builds the segment tree rooted in the node with number v and it corresponds to the segment [l,r].Now let's define \operatorname{build}(v,l,r): If l=r, this node v is a leaf so we stop adding more edges Else, we add the edges (v, 2v) and (v, 2v+1). Let m=\lfloor \frac{l+r}{2} \rfloor. Then we call \operatorname{build}(2v,l,m) and \operatorname{build}(2v+1,m+1,r). So, the whole tree is built by calling \operatorname{build}(1,1,n).Now Ibti will construct a segment tree for an array with n elements. He wants to find the sum of \operatorname{lca}^\dagger(S), where S is a non-empty subset of leaves. Notice that there are exactly 2^n - 1 possible subsets. Since this sum can be very large, output it modulo 998\,244\,353.^\dagger\operatorname{lca}(S) is the number of the least common ancestor for the nodes that are in S.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^3) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^{18}) — the length of the array for which the segment tree is built.OutputFor each test case, output a single integer — the required sum modulo 998\,244\,353.ExampleInput 5234553278Output 6 17 36 69 593324855 Note In the first test case:Let's look at all subsets of leaves. \operatorname{lca}(\{2\})=2; \operatorname{lca}(\{3\})=3; \operatorname{lca}(\{2,3\})=1. Thus, the answer is 2+3+1=6.In the second test case:Let's look at all subsets of leaves. \operatorname{lca}(\{4\})=4; \operatorname{lca}(\{5\})=5; \operatorname{lca}(\{3\})=3; \operatorname{lca}(\{4,5\})=2; \operatorname{lca}(\{4,3\})=1; \operatorname{lca}(\{5,3\})=1; \operatorname{lca}(\{4,5,3\})=1; Thus, the answer is 4+5+3+2+1+1+1=17.
5234553278
6 17 36 69 593324855
3 seconds
512 megabytes
['combinatorics', 'dfs and similar', 'dp', 'math', 'trees', '*2400']
D. Cyclic MEXtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor an array a, define its cost as \sum_{i=1}^{n} \operatorname{mex} ^\dagger ([a_1,a_2,\ldots,a_i]).You are given a permutation^\ddagger p of the set \{0,1,2,\ldots,n-1\}. Find the maximum cost across all cyclic shifts of p.^\dagger\operatorname{mex}([b_1,b_2,\ldots,b_m]) is the smallest non-negative integer x such that x does not occur among b_1,b_2,\ldots,b_m.^\ddaggerA permutation of the set \{0,1,2,...,n-1\} is an array consisting of n distinct integers from 0 to n-1 in arbitrary order. For example, [1,2,0,4,3] is a permutation, but [0,1,1] is not a permutation (1 appears twice in the array), and [0,2,3] is also not a permutation (n=3 but there is 3 in the array).InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^6) — the length of the permutation p.The second line of each test case contain n distinct integers p_1, p_2, \ldots, p_n (0 \le p_i < n) — the elements of the permutation p.It is guaranteed that sum of n over all test cases does not exceed 10^6.OutputFor each test case, output a single integer — the maximum cost across all cyclic shifts of p.ExampleInput 465 4 3 2 1 032 1 082 3 6 7 0 1 4 510Output 15 5 31 1 NoteIn the first test case, the cyclic shift that yields the maximum cost is [2,1,0,5,4,3] with cost 0+0+3+3+3+6=15.In the second test case, the cyclic shift that yields the maximum cost is [0,2,1] with cost 1+1+3=5.
465 4 3 2 1 032 1 082 3 6 7 0 1 4 510
15 5 31 1
2 seconds
512 megabytes
['data structures', 'implementation', 'math', 'two pointers', '*2000']
C. Largest Subsequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven is a string s of length n. In one operation you can select the lexicographically largest^\dagger subsequence of string s and cyclic shift it to the right^\ddagger. Your task is to calculate the minimum number of operations it would take for s to become sorted, or report that it never reaches a sorted state.^\daggerA string a is lexicographically smaller than a 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 differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.^\ddaggerBy cyclic shifting the string t_1t_2\ldots t_m to the right, we get the string t_mt_1\ldots t_{m-1}.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the string s.The second line of each test case contains a single string s of length n, consisting of lowercase English letters.It is guaranteed that sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum number of operations required to make s sorted, or -1 if it's impossible.ExampleInput 65aaabc3acb3bac4zbca15czddeneeeemigec13cdefmopqsvxzzOutput 0 1 -1 2 6 0 NoteIn the first test case, the string s is already sorted, so we need no operations.In the second test case, doing one operation, we will select cb and cyclic shift it. The string s is now abc which is sorted.In the third test case, s cannot be sorted.In the fourth test case we will perform the following operations: The lexicographically largest subsequence is zca. Then s becomes abzc. The lexicographically largest subsequence is zc. Then s becomes abcz. The string becomes sorted.Thus, we need 2 operations.
65aaabc3acb3bac4zbca15czddeneeeemigec13cdefmopqsvxzz
0 1 -1 2 6 0
1 second
256 megabytes
['greedy', 'strings', '*1400']
B. Begginer's Zeldatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree^{\dagger}. In one zelda-operation you can do follows: Choose two vertices of the tree u and v; Compress all the vertices on the path from u to v into one vertex. In other words, all the vertices on path from u to v will be erased from the tree, a new vertex w will be created. Then every vertex s that had an edge to some vertex on the path from u to v will have an edge to the vertex w. Illustration of a zelda-operation performed for vertices 1 and 5. Determine the minimum number of zelda-operations required for the tree to have only one vertex.^{\dagger}A tree is a connected acyclic undirected graph.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^5) — the number of vertices.i-th of the next n − 1 lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \ne v_i) — the numbers of vertices connected by the i-th edge.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single integer — the minimum number of zelda-operations required for the tree to have only one vertex.ExampleInput 441 21 33 493 13 53 25 66 77 87 96 471 21 32 44 53 62 761 21 31 44 52 6Output 1 3 2 2 NoteIn the first test case, it's enough to perform one zelda-operation for vertices 2 and 4.In the second test case, we can perform the following zelda-operations: u = 2, v = 1. Let the resulting added vertex be labeled as w = 10; u = 4, v = 9. Let the resulting added vertex be labeled as w = 11; u = 8, v = 10. After this operation, the tree consists of a single vertex.
441 21 33 493 13 53 25 66 77 87 96 471 21 32 44 53 62 761 21 31 44 52 6
1 3 2 2
1 second
256 megabytes
['greedy', 'trees', '*1100']
A. Constructive Problemstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGridlandia has been hit by flooding and now has to reconstruct all of it's cities. Gridlandia can be described by an n \times m matrix.Initially, all of its cities are in economic collapse. The government can choose to rebuild certain cities. Additionally, any collapsed city which has at least one vertically neighboring rebuilt city and at least one horizontally neighboring rebuilt city can ask for aid from them and become rebuilt without help from the government. More formally, collapsed city positioned in (i, j) can become rebuilt if both of the following conditions are satisfied: At least one of cities with positions (i + 1, j) and (i - 1, j) is rebuilt; At least one of cities with positions (i, j + 1) and (i, j - 1) is rebuilt. If the city is located on the border of the matrix and has only one horizontally or vertically neighbouring city, then we consider only that city. Illustration of two possible ways cities can be rebuilt by adjacent aid. White cells are collapsed cities, yellow cells are initially rebuilt cities (either by the government or adjacent aid), and orange cells are rebuilt cities after adjacent aid. The government wants to know the minimum number of cities it has to rebuild such that after some time all the cities can be rebuild.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The only line of each test case contains two integers n and m (2 \le n, m \le 100) — the sizes of Gridlandia.OutputFor each test case, output a single integer — the minimum number of cities the government needs to rebuild.ExampleInput 32 25 73 2Output 2 7 3 NoteIn the first test case, it's enough for the government to rebuild cities (1, 2) and (2, 1).In the second test case, it's enough for the government to rebuild cities (1, 4), (2, 2), (3, 1), (3, 6), (4, 3), (5, 5), (5, 7).
32 25 73 2
2 7 3
1 second
256 megabytes
['constructive algorithms', 'math', '*800']
F. Beautiful Treetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLunchbox has a tree of size n rooted at node 1. Each node is then assigned a value. Lunchbox considers the tree to be beautiful if each value is distinct and ranges from 1 to n. In addition, a beautiful tree must also satisfy m requirements of 2 types: "1 a b c" — The node with the smallest value on the path between nodes a and b must be located at c. "2 a b c" — The node with the largest value on the path between nodes a and b must be located at c. Now, you must assign values to each node such that the resulting tree is beautiful. If it is impossible to do so, output -1.InputThe first line contains two integers n and m (2 \le n, m \le 2 \cdot 10^5).The next n - 1 lines contain two integers u and v (1 \le u, v \le n, u \ne v) — denoting an edge between nodes u and v. It is guaranteed that the given edges form a tree.The next m lines each contain four integers t, a, b, and c (t \in \{1,2\}, 1 \le a, b, c \le n). It is guaranteed that node c is on the path between nodes a and b.OutputIf it is impossible to assign values such that the tree is beautiful, output -1. Otherwise, output n integers, the i-th of which denotes the value of node i.ExamplesInput 7 5 1 2 1 3 1 4 3 5 4 6 3 7 1 6 5 1 2 6 7 3 1 2 7 1 1 7 5 7 2 4 2 2 Output 1 6 7 5 3 4 2 Input 2 2 1 2 1 1 2 1 1 1 2 2 Output -1
7 5 1 2 1 3 1 4 3 5 4 6 3 7 1 6 5 1 2 6 7 3 1 2 7 1 1 7 5 7 2 4 2 2
1 6 7 5 3 4 2
4 seconds
512 megabytes
['data structures', 'dfs and similar', 'graphs', 'implementation', 'trees', '*2800']
E. Tree Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThose who don't work don't eat. Get the things you want with your own power. But believe, the earnest and serious people are the ones who have the last laugh... But even then, I won't give you a present.—Santa, Hayate no Gotoku!Since Hayate didn't get any Christmas presents from Santa, he is instead left solving a tree query problem.Hayate has a tree with n nodes.Hayate now wants you to answer q queries. Each query consists of a node x and k other additional nodes a_1,a_2,\ldots,a_k. These k+1 nodes are guaranteed to be all distinct.For each query, you must find the length of the longest simple path starting at node x^\dagger after removing nodes a_1,a_2,\ldots,a_k along with all edges connected to at least one of nodes a_1,a_2,\ldots,a_k.^\dagger A simple path of length k starting at node x is a sequence of distinct nodes x=u_0,u_1,\ldots,u_k such that there exists a edge between nodes u_{i-1} and u_i for all 1 \leq i \leq k.InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the number of nodes of the tree and the number of queries.The following n - 1 lines contain two integers u and v (1 \le u, v \le n, u \ne v) — denoting an edge between nodes u and v. It is guaranteed that the given edges form a tree.The following q lines describe the queries. Each line contains the integers x, k and a_1,a_2,\ldots,a_k (1 \leq x \leq n, 0 \leq k < n, 1 \leq a_i \leq n) — the starting node, the number of removed nodes and the removed nodes.It is guaranteed that for each query, x,a_1,a_2,\ldots,a_k are all distinct.It is guaranteed that the sum of k over all queries will not exceed 2 \cdot 10^5.OutputFor each query, output a single integer denoting the answer for that query.ExamplesInput 7 7 1 2 1 3 3 4 2 5 2 6 6 7 2 0 2 1 1 2 2 1 6 3 1 4 3 1 1 5 0 5 2 1 6 Output 3 2 1 4 1 4 1 Input 4 4 1 2 1 3 2 4 2 1 3 3 1 4 2 1 4 2 3 1 3 4 Output 1 2 2 0 NoteIn the first example, the tree is as follows: In the first query, no nodes are missing. The longest simple path starting from node 2 is 2 \to 1 \to 3 \to 4. Thus, the answer is 3.In the third query, nodes 1 and 6 are missing and the tree is shown below. The longest simple path starting from node 2 is 2 \to 5. Thus, the answer is 1.
7 7 1 2 1 3 3 4 2 5 2 6 6 7 2 0 2 1 1 2 2 1 6 3 1 4 3 1 1 5 0 5 2 1 6
3 2 1 4 1 4 1
4 seconds
512 megabytes
['data structures', 'dfs and similar', 'graphs', 'implementation', 'trees', '*2500']
D2. Set To Max (Hard Version)time limit per test4 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 n and the time limit. You can make hacks only if all versions of the problem are solved.You are given two arrays a and b of length n.You can perform the following operation some (possibly zero) times: choose l and r such that 1 \leq l \leq r \leq n. let x=\max(a_l,a_{l+1},\ldots,a_r). for all l \leq i \leq r, set a_i := x. Determine if you can make array a equal to array b.InputEach test contains multiple test cases. The first line contains an 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 length of the arrays.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of array a.The third line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n) — the elements of array b.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" (without quotes) if you can make a into b using any number of operations, and "NO" (without quotes) otherwise.You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).ExampleInput 551 2 3 2 41 3 3 2 453 4 2 2 43 4 3 4 453 2 1 1 13 3 3 2 221 11 231 1 22 1 2Output YES NO YES NO NO NoteIn the first test case, we can achieve array b by applying a single operation: (l,r)=(2,3).In the second test case, it can be shown we cannot achieve array b in any amount of operations.In the third test case, we can achieve array b by applying two operations: (l,r)=(2,5). followed by (l,r)=(1,3).In the fourth and fifth test cases, it can be shown we cannot achieve array b in any amount of operations.
551 2 3 2 41 3 3 2 453 4 2 2 43 4 3 4 453 2 1 1 13 3 3 2 221 11 231 1 22 1 2
YES NO YES NO NO
4 seconds
256 megabytes
['constructive algorithms', 'data structures', 'divide and conquer', 'greedy', 'implementation', 'sortings', '*1800']
D1. Set To Max (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 n and the time limit. You can make hacks only if all versions of the problem are solved.You are given two arrays a and b of length n.You can perform the following operation some (possibly zero) times: choose l and r such that 1 \leq l \leq r \leq n. let x=\max(a_l,a_{l+1},\ldots,a_r). for all l \leq i \leq r, set a_i := x. Determine if you can make array a equal to array b.InputEach test contains multiple test cases. The first line contains an 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 1000) — the length of the arrays.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of array a.The third line contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le n) — the elements of array b.It is guaranteed that the sum of n^2 over all test cases does not exceed 10^6.OutputFor each test case, output "YES" (without quotes) if you can make a into b using any number of operations, and "NO" (without quotes) otherwise.You can output "YES" and "NO" in any case (for example, strings "yES", "yes" and "Yes" will be recognized as a positive response).ExampleInput 551 2 3 2 41 3 3 2 453 4 2 2 43 4 3 4 453 2 1 1 13 3 3 2 221 11 231 1 22 1 2Output YES NO YES NO NO NoteIn the first test case, we can achieve array b by applying a single operation: (l,r)=(2,3).In the second test case, it can be shown we cannot achieve array b in any amount of operations.In the third test case, we can achieve array b by applying two operations: (l,r)=(2,5). followed by (l,r)=(1,3).In the fourth and fifth test cases, it can be shown we cannot achieve array b in any amount of operations.
551 2 3 2 41 3 3 2 453 4 2 2 43 4 3 4 453 2 1 1 13 3 3 2 221 11 231 1 22 1 2
YES NO YES NO NO
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*1600']
C. Array Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n positive integers. In one operation, you must pick some (i, j) such that 1\leq i < j\leq |a| and append |a_i - a_j| to the end of the a (i.e. increase n by 1 and set a_n to |a_i - a_j|). Your task is to minimize and print the minimum value of a after performing k operations.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (2\le n\le 2\cdot 10^3, 1\le k\le 10^9) — the length of the array and the number of operations you should perform.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1\le a_i\le 10^{18}) — the elements of the array a.It is guaranteed that the sum of n^2 over all test cases does not exceed 4\cdot 10^6.OutputFor each test case, print a single integer — the smallest possible value of the minimum of array a after performing k operations.ExampleInput 45 23 9 7 15 14 37 4 15 126 242 47 50 54 62 792 1500000000000000000 1000000000000000000Output 1 0 3 500000000000000000 NoteIn the first test case, after any k=2 operations, the minimum value of a will be 1.In the second test case, an optimal strategy is to first pick i=1, j=2 and append |a_1 - a_2| = 3 to the end of a, creating a=[7, 4, 15, 12, 3]. Then, pick i=3, j=4 and append |a_3 - a_4| = 3 to the end of a, creating a=[7, 4, 15, 12, 3, 3]. In the final operation, pick i=5, j=6 and append |a_5 - a_6| = 0 to the end of a. Then the minimum value of a will be 0.In the third test case, an optimal strategy is to first pick i=2, j=3 to append |a_2 - a_3| = 3 to the end of a. Any second operation will still not make the minimum value of a be less than 3.
45 23 9 7 15 14 37 4 15 126 242 47 50 54 62 792 1500000000000000000 1000000000000000000
1 0 3 500000000000000000
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'sortings', 'two pointers', '*1400']
B. Collecting Gametime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n positive integers and a score. If your score is greater than or equal to a_i, then you can increase your score by a_i and remove a_i from the array. For each index i, output the maximum number of additional array elements that you can remove if you remove a_i and then set your score to a_i. Note that the removal of a_i should not be counted in the answer.InputEach test contains multiple test cases. The first line contains an 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 a single integer n (1 \le n \le 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the elements of the array.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 i-th of which denotes the maximum number of additional array elements that you can remove if you remove a_i from the array and then set your score to a_i.ExampleInput 4520 5 1 4 231434 7 1442115999999999 999999999 999999999 1000000000 1000000000Output 4 3 0 3 1 1 0 2 0 4 4 4 4 4 NoteIn the first test case, the answers are as follows:If we start with i=4, our initial score is a_4=4 and a=[20,5,1,2]. We can remove 3 additional elements in the following order: Since 4 \ge 1, we can remove 1 and our score becomes 5. After this, a=[20,5,2]. Since 5 \ge 5, we can remove 5 and our score becomes 10. After this, a=[20,2]. Since 10 \ge 2, we can remove 2 and our score becomes 12. After this, a=[20]. If we start with i=1 we can remove all remaining elements in the array, so the answer is 4.If we start with i=2, we can remove 3 additional elements in the following order: 1, 4, 2.If we start with i=3, we can remove no additional elements.If we start with i=5, we can remove 1 additional element: 1.
4520 5 1 4 231434 7 1442115999999999 999999999 999999999 1000000000 1000000000
4 3 0 3 1 1 0 2 0 4 4 4 4 4
1 second
256 megabytes
['binary search', 'dp', 'greedy', 'sortings', 'two pointers', '*1100']
A. Forked!time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLunchbox is done with playing chess! His queen and king just got forked again!In chess, a fork is when a knight attacks two pieces of higher value, commonly the king and the queen. Lunchbox knows that knights can be tricky, and in the version of chess that he is playing, knights are even trickier: instead of moving 1 tile in one direction and 2 tiles in the other, knights in Lunchbox's modified game move a tiles in one direction and b tiles in the other.Lunchbox is playing chess on an infinite chessboard which contains all cells (x,y) where x and y are (possibly negative) integers. Lunchbox's king and queen are placed on cells (x_K,y_K) and (x_Q,y_Q) respectively. Find the number of positions such that if a knight was placed on that cell, it would attack both the king and queen.InputEach test contains multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers a and b (1 \le a, b \le 10^8) — describing the possible moves of the knight.The second line of each test case contains two integers x_K and y_K (0 \le x_K, y_K \le 10^8) — the position of Lunchbox's king. The third line in a test case contains x_Q and y_Q (0 \le x_Q, y_Q \le 10^8) — the position of Lunchbox's queen.It is guaranteed that Lunchbox's queen and king will occupy different cells. That is, (x_K,y_K) \neq (x_Q,y_Q).OutputFor each test case, output the number of positions on an infinite chessboard such that a knight can attack both the king and the queen. ExampleInput 42 10 03 31 13 11 34 40 08 04 21 43 4Output 2 1 2 0 NoteIn the first test case, the knight can move 2 squares in one direction and 1 square in the other (it is essentially the same as the knight in standard chess). A knight placed on (2, 1) or (1, 2) would attack both the king and queen. Example of a knight placement that forks the queen and king in the first test case. The squares that the knight attacks are highlighted in red. In the second test case, a knight placed on (2, 2) would attack both the king and queen. Example of a knight placement that does not fork the queen and king in the second test case. The knight attacks the king but not the queen. In the third test case, a knight placed on (4, 4) or (4, -4) would attack both the king and queen. In the fourth test case, there are no positions where the knight can attack both the king and the queen.(Credits to EnDeRBeaT for the nice images)
42 10 03 31 13 11 34 40 08 04 21 43 4
2 1 2 0
2 seconds
256 megabytes
['brute force', 'implementation', '*900']
F. Babysittingtime limit per test7 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis wants to play video games, however he should also take care of his sister. Since Theofanis is a CS major, he found a way to do both. He will install some cameras in his house in order to make sure his sister is okay.His house is an undirected graph with n nodes and m edges. His sister likes to play at the edges of the graph, so he has to install a camera to at least one endpoint of every edge of the graph. Theofanis wants to find a vertex cover that maximizes the minimum difference between indices of the chosen nodes.More formally, let a_1, a_2, \ldots, a_k be a vertex cover of the graph. Let the minimum difference between indices of the chosen nodes be the minimum \lvert a_i - a_j \rvert (where i \neq j) out of the nodes that you chose. If k = 1 then we assume that the minimum difference between indices of the chosen nodes is n. Can you find the maximum possible minimum difference between indices of the chosen nodes over all vertex covers?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 m (1 \le n \le 10^{5}, 1 \le m \le 2 \cdot 10^{5}) — the number of nodes and the number of edges. The i-th of the following m lines in the test case contains two positive integers u_i and v_i (1 \le u_i,v_i \le n), meaning that there exists an edge between them in the graph. It is guaranteed that the sum of n over all test cases does not exceed 10^{5}.It is guaranteed that the sum of m over all test cases does not exceed 2 \cdot 10^{5}.OutputFor each test case, print the maximum minimum difference between indices of the chosen nodes over all vertex covers.ExampleInput 37 61 21 31 41 62 35 73 31 21 31 12 41 21 22 11 1Output 2 3 2 NoteIn the first test case, we can install cameras at nodes 1, 3, and 7, so the answer is 2. In the second test case, we can install only one camera at node 1, so the answer is 3.
37 61 21 31 41 62 35 73 31 21 31 12 41 21 22 11 1
2 3 2
7 seconds
256 megabytes
['2-sat', 'binary search', 'data structures', 'graphs', 'trees', '*2500']
E. Geo Gametime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.Theofanis and his sister are playing the following game. They have n points in a 2D plane and a starting point (s_x,s_y). Each player (starting from the first player) chooses one of the n points that wasn't chosen before and adds to the sum (which is initially 0) the square of the Euclidean distance from the previous point (which is either the starting point or it was chosen by the other person) to the new point (that the current player selected).The game ends after exactly n moves (after all the points are chosen). The first player wins if the sum is even in the end. Otherwise, the second player wins.Theofanis is a very competitive person and he hates losing. Thus, he wants to choose whether he should play first or second. Can you show him, which player to choose, and how he should play to beat his sister?InputThe first line contains a single integer t (1 \le t \le 2000) — the number of test cases.The data for each test case is only available after the end of the interaction (the end of the game) for all previous test cases.The first line of each test case contains a single integer n (1 \le n \le 10^{5}) — the number of points.The second line of each test case contains two integers s_x, s_y (0 \le s_x, s_y \le 10^{9}) — the coordinates of the starting point. Two or more points may have the same coordinates.The i-th of the following n lines contains two integers x_i and y_i (0 \le x_i, y_i \le 10^{9}) — the coordinates of the i-th point.It is guaranteed that the sum of n over all test cases does not exceed 10^{5}.InteractionFor each test case, you should first output the player that you want to play as (First or Second).Then, you should play the game. When it's your turn, you should output the index j (1 \le j \le n) of the point that you want to choose, and when it's the other player's turn, you should read the index that they choose. When all the turns are done, continue with reading the input for the next test case, or finish the program, if there are none.If you receive the integer -1 instead of an index or a valid value of n, it means your program has made an invalid move or has lost the game in the previous test case. Your program must terminate immediately to receive a Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a choice for a player, or a turn, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. HacksTo hack, use the following format.The first line contains a single integer t (1 \le t \le 2000) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 10^{5}) — the number of points.The second line of each test case contains two integers s_x, s_y (0 \le s_x, s_y \le 10^{9}) — the coordinates of the starting point.The i-th of the following n lines contains two integers x_i and y_i (0 \le x_i, y_i \le 10^{9}) — the coordinates of the i-th point.The sum of n over all test cases should not exceed 10^{5}.ExampleInput 2 6 4 6 7 6 8 5 2 1 6 2 6 4 3 3 2 5 1 4 1 1 3 2 2 1 3 3 1 2 2 3 Output Second 4 6 3 First 1 4 NoteThe examples above do not necessarily showcase optimal strategies or the correct player to choose.In the picture below, you can see the moves that each player made in the first example. The first player is red, and the second player is black.
2 6 4 6 7 6 8 5 2 1 6 2 6 4 3 3 2 5 1 4 1 1 3 2 2 1 3 3 1 2 2 3
Second 4 6 3 First 1 4
2.5 seconds
256 megabytes
['greedy', 'interactive', 'math', '*2000']
D2. Maximum And Queries (hard version)time limit per test7 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 n and q, the memory and time limits. You can make hacks only if all versions of the problem are solved.Theofanis really likes to play with the bits of numbers. He has an array a of size n and an integer k. He can make at most k operations in the array. In each operation, he picks a single element and increases it by 1.He found the maximum bitwise AND that array a can have after at most k operations.Theofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of k.Help Theofanis by calculating the maximum possible bitwise AND for q different values of k. Note that queries are independent.InputThe first line contains two integers n and q (1 \le n, q \le 10^6) — the size of the array and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6) — the elements of the array.Next q lines describe the queries. The i-th line contains one integer k_i (0 \le k_i \le 10^{18}) — the number of operations that can be done in the i-th query.OutputFor each query, print one integer — the maximum bitwise AND that array a can have after at most k_i operations.ExamplesInput 4 21 3 7 5210Output 2 6 Input 3 54 0 2981713Output 5 4 7 0 1 Input 1 21052318381298321Output 15 2318381298331 NoteIn the first test case, in the first query, we add 1 in the first and last elements of the array. Thus, the array becomes [2,3,7,6] with bitwise AND equal to 2.In the second test case, in the first query, we add 1 in the first element, 5 in the second, and 3 in the third and now all the elements are equal to 5.
4 21 3 7 5210
2 6
7 seconds
512 megabytes
['bitmasks', 'divide and conquer', 'dp', 'greedy', '*2500']
D1. Maximum And Queries (easy version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on n and q, the memory and time limits. You can make hacks only if all versions of the problem are solved.Theofanis really likes to play with the bits of numbers. He has an array a of size n and an integer k. He can make at most k operations in the array. In each operation, he picks a single element and increases it by 1.He found the maximum bitwise AND that array a can have after at most k operations.Theofanis has put a lot of work into finding this value and was very happy with his result. Unfortunately, Adaś, being the evil person that he is, decided to bully him by repeatedly changing the value of k.Help Theofanis by calculating the maximum possible bitwise AND for q different values of k. Note that queries are independent.InputThe first line contains two integers n and q (1 \le n, q \le 10^5 and n \cdot q \le 10^5) — the size of the array and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^6) — the elements of the array.Next q lines describe the queries. The i-th line contains one integer k_i (0 \le k_i \le 10^{18}) — the number of operations that can be done in the i-th query.OutputFor each query, print one integer — the maximum bitwise AND that array a can have after at most k_i operations.ExamplesInput 4 2 1 3 7 5 2 10 Output 2 6 Input 3 5 4 0 2 9 8 17 1 3 Output 5 4 7 0 1 Input 1 2 10 5 2318381298321 Output 15 2318381298331 NoteIn the first test case, in the first query, we add 1 in the first and last elements of the array. Thus, the array becomes [2,3,7,6] with bitwise AND equal to 2.In the second test case, in the first query, we add 1 in the first element, 5 in the second, and 3 in the third and now all the elements are equal to 5.
4 2 1 3 7 5 2 10
2 6
2 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'greedy', '*1700']
C. Theofanis' Nightmaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis easily gets obsessed with problems before going to sleep and often has nightmares about them. To deal with his obsession he visited his doctor, Dr. Emix.In his latest nightmare, he has an array a of size n and wants to divide it into non-empty subarrays^{\dagger} such that every element is in exactly one of the subarrays.For example, the array [1,-3,7,-6,2,5] can be divided to [1] [-3,7] [-6,2] [5]. The Cypriot value of such division is equal to \Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i where k is the number of subarrays that we divided the array into and \mathrm{sum}_i is the sum of the i-th subarray.The Cypriot value of this division of the array [1] [-3,7] [-6,2] [5] = 1 \cdot 1 + 2 \cdot (-3 + 7) + 3 \cdot (-6 + 2) + 4 \cdot 5 = 17. Theofanis is wondering what is the maximum Cypriot value of any division of the array.^{\dagger} An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of two lines. 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 (-10^8 \le a_i \le 10^{8}) — 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, print one integer — the maximum Cypriot value of the array a.ExampleInput 461 -3 7 -6 2 542 9 -5 -38-3 -4 2 -5 1 10 17 231830Output 32 4 343 830 NoteIn the first test case, to get the maximum Cypriot value we divide the array into [1][-3][7][-6][2][5] which gives us: \Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 1 + 2 \cdot (-3) + 3 \cdot 7 + 4 \cdot (-6) + 5 \cdot 2 + 6 \cdot 5 = 32Similarly, in the second test case we divide the array into [2][9,-5,-3] which gives us \Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 2 + 2 \cdot (9 + (-5) + (-3)) = 4.
461 -3 7 -6 2 542 9 -5 -38-3 -4 2 -5 1 10 17 231830
32 4 343 830
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1400']
B. StORage roomtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn Cyprus, the weather is pretty hot. Thus, Theofanis saw this as an opportunity to create an ice cream company. He keeps the ice cream safe from other ice cream producers by locking it inside big storage rooms. However, he forgot the password. Luckily, the lock has a special feature for forgetful people! It gives you a table M with n rows and n columns of non-negative integers, and to open the lock, you need to find an array a of n elements such that: 0 \le a_i < 2^{30}, and M_{i,j} = a_i | a_j for all i \neq j, where | denotes the bitwise OR operation. The lock has a bug, and sometimes it gives tables without any solutions. In that case, the ice cream will remain frozen for the rest of eternity.Can you find an array to open the lock? 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 a single integer n (1 \le n \le 10^{3}) — the size of the hidden array.The next n lines describe the rows of M, line i contains the table values M_{i,1}, M_{i,2}, \ldots, M_{i,n} (0 \le M_{i,j} < 2^{30}).It is guaranteed that M_{i,i} = 0 and M_{i,j} = M_{j,i} for all 1 \le i,j \le n.It is also guaranteed that the sum of n over all test cases does not exceed 10^{3}.OutputFor each test case, if there is a solution print YES and an array that satisfies the property, otherwise print NO.If there are multiple solutions, print any of them.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 41040 3 3 53 0 3 73 3 0 75 7 7 050 7 7 5 57 0 3 2 67 3 0 3 75 2 3 0 45 6 7 4 030 0 10 0 01 0 0Output YES 7 YES 1 3 2 5 YES 5 2 3 0 4 NO
41040 3 3 53 0 3 73 3 0 75 7 7 050 7 7 5 57 0 3 2 67 3 0 3 75 2 3 0 45 6 7 4 030 0 10 0 01 0 0
YES 7 YES 1 3 2 5 YES 5 2 3 0 4 NO
2 seconds
256 megabytes
['bitmasks', 'brute force', 'constructive algorithms', 'greedy', '*1200']
A. Halloumi Boxestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTheofanis is busy after his last contest, as now, he has to deliver many halloumis all over the world. He stored them inside n boxes and each of which has some number a_i written on it. He wants to sort them in non-decreasing order based on their number, however, his machine works in a strange way. It can only reverse any subarray^{\dagger} of boxes with length at most k.Find if it's possible to sort the boxes using any number of reverses.^{\dagger} Reversing a subarray means choosing two indices i and j (where 1 \le i \le j \le n) and changing the array a_1, a_2, \ldots, a_n to a_1, a_2, \ldots, a_{i-1}, \; a_j, a_{j-1}, \ldots, a_i, \; a_{j+1}, \ldots, a_{n-1}, a_n. The length of the subarray is then j - i + 1.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.Each test case consists of two lines. The first line of each test case contains two integers n and k (1 \le k \le n \le 100) — the number of boxes and the length of the maximum reverse that Theofanis can make. The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{9}) — the number written on each box.OutputFor each test case, print YES (case-insensitive), if the array can be sorted in non-decreasing order, or NO (case-insensitive) otherwise.ExampleInput 53 21 2 33 19 9 94 46 4 2 14 310 3 830 142 13 1Output YES YES YES YES NO NoteIn the first two test cases, the boxes are already sorted in non-decreasing order.In the third test case, we can reverse the whole array.In the fourth test case, we can reverse the first two boxes and the last two boxes.In the fifth test case, it can be shown that it's impossible to sort the boxes.
53 21 2 33 19 9 94 46 4 2 14 310 3 830 142 13 1
YES YES YES YES NO
1 second
256 megabytes
['brute force', 'greedy', 'sortings', '*800']
F. Trees and XOR Queries Againtime limit per test6.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. There is an integer written on each vertex; the i-th vertex has integer a_i written on it.You have to process q queries. The i-th query consists of three integers x_i, y_i and k_i. For this query, you have to answer if it is possible to choose a set of vertices v_1, v_2, \dots, v_m (possibly empty) such that: every vertex v_j is on the simple path between x_i and y_i (endpoints can be used as well); a_{v_1} \oplus a_{v_2} \oplus \dots \oplus a_{v_m} = k_i, where \oplus denotes the bitwise XOR operator. 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 (0 \le a_i \le 2^{20} - 1).Then n-1 lines follow. Each of them contains two integers u and v (1 \le u, v \le n; u \ne v) denoting an edge of the tree.The next line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow. The i-th of them contains three integers x_i, y_i and k_i (1 \le x_i, y_i \le n; 0 \le k_i \le 2^{20} - 1).OutputFor each query, print YES if it is possible to form a set of vertices meeting the constraints. Otherwise, print NO.You can print each letter in any case.ExampleInput 40 1 2 102 13 24 283 3 03 4 13 4 71 3 11 3 21 3 101 4 101 4 11Output YES YES NO YES YES NO YES YES
40 1 2 102 13 24 283 3 03 4 13 4 71 3 11 3 21 3 101 4 101 4 11
YES YES NO YES YES NO YES YES
6.5 seconds
512 megabytes
['data structures', 'dfs and similar', 'divide and conquer', 'graphs', 'implementation', 'math', 'trees', '*2400']
E. Collapsing Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n strings s_1, s_2, \dots, s_n, consisting of lowercase Latin letters. Let |x| be the length of string x.Let a collapse C(a, b) of two strings a and b be the following operation: if a is empty, C(a, b) = b; if b is empty, C(a, b) = a; if the last letter of a is equal to the first letter of b, then C(a, b) = C(a_{1,|a|-1}, b_{2,|b|}), where s_{l,r} is the substring of s from the l-th letter to the r-th one; otherwise, C(a, b) = a + b, i. e. the concatenation of two strings. Calculate \sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|.InputThe first line contains a single integer n (1 \le n \le 10^6).Each of the next n lines contains a string s_i (1 \le |s_i| \le 10^6), consisting of lowercase Latin letters.The total length of the strings doesn't exceed 10^6.OutputPrint a single integer — \sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|.ExamplesInput 3abaabbaOutput 20 Input 5ababbabxxabxbababOutput 126
3abaabba
20
2 seconds
256 megabytes
['data structures', 'strings', 'trees', '*1900']
D. Robot Queriestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an infinite 2-dimensional grid. Initially, a robot stands in the point (0, 0). The robot can execute four commands: U — move from point (x, y) to (x, y + 1); D — move from point (x, y) to (x, y - 1); L — move from point (x, y) to (x - 1, y); R — move from point (x, y) to (x + 1, y). You are given a sequence of commands s of length n. Your task is to answer q independent queries: given four integers x, y, l and r; determine whether the robot visits the point (x, y), while executing a sequence s, but the substring from l to r is reversed (i. e. the robot performs commands in order s_1 s_2 s_3 \dots s_{l-1} s_r s_{r-1} s_{r-2} \dots s_l s_{r+1} s_{r+2} \dots s_n).InputThe first line contains two integers n and q (1 \le n, q \le 2 \cdot 10^5) — the length of the command sequence and the number of queries, respectively.The second line contains a string s of length n, consisting of characters U, D, L and/or R.Then q lines follow, the i-th of them contains four integers x_i, y_i, l_i and r_i (-n \le x_i, y_i \le n; 1 \le l \le r \le n) describing the i-th query.OutputFor each query, print YES if the robot visits the point (x, y), while executing a sequence s, but the substring from l to r is reversed; otherwise print NO.ExamplesInput 8 3RDLLUURU-1 2 1 70 0 3 40 1 7 8Output YES YES NO Input 4 2RLDU0 0 2 2-1 -1 2 3Output YES NO Input 10 6DLUDLRULLD-1 0 1 10-1 -2 2 5-4 -2 6 10-1 0 3 90 1 4 7-3 -1 5 8Output YES YES YES NO YES YES NoteIn the first query of the first sample, the path of the robot looks as follows: In the second query of the first sample, the path of the robot looks as follows: In the third query of the first sample, the path of the robot looks as follows:
8 3RDLLUURU-1 2 1 70 0 3 40 1 7 8
YES YES NO
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'implementation', '*1900']
C. Insert and Equalizetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \dots, a_n, all its elements are distinct.First, you are asked to insert one more integer a_{n+1} into this array. a_{n+1} should not be equal to any of a_1, a_2, \dots, a_n.Then, you will have to make all elements of the array equal. At the start, you choose a positive integer x (x > 0). In one operation, you add x to exactly one element of the array. Note that x is the same for all operations.What's the smallest number of operations it can take you to make all elements equal, after you choose a_{n+1} and x?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 (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). All a_i are distinct.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print a single integer — the smallest number of operations it can take you to make all elements equal, after you choose integers a_{n+1} and x.ExampleInput 331 2 351 -19 17 -3 -15110Output 6 27 1 NoteIn the first testcase, you can choose a_{n+1} = 4, the array becomes [1, 2, 3, 4]. Then choose x = 1 and apply the operation 3 times to the first element, 2 times to the second element, 1 time to the third element and 0 times to the fourth element.In the second testcase, you can choose a_{n+1} = 13, x = 4.In the third testcase, you can choose a_{n+1} = 9, x = 1. Then apply the operation once to a_{n+1}.
331 2 351 -19 17 -3 -15110
6 27 1
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', 'math', 'number theory', '*1300']
B. Getting Pointstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is a student at Berland State University. Due to recent changes in the Berland education system, Monocarp has to study only one subject — programming.The academic term consists of n days, and in order not to get expelled, Monocarp has to earn at least P points during those n days. There are two ways to earn points — completing practical tasks and attending lessons. For each practical task Monocarp fulfills, he earns t points, and for each lesson he attends, he earns l points.Practical tasks are unlocked "each week" as the term goes on: the first task is unlocked on day 1 (and can be completed on any day from 1 to n), the second task is unlocked on day 8 (and can be completed on any day from 8 to n), the third task is unlocked on day 15, and so on.Every day from 1 to n, there is a lesson which can be attended by Monocarp. And every day, Monocarp chooses whether to study or to rest the whole day. When Monocarp decides to study, he attends a lesson and can complete no more than 2 tasks, which are already unlocked and not completed yet. If Monocarp rests the whole day, he skips a lesson and ignores tasks.Monocarp wants to have as many days off as possible, i. e. he wants to maximize the number of days he rests. Help him calculate the maximum number of days he can rest!InputThe first line contains a single integer tc (1 \le tc \le 10^4) — the number of test cases. The description of the test cases follows.The only line of each test case contains four integers n, P, l and t (1 \le n, l, t \le 10^9; 1 \le P \le 10^{18}) — the number of days, the minimum total points Monocarp has to earn, the points for attending one lesson and points for completing one task.It's guaranteed for each test case that it's possible not to be expelled if Monocarp will attend all lessons and will complete all tasks.OutputFor each test, print one integer — the maximum number of days Monocarp can rest without being expelled from University.ExampleInput 51 5 5 214 3000000000 1000000000 500000000100 20 1 108 120 10 2042 280 13 37Output 0 12 99 0 37 NoteIn the first test case, the term lasts for 1 day, so Monocarp should attend at day 1. Since attending one lesson already gives 5 points (5 \ge P), so it doesn't matter, will Monocarp complete the task or not.In the second test case, Monocarp can, for example, study at days 8 and 9: at day 8 he will attend a lesson for 10^9 points and complete two tasks for another 5 \cdot 10^8 + 5 \cdot 10^8 points. And at day 9 he only attends a lesson for another 10^9 points.In the third test case, Monocarp can, for example, study at day 42: attending a lesson gives him 1 point and solving 2 out of 6 available tasks gives him another 2 \cdot 10 points.In the fourth test case, Monocarp has to attend all lessons and complete all tasks to get 8 \cdot 10 + 2 \cdot 20 = 120 points.In the fifth test case, Monocarp can, for example, study at days: 8 — one lesson and first and second tasks; 15 — one lesson and the third task; 22 — one lesson and the fourth task; 29 — one lesson and the fifth task; 36 — one lesson and the sixth task.
51 5 5 214 3000000000 1000000000 500000000100 20 1 108 120 10 2042 280 13 37
0 12 99 0 37
1 second
256 megabytes
['binary search', 'brute force', 'greedy', '*1100']
A. Binary Imbalancetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting only of characters '0' and/or '1'.In one operation, you choose a position i from 1 to |s| - 1, where |s| is the current length of string s. Then you insert a character between the i-th and the (i+1)-st characters of s. If s_i = s_{i+1}, you insert '1'. If s_i \neq s_{i+1}, you insert '0'.Is it possible to make the number of zeroes in the string strictly greater than the number of ones, using any number of operations (possibly, none)?InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.The first line of each testcase contains an integer n (1 \le n \le 100).The second line contains a string s of length exactly n, consisting only of characters '0' and/or '1'.OutputFor each testcase, print "YES" if it's possible to make the number of zeroes in s strictly greater than the number of ones, using any number of operations (possibly, none). Otherwise, print "NO".ExampleInput 3200211210Output YES NO YES NoteIn the first testcase, the number of zeroes is already greater than the number of ones.In the second testcase, it's impossible to insert any zeroes in the string.In the third testcase, you can choose i = 1 to insert a zero between the 1-st and the 2-nd characters. Since s_1 \neq s_2, you insert a '0'. The resulting string is "100". It has two zeroes and only a single one, so the answer is "YES".
3200211210
YES NO YES
2 seconds
256 megabytes
['constructive algorithms', '*800']
F. Landscapingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are appointed to a very important task: you are in charge of flattening one specific road.The road can be represented as a polygonal line starting at (0, 0), ending at (n - 1, 0) and consisting of n vertices (including starting and ending points). The coordinates of the i-th vertex of the polyline are (i, a_i)."Flattening" road is equivalent to choosing some line segment from (0, y_0) to (n - 1, y_1) such that all points of the polyline are below the chosen segment (or on the same height). Values y_0 and y_1 may be real.You can imagine that the road has some dips and pits, and you start pouring pavement onto it until you make the road flat. Points 0 and n - 1 have infinitely high walls, so pavement doesn't fall out of segment [0, n - 1]. The cost of flattening the road is equal to the area between the chosen segment and the polyline. You want to minimize the cost, that's why the flattened road is not necessary horizontal.But there is a problem: your data may be too old, so you sent a person to measure new heights. The person goes from 0 to n - 1 and sends you new heights b_i of each vertex i of the polyline.Since measuring new heights may take a while, and you don't know when you'll be asked, calculate the minimum cost (and corresponding y_0 and y_1) to flatten the road after each new height b_i you get.InputThe first line contains a single integer n (3 \le n \le 2 \cdot 10^5) — the number of vertices of the polyline.The second line contains n integers a_0, a_1, \dots, a_{n - 1} (0 \le a_i \le 10^9; a_0 = a_{n - 1} = 0) — the heights of the corresponding vertices.The third line contains n integers b_0, b_1, \dots, b_{n - 1} (0 \le b_i \le 10^9; b_0 = b_{n - 1} = 0) — the new heights of the corresponding vertices.OutputPrint n numbers: as the i-th number (0-indexed) print y_0 + y_1 of the "best segment" (i. e. the sum of coordinates of the segment that gives the minimum cost) if you already know actual heights b_0, \dots, b_i.If there are several "best segments", print the minimum possible y_0 + y_1 among them.Your answer is considered correct if its absolute or relative error does not exceed 10^{-9}.Formally, let your answer be x, and the jury's answer be y. Your answer is accepted if and only if \frac{|x - y|}{\max{(1, |y|)}} \le 10^{-9}.ExamplesInput 50 5 1 3 00 1 3 2 0Output 8.000000000000 4.000000000000 6.000000000000 6.000000000000 6.000000000000 Input 60 4 1 3 3 00 1 4 0 1 0Output 7.000000000000 5.000000000000 7.500000000000 7.500000000000 6.666666666667 6.666666666667 NoteThe first answer in the first example is shown on the picture above.You can achieve the second answer with the following "best segment": You can achieve the third answer using the following "best segment": You can achieve the fourth answer with the "best segment" shown below:
50 5 1 3 00 1 3 2 0
8.000000000000 4.000000000000 6.000000000000 6.000000000000 6.000000000000
2 seconds
256 megabytes
['binary search', 'geometry', 'two pointers', '*2900']
E. Compressed Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.You can perform the following operation any number of times (possibly zero): choose a vertex which has at most 1 incident edge and remove this vertex from the tree. Note that you can delete all vertices.After all operations are done, you're compressing the tree. The compression process is done as follows. While there is a vertex having exactly 2 incident edges in the tree, perform the following operation: delete this vertex, connect its neighbors with an edge. It can be shown that if there are multiple ways to choose a vertex to delete during the compression process, the resulting tree is still the same.Your task is to calculate the maximum possible sum of numbers written on vertices after applying the aforementioned operation any number of times, and then compressing the tree.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 5 \cdot 10^5) — the number of vertices.The second line contains n integers a_1, a_2, \dots, a_n (-10^9 \le a_i \le 10^9).Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers v_i and u_i, the labels of vertices it connects (1 \le v_i, u_i \le n, v_i \ne u_i). These edges form a tree. Additional constraint on the input: the sum of n over all test cases doesn't exceed 5 \cdot 10^5.OutputFor each test case, print a single integer — the maximum possible sum of numbers written on vertices after applying the aforementioned operation any number of times, and then compressing the tree.ExampleInput 341 -2 2 11 23 22 42-2 -52 17-2 4 -2 3 3 2 -11 22 33 43 54 64 7Output 3 0 9
341 -2 2 11 23 22 42-2 -52 17-2 4 -2 3 3 2 -11 22 33 43 54 64 7
3 0 9
2 seconds
256 megabytes
['dfs and similar', 'dp', 'graphs', 'greedy', 'sortings', 'trees', '*2200']
D. Yet Another Monster Fighttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya is a sorcerer that fights monsters. Again. There are n monsters standing in a row, the amount of health points of the i-th monster is a_i.Vasya is a very powerful sorcerer who knows many overpowered spells. In this fight, he decided to use a chain lightning spell to defeat all the monsters. Let's see how this spell works.Firstly, Vasya chooses an index i of some monster (1 \le i \le n) and the initial power of the spell x. Then the spell hits monsters exactly n times, one hit per monster. The first target of the spell is always the monster i. For every target except for the first one, the chain lightning will choose a random monster who was not hit by the spell and is adjacent to one of the monsters that already was hit. So, each monster will be hit exactly once. The first monster hit by the spell receives x damage, the second monster receives (x-1) damage, the third receives (x-2) damage, and so on.Vasya wants to show how powerful he is, so he wants to kill all the monsters with a single chain lightning spell. The monster is considered dead if the damage he received is not less than the amount of its health points. On the other hand, Vasya wants to show he doesn't care that much, so he wants to choose the minimum initial power of the spell x such that it kills all monsters, no matter which monster (among those who can get hit) gets hit on each step.Of course, Vasya is a sorcerer, but the amount of calculations required to determine the optimal spell setup is way above his possibilities, so you have to help him find the minimum spell power required to kill all the monsters.Note that Vasya chooses the initial target and the power of the spell, other things should be considered random and Vasya wants to kill all the monsters even in the worst possible scenario.InputThe first line of the input contains one integer n (1 \le n \le 3 \cdot 10^5) — the number of monsters.The second line of the input contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9), where a_i is the amount of health points of the i-th monster.OutputPrint one integer — the minimum spell power required to kill all the monsters if Vasya chooses the first target optimally, and the order of spell hits can be any possible within the given rules.ExamplesInput 6 2 1 5 6 4 3 Output 8 Input 5 4 4 4 4 4 Output 8 Input 2 1 1000000000 Output 1000000000
6 2 1 5 6 4 3
8
2 seconds
256 megabytes
['binary search', 'dp', 'greedy', 'implementation', 'math', '*1700']
C. Add, Divide and Floortime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer array a_1, a_2, \dots, a_n (0 \le a_i \le 10^9). In one operation, you can choose an integer x (0 \le x \le 10^{18}) and replace a_i with \lfloor \frac{a_i + x}{2} \rfloor (\lfloor y \rfloor denotes rounding y down to the nearest integer) for all i from 1 to n. Pay attention to the fact that all elements of the array are affected on each operation. Print the smallest number of operations required to make all elements of the array equal.If the number of operations is less than or equal to n, then print the chosen x for each operation. If there are multiple answers, print any of them.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 (1 \le n \le 2 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 10^9).The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print the smallest number of operations required to make all elements of the array equal.If the number of operations is less than or equal to n, then print the chosen x for each operation in the next line. If there are multiple answers, print any of them.ExampleInput 411024 662 1 2 1 2 120 32Output 0 2 2 5 1 1 6 NoteIn the first testcase, all elements are already equal, so 0 operations are required. It doesn't matter if you print an empty line afterwards or not.In the second testcase, you can't make less than 2 operations. There are multiple answers, let's consider the answer sequence [2, 5]. After applying an operation with x = 2, the array becomes [\lfloor \frac{4 + 2}{2} \rfloor, \lfloor \frac{6 + 2}{2} \rfloor] = [3, 4]. After applying an operation with x = 5 after that, the array becomes [\lfloor \frac{3 + 5}{2} \rfloor, \lfloor \frac{4 + 5}{2} \rfloor] = [4, 4]. Both elements are the same, so we are done.In the last testcase, you can't make less than 6 operations. Since 6 is greater than n, you don't have to print them. One possible answer sequence is [0, 0, 0, 0, 0, 0]. We are just dividing the second element by 2 every time and not changing the first element.
411024 662 1 2 1 2 120 32
0 2 2 5 1 1 6
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', '*1400']
B. Chip and Ribbontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a ribbon divided into n cells, numbered from 1 to n from left to right. Initially, an integer 0 is written in each cell.Monocarp plays a game with a chip. The game consists of several turns. During the first turn, Monocarp places the chip in the 1-st cell of the ribbon. During each turn except for the first turn, Monocarp does exactly one of the two following actions: move the chip to the next cell (i. e. if the chip is in the cell i, it is moved to the cell i+1). This action is impossible if the chip is in the last cell; choose any cell x and teleport the chip into that cell. It is possible to choose the cell where the chip is currently located. At the end of each turn, the integer written in the cell with the chip is increased by 1.Monocarp's goal is to make some turns so that the 1-st cell contains the integer c_1, the 2-nd cell contains the integer c_2, ..., the n-th cell contains the integer c_n. He wants to teleport the chip as few times as possible.Help Monocarp calculate the minimum number of times he has to teleport the chip. 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 2 \cdot 10^5); the second line contains n integers c_1, c_2, \dots, c_n (0 \le c_i \le 10^9; c_1 \ge 1). It can be shown that under these constraints, it is always possible to make a finite amount of turns so that the integers in the cells match the sequence c_1, c_2, \dots, c_n.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, print one integer — the minimum number of times Monocarp has to teleport the chip.ExampleInput 441 2 2 151 0 1 0 155 4 3 2 1112Output 1 2 4 11 NoteIn the first test case of the example, Monocarp can perform the turns as follows: place the chip in the 1-st cell; the numbers in the cells are [1, 0, 0, 0]; move the chip to the next (2-nd) cell; the numbers in the cells are [1, 1, 0, 0]; move the chip to the next (3-rd) cell; the numbers in the cells are [1, 1, 1, 0]; teleport the chip to the 2-nd cell; the numbers in the cells are [1, 2, 1, 0]; move the chip to the next (3-rd) cell; the numbers in the cells are [1, 2, 2, 0]; move the chip to the next (4-th) cell; the numbers in the cells are [1, 2, 2, 1].
441 2 2 151 0 1 0 155 4 3 2 1112
1 2 4 11
2 seconds
256 megabytes
['greedy', 'math', '*1100']
A. Line Triptime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a road, which can be represented as a number line. You are located in the point 0 of the number line, and you want to travel from the point 0 to the point x, and back to the point 0.You travel by car, which spends 1 liter of gasoline per 1 unit of distance travelled. When you start at the point 0, your car is fully fueled (its gas tank contains the maximum possible amount of fuel).There are n gas stations, located in points a_1, a_2, \dots, a_n. When you arrive at a gas station, you fully refuel your car. Note that you can refuel only at gas stations, and there are no gas stations in points 0 and x.You have to calculate the minimum possible volume of the gas tank in your car (in liters) that will allow you to travel from the point 0 to the point x and back to the point 0.InputThe first line contains one integer t (1 \le t \le 1000) — the number of test cases.Each test case consists of two lines: the first line contains two integers n and x (1 \le n \le 50; 2 \le x \le 100); the second line contains n integers a_1, a_2, \dots, a_n (0 < a_1 < a_2 < \dots < a_n < x). OutputFor each test case, print one integer — the minimum possible volume of the gas tank in your car that will allow you to travel from the point 0 to the point x and back.ExampleInput 33 71 2 53 61 2 51 107Output 4 3 7 NoteIn the first test case of the example, if the car has a gas tank of 4 liters, you can travel to x and back as follows: travel to the point 1, then your car's gas tank contains 3 liters of fuel; refuel at the point 1, then your car's gas tank contains 4 liters of fuel; travel to the point 2, then your car's gas tank contains 3 liters of fuel; refuel at the point 2, then your car's gas tank contains 4 liters of fuel; travel to the point 5, then your car's gas tank contains 1 liter of fuel; refuel at the point 5, then your car's gas tank contains 4 liters of fuel; travel to the point 7, then your car's gas tank contains 2 liters of fuel; travel to the point 5, then your car's gas tank contains 0 liters of fuel; refuel at the point 5, then your car's gas tank contains 4 liters of fuel; travel to the point 2, then your car's gas tank contains 1 liter of fuel; refuel at the point 2, then your car's gas tank contains 4 liters of fuel; travel to the point 1, then your car's gas tank contains 3 liters of fuel; refuel at the point 1, then your car's gas tank contains 4 liters of fuel; travel to the point 0, then your car's gas tank contains 3 liters of fuel.
33 71 2 53 61 2 51 107
4 3 7
2 seconds
256 megabytes
['greedy', 'math', '*800']
F. Local Deletionstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFor an array b_1, b_2, \ldots, b_m, for some i (1 < i < m), element b_i is said to be a local minimum if b_i < b_{i-1} and b_i < b_{i+1}. Element b_1 is said to be a local minimum if b_1 < b_2. Element b_m is said to be a local minimum if b_m < b_{m-1}.For an array b_1, b_2, \ldots, b_m, for some i (1 < i < m), element b_i is said to be a local maximum if b_i > b_{i-1} and b_i > b_{i+1}. Element b_1 is said to be a local maximum if b_1 > b_2. Element b_m is said to be a local maximum if b_m > b_{m-1}.Let x be an array of distinct elements. We define two operations on it: 1 — delete all elements from x that are not local minima. 2 — delete all elements from x that are not local maxima. Define f(x) as follows. Repeat operations 1, 2, 1, 2, \ldots in that order until you get only one element left in the array. Return that element.For example, take an array [1,3,2]. We will first do type 1 operation and get [1, 2]. Then we will perform type 2 operation and get [2]. Therefore, f([1,3,2]) = 2.You are given a permutation^\dagger a of size n and q queries. Each query consists of two integers l and r such that 1 \le l \le r \le n. The query asks you to compute f([a_l, a_{l+1}, \ldots, a_r]). ^\dagger A permutation of length n is an array of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3, but there is 4 in the array).InputThe first line contains two integers n and q (1 \le n, q \le 10^5) — the length of the permutation a and the number of queries.The second line contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of permutation a.The i-th of the next q lines contains two integers l_i and r_i (1 \le l_i \le r_i \le n) — the description of i-th query.OutputFor each query, output a single integer — the answer to that query.ExamplesInput 7 5 1 4 3 6 2 7 5 1 1 1 2 2 3 1 4 1 7 Output 1 1 3 3 3 Input 10 1 1 2 3 4 5 6 7 8 9 10 1 10 Output 1 NoteIn the first query of the first example, the only number in the subarray is 1, therefore it is the answer.In the second query of the first example, our subarray initially looks like [1, 4]. After performing type 1 operation we get [1].In the third query of the first example, our subarray initially looks like [4, 3]. After performing type 1 operation we get [3].In the fourth query of the first example, our subarray initially looks like [1, 4, 3, 6]. After performing type 1 operation we get [1, 3]. Then we perform type 2 operation and we get [3].In the fifth query of the first example, our subarray initially looks like [1, 4, 3, 6, 2, 7, 5]. After performing type 1 operation we get [1,3,2,5]. After performing type 2 operation we get [3,5]. Then we perform type 1 operation and we get [3].In the first and only query of the second example our subarray initially looks like [1,2,3,4,5,6,7,8,9,10]. Here 1 is the only local minimum, so only it is left after performing type 1 operation.
7 5 1 4 3 6 2 7 5 1 1 1 2 2 3 1 4 1 7
1 1 3 3 3
3 seconds
256 megabytes
['binary search', 'data structures', 'implementation', '*2800']
E. Transitive Graphtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a directed graph G with n vertices and m edges between them.Initially, graph H is the same as graph G. Then you decided to perform the following actions: If there exists a triple of vertices a, b, c of H, such that there is an edge from a to b and an edge from b to c, but there is no edge from a to c, add an edge from a to c. Repeat the previous step as long as there are such triples. Note that the number of edges in H can be up to n^2 after performing the actions.You also wrote some values on vertices of graph H. More precisely, vertex i has the value of a_i written on it.Consider a simple path consisting of k distinct vertices with indexes v_1, v_2, \ldots, v_k. The length of such a path is k. The value of that path is defined as \sum_{i = 1}^k a_{v_i}.A simple path is considered the longest if there is no other simple path in the graph with greater length.Among all the longest simple paths in H, find the one with the smallest value.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 \le n,m \le 2 \cdot 10^5) — the number of vertices and the number of edges.The second line contains n integers a_1, a_2, \ldots, a_n (0 \le a_i \le 10^9) — the numbers written on the vertices of graph H.The i-th of the next m lines contains two integers v_i and u_i (1 \le v_i, u_i \le n) — meaning that there is an edge going from vertex v_i to vertex u_i in graph G. Note that edges are directed. Also note that the graph may have self-loops and multiple edges.It is guaranteed that neither the sum of n nor the sum of m over all test cases exceeds 2 \cdot 10^5.OutputFor each test case, output two numbers — the length of the longest simple path in H and the minimal possible value of such path.ExampleInput 35 62 2 4 1 31 21 32 43 44 55 27 7999999999 999999999 999999999 999999999 1000000000 999999999 10000000001 22 33 44 14 54 66 714 222 3 5 7 3 4 1 4 3 4 2 2 5 11 22 32 43 14 44 55 65 65 126 76 87 57 77 98 49 1110 911 1011 1012 1313 1414 12Output 5 12 6 5999999995 11 37 NoteIn the first test case, the longest path in both graphs is 1 \to 3 \to 4 \to 5 \to 2. As the path includes all vertices, the minimal possible value of the longest path is the sum of values on all vertices, which is 12.In the second test case, the longest possible path is 1 \to 2 \to 3 \to 4 \to 6 \to 7. As there are no longest paths with vertex 5 in them, this path has the minimal possible value of 5\,999\,999\,995.In the third test case, it can be proven that there is no path longer than 11 and that the value of the longest path cannot be less than 37. Also, notice that the given graph has both self-loops and multiple edges.
35 62 2 4 1 31 21 32 43 44 55 27 7999999999 999999999 999999999 999999999 1000000000 999999999 10000000001 22 33 44 14 54 66 714 222 3 5 7 3 4 1 4 3 4 2 2 5 11 22 32 43 14 44 55 65 65 126 76 87 57 77 98 49 1110 911 1011 1012 1313 1414 12
5 12 6 5999999995 11 37
3 seconds
256 megabytes
['dfs and similar', 'dp', 'dsu', 'graphs', 'implementation', '*2100']
D. Small GCDtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet a, b, and c be integers. We define function f(a, b, c) as follows:Order the numbers a, b, c in such a way that a \le b \le c. Then return \gcd(a, b), where \gcd(a, b) denotes the greatest common divisor (GCD) of integers a and b.So basically, we take the \gcd of the 2 smaller values and ignore the biggest one. You are given an array a of n elements. Compute the sum of f(a_i, a_j, a_k) for each i, j, k, such that 1 \le i < j < k \le n. More formally, compute \sum_{i = 1}^n \sum_{j = i+1}^n \sum_{k =j +1}^n f(a_i, a_j, a_k). InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10). The description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 8 \cdot 10^4) — 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^5) — elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 8 \cdot 10^4.OutputFor each test case, output a single number — the sum from the problem statement.ExampleInput 252 3 6 12 1786 12 8 10 15 12 18 16Output 24 203 NoteIn the first test case, the values of f are as follows: i=1, j=2, k=3, f(a_i,a_j,a_k)=f(2,3,6)=\gcd(2,3)=1; i=1, j=2, k=4, f(a_i,a_j,a_k)=f(2,3,12)=\gcd(2,3)=1; i=1, j=2, k=5, f(a_i,a_j,a_k)=f(2,3,17)=\gcd(2,3)=1; i=1, j=3, k=4, f(a_i,a_j,a_k)=f(2,6,12)=\gcd(2,6)=2; i=1, j=3, k=5, f(a_i,a_j,a_k)=f(2,6,17)=\gcd(2,6)=2; i=1, j=4, k=5, f(a_i,a_j,a_k)=f(2,12,17)=\gcd(2,12)=2; i=2, j=3, k=4, f(a_i,a_j,a_k)=f(3,6,12)=\gcd(3,6)=3; i=2, j=3, k=5, f(a_i,a_j,a_k)=f(3,6,17)=\gcd(3,6)=3; i=2, j=4, k=5, f(a_i,a_j,a_k)=f(3,12,17)=\gcd(3,12)=3; i=3, j=4, k=5, f(a_i,a_j,a_k)=f(6,12,17)=\gcd(6,12)=6. The sum over all triples is 1+1+1+2+2+2+3+3+3+6=24.In the second test case, there are 56 ways to choose values of i, j, k. The sum over all f(a_i,a_j,a_k) is 203.
252 3 6 12 1786 12 8 10 15 12 18 16
24 203
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'math', 'number theory', '*2000']
C. Anji's Binary Treetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKeksic keeps getting left on seen by Anji. Through a mutual friend, he's figured out that Anji really likes binary trees and decided to solve her problem in order to get her attention.Anji has given Keksic a binary tree with n vertices. Vertex 1 is the root and does not have a parent. All other vertices have exactly one parent. Each vertex can have up to 2 children, a left child, and a right child. For each vertex, Anji tells Keksic index of both its left and its right child or tells him that they do not exist. Additionally, each of the vertices has a letter s_i on it, which is either 'U', 'L' or 'R'.Keksic begins his journey on the root, and in each move he does the following: If the letter on his current vertex is 'U', he moves to its parent. If it doesn't exist, he does nothing. If the letter on his current vertex is 'L', he moves to its left child. If it doesn't exist, he does nothing. If the letter on his current vertex is 'R', he moves to its right child. If it doesn't exist, he does nothing. Before his journey, he can perform the following operations: choose any node, and replace the letter written on it with another one. You are interested in the minimal number of operations he needs to do before his journey, such that when he starts his journey, he will reach a leaf at some point. A leaf is a vertex that has no children. It does not matter which leaf he reaches. Note that it does not matter whether he will stay in the leaf, he just needs to move to it. Additionally, note that it does not matter how many times he needs to move before reaching a leaf.Help Keksic solve Anji's tree so that he can win her heart, and make her come to Čačak.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 5 \cdot 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 3 \cdot 10^5) — the number of vertices in a tree.The second line of each test case contains a string s of n characters — characters are written on the vertices. It is guaranteed that s consists only of characters 'U', 'L', and 'R'.The i-th of the next n lines contains two integers l_i and r_i (0 \le l_i, r_i \le n) — indices of left and right child of the vertex i. If l_i = 0, it means that vertex i does not have a left child. If r_i = 0, it means that vertex i does not have a right child. It is guaranteed that this data describes a valid binary tree rooted at 1.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output a single integer — the minimal number of operations Keksic needs to do to reach a leaf.ExampleInput 53LRU2 30 00 03ULR3 20 00 02LU0 20 04RULR3 00 00 42 07LLRRRLU5 23 60 07 04 00 00 0Output 0 1 1 3 1 NoteIn the first test case, vertex 1 has 2 as its left child and 3 as its right child. Vertices 2 and 3 do not have children and are therefore leaves. As 'L' is written on vertex 1, Keksic will go to vertex 2, therefore he has to do no operations.In the second test case, vertex 1 has 3 as its left child and 2 as its right child. Vertices 2 and 3 are leaves. As 'U' is written on vertex 1, Keksic needs to change it to either 'L' or 'R' in order for him to reach a leaf.In the third case, vertex 1 has only a right child, which is vertex 2. As 'L' is written on it, Keksic needs to change it to 'R', otherwise he would be stuck on vertex 1.In the fourth case, he can change 3 characters so that letters on the vertices are "LURL", which makes him reach vertex 2.In the fifth case, there are 3 leaves, 3, 6 and 7. To reach either leaf 6 or leaf 7, he needs to change 2 characters. However, if he changes character on vertex 1 to 'R', he will reach leaf 3, therefore the answer is 1. The initial tree in test case 5.
53LRU2 30 00 03ULR3 20 00 02LU0 20 04RULR3 00 00 42 07LLRRRLU5 23 60 07 04 00 00 0
0 1 1 3 1
2.5 seconds
256 megabytes
['dfs and similar', 'dp', 'trees', '*1300']
B. Laura and Operationstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLaura is a girl who does not like combinatorics. Nemanja will try to convince her otherwise.Nemanja wrote some digits on the board. All of them are either 1, 2, or 3. The number of digits 1 is a. The number of digits 2 is b and the number of digits 3 is c. He told Laura that in one operation she can do the following: Select two different digits and erase them from the board. After that, write the digit (1, 2, or 3) different from both erased digits. For example, let the digits be 1, 1, 1, 2, 3, 3. She can choose digits 1 and 3 and erase them. Then the board will look like this 1, 1, 2, 3. After that, she has to write another digit 2, so at the end of the operation, the board will look like 1, 1, 2, 3, 2.Nemanja asked her whether it was possible for only digits of one type to remain written on the board after some operations. If so, which digits can they be?Laura was unable to solve this problem and asked you for help. As an award for helping her, she will convince Nemanja to give you some points.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first and only line of each test case contains three integers a, b, c (1 \le a, b, c \le 100) — the number of ones, number of twos, and number of threes, respectively.OutputFor each test case, output one line containing 3 integers. The first one should be 1 if it is possible that after some operations only digits 1 remain on the board, and 0 otherwise. Similarly, the second one should be 1 if it is possible that after some operations only digits 2 remain on the board, and 0 otherwise. Similarly, the third one should be 1 if it is possible that after some operations only digits 3 remain on the board, and 0 otherwise.ExampleInput 31 1 12 3 282 47 59Output 1 1 1 0 1 0 1 0 0 NoteIn the first test case, Laura can remove digits 2 and 3 and write digit 1. After that, the board will have 2 digits 1. She can make it have only digits 2 or 3 left by performing a similar operation.In the second test case, she can remove digits 1 and 3 and write a digit 2. After performing that operation 2 times, the board will have only digits 2 left. It can be proven that there is no way to have only digits 1 or only digits 3 left.In the third test case, there is a sequence of operations that leaves only digits 1 on the board. It can be proven that there is no way to have only digits 2 or only digits 3 left.
31 1 12 3 282 47 59
1 1 1 0 1 0 1 0 0
2 seconds
256 megabytes
['dp', 'math', '*900']
A. Cover in Watertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputFilip has a row of cells, some of which are blocked, and some are empty. He wants all empty cells to have water in them. He has two actions at his disposal: 1 — place water in an empty cell. 2 — remove water from a cell and place it in any other empty cell. If at some moment cell i (2 \le i \le n-1) is empty and both cells i-1 and i+1 contains water, then it becomes filled with water.Find the minimum number of times he needs to perform action 1 in order to fill all empty cells with water. Note that you don't need to minimize the use of action 2. Note that blocked cells neither contain water nor can Filip place water in them.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 100) — the number of cells. The next line contains a string s of length n. The i-th character of s is '.' if the cell i is empty and '#' if cell i is blocked.OutputFor each test case, output a single number — the minimal amount of actions 1 needed to fill all empty cells with water.ExampleInput 53...7##....#7..#.#..4####10#...#..#.#Output 2 2 5 0 2 NoteTest Case 1In the first test case, Filip can put water in cells 1 and 3. As cell 2 is between 2 cells with water, it gets filled with water too.Test Case 2In the second case, he can put water sources in cells 3 and 5. That results in cell 4 getting filled with water. Then he will remove water from cell 5 and place it into cell 6. As cell 5's neighbors, cell 4 and cell 6, have water in them, cell 5 also gets filled with water. You can see the illustration of this case below. Operations in the second test case. White cells are empty, grey ones are blocked, and blue ones are water. Test Case 3In the third case, he can put water in all the empty cells. That requires 5 actions of type 1.Test Case 4In the fourth case, there are no empty cells. Therefore, he does not have to put any water in them.Test Case 5In the fifth test case, there exists a sequence of actions that requires only 2 type 1 actions.
53...7##....#7..#.#..4####10#...#..#.#
2 2 5 0 2
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'strings', '*800']
G. Unusual Entertainmenttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA tree is a connected graph without cycles.A permutation is an array consisting of n distinct integers from 1 to n in any order. For example, [5, 1, 3, 2, 4] is a permutation, but [2, 1, 1] is not a permutation (as 1 appears twice in the array) and [1, 3, 2, 5] is also not a permutation (as n = 4, but 5 is present in the array).After a failed shoot in the BrMeast video, Alex fell into depression. Even his birthday did not make him happy. However, after receiving a gift from Timofey, Alex's mood suddenly improved. Now he spent days playing with the gifted constructor. Recently, he came up with an unusual entertainment.Alex builds a tree from his constructor, consisting of n vertices numbered from 1 to n, with the root at vertex 1. Then he writes down each integer from 1 to n in some order, obtaining a permutation p. After that, Alex comes up with q triples of integers l, r, x. For each triple, he tries to determine if there is at least one descendant of vertex x among the vertices p_l, p_{l+1}, \ldots, p_r.A vertex u is a descendant of vertex v if and only if \mathrm{dist}(1, v) + \mathrm{dist}(v, u) = \mathrm{dist}(1, u), where \mathrm{dist}(a, b) is the distance between vertices a and b. In other words, vertex v must be on the path from the root to vertex u.Alex told Zakhar about this entertainment. Now Alex tells his friend q triples as described above, hoping that Zakhar can check for the presence of a descendant. Zakhar is very sleepy, so he turned to you for help. Help Zakhar answer all of Alex's questions and finally go to sleep.InputThe first line of the input 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, q (1 \le n, q \le 10^5) — the number of vertices in the tree and the number of questions, respectively.Each of the next n - 1 lines contains two integers u_i and v_i (1 \le u_i, v_i \le n), indicating that there is an edge between vertices u_i and v_i (it is guaranteed that the resulting graph is a tree).The next line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n) — the permutation p (it is guaranteed that each integer from 1 to n appears exactly once).Then follow q lines describing Alex's questions. The i-th line contains three integers l, r, x (1 \le l \le r \le n, 1 \le x \le n), as described in the statement.It is guaranteed that the sum of n and the sum of q over all test cases do not exceed 10^5.OutputFor each of Alex's questions, print "Yes" (without quotes) if the described descendant exists, otherwise print "No" (without quotes).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 33 51 22 31 2 31 2 21 2 32 3 11 2 32 3 310 102 62 72 41 72 810 68 59 43 410 2 5 9 1 7 6 4 3 88 9 87 8 17 10 64 8 95 5 107 10 19 9 29 10 66 6 210 10 61 111 1 1Output YES NO YES NO YES NO YES YES YES NO YES YES NO NO NO YES
33 51 22 31 2 31 2 21 2 32 3 11 2 32 3 310 102 62 72 41 72 810 68 59 43 410 2 5 9 1 7 6 4 3 88 9 87 8 17 10 64 8 95 5 107 10 19 9 29 10 66 6 210 10 61 111 1 1
YES NO YES NO YES NO YES YES YES NO YES YES NO NO NO YES
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'dsu', 'shortest paths', 'sortings', 'trees', 'two pointers', '*1900']
F. Alex's whimstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTree is a connected graph without cycles. It can be shown that any tree of n vertices has exactly n - 1 edges.Leaf is a vertex in the tree with exactly one edge connected to it.Distance between two vertices u and v in a tree is the minimum number of edges that must be passed to come from vertex u to vertex v.Alex's birthday is coming up, and Timofey would like to gift him a tree of n vertices. However, Alex is a very moody boy. Every day for q days, he will choose an integer, denoted by the integer chosen on the i-th day by d_i. If on the i-th day there are not two leaves in the tree at a distance exactly d_i, Alex will be disappointed.Timofey decides to gift Alex a designer so that he can change his tree as he wants. Timofey knows that Alex is also lazy (a disaster, not a human being), so at the beginning of every day, he can perform no more than one operation of the following kind: Choose vertices u, v_1, and v_2 such that there is an edge between u and v_1 and no edge between u and v_2. Then remove the edge between u and v_1 and add an edge between u and v_2. This operation cannot be performed if the graph is no longer a tree after it.Somehow Timofey managed to find out all the d_i. After that, he had another brilliant idea — just in case, make an instruction manual for the set, one that Alex wouldn't be disappointed.Timofey is not as lazy as Alex, but when he saw the integer n, he quickly lost the desire to develop the instruction and the original tree, so he assigned this task to you. It can be shown that a tree and a sequence of operations satisfying the described conditions always exist.Here is an example of an operation where vertices were selected: u — 6, v_1 — 1, v_2 — 4.InputThe first line contains the integer t (1 \leq t \leq 100) — the number of test cases.The first line of each test case contains two integers n (3 \leq n \leq 500) and q (1 \leq q \leq 500) — the number of nodes in the tree and the number of days, respectively.The ith of the following q lines contains the integer d_i (2 \leq d_i \leq n - 1).It is guaranteed that the sum of n over all test cases does not exceed 500. The same is guaranteed for q.It can be shown that a tree and a sequence of operations satisfying the described conditions always exist.OutputFor each test case, first print an n - 1 string describing the edges of the tree. If you want the tree to have an edge between nodes u and v, there must be a string v u or u v among these n - 1 lines.In the next q lines, print three integers each u v_1 v_2 — a description of the operations. If Alex doesn't need to perform an operation the following day, print -1 -1 -1.ExampleInput 33 32225 64234324 9233222322Output 1 2 2 3 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 2 2 3 3 4 4 5 -1 -1 -1 4 3 2 5 4 3 4 2 5 4 5 2 5 3 4 1 2 2 3 3 4 4 3 2 4 2 3 -1 -1 -1 4 3 2 -1 -1 -1 -1 -1 -1 4 2 3 4 3 2 -1 -1 -1
33 32225 64234324 9233222322
1 2 2 3 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 2 2 3 3 4 4 5 -1 -1 -1 4 3 2 5 4 3 4 2 5 4 5 2 5 3 4 1 2 2 3 3 4 4 3 2 4 2 3 -1 -1 -1 4 3 2 -1 -1 -1 -1 -1 -1 4 2 3 4 3 2 -1 -1 -1
1 second
256 megabytes
['constructive algorithms', 'graphs', 'greedy', 'shortest paths', 'trees', '*1600']
E. Queue Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad found an array a of n integers and decided to sort it in non-decreasing order.To do this, Vlad can apply the following operation any number of times: Extract the first element of the array and insert it at the end; Swap that element with the previous one until it becomes the first or until it becomes strictly greater than the previous one. Note that both actions are part of the operation, and for one operation, you must apply both actions.For example, if you apply the operation to the array [4, 3, 1, 2, 6, 4], it will change as follows: [\color{red}{4}, 3, 1, 2, 6, 4]; [3, 1, 2, 6, 4, \color{red}{4}]; [3, 1, 2, 6, \color{red}{4}, 4]; [3, 1, 2, \color{red}{4}, 6, 4].Vlad doesn't have time to perform all the operations, so he asks you to determine the minimum number of operations required to sort the array or report that it is impossible.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Descriptions of the test cases follow.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the array.The second line of each test case contains n integers a_1, a_2, a_3, \dots, a_n (1 \le a_i \le 10^9) — the elements of the array.It is guaranteed that the sum of n over all testcases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the minimum number of operations needed to sort the array. If it is impossible to do so, output -1 as the answer.ExampleInput 556 4 1 2 574 5 3 7 8 6 264 3 1 2 6 445 2 4 232 2 3Output 2 6 -1 -1 0
556 4 1 2 574 5 3 7 8 6 264 3 1 2 6 445 2 4 232 2 3
2 6 -1 -1 0
1 second
256 megabytes
['greedy', 'implementation', 'sortings', '*1300']
D. Yarik and Musical Notestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYarik is a big fan of many kinds of music. But Yarik loves not only listening to music but also writing it. He likes electronic music most of all, so he has created his own system of music notes, which, in his opinion, is best for it.Since Yarik also likes informatics, in his system notes are denoted by integers of 2^k, where k \ge 1 — a positive integer. But, as you know, you can't use just notes to write music, so Yarik uses combinations of two notes. The combination of two notes (a, b), where a = 2^k and b = 2^l, he denotes by the integer a^b.For example, if a = 8 = 2^3, b = 4 = 2^2, then the combination (a, b) is denoted by the integer a^b = 8^4 = 4096. Note that different combinations can have the same notation, e.g., the combination (64, 2) is also denoted by the integer 4096 = 64^2.Yarik has already chosen n notes that he wants to use in his new melody. However, since their integers can be very large, he has written them down as an array a of length n, then the note i is b_i = 2^{a_i}. The integers in array a can be repeated.The melody will consist of several combinations of two notes. Yarik was wondering how many pairs of notes b_i, b_j (i < j) exist such that the combination (b_i, b_j) is equal to the combination (b_j, b_i). In other words, he wants to count the number of pairs (i, j) (i < j) such that b_i^{b_j} = b_j^{b_i}. Help him find the number of such pairs.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains one integer n (1 \leq n \leq 2 \cdot 10^5) — the length of the arrays.The next line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — 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 the number of pairs that satisfy the given condition.ExampleInput 51243 1 3 221000 100031 1 1192 4 1 6 2 8 5 4 2 10 5 10 8 7 4 3 2 6 10Output 0 2 1 3 19
51243 1 3 221000 100031 1 1192 4 1 6 2 8 5 4 2 10 5 10 8 7 4 3 2 6 10
0 2 1 3 19
1 second
256 megabytes
['hashing', 'math', 'number theory', '*1300']
C. Yarik and Arraytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA subarray is a continuous part of array.Yarik recently found an array a of n elements and became very interested in finding the maximum sum of a non empty subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements.For example, [1, 2, 3] is acceptable, but [1, 2, 4] is not, as 2 and 4 are both even and adjacent.You need to help Yarik by finding the maximum sum of such a subarray.InputThe first line contains an integer t (1 \le t \le 10^4) — number of test cases. Each test case is described as follows.The first line of each test case contains an integer n (1 \le n \le 2 \cdot 10^5) — length of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (-10^3 \le a_i \le 10^3) — elements of the array.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the answer to the problem.ExampleInput 751 2 3 4 549 9 8 86-1 4 -1 0 5 -44-1 2 4 -31-10003101 -99 10120-10 5 -8 10 6 -10 7 9 -2 -6 7 2 -4 6 -1 7 -6 -7 4 1Output 15 17 8 4 -1000 101 10
751 2 3 4 549 9 8 86-1 4 -1 0 5 -44-1 2 4 -31-10003101 -99 10120-10 5 -8 10 6 -10 7 9 -2 -6 7 2 -4 6 -1 7 -6 -7 4 1
15 17 8 4 -1000 101 10
1 second
256 megabytes
['dp', 'greedy', 'two pointers', '*1100']
B. 250 Thousand Tons of TNTtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex is participating in the filming of another video of BrMeast, and BrMeast asked Alex to prepare 250 thousand tons of TNT, but Alex didn't hear him well, so he prepared n boxes and arranged them in a row waiting for trucks. The i-th box from the left weighs a_i tons.All trucks that Alex is going to use hold the same number of boxes, denoted by k. Loading happens the following way: The first k boxes goes to the first truck, The second k boxes goes to the second truck, \dotsb The last k boxes goes to the \frac{n}{k}-th truck. Upon loading is completed, each truck must have exactly k boxes. In other words, if at some point it is not possible to load exactly k boxes into the truck, then the loading option with that k is not possible.Alex hates justice, so he wants the maximum absolute difference between the total weights of two trucks to be as great as possible. If there is only one truck, this value is 0.Alex has quite a lot of connections, so for every 1 \leq k \leq n, he can find a company such that each of its trucks can hold exactly k boxes. Print the maximum absolute difference between the total weights of any two trucks.InputThe first line contains one integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains one integer n (1 \leq n \leq 150\,000) — the number of boxes.The second line contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the weights of the boxes.It is guaranteed that the sum of n for all test cases does not exceed 150\,000.OutputFor each test case, print a single integer — the answer to the problem.ExampleInput 521 2610 2 3 6 1 341000000000 1000000000 1000000000 10000000001560978 82265 78961 56708 39846 31071 4913 4769 29092 91348 64119 72421 98405 222 14294819957 69913 37531 96991 57838 21008 14207 19198Output 1 9 0 189114 112141 NoteIn the first case, we should pick two trucks, so the first one will have only the first box, and the second one will have only the second box.In the second case, we should pick six trucks, so the maximum will be 10, the minimum will be 1, and the answer is 10 - 1 = 9.In the third case, for any possible k, the trucks will have the same total weight of boxes, so the answer is 0.
521 2610 2 3 6 1 341000000000 1000000000 1000000000 10000000001560978 82265 78961 56708 39846 31071 4913 4769 29092 91348 64119 72421 98405 222 14294819957 69913 37531 96991 57838 21008 14207 19198
1 9 0 189114 112141
2 seconds
256 megabytes
['brute force', 'implementation', 'number theory', '*1100']
A. Game with Integerstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVanya and Vova are playing a game. Players are given an integer n. On their turn, the player can add 1 to the current integer or subtract 1. The players take turns; Vanya starts. If after Vanya's move the integer is divisible by 3, then he wins. If 10 moves have passed and Vanya has not won, then Vova wins.Write a program that, based on the integer n, determines who will win if both players play optimally.InputThe first line contains the integer t (1 \leq t \leq 100) — the number of test cases.The single line of each test case contains the integer n (1 \leq n \leq 1000).OutputFor each test case, print "First" without quotes if Vanya wins, and "Second" without quotes if Vova wins.ExampleInput 61351009991000Output First Second First First Second First
61351009991000
First Second First First Second First
1 second
256 megabytes
['games', 'math', 'number theory', '*800']
F. Vova Escapes the Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputFollowing a world tour, Vova got himself trapped inside an n \times m matrix. Rows of this matrix are numbered by integers from 1 to n from top to bottom, and the columns are numbered by integers from 1 to m from left to right. The cell (i, j) is the cell on the intersection of row i and column j for 1 \leq i \leq n and 1 \leq j \leq m.Some cells of this matrix are blocked by obstacles, while all other cells are empty. Vova occupies one of the empty cells. It is guaranteed that cells (1, 1), (1, m), (n, 1), (n, m) (that is, corners of the matrix) are blocked.Vova can move from one empty cell to another empty cell if they share a side. Vova can escape the matrix from any empty cell on the boundary of the matrix; these cells are called exits.Vova defines the type of the matrix based on the number of exits he can use to escape the matrix: The 1-st type: matrices with no exits he can use to escape. The 2-nd type: matrices with exactly one exit he can use to escape. The 3-rd type: matrices with multiple (two or more) exits he can use to escape. Before Vova starts moving, Misha can create more obstacles to block more cells. However, he cannot change the type of the matrix. What is the maximum number of cells Misha can block, so that the type of the matrix remains the same? Misha cannot block the cell Vova is currently standing on.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of test cases follows.The first line of each test case contains two integers n and m (3 \leq n,m \leq 1000) — the dimensions of the matrix.The next n lines contain the description of the matrix: the i-th (1 \le i \le n) of them contains a string of length m, consisting of characters '.', '#', and 'V'. The j-th character of the i-th line describes the cell (i, j) of the matrix. The dot '.' denotes an empty cell, the sharp '#' denotes a blocked cell, and the letter 'V' denotes an empty cell where Vova initially is.It is guaranteed that the corners of the matrix are blocked (the first and the last characters of the first and the last lines of the matrix description are '#'). It is guaranteed that the letter 'V' appears in the matrix description exactly once.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 1\,000\,000.OutputFor each test case, output a single integer — the maximum number of cells Misha may block.ExampleInput 84 4#..#..V.....#..#3 6#.#####....#####V#3 3####V####6 5#.####...####.##V..##.#####..#7 5######.V.##.#.##.#.##.#.##...##.#.#3 7#.....#.#####.#...V.#5 8####.####..V#..##...#..##...##.####.####5 5#...###.####V####.###...#Output 9 0 0 3 4 10 12 5 NoteIn the first test case, the matrix is of the 3-rd type. Misha can create obstacles in all empty cells except the cells (1, 3), (2, 3), (2, 4). There are 9 such cells, and adding such obstacles does not change the type of the matrix.In the second test case, the matrix is of the 3-rd type. Blocking any cell changes the matrix type to the 2-nd: one of the two exits will become unavailable for Vova. Thus, the answer is 0.In the third test case, the matrix is of the 1-st type. No free cell exists (besides Vova's), so Misha cannot block any cell.In the fourth test case, the matrix is of the 2-nd type. Misha can create 3 obstacles in cells (5, 2), (6, 3), (6, 4) without changing the type of the matrix.In the fifth test case, the matrix is of the 3-rd type. Misha can create 4 obstacles in cells (2, 2), (3, 2), (4, 2), (5, 2) or 4 obstacles in cells (2, 4), (3, 4), (4, 4), (5, 4) without changing the type of the matrix.
84 4#..#..V.....#..#3 6#.#####....#####V#3 3####V####6 5#.####...####.##V..##.#####..#7 5######.V.##.#.##.#.##.#.##...##.#.#3 7#.....#.#####.#...V.#5 8####.####..V#..##...#..##...##.####.####5 5#...###.####V####.###...#
9 0 0 3 4 10 12 5
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'divide and conquer', 'shortest paths', '*2600']
E. Sofia and Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSofia has a string s of length n, consisting only of lowercase English letters. She can perform operations of the following types with this string. Select an index 1 \le i \le |s| and remove the character s_i from the string. Select a pair of indices (l, r) (1 \le l \le r \le |s|) and sort the substring s_{l} s_{l+1} \ldots s_r in alphabetical order. Here, |s| denotes the current length of s. In particular, |s| = n before the first operation. For example, if s = \mathtt{sofia}, then performing the operation of the first type with i=4 results in s becoming \mathtt{sofa}, and performing the operation of the second type with (l, r) = (2, 4) after that results in s becoming \mathtt{safo}.Sofia wants to obtain the string t of length m after performing zero or more operations on string s as described above. Please determine whether it is possible or not.InputThe first line contains one integer t (1 \leq t \leq 10\,000) — the number of test cases.The first line of each test case contains two integers n, m (1\leq m \leq n \leq 2\cdot 10^5) — the lengths of string s and t, respectively.The second line of each test case contains the string s of length n, consisting only of lowercase English letters.The third line of each test case contains the string t of length m, consisting only of lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output "YES" if Sofia can obtain the string t from s using the operations above. Otherwise, output "NO".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 85 5sofiaafios3 2cbabc5 1sofiae15 7anavolimilovanaaamanan26 4abcdefghijklmnopqrstuvwxyznope26 4zyxwvutsrqponmlkjihgfedcbanope7 3apricotcat3 3cbaacbOutput YES YES NO YES NO YES NO YES NoteIn the first test case, Sofia can perform the following operation: operation of the second type with l=1 and r=5: string s becomes \mathtt{afios} after it. In the second test case, Sofia can perform the following operations: operation of the second type with l=1 and r=2: string s becomes \mathtt{bca} after it; operation of the first type with i=3: string s becomes \mathtt{bc} after it. In the third test case, it can be shown that it is impossible to obtain t from s using the provided operations.
85 5sofiaafios3 2cbabc5 1sofiae15 7anavolimilovanaaamanan26 4abcdefghijklmnopqrstuvwxyznope26 4zyxwvutsrqponmlkjihgfedcbanope7 3apricotcat3 3cbaacb
YES YES NO YES NO YES NO YES
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', 'strings', 'two pointers', '*2200']
D. Absolute Beautytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKirill has two integer arrays a_1,a_2,\ldots,a_n and b_1,b_2,\ldots,b_n of length n. He defines the absolute beauty of the array b as \sum_{i=1}^{n} |a_i - b_i|. Here, |x| denotes the absolute value of x.Kirill can perform the following operation at most once: select two indices i and j (1 \leq i < j \leq n) and swap the values of b_i and b_j. Help him find the maximum possible absolute beauty of the array b after performing at most one swap.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of test cases follows.The first line of each test case contains a single integer n (2\leq n\leq 2\cdot 10^5) — the length of the arrays a and b.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1\leq a_i\leq 10^9) — the array a.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1\leq b_i\leq 10^9) — the array b.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output one integer — the maximum possible absolute beauty of the array b after no more than one swap.ExampleInput 631 3 53 3 321 21 221 22 141 2 3 45 6 7 8101 8 2 5 3 5 3 1 1 32 9 2 4 8 2 3 5 3 1347326 6958 3586533587 35863 59474Output 4 2 2 16 31 419045 NoteIn the first test case, each of the possible swaps does not change the array b.In the second test case, the absolute beauty of the array b without performing the swap is |1-1| + |2-2| = 0. After swapping the first and the second element in the array b, the absolute beauty becomes |1-2| + |2-1| = 2. These are all the possible outcomes, hence the answer is 2.In the third test case, it is optimal for Kirill to not perform the swap. Similarly to the previous test case, the answer is 2.In the fourth test case, no matter what Kirill does, the absolute beauty of b remains equal to 16.
631 3 53 3 321 21 221 22 141 2 3 45 6 7 8101 8 2 5 3 5 3 1 1 32 9 2 4 8 2 3 5 3 1347326 6958 3586533587 35863 59474
4 2 2 16 31 419045
2 seconds
256 megabytes
['greedy', 'math', '*1900']
C. Colorful Gridtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputElena has a grid formed by n horizontal lines and m vertical lines. The horizontal lines are numbered by integers from 1 to n from top to bottom. The vertical lines are numbered by integers from 1 to m from left to right. For each x and y (1 \leq x \leq n, 1 \leq y \leq m), the notation (x, y) denotes the point at the intersection of the x-th horizontal line and y-th vertical line.Two points (x_1,y_1) and (x_2,y_2) are adjacent if and only if |x_1-x_2| + |y_1-y_2| = 1. The grid formed by n=4 horizontal lines and m=5 vertical lines. Elena calls a sequence of points p_1, p_2, \ldots, p_g of length g a walk if and only if all the following conditions hold: The first point p_1 in this sequence is (1, 1). The last point p_g in this sequence is (n, m). For each 1 \le i < g, the points p_i and p_{i+1} are adjacent. Note that the walk may contain the same point more than once. In particular, it may contain point (1, 1) or (n, m) multiple times.There are n(m-1)+(n-1)m segments connecting the adjacent points in Elena's grid. Elena wants to color each of these segments in blue or red color so that there exists a walk p_1, p_2, \ldots, p_{k+1} of length k+1 such that out of k segments connecting two consecutive points in this walk, no two consecutive segments have the same color (in other words, for each 1 \le i < k, the color of the segment between points p_i and p_{i+1} differs from the color of the segment between points p_{i+1} and p_{i+2}). Please find any such coloring or report that there is no such coloring.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 32). The description of test cases follows.The only line of each test case contains three integers n, m, and k (3 \leq n,m \leq 16, 1 \leq k \leq 10^9) — the dimensions of the grid and the number of segments in the walk Elena is looking for.OutputFor each test case, output "NO" if it is not possible to color each of the n(m-1)+(n-1)m segments in blue or red color, so that there exists a walk of length k+1 satisfying the condition from the statement.Otherwise, output in the first line "YES", and then provide the required coloring.In each of the first n lines of coloring description, output m-1 space-separated characters. The j-th character in the i-th of these n lines should denote the color of the segment between points (i,j) and (i,j+1). Here, use 'B' to denote the blue color and 'R' to denote the red color.In each of the next n-1 lines of coloring description, output m space-separated characters. The j-th character in the i-th of these n-1 lines should denote the color of the segment between points (i,j) and (i+1,j). Similarly, use 'B' to denote the blue color and 'R' to denote the red color.You can output each letter in the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses, and both 'R' and 'r' are valid notation of red.ExampleInput 54 5 113 3 23 4 10000000003 3 125884 4 8Output YES R R B B R R R R B B B R R R B B R B B R B R B B B B B B R R R NO NO YES R B B B B R B B R R B B YES B B R R B R B R R R R B B R R B B B B B B R R R NoteIn the first test case, one of the correct answers is shown in the picture below. The color-alternating walk of length 12 is highlighted. In the second and the third test cases, it can be shown that there is no coloring satisfying the condition from the statement.
54 5 113 3 23 4 10000000003 3 125884 4 8
YES R R B B R R R R B B B R R R B B R B B R B R B B B B B B R R R NO NO YES R B B B B R B B R R B B YES B B R R B R B R R R R B B R R B B B B B B R R R
2 seconds
256 megabytes
['constructive algorithms', '*1700']
B. Milena and Admirertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMilena has received an array of integers a_1, a_2, \ldots, a_n of length n from a secret admirer. She thinks that making it non-decreasing should help her identify the secret admirer.She can use the following operation to make this array non-decreasing: Select an element a_i of array a and an integer x such that 1 \le x < a_i. Then, replace a_i by two elements x and a_i - x in array a. New elements (x and a_i - x) are placed in the array a in this order instead of a_i.More formally, let a_1, a_2, \ldots, a_i, \ldots, a_k be an array a before the operation. After the operation, it becomes equal to a_1, a_2, \ldots, a_{i-1}, x, a_i - x, a_{i+1}, \ldots, a_k. Note that the length of a increases by 1 on each operation. Milena can perform this operation multiple times (possibly zero). She wants you to determine the minimum number of times she should perform this operation to make array a non-decreasing.An array x_1, x_2, \ldots, x_k of length k is called non-decreasing if x_i \le x_{i+1} for all 1 \le i < k.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10\,000). The description of 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\leq a_i\leq 10^9) – 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 one integer — the minimum number of operations required to make the array non-decreasing.It can be shown that it is always possible to make the array a non-decreasing in the finite number of operations.ExampleInput 431 3 241 2 3 433 2 171 4 4 3 5 7 6Output 1 0 3 9 NoteIn the first test case, Milena can replace the second element of array a by integers 1 and 2, so the array would become [\, 1, \, \underline{1}, \, \underline{2}, \, 2 \,]. Only 1 operation is required.In the second test case, the array a is already non-decreasing, so the answer is 0.In the third test case, Milena can make array a non-decreasing in 3 operations as follows. Select i=1 and x=2 and replace a_1 by 2 and 1. The array a becomes equal to [\, \underline{2}, \, \underline{1}, \, 2, \, 1 \, ]. Select i=3 and x=1 and replace a_3 by 1 and 1. The array a becomes equal to [\, 2, \, 1, \, \underline{1}, \, \underline{1}, \, 1 \,]. Select i=1 and x=1 and replace a_1 by 2 and 1. The array a becomes equal to [\, \underline{1}, \, \underline{1}, \, 1, \, 1, \, 1, \, 1 \,]. It can be shown that it is impossible to make it non-decreasing in 2 or less operations, so the answer is 3.
431 3 241 2 3 433 2 171 4 4 3 5 7 6
1 0 3 9
1 second
256 megabytes
['greedy', 'math', '*1500']
A. Milica and Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMilica has a string s of length n, consisting only of characters A and B. She wants to modify s so it contains exactly k instances of B. In one operation, she can do the following: Select an integer i (1 \leq i \leq n) and a character c (c is equal to either A or B). Then, replace each of the first i characters of string s (that is, characters s_1, s_2, \ldots, s_i) with c. Milica does not want to perform too many operations in order not to waste too much time on them.She asks you to find the minimum number of operations required to modify s so it contains exactly k instances of B. She also wants you to find these operations (that is, integer i and character c selected in each operation).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 500). The description of test cases follows.The first line of each test case contains two integers n and k (3 \leq n \leq 100, 0 \leq k \leq n) — the length of the string s and the number of characters B Milica wants to appear in s in the end.The second line of each test case contains the string s of length n, consisting only of characters A and B.OutputFor each test case, in the first line output a single integer m — the minimum number of operations Milica should perform.In the j-th of the next m lines output an integer i (1 \le i \le n) and a character c (c is 'A' or 'B') — the parameters of the j-th operation as described in the statement.If there are multiple solutions with the minimum possible number of operations, output any of them.ExampleInput 5 5 2 AAABB 5 3 AABAB 5 0 BBBBB 3 0 BAA 10 3 BBBABBBBAB Output 0 1 1 B 1 5 A 1 2 A 1 6 A NoteIn the first test case, there are already 2 characters B in s, so Milica does not have to perform any operations.In the second test case, the only way to achieve 3 characters B in s in one operation is to replace the first character of s by B on the first operation: AABAB \rightarrow BABAB.In the third test case, the only way to achieve 0 characters B in s in one operation is to replace the first 5 characters of s by A on the first operation: BBBBB \rightarrow AAAAA.In the fourth test case, one of the ways to achieve 0 characters B in s in one operation is to replace the first 2 characters of s by A on the first operation: BAA \rightarrow AAA. Note that "1 A" and "3 A" are also correct one-operation solutions.
5 5 2 AAABB 5 3 AABAB 5 0 BBBBB 3 0 BAA 10 3 BBBABBBBAB
0 1 1 B 1 5 A 1 2 A 1 6 A
1 second
256 megabytes
['brute force', 'implementation', 'strings', '*800']
H2. Cyclic Hamming (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the two versions is the constraint on k. You can make hacks only if all versions of the problem are solved.In this statement, all strings are 0-indexed.For two strings a, b of the same length p, we define the following definitions: The hamming distance between a and b, denoted as h(a, b), is defined as the number of positions i such that 0 \le i < p and a_i \ne b_i. b is a cyclic shift of a if there exists some 0 \leq k < p such that b_{(i+k) \bmod p} = a_i for all 0 \le i < p. Here x \bmod y denotes the remainder from dividing x by y. You are given two binary strings s and t of length 2^{k+1} each. Both strings may contain missing characters (denoted by the character '?'). Your task is to count the number of ways to replace the missing characters in both strings with the characters '0' or '1' such that: Each string s and t contains exactly 2^k occurrences of each character '0' and '1' h(s, c) \ge 2^k for all strings c that is a cyclic shift of t. As the result can be very large, you should print the value modulo 998\,244\,353.InputThe first line of the input contains a single integer k (1 \le k \le 12).The second line of the input contains string s of size 2^{k+1}, consisting of the characters '0', '1' and '?'.The third line of the input contains string t of size 2^{k+1}, consisting of the characters '0', '1' and '?'.It is guaranteed that both strings s and t contains no more than 2^k character '0' or '1'.OutputPrint a single integer — the answer to the problem modulo 998\,244\,353.ExamplesInput 1 0011 0101 Output 1 Input 1 0011 0110 Output 0 Input 1 0??1 01?? Output 2 Input 2 000????? 01010101 Output 3 Input 2 0??????? 1??????? Output 68 Input 5 0101010101010101010101010101010101010101010101010101010101010101 ???????????????????????????????????????????????????????????????? Output 935297567 NoteIn the first example, we can check that the condition h(s, c) \ge 2^k for all cyclic shift c of t is satisfied. In particular: for c = \mathtt{0101}, h(s, c) = h(\mathtt{0110}, \mathtt{0101}) = 2 \ge 2^1; for c = \mathtt{1010}, h(s, c) = h(\mathtt{0110}, \mathtt{1010}) = 2 \ge 2^1. In the second example, there exists a cycle shift c of t such that h(s, c) < 2^k (in particular, c = \mathtt{0011}, and h(s, c) = h(\mathtt{0011}, \mathtt{0011}) = 0).In the third example, there are 2 possible ways to recover the missing characters: s = \mathtt{0101}, t = \mathtt{0110}; s = \mathtt{0011}, t = \mathtt{0101}. In the fourth example, there are 3 possible ways to recover the missing characters: s = \mathtt{00011110}, t = \mathtt{01010101}; s = \mathtt{00011011}, t = \mathtt{01010101}; s = \mathtt{00001111}, t = \mathtt{01010101}.
1 0011 0101
1
2 seconds
256 megabytes
['brute force', 'dp', 'fft', 'math', 'number theory', '*3500']
H1. Cyclic Hamming (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference between the two versions is the constraint on k. You can make hacks only if all versions of the problem are solved.In this statement, all strings are 0-indexed.For two strings a, b of the same length p, we define the following definitions: The hamming distance between a and b, denoted as h(a, b), is defined as the number of positions i such that 0 \le i < p and a_i \ne b_i. b is a cyclic shift of a if there exists some 0 \leq k < p such that b_{(i+k) \bmod p} = a_i for all 0 \le i < p. Here x \bmod y denotes the remainder from dividing x by y. You are given two binary strings s and t of length 2^{k+1} each. Both strings may contain missing characters (denoted by the character '?'). Your task is to count the number of ways to replace the missing characters in both strings with the characters '0' or '1' such that: Each string s and t contains exactly 2^k occurrences of each character '0' and '1' h(s, c) \ge 2^k for all strings c that is a cyclic shift of t. As the result can be very large, you should print the value modulo 998\,244\,353.InputThe first line of the input contains a single integer k (1 \le k \le 7).The second line of the input contains string s of size 2^{k+1}, consisting of the characters '0', '1' and '?'.The third line of the input contains string t of size 2^{k+1}, consisting of the characters '0', '1' and '?'.It is guaranteed that both strings s and t contains no more than 2^k character '0' or '1'.OutputPrint a single integer — the answer to the problem modulo 998\,244\,353.ExamplesInput 1 0011 0101 Output 1 Input 1 0011 0110 Output 0 Input 1 0??1 01?? Output 2 Input 2 000????? 01010101 Output 3 Input 2 0??????? 1??????? Output 68 Input 5 0101010101010101010101010101010101010101010101010101010101010101 ???????????????????????????????????????????????????????????????? Output 935297567 NoteIn the first example, we can check that the condition h(s, c) \ge 2^k for all cyclic shift c of t is satisfied. In particular: for c = \mathtt{0101}, h(s, c) = h(\mathtt{0110}, \mathtt{0101}) = 2 \ge 2^1; for c = \mathtt{1010}, h(s, c) = h(\mathtt{0110}, \mathtt{1010}) = 2 \ge 2^1. In the second example, there exists a cycle shift c of t such that h(s, c) < 2^k (in particular, c = \mathtt{0011}, and h(s, c) = h(\mathtt{0011}, \mathtt{0011}) = 0).In the third example, there are 2 possible ways to recover the missing characters: s = \mathtt{0101}, t = \mathtt{0110}; s = \mathtt{0011}, t = \mathtt{0101}. In the fourth example, there are 3 possible ways to recover the missing characters: s = \mathtt{00011110}, t = \mathtt{01010101}; s = \mathtt{00011011}, t = \mathtt{01010101}; s = \mathtt{00001111}, t = \mathtt{01010101}.
1 0011 0101
1
2 seconds
256 megabytes
['brute force', 'divide and conquer', 'dp', 'fft', 'math', 'number theory', '*3400']
G. Pepe Racingtime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There are n^2 pepes labeled 1, 2, \ldots, n^2 with pairwise distinct speeds. You would like to set up some races to find out the relative speed of these pepes.In one race, you can choose exactly n distinct pepes and make them race against each other. After each race, you will only know the fastest pepe of these n pepes.Can you order the n^2-n+1 fastest pepes in at most 2n^2 - 2n + 1 races? Note that the slowest n - 1 pepes are indistinguishable from each other.Note that the interactor is adaptive. That is, the relative speeds of the pepes are not fixed in the beginning and may depend on your queries. But it is guaranteed that at any moment there is at least one initial configuration of pepes such that all the answers to the queries are consistent.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 only line of each test case contains a single integer n (2 \le n \le 20) — the number of pepes in one race.After reading the integer n for each test case, you should begin the interaction.It is guaranteed that the sum of n^3 over all test cases does not exceed 3 \cdot 10^5.InteractionTo set up a race, print a line with the following format: \mathtt{?}\,x_1\,x_2 \ldots x_n (1 \le x_i \le n^2, x_i are pairwise distinct) — the labels of the pepes in the race. After each race, you should read a line containing a single integer p (1\le p\le n^2) — the label of the fastest pepe in the race.When you know the n^2-n+1 fastest pepes, print one line in the following format: \mathtt{!}\,p_1\,p_2 \ldots p_{n^2 - n + 1} (1 \le p_i \le n^2, p_i are pairwise distinct) where p is the sequence of these pepe's labels in descending order of speed.After that, move on to the next test case, or terminate the program if no more test cases are remaining.If your program performs more than 2n^2 - 2n + 1 races for one test case or makes an invalid race, you may receive a Wrong Answer verdict.After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. Hack formatFor hacks, use the following format.The first line should contain t — the number of test cases.The first line of each test case should contain an integer n followed by the string manual.The second line of each test case should contain a permutation a_1,a_2,\ldots,a_{n^2} of the integers from 1 to n^2. a_i > a_j if and only if pepe i has a faster speed than pepe j.As an example, the hack format for the example input is: \mathtt{1}\\\mathtt{2}~\mathtt{manual}\\\mathtt{1}~\mathtt{2}~\mathtt{3}~\mathtt{4}ExampleInput 1 2 2 4 4 3 2Output ? 1 2 ? 3 4 ? 2 4 ? 2 3 ? 2 1 ! 4 3 2
1 2 2 4 4 3 2
? 1 2 ? 3 4 ? 2 4 ? 2 3 ? 2 1 ! 4 3 2
5 seconds
256 megabytes
['constructive algorithms', 'implementation', 'interactive', 'sortings', '*3200']
F. Bracket Xoringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s of length 2n where each element is \mathtt{0} or \mathtt{1}. You can do the following operation: Choose a balanced bracket sequence^\dagger b of length 2n. For every index i from 1 to 2n in order, where b_i is an open bracket, let p_i denote the minimum index such that b[i,p_i] is a balanced bracket sequence. Then, we perform a range toggle operation^\ddagger from i to p_i on s. Note that since a balanced bracket sequence of length 2n will have n open brackets, we will do n range toggle operations on s. Your task is to find a sequence of no more than 10 operations that changes all elements of s to \mathtt{0}, or determine that it is impossible to do so. Note that you do not have to minimize the number of operations.Under the given constraints, it can be proven that if it is possible to change all elements of s to \mathtt{0}, there exists a way that requires no more than 10 operations.^\dagger A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences "(())()", "()", and "(()(()))" are balanced, while ")(", "(()", and "(()))(" are not.^\ddagger If we perform a range toggle operation from l to r on a binary string s, then we toggle all values of s_i such that l \leq i \leq r. If s_i is toggled, we will set s_i := \mathtt{0} if s_i = \mathtt{1} or vice versa. For example, if s=\mathtt{1000101} and we perform a range toggle operation from 3 to 5, s will be changed to s=\mathtt{1011001}.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 2\cdot 10^5) — where 2n is the length of string s.The second line of each test case contains a binary string s of length 2n (s_i = \mathtt{0} or s_i = \mathtt{1}).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output -1 in a single line if it is impossible to change all elements of s to \mathtt{0}.Otherwise, output a single integer k (0 \le k \le 10) representing the number of operations needed to change all elements of s to \mathtt{0}. Then, on each of the next k lines, output a balanced bracket sequence of length 2n representing the operations needed to change all elements of s to 0s.If there are multiple ways to change all elements of s to \mathtt{0} that require not more than 10 operations, you can output any of them.ExampleInput 4101200003100111401011100Output -1 2 ()() ()() 1 (())() 2 (((()))) ()()(()) NoteIn the first test case, it can be proven that it is impossible to change all elements of s to \mathtt{0}.In the second test case, the first operation using the bracket sequence b = \mathtt{()()} will convert the binary string s=\mathtt{0000} to s=\mathtt{1111}. Then, the second operation using the same bracket sequence b = \mathtt{()()} will convert the binary string s=\mathtt{1111} back to s=\mathtt{0000}. Note that since all elements of s is already \mathtt{0} initially, using 0 operations is also a valid answer.In the third test case, a single operation using the bracket sequence b = \mathtt{(())()} will change all elements of s to \mathtt{0}. The operation will happen as follows. b_1 is an open bracket and p_1 = 4 since b[1,4]=\mathtt{(())} is a balanced bracket sequence. Hence, we do a range toggle operation from 1 to 4 on the binary string s = \mathtt{100111} to obtain s = \mathtt{011011}. b_2 is an open bracket and p_2 = 3 since b[2,3]=\mathtt{()} is a balanced bracket sequence. Hence, we do a range toggle operation from 2 to 3 on the binary string s = \mathtt{011011} to obtain s = \mathtt{000011}. b_3 is not an open bracket, so no range toggle operation is done at this step. b_4 is not an open bracket, so no range toggle operation is done at this step. b_5 is an open bracket and p_5 = 6 since b[5,6]=\mathtt{()} is a balanced bracket sequence. Hence, we do a range toggle operation from 5 to 6 on the binary string s = \mathtt{000011} to obtain s = \mathtt{000000}. b_6 is not an open bracket, so no range toggle operation is done at this step. In the fourth test case, the first operation using the bracket sequence b = \mathtt{(((())))} will convert the binary string s = \mathtt{01011100} to s = \mathtt{11111001}. Then, the second operation using the bracket sequence b = \mathtt{()()(())} will convert the binary string s = \mathtt{11111001} to s=\mathtt{00000000}.
4101200003100111401011100
-1 2 ()() ()() 1 (())() 2 (((()))) ()()(())
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*2600']
E. Permutation Sortingtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^\dagger a of size n. We call an index i good if a_i=i is satisfied. After each second, we rotate all indices that are not good to the right by one position. Formally, Let s_1,s_2,\ldots,s_k be the indices of a that are not good in increasing order. That is, s_j < s_{j+1} and if index i is not good, then there exists j such that s_j=i. For each i from 1 to k, we assign a_{s_{(i \% k+1)}} := a_{s_i} all at once. For each i from 1 to n, find the first time that index i becomes good. ^\dagger A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains 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^6) — the size of permutation a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of permutation a.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output a single line containing n integers where the i-th integer represents the first time that index i becomes good.ExampleInput 253 2 4 1 562 1 4 6 5 3Output 1 0 1 1 0 2 1 2 1 0 1 NoteIn the first test case, 2 and 5 are already in the correct position so indices 2 and 5 become good at 0 second. After 1 second, a cyclic shift will be done with s=[1, 3, 4], resulting in array a=[1, 2, 3, 4, 5]. Notice that indices 1, 3 and 4 become good at 1 second.In the second test case, 5 is already in the correct position, so index 5 becomes good at 0 second. After 1 second, a cyclic shift will be done with s=[1, 2, 3, 4, 6], resulting in array a=[3, 2, 1, 4, 5, 6]. Notice that indices 2, 4 and 6 become good at 1 second. After 2 seconds, a cyclic shift will be done with s=[1, 3], resulting in array a=[1, 2, 3, 4, 5, 6]. Notice that indices 1 and 3 become good at 2 second.
253 2 4 1 562 1 4 6 5 3
1 0 1 1 0 2 1 2 1 0 1
4 seconds
256 megabytes
['data structures', 'sortings', '*2100']
D. Ones and Twostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a 1-indexed array a of length n where each element is 1 or 2.Process q queries of the following two types: "1 s": check if there exists a subarray^{\dagger} of a whose sum equals to s. "2 i v": change a_i to v. ^{\dagger} An array b is a subarray of an array a if b can be obtained from a by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and q (1\le n,q\le 10^5) — the length of array a and the number of queries.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (a_i is 1 or 2) — the elements of array a.Each of the following q lines of each test case contains some integers. The first integer \mathrm{op} is either 1 or 2. If \mathrm{op} is 1, it is followed by one integer s (1 \leq s \leq 2n). If \mathrm{op} is 2, it is followed by two integers i and v (1 \leq i \leq n, v is 1 or 2). It is guaranteed that the sum of n and the sum of q over all test cases both do not exceed 10^5.OutputFor each query with \mathrm{op}=1, output "YES" in one line if there exists a subarray of a whose sum is equals to s, otherwise output "NO".You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 25 52 1 2 1 21 51 61 72 4 21 73 22 2 21 61 5Output YES YES NO YES YES NONoteConsider the first example: The answer for the first query is "YES" because a_1+a_2+a_3=2+1+2=5. The answer for the second query is "YES" because a_1+a_2+a_3+a_4=2+1+2+1=6. The answer for the third query is "NO" because we cannot find any subarray of a whose sum is 7. After the fourth query, the array a becomes [2,1,2,2,2]. The answer for the fifth query is "YES" because a_2+a_3+a_4+a_5=1+2+2+2=7.
25 52 1 2 1 21 51 61 72 4 21 73 22 2 21 61 5
YES YES NO YES YES NO
2 seconds
256 megabytes
['binary search', 'data structures', 'divide and conquer', 'math', 'two pointers', '*1700']
C. Matching Arraystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two arrays a and b of size n. The beauty of the arrays a and b is the number of indices i such that a_i > b_i.You are also given an integer x. Determine whether it is possible to rearrange the elements of b such that the beauty of the arrays becomes x. If it is possible, output one valid rearrangement of b.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 x (1 \le n \le 2\cdot 10^5, 0 \le x \le n) — the size of arrays a and b and the desired beauty of the arrays.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 2n) — the elements of array a.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 2n) — the elements of array b.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output "NO" if it is not possible to rearrange b to make the beauty of the arrays equal to x.Otherwise, output "YES". Then, on the next line, output n integers which represent the rearrangement of b.If there are multiple solutions, you may output any of them.You can output "YES" and "NO" in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 71 0121 1123 02 4 34 1 23 12 4 34 1 23 22 4 34 1 23 32 4 34 1 25 26 4 5 6 29 7 9 1 1Output YES 2 NO NO YES 2 4 1 YES 4 1 2 NO YES 1 9 9 7 1 NoteIn test cases 1 and 2, the beauty of the arrays has to be 0 since a_1 = 1 \le 2 = b_1.In test cases 3, 4, 5 and 6, the only possible beauty of the arrays is x = 1 and x = 2. In particular, if b is rearranged to [2, 4, 1], then a_3 = 3 > 1 = b_3, so the beauty of the arrays is 1. If b is kept in the same order as given the input, then a_2 = 4 > b_2 = 1 and a_3 = 3 > 2 = b_3, so the beauty of the arrays is 2.
71 0121 1123 02 4 34 1 23 12 4 34 1 23 22 4 34 1 23 32 4 34 1 25 26 4 5 6 29 7 9 1 1
YES 2 NO NO YES 2 4 1 YES 4 1 2 NO YES 1 9 9 7 1
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'sortings', '*1400']
B. AB Flippingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of characters \texttt{A} and \texttt{B}. You are allowed to do the following operation: Choose an index 1 \le i \le n - 1 such that s_i = \texttt{A} and s_{i + 1} = \texttt{B}. Then, swap s_i and s_{i+1}. You are only allowed to do the operation at most once for each index 1 \le i \le n - 1. However, you can do it in any order you want. Find the maximum number of operations that you can carry out. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). Description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2\cdot 10^5) — the length of string s.The second line of each test case contains the string s (s_i=\texttt{A} or s_i=\texttt{B}).It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print a single integer containing the maximum number of operations that you can carry out.ExampleInput 32AB4BBBA4AABBOutput 1 0 3 NoteIn the first test case, we can do the operation exactly once for i=1 as s_1=\texttt{A} and s_2=\texttt{B}.In the second test case, it can be proven that it is not possible to do an operation.In the third test case, we can do an operation on i=2 to form \texttt{ABAB}, then another operation on i=3 to form \texttt{ABBA}, and finally another operation on i=1 to form \texttt{BABA}. Note that even though at the end, s_2 = \texttt{A} and s_3 = \texttt{B}, we cannot do an operation on i=2 again as we can only do the operation at most once for each index.
32AB4BBBA4AABB
1 0 3
1 second
256 megabytes
['greedy', 'strings', 'two pointers', '*900']
A. Jagged Swapstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^\dagger a of size n. You can do the following operation Select an index i from 2 to n - 1 such that a_{i - 1} < a_i and a_i > a_{i+1}. Swap a_i and a_{i+1}. Determine whether it is possible to sort the permutation after a finite number of operations.^\dagger A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 5000). Description of the test cases follows.The first line of each test case contains a single integer n (3 \le n \le 10) — the size of the permutation.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le n) — the elements of permutation a.OutputFor each test case, print "YES" if it is possible to sort the permutation, and "NO" otherwise.You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).ExampleInput 631 2 351 3 2 5 455 4 3 2 133 1 242 3 1 455 1 2 3 4Output YES YES NO NO NO NO NoteIn the first test case, the permutation is already sorted.In the second test case, we can choose index i=2 as 1<3 and 3>2 to form [1, 2, 3, 5, 4]. Then, we can choose index i=4 as 3<5 and 5>4 to form [1, 2, 3, 4, 5].In the third test case, it can be proven that it is impossible to sort the permutation.
631 2 351 3 2 5 455 4 3 2 133 1 242 3 1 455 1 2 3 4
YES YES NO NO NO NO
1 second
256 megabytes
['sortings', '*800']
G. Two Characters, Two Colorstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string consisting of characters 0 and/or 1. You have to paint every character of this string into one of two colors, red or blue.If you paint the i-th character red, you get r_i coins. If you paint it blue, you get b_i coins.After coloring the string, you remove every blue character from it, and count the number of inversions in the resulting string (i. e. the number of pairs of characters such that the left character in the pair is 1, and the right character in the pair is 0). For each inversion, you have to pay 1 coin.What is the maximum number of coins you can earn?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 four lines: the first line contains one integer n (1 \le n \le 4 \cdot 10^5) — the length of the string; the second line contains s — a string of n characters, where each character is either 0 or 1; the third line contains n integers r_1, r_2, \dots, r_n (1 \le r_i \le 10^{12}); the fourth line contains n integers b_1, b_2, \dots, b_n (1 \le b_i \le 10^{12}). Additional constraint on the input: the sum of values of n over all test cases does not exceed 4 \cdot 10^5.OutputFor each test case, print one integer — the maximum number of coins you can earn.ExampleInput 4701000106 6 6 7 7 6 63 3 5 4 7 6 75101119 8 5 7 54 4 7 8 41001000000007 7 6 5 2 2 5 3 8 38 6 9 6 6 8 9 7 7 98010100008 7 7 7 8 7 7 84 4 4 2 1 4 4 4Output 43 36 76 52 NoteExplanations for the test cases for the example (blue characters are underlined, red ones are not): 0100\underline{0}1\underline{0}; 10\underline{11}1; \underline{0}1\underline{00000000}; 0\underline{1}010000.
4701000106 6 6 7 7 6 63 3 5 4 7 6 75101119 8 5 7 54 4 7 8 41001000000007 7 6 5 2 2 5 3 8 38 6 9 6 6 8 9 7 7 98010100008 7 7 7 8 7 7 84 4 4 2 1 4 4 4
43 36 76 52
4 seconds
512 megabytes
['binary search', 'data structures', 'dp', 'flows', 'greedy', '*3100']
F. Fancy Arraystime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call an array a of n non-negative integers fancy if the following conditions hold: at least one from the numbers x, x + 1, ..., x+k-1 appears in the array; consecutive elements of the array differ by at most k (i.e. |a_i-a_{i-1}| \le k for each i \in [2, n]). You are given n, x and k. Your task is to calculate the number of fancy arrays of length n. Since the answer can be large, print it modulo 10^9+7.InputThe first line contains a single integer t (1 \le t \le 50) — the number of test cases.The only line of each test case contains three integers n, x and k (1 \le n, k \le 10^9; 0 \le x \le 40).OutputFor each test case, print a single integer — the number of fancy arrays of length n, taken modulo 10^9+7.ExampleInput 43 0 11 4 254 7 21000000000 40 1000000000Output 9 25 582 514035484 NoteIn the first test case of the example, the following arrays are fancy: [0, 0, 0]; [0, 0, 1]; [0, 1, 0]; [0, 1, 1]; [0, 1, 2]; [1, 0, 0]; [1, 0, 1]; [1, 1, 0]; [2, 1, 0].
43 0 11 4 254 7 21000000000 40 1000000000
9 25 582 514035484
4 seconds
512 megabytes
['combinatorics', 'dp', 'math', 'matrices', '*2600']
E. Infinite Card Gametime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp and Bicarp are playing a card game. Each card has two parameters: an attack value and a defence value. A card s beats another card t if the attack of s is strictly greater than the defence of t.Monocarp has n cards, the i-th of them has an attack value of \mathit{ax}_i and a defence value of \mathit{ay}_i. Bicarp has m cards, the j-th of them has an attack value of \mathit{bx}_j and a defence value of \mathit{by}_j.On the first move, Monocarp chooses one of his cards and plays it. Bicarp has to respond with his own card that beats that card. After that, Monocarp has to respond with a card that beats Bicarp's card. After that, it's Bicarp's turn, and so forth.After a card is beaten, it returns to the hand of the player who played it. It implies that each player always has the same set of cards to play as at the start of the game. The game ends when the current player has no cards that beat the card which their opponent just played, and the current player loses.If the game lasts for 100^{500} moves, it's declared a draw.Both Monocarp and Bicarp play optimally. That is, if a player has a winning strategy regardless of his opponent's moves, he plays for a win. Otherwise, if he has a drawing strategy, he plays for a draw.You are asked to calculate three values: the number of Monocarp's starting moves that result in a win for Monocarp; the number of Monocarp's starting moves that result in a draw; the number of Monocarp's starting moves that result in a win for Bicarp. 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 an integer n (1 \le n \le 3 \cdot 10^5) — the number of cards Monocarp has.The second line contains n integers \mathit{ax}_1, \mathit{ax}_2, \dots, \mathit{ax}_n (1 \le \mathit{ax}_i \le 10^6) — the attack values of Monocarp's cards.The third line contains n integers \mathit{ay}_1, \mathit{ay}_2, \dots, \mathit{ay}_n (1 \le \mathit{ay}_i \le 10^6) — the defence values of Monocarp's cards.The fourth line contains a single integer m (1 \le m \le 3 \cdot 10^5) — the number of cards Bicarp has.The fifth line contains m integers \mathit{bx}_1, \mathit{bx}_2, \dots, \mathit{bx}_m (1 \le \mathit{bx}_j \le 10^6) — the attack values of Bicarp's cards.The sixth line contains m integers \mathit{by}_1, \mathit{by}_2, \dots, \mathit{by}_m (1 \le \mathit{by}_j \le 10^6) — the defence values of Bicarp's cards.Additional constraints on the input: the sum of n over all test cases doesn't exceed 3 \cdot 10^5, the sum of m over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print three integers: the number of Monocarp's starting moves that result in a win for Monocarp; the number of Monocarp's starting moves that result in a draw; the number of Monocarp's starting moves that result in a win for Bicarp. ExampleInput 338 7 47 1 1028 45 1098 8 5 5 5 4 4 1 42 7 5 2 8 9 7 1 9109 8 7 6 5 5 4 3 2 17 1 6 7 5 8 8 4 9 611051105Output 1 1 1 2 4 3 0 1 0
338 7 47 1 1028 45 1098 8 5 5 5 4 4 1 42 7 5 2 8 9 7 1 9109 8 7 6 5 5 4 3 2 17 1 6 7 5 8 8 4 9 611051105
1 1 1 2 4 3 0 1 0
3 seconds
512 megabytes
['binary search', 'brute force', 'data structures', 'dfs and similar', 'dp', 'dsu', 'games', 'graphs', 'greedy', 'sortings', 'two pointers', '*2300']
D. XOR Constructiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given n-1 integers a_1, a_2, \dots, a_{n-1}.Your task is to construct an array b_1, b_2, \dots, b_n such that: every integer from 0 to n-1 appears in b exactly once; for every i from 1 to n-1, b_i \oplus b_{i+1} = a_i (where \oplus denotes the bitwise XOR operator). InputThe first line contains one integer n (2 \le n \le 2 \cdot 10^5).The second line contains n-1 integers a_1, a_2, \dots, a_{n-1} (0 \le a_i \le 2n).Additional constraint on the input: it's always possible to construct at least one valid array b from the given sequence a.OutputPrint n integers b_1, b_2, \dots, b_n. If there are multiple such arrays, you may print any of them.ExamplesInput 42 1 2Output 0 2 3 1 Input 61 6 1 4 1Output 2 3 5 4 0 1
42 1 2
0 2 3 1
2 seconds
512 megabytes
['bitmasks', 'constructive algorithms', 'data structures', 'math', 'string suffix structures', 'trees', '*1900']
C. Torn Lucky Tickettime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA ticket is a non-empty string of digits from 1 to 9.A lucky ticket is such a ticket that: it has an even length; the sum of digits in the first half is equal to the sum of digits in the second half. You are given n ticket pieces s_1, s_2, \dots, s_n. How many pairs (i, j) (for 1 \le i, j \le n) are there such that s_i + s_j is a lucky ticket? Note that it's possible that i=j.Here, the + operator denotes the concatenation of the two strings. For example, if s_i is 13, and s_j is 37, then s_i + s_j is 1337.InputThe first line contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of ticket pieces.The second line contains n non-empty strings s_1, s_2, \dots, s_n, each of length at most 5 and consisting only of digits from 1 to 9.OutputPrint a single integer — the number of pairs (i, j) (for 1 \le i, j \le n) such that s_i + s_j is a lucky ticket.ExamplesInput 105 93746 59 3746 593 746 5937 46 59374 6Output 20 Input 52 22 222 2222 22222Output 13 Input 31 1 1Output 9
105 93746 59 3746 593 746 5937 46 59374 6
20
2 seconds
512 megabytes
['brute force', 'dp', 'hashing', 'implementation', 'math', '*1400']
B. Points and Minimum Distancetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a sequence of integers a of length 2n. You have to split these 2n integers into n pairs; each pair will represent the coordinates of a point on a plane. Each number from the sequence a should become the x or y coordinate of exactly one point. Note that some points can be equal.After the points are formed, you have to choose a path s that starts from one of these points, ends at one of these points, and visits all n points at least once.The length of path s is the sum of distances between all adjacent points on the path. In this problem, the distance between two points (x_1, y_1) and (x_2, y_2) is defined as |x_1-x_2| + |y_1-y_2|.Your task is to form n points and choose a path s in such a way that the length of path s is minimized.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 (2 \le n \le 100) — the number of points to be formed.The next line contains 2n integers a_1, a_2, \dots, a_{2n} (0 \le a_i \le 1\,000) — the description of the sequence a.OutputFor each testcase, print the minimum possible length of path s in the first line.In the i-th of the following n lines, print two integers x_i and y_i — the coordinates of the point that needs to be visited at the i-th position.If there are multiple answers, print any of them.ExampleInput 2215 1 10 5310 30 20 20 30 10Output 9 10 1 15 5 20 20 20 10 30 10 30 NoteIn the first testcase, for instance, you can form points (10, 1) and (15, 5) and start the path s from the first point and end it at the second point. Then the length of the path will be |10 - 15| + |1 - 5| = 5 + 4 = 9.In the second testcase, you can form points (20, 20), (10, 30), and (10, 30), and visit them in that exact order. Then the length of the path will be |20 - 10| + |20 - 30| + |10 - 10| + |30 - 30| = 10 + 10 + 0 + 0 = 20.
2215 1 10 5310 30 20 20 30 10
9 10 1 15 5 20 20 20 10 30 10 30
2 seconds
512 megabytes
['greedy', 'math', 'sortings', '*800']
A. Treasure Chesttime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp has found a treasure map. The map represents the treasure location as an OX axis. Monocarp is at 0, the treasure chest is at x, the key to the chest is at y.Obviously, Monocarp wants to open the chest. He can perform the following actions: go 1 to the left or 1 to the right (spending 1 second); pick the key or the chest up if he is in the same point as that object (spending 0 seconds); put the chest down in his current point (spending 0 seconds); open the chest if he's in the same point as the chest and has picked the key up (spending 0 seconds). Monocarp can carry the chest, but the chest is pretty heavy. He knows that he can carry it for at most k seconds in total (putting it down and picking it back up doesn't reset his stamina).What's the smallest time required for Monocarp to open the chest?InputThe first line contains a single integer t (1 \le t \le 100) — the number of testcases.The only line of each testcase contains three integers x, y and k (1 \le x, y \le 100; x \neq y; 0 \le k \le 100) — the initial point of the chest, the point where the key is located, and the maximum time Monocarp can carry the chest for.OutputFor each testcase, print a single integer — the smallest time required for Monocarp to open the chest.ExampleInput 35 7 210 5 05 8 2Output 7 10 9 NoteIn the first testcase, Monocarp can open the chest in 7 seconds with the following sequence of moves: go 5 times to the right (5 seconds); pick up the chest (0 seconds); go 2 times to the right (2 seconds); pick up the key (0 seconds); put the chest down (0 seconds); open the chest (0 seconds). He only carries the chest for 2 seconds, which he has the stamina for.In the second testcase, Monocarp can pick up the key on his way to the chest.In the third testcase, Monocarp can't use the strategy from the first testcase because he would have to carry the chest for 3 seconds, while he only has the stamina for 2 seconds. Thus, he carries the chest to 7, puts it down, moves 1 to the right to pick up the key and returns 1 left to open the chest.
35 7 210 5 05 8 2
7 10 9
2 seconds
512 megabytes
['math', '*800']
B. Two Out of Threetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a_1, a_2, \ldots, a_n. You need to find an array b_1, b_2, \ldots, b_n consisting of numbers 1, 2, 3 such that exactly two out of the following three conditions are satisfied: There exist indices 1 \leq i, j \leq n such that a_i = a_j, b_i = 1, b_j = 2. There exist indices 1 \leq i, j \leq n such that a_i = a_j, b_i = 1, b_j = 3. There exist indices 1 \leq i, j \leq n such that a_i = a_j, b_i = 2, b_j = 3.If such an array does not exist, you should report it.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 500) — the number of test cases. Each test case is described as follows.The first line of each test case contains an integer n (1 \leq n \leq 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 \leq a_i \leq 100) — the elements of the array a.OutputFor each test case, print -1 if there is no solution. Otherwise, print b_1, b_2, \ldots, b_n — an array consisting of numbers 1, 2, 3 that satisfies exactly two out of three conditions. If there are multiple possible answers, you can print any of them.ExampleInput 961 2 3 2 2 377 7 7 7 7 7 741 1 2 271 2 3 4 5 6 752 3 3 3 231 2 191 1 1 7 7 7 9 9 9111893 84 50 21 88 52 16 50 63 1 30 85 29 67 63 58 37 69Output 1 2 3 1 1 1 -1 3 2 2 1 -1 2 1 2 1 3 -1 1 1 2 2 1 2 2 3 3 -1 3 2 1 3 3 3 3 2 2 1 1 2 3 1 3 1 1 2 NoteIn the first test case, b = [1, 2, 3, 1, 1, 1] satisfies condition 1 because for i = 4, j = 2: a_i = a_j, b_i = 1, and b_j = 2. It also satisfies condition 2 because for i = 6, j = 3: a_i = a_j, b_i = 1, and b_j = 3. However, it does not satisfy condition 3. In total, exactly two out of three conditions are satisfied.
961 2 3 2 2 377 7 7 7 7 7 741 1 2 271 2 3 4 5 6 752 3 3 3 231 2 191 1 1 7 7 7 9 9 9111893 84 50 21 88 52 16 50 63 1 30 85 29 67 63 58 37 69
1 2 3 1 1 1 -1 3 2 2 1 -1 2 1 2 1 3 -1 1 1 2 2 1 2 2 3 3 -1 3 2 1 3 3 3 3 2 2 1 1 2 3 1 3 1 1 2
3 seconds
512 megabytes
['constructive algorithms', '*1000']
A. Secret Sporttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's consider a game in which two players, A and B, participate. This game is characterized by two positive integers, X and Y.The game consists of sets, and each set consists of plays. In each play, exactly one of the players, either A or B, wins. A set ends exactly when one of the players reaches X wins in the plays of that set. This player is declared the winner of the set. The players play sets until one of them reaches Y wins in the sets. After that, the game ends, and this player is declared the winner of the entire game.You have just watched a game but didn't notice who was declared the winner. You remember that during the game, n plays were played, and you know which player won each play. However, you do not know the values of X and Y. Based on the available information, determine who won the entire game — A or B. If there is not enough information to determine the winner, you should also report it.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 an integer n (1 \leq n \leq 20) - the number of plays played during the game.The second line of each test case contains a string s of length n, consisting of characters \texttt{A} and \texttt{B}. If s_i = \texttt{A}, it means that player A won the i-th play. If s_i = \texttt{B}, it means that player B won the i-th play.It is guaranteed that the given sequence of plays corresponds to at least one valid game scenario, for some values of X and Y.OutputFor each test case, output: \texttt{A} — if player A is guaranteed to be the winner of the game. \texttt{B} — if player B is guaranteed to be the winner of the game. \texttt{?} — if it is impossible to determine the winner of the game.ExampleInput 75ABBAA3BBB7BBAAABA20AAAAAAAABBBAABBBBBAB1A13AAAABABBABBAB7BBBAAAAOutput A B A B A B A NoteIn the first test case, the game could have been played with parameters X = 3, Y = 1. The game consisted of 1 set, in which player A won, as they won the first 3 plays. In this scenario, player A is the winner. The game could also have been played with parameters X = 1, Y = 3. It can be shown that there are no such X and Y values for which player B would be the winner.In the second test case, player B won all the plays. It can be easily shown that in this case, player B is guaranteed to be the winner of the game.In the fourth test case, the game could have been played with parameters X = 3, Y = 3: In the first set, 3 plays were played: AAA. Player A is declared the winner of the set. In the second set, 3 plays were played: AAA. Player A is declared the winner of the set. In the third set, 5 plays were played: AABBB. Player B is declared the winner of the set. In the fourth set, 5 plays were played: AABBB. Player B is declared the winner of the set. In the fifth set, 4 plays were played: BBAB. Player B is declared the winner of the set.In total, player B was the first player to win 3 sets. They are declared the winner of the game.
75ABBAA3BBB7BBAAABA20AAAAAAAABBBAABBBBBAB1A13AAAABABBABBAB7BBBAAAA
A B A B A B A
3 seconds
512 megabytes
['implementation', 'strings', '*800']
E. Cacti Symphonytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an undirected connected graph in which any two distinct simple cycles do not have common vertices. Since the graph can be very large, it is given to you in a compressed form: for each edge, you are also given a number d, which indicates that there are d additional vertices on this edge.You need to assign a weight to each vertex and each edge of the graph — an integer from 1 to 3.An edge of the graph is called good if the bitwise XOR of the weights of its adjacent vertices is not equal to 0 and not equal to the weight of that edge.Similarly, a vertex of the graph is called good if the bitwise XOR of the weights of its adjacent edges is not equal to 0 and not equal to the weight of that vertex.You need to determine how many ways there are to assign weights to the vertices and edges of the graph so that all vertices and edges are good. Since the answer can be quite large, you need to calculate the remainder of the answer divided by 998\,244\,353.InputThe first line contains two integers n and m — the number of vertices and the number of edges in the graph (2 \le n \le 5 \cdot 10^5, n - 1 \le m \le 10^6).Each of the next m lines contains three integers a_i, b_i, and d_i (1 \le a_i, b_i \le n, a_i \ne b_i, 0 \le d_i \le 10^9), indicating that there is an edge in the graph connecting vertices a_i and b_i. Additionally, on this edge, there are d_i additional vertices. It is guaranteed that the given graph is connected, there are no multiple edges, loops, and any two distinct simple cycles of the graph do not have common vertices.OutputOutput a single integer — the answer to the problem modulo 998\,244\,353.ExamplesInput 3 3 1 2 0 2 3 0 3 1 0 Output 12 Input 6 7 1 2 0 2 3 0 3 1 0 4 5 0 5 6 0 6 4 0 4 3 0 Output 0 Input 2 1 2 1 777 Output 0 Input 3 3 1 2 0 2 3 110850709 3 1 1000000000 Output 179179178 NoteIn the first test, the graph is a simple cycle of 3 vertices. It can be shown, that there are exactly 12 ways to assign weights, to make all vertexes and edges good.In the second test, the graph has the form of two simple cycles of 3 vertices connected by an edge. It can be shown that for such a graph there are no ways to arrange weights so that all vertices and edges are good.
3 3 1 2 0 2 3 0 3 1 0
12
3 seconds
512 megabytes
['combinatorics', 'dfs and similar', 'dp', 'graphs', '*3500']
D. Colorful Constructivetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou have n colored cubes, the i-th cube has color a_i.You need to distribute all the cubes on shelves. There are a total of m shelves, the i-th shelf can hold s_i cubes. Also, s_1 + s_2 + \ldots + s_m = n.Suppose on a shelf of size k there are cubes of colors c_1, c_2, \ldots, c_k, in this order. Then we define the colorfulness of the shelf as the minimum distance between two different cubes of the same color on the shelf. If all the cubes on the shelf have different colors, then the colorfulness is considered to be equal to the size of the shelf, that is, the number k.More formally, the colorfulness of c_1, c_2, \ldots, c_k is defined as follows: If all the colors c_1, c_2, \ldots, c_k are different, the colorfulness is considered to be k. Otherwise, the colorfulness is considered to be the smallest integer x \geq 1 such that there exists an index i (1 \le i \le k - x) such that c_i = c_{i+x}.For each shelf, you are given the minimum required colorfulness, that is, you are given numbers d_1, d_2, \ldots, d_m, which mean that shelf i must have a colorfulness \geq d_i for all i.Distribute the available cubes among the shelves to ensure the required colorfulness, or report that it is impossible.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, m (1 \leq m \leq n \leq 2 \cdot 10^5) — the number of cubes and the number of shelves to distribute them to.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq n) — the colors of the cubes.The third line of each test case contains m integers s_1, s_2, \ldots, s_m (1 \leq s_i \leq n) — the sizes of the shelves. It's guaranteed, that s_1 + \ldots + s_m = n.The fourth line of each test case contains m integers d_1, d_2, \ldots, d_m (1 \leq d_i \leq s_i) — the minimum required colorfulness of the shelves.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, if it is impossible to distribute the cubes on the shelves satisfying all the requirements, output a single number -1. Otherwise, output m lines, where the i-th line should contain s_i numbers representing the colors of the cubes on the i-th shelf, in the appropriate order.ExampleInput 610 31 1 1 1 2 2 2 3 3 46 2 24 1 18 27 7 7 7 8 8 8 84 42 25 15 4 3 2 1537 31 2 2 2 2 3 41 2 41 2 412 76 6 6 6 6 6 6 6 6 7 8 92 2 2 2 2 1 11 2 2 2 1 1 120 211 20 15 6 8 18 12 16 8 20 10 12 3 12 20 11 15 8 17 178 123 5Output 1 3 4 2 1 3 1 1 2 2 8 7 8 7 8 7 8 7 2 4 5 3 1 -1 6 6 7 6 8 6 9 6 6 6 6 6 12 17 20 15 8 20 16 11 15 20 17 12 10 8 3 18 12 11 8 6
610 31 1 1 1 2 2 2 3 3 46 2 24 1 18 27 7 7 7 8 8 8 84 42 25 15 4 3 2 1537 31 2 2 2 2 3 41 2 41 2 412 76 6 6 6 6 6 6 6 6 7 8 92 2 2 2 2 1 11 2 2 2 1 1 120 211 20 15 6 8 18 12 16 8 20 10 12 3 12 20 11 15 8 17 178 123 5
1 3 4 2 1 3 1 1 2 2 8 7 8 7 8 7 8 7 2 4 5 3 1 -1 6 6 7 6 8 6 9 6 6 6 6 6 12 17 20 15 8 20 16 11 15 20 17 12 10 8 3 18 12 11 8 6
3 seconds
512 megabytes
['constructive algorithms', 'data structures', 'greedy', '*2600']
C. Freedom of Choicetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's define the anti-beauty of a multiset \{b_1, b_2, \ldots, b_{len}\} as the number of occurrences of the number len in the multiset.You are given m multisets, where the i-th multiset contains n_i distinct elements, specifically: c_{i, 1} copies of the number a_{i,1}, c_{i, 2} copies of the number a_{i,2}, \ldots, c_{i, n_i} copies of the number a_{i, n_i}. It is guaranteed that a_{i, 1} < a_{i, 2} < \ldots < a_{i, n_i}. You are also given numbers l_1, l_2, \ldots, l_m and r_1, r_2, \ldots, r_m such that 1 \le l_i \le r_i \le c_{i, 1} + \ldots + c_{i, n_i}.Let's create a multiset X, initially empty. Then, for each i from 1 to m, you must perform the following action exactly once: Choose some v_i such that l_i \le v_i \le r_i Choose any v_i numbers from the i-th multiset and add them to the multiset X.You need to choose v_1, \ldots, v_m and the added numbers in such a way that the resulting multiset X has the minimum possible anti-beauty.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer m (1 \le m \le 10^5) — the number of given multisets.Then, for each i from 1 to m, a data block consisting of three lines is entered.The first line of each block contains three integers n_i, l_i, r_i (1 \le n_i \le 10^5, 1 \le l_i \le r_i \le c_{i, 1} + \ldots + c_{i, n_i} \le 10^{17}) — the number of distinct numbers in the i-th multiset and the limits on the number of elements to be added to X from the i-th multiset.The second line of the block contains n_i integers a_{i, 1}, \ldots, a_{i, n_i} (1 \le a_{i, 1} < \ldots < a_{i, n_i} \le 10^{17}) — the distinct elements of the i-th multiset.The third line of the block contains n_i integers c_{i, 1}, \ldots, c_{i, n_i} (1 \le c_{i, j} \le 10^{12}) — the number of copies of the elements in the i-th multiset.It is guaranteed that the sum of the values of m for all test cases does not exceed 10^5, and also the sum of n_i for all blocks of all test cases does not exceed 10^5.OutputFor each test case, output the minimum possible anti-beauty of the multiset X that you can achieve.ExampleInput 733 5 610 11 123 3 11 1 31242 4 412 131 517 1000 10061000 1001 1002 1003 1004 1005 1006147 145 143 143 143 143 14212 48 5048 5025 2521 1 1111 1 12111 1 11221 1 1112 1 11 21 124 8 1011 12 13 143 3 3 32 3 411 122 2Output 1 139 0 1 1 0 0 NoteIn the first test case, the multisets have the following form: \{10, 10, 10, 11, 11, 11, 12\}. From this multiset, you need to select between 5 and 6 numbers. \{12, 12, 12, 12\}. From this multiset, you need to select between 1 and 3 numbers. \{12, 13, 13, 13, 13, 13\}. From this multiset, you need to select 4 numbers.You can select the elements \{10, 11, 11, 11, 12\} from the first multiset, \{12\} from the second multiset, and \{13, 13, 13, 13\} from the third multiset. Thus, X = \{10, 11, 11, 11, 12, 12, 13, 13, 13, 13\}. The size of X is 10, the number 10 appears exactly 1 time in X, so the anti-beauty of X is 1. It can be shown that it is not possible to achieve an anti-beauty less than 1.
733 5 610 11 123 3 11 1 31242 4 412 131 517 1000 10061000 1001 1002 1003 1004 1005 1006147 145 143 143 143 143 14212 48 5048 5025 2521 1 1111 1 12111 1 11221 1 1112 1 11 21 124 8 1011 12 13 143 3 3 32 3 411 122 2
1 139 0 1 1 0 0
3 seconds
512 megabytes
['brute force', 'greedy', 'implementation', '*2000']
B. Neutral Tonalitytime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers, as well as an array b consisting of m integers.Let \text{LIS}(c) denote the length of the longest increasing subsequence of array c. For example, \text{LIS}([2, \underline{1}, 1, \underline{3}]) = 2, \text{LIS}([\underline{1}, \underline{7}, \underline{9}]) = 3, \text{LIS}([3, \underline{1}, \underline{2}, \underline{4}]) = 3.You need to insert the numbers b_1, b_2, \ldots, b_m into the array a, at any positions, in any order. Let the resulting array be c_1, c_2, \ldots, c_{n+m}. You need to choose the positions for insertion in order to minimize \text{LIS}(c).Formally, you need to find an array c_1, c_2, \ldots, c_{n+m} that simultaneously satisfies the following conditions: The array a_1, a_2, \ldots, a_n is a subsequence of the array c_1, c_2, \ldots, c_{n+m}. The array c_1, c_2, \ldots, c_{n+m} consists of the numbers a_1, a_2, \ldots, a_n, b_1, b_2, \ldots, b_m, possibly rearranged. The value of \text{LIS}(c) is the minimum possible among all suitable arrays c.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, m (1 \leq n \leq 2 \cdot 10^5, 1 \leq m \leq 2 \cdot 10^5) — the length of array a and the length of array b.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the elements of the array a.The third line of each test case contains m integers b_1, b_2, \ldots, b_m (1 \leq b_i \leq 10^9) — the elements of the array b.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5, and the sum of m over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output n + m numbers — the elements of the final array c_1, c_2, \ldots, c_{n+m}, obtained after the insertion, such that the value of \text{LIS}(c) is minimized. If there are several answers, you can output any of them.ExampleInput 72 16 455 51 7 2 4 55 4 1 2 71 971 2 3 4 5 6 7 8 93 21 3 52 410 51 9 2 3 8 1 4 7 2 97 8 5 4 62 12 216 11 1 1 1 1 1777Output 6 5 4 1 1 7 7 2 2 4 4 5 5 9 8 7 7 6 5 4 3 2 1 1 3 5 2 4 1 9 2 3 8 8 1 4 4 7 7 2 9 6 5 2 2 1 777 1 1 1 1 1 1 NoteIn the first test case, \text{LIS}(a) = \text{LIS}([6, 4]) = 1. We can insert the number 5 between 6 and 4, then \text{LIS}(c) = \text{LIS}([6, 5, 4]) = 1.In the second test case, \text{LIS}([\underline{1}, 7, \underline{2}, \underline{4}, \underline{5}]) = 4. After the insertion, c = [1, 1, 7, 7, 2, 2, 4, 4, 5, 5]. It is easy to see that \text{LIS}(c) = 4. It can be shown that it is impossible to achieve \text{LIS}(c) less than 4.
72 16 455 51 7 2 4 55 4 1 2 71 971 2 3 4 5 6 7 8 93 21 3 52 410 51 9 2 3 8 1 4 7 2 97 8 5 4 62 12 216 11 1 1 1 1 1777
6 5 4 1 1 7 7 2 2 4 4 5 5 9 8 7 7 6 5 4 3 2 1 1 3 5 2 4 1 9 2 3 8 8 1 4 4 7 7 2 9 6 5 2 2 1 777 1 1 1 1 1 1
3 seconds
512 megabytes
['constructive algorithms', 'greedy', 'sortings', 'two pointers', '*1700']
A. Anonymous Informanttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array b_1, b_2, \ldots, b_n.An anonymous informant has told you that the array b was obtained as follows: initially, there existed an array a_1, a_2, \ldots, a_n, after which the following two-component operation was performed k times: A fixed point^{\dagger} x of the array a was chosen. Then, the array a was cyclically shifted to the left^{\ddagger} exactly x times.As a result of k such operations, the array b_1, b_2, \ldots, b_n was obtained. You want to check if the words of the anonymous informant can be true or if they are guaranteed to be false.^{\dagger}A number x is called a fixed point of the array a_1, a_2, \ldots, a_n if 1 \leq x \leq n and a_x = x.^{\ddagger}A cyclic left shift of the array a_1, a_2, \ldots, a_n is the array a_2, \ldots, a_n, a_1.InputEach test contains multiple test cases. The first line contains an integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n, k (1 \le n \le 2 \cdot 10^5, 1 \le k \le 10^9) — the length of the array b and the number of operations performed.The second line of each test case contains n integers b_1, b_2, \ldots, b_n (1 \le b_i \le 10^9) — the elements of the array b.It is guaranteed that the sum of the values of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "Yes" if the words of the anonymous informant can be true, and "No" if they are guaranteed to be false.ExampleInput 65 34 3 3 2 33 1007 2 15 56 1 1 1 11 100000000018 489 10 11 12 13 14 15 82 11 42Output Yes Yes No Yes Yes No NoteIn the first test case, the array a could be equal to [3, 2, 3, 4, 3]. In the first operation, a fixed point x = 2 was chosen, and after 2 left shifts, the array became [3, 4, 3, 3, 2]. In the second operation, a fixed point x = 3 was chosen, and after 3 left shifts, the array became [3, 2, 3, 4, 3]. In the third operation, a fixed point x = 3 was chosen again, and after 3 left shifts, the array became [4, 3, 3, 2, 3], which is equal to the array b.In the second test case, the array a could be equal to [7, 2, 1]. After the operation with a fixed point x = 2, the array became [1, 7, 2]. Then, after the operation with a fixed point x = 1, the array returned to its initial state [7, 2, 1]. These same 2 operations (with x = 2, and x = 1) were repeated 49 times. So, after 100 operations, the array returned to [7, 2, 1].In the third test case, it can be shown that there is no solution.
65 34 3 3 2 33 1007 2 15 56 1 1 1 11 100000000018 489 10 11 12 13 14 15 82 11 42
Yes Yes No Yes Yes No
3 seconds
512 megabytes
['brute force', 'dfs and similar', 'graphs', 'implementation', '*1400']
F. A Growing Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree with the root at vertex 1, initially consisting of a single vertex. Each vertex has a numerical value, initially set to 0. There are also q queries of two types: The first type: add a child vertex with the number sz + 1 to vertex v, where sz is the current size of the tree. The numerical value of the new vertex will be 0. The second type: add x to the numerical values of all vertices in the subtree of vertex v. After all queries, output the numerical value of all of the vertices in the final tree.InputThe first line contains a single integer T (1 \leq T \leq 10^4) — the number of test cases. The descriptions of the test cases follow.The first line of each test case contains a single integer q (1 \leq q \leq 5 \cdot 10^5) — the number of queries.The following q lines can fall into two cases: The first type of query: The i-th line contains two integers t_i (t_i = 1), v_i. You need to add a child with the number sz + 1 to vertex v_i, where sz is the current size of the tree. It is guaranteed that 1 \leq v_i \leq sz. The second type of query: The i-th line contains three integers t_i (t_i = 2), v_i, x_i (-10^9 \leq x_i \leq 10^9). You need to add x_i to all numerical values of vertices in the subtree of v_i. It is guaranteed that 1 \leq v_i \leq sz, where sz is the current size of the tree. It is guaranteed that the sum of q across all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, output the numerical value of each vertex of the final tree after all queries have been performed.ExampleInput 392 1 31 12 2 11 12 3 21 32 1 41 32 3 252 1 11 12 1 -11 12 1 151 11 12 1 12 1 32 2 10Output 7 5 8 6 2 1 0 1 4 14 4 NoteIn the first case, the final tree with the assigned numerical values will look like this: The final tree with the assigned numerical values
392 1 31 12 2 11 12 3 21 32 1 41 32 3 252 1 11 12 1 -11 12 1 151 11 12 1 12 1 32 2 10
7 5 8 6 2 1 0 1 4 14 4
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'trees', '*2000']
E. Brukhovich and Examstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe boy Smilo is learning algorithms with a teacher named Brukhovich.Over the course of the year, Brukhovich will administer n exams. For each exam, its difficulty a_i is known, which is a non-negative integer.Smilo doesn't like when the greatest common divisor of the difficulties of two consecutive exams is equal to 1. Therefore, he considers the sadness of the academic year to be the number of such pairs of exams. More formally, the sadness is the number of indices i (1 \leq i \leq n - 1) such that gcd(a_i, a_{i+1}) = 1, where gcd(x, y) is the greatest common divisor of integers x and y.Brukhovich wants to minimize the sadness of the year of Smilo. To do this, he can set the difficulty of any exam to 0. However, Brukhovich doesn't want to make his students' lives too easy. Therefore, he will perform this action no more than k times.Help Smilo determine the minimum sadness that Brukhovich can achieve if he performs no more than k operations.As a reminder, the greatest common divisor (GCD) of two non-negative integers x and y is the maximum integer that is a divisor of both x and y and is denoted as gcd(x, y). In particular, gcd(x, 0) = gcd(0, x) = x for any non-negative integer x.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The descriptions of the test cases follow.The first line of each test case contains two integers n and k (1 \leq k \leq n \leq 10^5) — the total number of exams and the maximum number of exams that can be simplified, respectively. The second line of each test case contains n integers a_1, a_2, a_3, \ldots, a_n — the elements of array a, which are the difficulties of the exams (0 \leq a_i \leq 10^9).It is guaranteed that the sum of n across all test cases does not exceed 10^5.OutputFor each test case, output the minimum possible sadness that can be achieved by performing no more than k operations.ExampleInput 95 21 3 5 7 95 23 5 7 9 118 217 15 10 1 1 5 14 85 31 1 1 1 15 51 1 1 1 119 71 1 2 3 4 5 5 6 6 7 8 9 10 1 1 1 2 3 115 62 1 1 1 1 2 1 1 2 1 1 1 2 1 25 21 1 1 1 25 21 0 1 0 1Output 1 0 2 2 0 5 5 2 1 NoteIn the first test case, a sadness of 1 can be achieved. To this, you can simplify the second and fourth exams. After this, there will be only one pair of adjacent exams with a greatest common divisor (GCD) equal to one, which is the first and second exams.In the second test case, a sadness of 0 can be achieved by simplifying the second and fourth exams.
95 21 3 5 7 95 23 5 7 9 118 217 15 10 1 1 5 14 85 31 1 1 1 15 51 1 1 1 119 71 1 2 3 4 5 5 6 6 7 8 9 10 1 1 1 2 3 115 62 1 1 1 1 2 1 1 2 1 1 1 2 1 25 21 1 1 1 25 21 0 1 0 1
1 0 2 2 0 5 5 2 1
1 second
256 megabytes
['brute force', 'greedy', 'implementation', 'math', 'sortings', '*2500']
D. Suspicious logarithmstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet f(x) be the floor of the binary logarithm of x. In other words, f(x) is largest non-negative integer y, such that 2^y does not exceed x.Let g(x) be the floor of the logarithm of x with base f(x). In other words, g(x) is the largest non-negative integer z, such that {f(x)}^{z} does not exceed x.You are given q queries. The i-th query consists of two integers l_i and r_i. The answer to the query is the sum of g(k) across all integers k, such that l_i \leq k \leq r_i. Since the answers might be large, print them modulo {10^9 + 7}.InputThe first line contains a single integer q — the number of queries (1 \leq q \leq 10^5).The next q lines each contain two integers l_i and r_i — the bounds of the i-th query (4 \leq l_i \leq r_i \leq 10^{18}). OutputFor each query, output the answer to the query modulo 10^9 + 7.ExampleInput 12 4 6 4 7 4 8 4 100000 179 1000000000000000000 57 179 4 201018959 7 201018960 729 50624 728 50624 728 50625 729 50625 Output 6 8 9 348641 41949982 246 1 0 149688 149690 149694 149692 NoteThe table below contains the values of the functions f(x) and g(x) for all x such that 1 \leq x \leq 8. x12345678f01122223g---22221
12 4 6 4 7 4 8 4 100000 179 1000000000000000000 57 179 4 201018959 7 201018960 729 50624 728 50624 728 50625 729 50625
6 8 9 348641 41949982 246 1 0 149688 149690 149694 149692
1 second
256 megabytes
['binary search', 'brute force', 'math', '*1900']
C. Smilo and Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA boy called Smilo is playing a new game! In the game, there are n hordes of monsters, and the i-th horde contains a_i monsters. The goal of the game is to destroy all the monsters. To do this, you have two types of attacks and a combo counter x, initially set to 0: The first type: you choose a number i from 1 to n, such that there is at least one monster left in the horde with the number i. Then, you kill one monster from horde number i, and the combo counter x increases by 1. The second type: you choose a number i from 1 to n, such that there are at least x monsters left in the horde with number i. Then, you use an ultimate attack and kill x monsters from the horde with number i. After that, x is reset to zero.Your task is to destroy all of the monsters, meaning that there should be no monsters left in any of the hordes. Smilo wants to win as quickly as possible, so he wants to the minimum number of attacks required to win the game. InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The descriptions of the test cases follow.The first line of each input data set contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of hordes of monsters.The second line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the number of monsters in each horde.It is guaranteed that the sum of n across all test cases does not exceed 2 \cdot {10^5}.OutputFor each test case, out put the minimum number of attacks required to kill all monsters.ExampleInput 441 3 1 141 2 1 163 2 1 5 2 421 6Output 4 4 11 5 NoteIn the first test case, we can use an attack of the first type on the 1-st, 3-rd and 4-th hordes, and then use an attack of the second type to finish off the 2-nd horde. We need 4 attacks in total.In the second test case, we can use an attack of the first type on the 1-st and 3-rd hordes, then use an attack of the second type to finish off the 2-nd horde, and then use an attack of the first type on the 4-th horde. We need 4 attacks in total.In the fourth test case, we can use an attack of the first type once on the 1-st horde, twice on the 2-nd horde, and then use an attack of the second type on the 2-nd horde, and finally use an attack of the first type to finish off the 2-nd horde. We need 5 attacks in total.
441 3 1 141 2 1 163 2 1 5 2 421 6
4 4 11 5
1 second
256 megabytes
['binary search', 'constructive algorithms', 'greedy', 'sortings', 'two pointers', '*1500']
B. Deja Vutime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n, consisting of positive integers, and an array x of length q, also consisting of positive integers.There are q modification. On the i-th modification (1 \leq i \leq q), for each j (1 \leq j \leq n), such that a_j is divisible by 2^{x_i}, you add 2^{x_i-1} to a_j. Note that x_i (1 \leq x_i \leq 30) is a positive integer not exceeding 30.After all modification queries, you need to output the final array.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and q (1 \leq n, q \leq 10^5) —the length of the array a and the number of queries respectively.The second line of each test case contains n integers a_1, a_2, a_3, \ldots, a_n — the elements of the array a (1 \leq a_i \leq 10^9).The third line of each test case contains q integers x_1, x_2, x_3, \ldots, x_q — the elements of the array x (1 \leq x_i \leq 30), which are the modification queries.It is guaranteed that the sum of n and the sum of q across all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the array after all of the modification queries.ExampleInput 45 31 2 3 4 42 3 47 37 8 12 36 48 6 310 4 25 42 2 2 2 21 1 1 15 51 2 4 8 165 2 3 4 1Output 1 2 3 6 6 7 10 14 38 58 6 3 3 3 3 3 3 1 3 7 11 19 NoteIn the first test case, the first query will add 2 to the integers in positions 4 and 5. After this addition, the array would be [1, 2, 3, 6, 6]. Other operations will not modify the array.In the second test case, the first modification query does not change the array. The second modification query will add 8 to the integer in position 5, so that the array would look like this: [7, 8, 12, 36, 56, 6, 3]. The third modification query will add 2 to the integers in positions 2, 3, 4 and 5. The array would then look like this: [7, 10, 14, 38, 58, 6, 3].
45 31 2 3 4 42 3 47 37 8 12 36 48 6 310 4 25 42 2 2 2 21 1 1 15 51 2 4 8 165 2 3 4 1
1 2 3 6 6 7 10 14 38 58 6 3 3 3 3 3 3 1 3 7 11 19
2 seconds
256 megabytes
['brute force', 'math', 'sortings', '*1100']
A. Sorting with Twostime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1, a_2, \ldots, a_n. In one operation, you do the following: Choose a non-negative integer m, such that 2^m \leq n. Subtract 1 from a_i for all integers i, such that 1 \leq i \leq 2^m. Can you sort the array in non-decreasing order by performing some number (possibly zero) of operations?An array is considered non-decreasing if a_i \leq a_{i + 1} for all integers i such that 1 \leq i \leq n - 1.InputThe 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 20) — the length of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n — the integers in array a (0 \leq a_i \leq 1000).OutputFor each test case, output "YES" if the array can be sorted, and "NO" otherwise.ExampleInput 851 2 3 4 556 5 3 4 496 5 5 7 5 6 6 8 744 3 2 162 2 4 5 3 281 3 17 19 27 57 179 1353 17 57 179 92101 2 3 4 0 6 7 8 9 10Output YES YES YES NO NO NO YES YES NoteIn the first test case, the array is already sorted in non-decreasing order, so we don't have to perform any operations.In the second test case, we can choose m = 1 twice to get the array [4, 3, 3, 4, 4]. Then, we can choose m = 0 once and get the sorted in non-decreasing order array [3, 3, 3, 4, 4].In the third test case, we can choose m = 0 once and get the array [5, 5, 5, 7, 5, 6, 6, 8, 7]. Then, we can choose m = 2 twice and get the array [3, 3, 3, 5, 5, 6, 6, 8, 7]. After that, we can choose m = 3 once and get the sorted in non-decreasing order array [2, 2, 2, 4, 4, 5, 5, 7, 7].For the fourth and fifth test case, it can be shown that the array could not be sorted using these operations.
851 2 3 4 556 5 3 4 496 5 5 7 5 6 6 8 744 3 2 162 2 4 5 3 281 3 17 19 27 57 179 1353 17 57 179 92101 2 3 4 0 6 7 8 9 10
YES YES YES NO NO NO YES YES
2 seconds
256 megabytes
['constructive algorithms', 'sortings', '*800']
B. Qingshan Loves Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputQingshan has a string s, while Daniel has a string t. Both strings only contain \texttt{0} and \texttt{1}.A string a of length k is good if and only if a_i \ne a_{i+1} for all i=1,2,\ldots,k-1. For example, \texttt{1}, \texttt{101}, \texttt{0101} are good, while \texttt{11}, \texttt{1001}, \texttt{001100} are not good.Qingshan wants to make s good. To do this, she can do the following operation any number of times (possibly, zero): insert t to any position of s (getting a new s). Please tell Qingshan if it is possible to make s good.InputThe input consists of multiple test cases. The first line contains a single integer T (1\le T\le 2000) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and m (1 \le n,m \le 50) — the length of the strings s and t, respectively.The second line of each test case contains a string s of length n.The third line of each test case contains a string t of length m.It is guaranteed that s and t only contain \texttt{0} and \texttt{1}.OutputFor each test case, print "YES" (without quotes), if it is possible to make s good, and "NO" (without quotes) otherwise.You can print letters in any case (upper or lower).ExampleInput 51 1103 31110103 2111006 7101100101010110 2100100100010Output Yes Yes No No No NoteIn the first test case, s is good initially, so you can get a good s by doing zero operations.In the second test case, you can do the following two operations (the inserted string t is underlined): \texttt{1}\underline{\texttt{010}}\texttt{11} \texttt{10101}\underline{\texttt{010}}\texttt{1} and get s = \texttt{101010101}, which is good.In the third test case, there is no way to make s good after any number of operations.
51 1103 31110103 2111006 7101100101010110 2100100100010
Yes Yes No No No
1 second
256 megabytes
['constructive algorithms', 'implementation', '*800']
A. Doremy's Paint 3time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array b_1, b_2, \ldots, b_n of positive integers is good if all the sums of two adjacent elements are equal to the same value. More formally, the array is good if there exists a k such that b_1 + b_2 = b_2 + b_3 = \ldots = b_{n-1} + b_n = k.Doremy has an array a of length n. Now Doremy can permute its elements (change their order) however she wants. Determine if she can make the array good.InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 100) — the number of test cases. The description of 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^5).There are no constraints on the sum of n over all test cases.OutputFor each test case, print "Yes" (without quotes), if it is possible to make the array good, and "No" (without quotes) otherwise.You can output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 528 931 1 241 1 4 552 3 3 3 34100000 100000 100000 100000Output Yes Yes No No Yes NoteIn the first test case, [8,9] and [9,8] are good.In the second test case, [1,2,1] is good because a_1+a_2=a_2+a_3=3.In the third test case, it can be shown that no permutation is good.
528 931 1 241 1 4 552 3 3 3 34100000 100000 100000 100000
Yes Yes No No Yes
1 second
256 megabytes
['constructive algorithms', '*800']
F. Doremy's Average Treetime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputDoremy has a rooted tree of size n whose root is vertex r. Initially there is a number w_i written on vertex i. Doremy can use her power to perform this operation at most k times: Choose a vertex x (1 \leq x \leq n). Let s = \frac{1}{|T|}\sum_{i \in T} w_i where T is the set of all vertices in x's subtree. For all i \in T, assign w_i := s. Doremy wants to know what is the lexicographically smallest^\dagger array w after performing all the operations. Can you help her?If there are multiple answers, you may output any one.^\dagger For arrays a and b both of length n, a is lexicographically smaller than b if and only if there exist an index i (1 \leq i \le n) such that a_i < b_i and for all indices j such that j<i, a_j=b_j is satisfied.InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 10^4) — the number of test cases. The description of the test cases follows.The first line contains three integers n, r, k (2 \le n \le 5000, 1 \le r \le n, 0 \le k \le \min(500,n)).The second line contains n integers w_1,w_2,\ldots,w_n (1 \le w_i \le 10^6).Each of the next n-1 lines contains two integers u_i, v_i (1 \leq u_i, v_i \leq n), representing an edge between u_i and v_i.It is guaranteed that the given edges form a tree.It is guaranteed that the sum of n does not exceed 50\,000.OutputFor each test case, In the first line, output a single integer cnt (0 \le cnt \le k) — the number of operations you perform.Then, in the second line output cnt integers p_1,p_2,\ldots,p_{cnt} — x is chosen to be p_i for i-th operation.If there are multiple answers, you may output any one.ExampleInput 46 1 11 9 2 6 1 81 21 32 43 63 57 7 23 1 3 3 1 1 27 17 27 41 52 34 66 5 13 1 3 1 1 35 35 15 63 41 23 2 11000000 999999 9999972 11 3Output 1 2 2 1 4 1 5 1 1 NoteIn the first test case:At first w=[1,9,2,6,1,8]. You can choose some vertex x to perform at most one operation. If x=1, w=[\frac{9}{2},\frac{9}{2},\frac{9}{2},\frac{9}{2},\frac{9}{2},\frac{9}{2}]. If x=2, w=[1,\frac{15}{2},2,\frac{15}{2},1,8]. If x=3, w=[1,9,\frac{11}{3},6,\frac{11}{3},\frac{11}{3}]. If x \in \{4, 5, 6\}, w=[1,9,2,6,1,8]. If you don't perform any operation, w=[1,9,2,6,1,8]. w is lexicographically smallest when x=2.
46 1 11 9 2 6 1 81 21 32 43 63 57 7 23 1 3 3 1 1 27 17 27 41 52 34 66 5 13 1 3 1 1 35 35 15 63 41 23 2 11000000 999999 9999972 11 3
1 2 2 1 4 1 5 1 1
3 seconds
1024 megabytes
['data structures', 'dp', 'greedy', 'trees', '*3500']
E. Doremy's Swapping Treestime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputConsider two undirected graphs G_1 and G_2. Every node in G_1 and in G_2 has a label. Doremy calls G_1 and G_2 similar if and only if: The labels in G_1 are distinct, and the labels in G_2 are distinct. The set S of labels in G_1 coincides with the set of labels in G_2. For every pair of two distinct labels u and v in S, the corresponding nodes are in the same connected component in G_1 if and only if they are in the same connected component in G_2. Now Doremy gives you two trees T_1 and T_2 with n nodes, labeled from 1 to n. You can do the following operation any number of times: Choose an edge set E_1 from T_1 and an edge set E_2 from T_2, such that \overline{E_1} and \overline{E_2} are similar. Here \overline{E} represents the graph which is given by only reserving the edge set E from T (i.e., the edge-induced subgraph). In other words, \overline{E} is obtained from T by removing all edges not included in E and further removing all isolated vertices. Swap the edge set E_1 in T_1 with the edge set E_2 in T_2. Now Doremy is wondering how many distinct T_1 you can get after any number of operations. Can you help her find the answer? Output the answer modulo 10^9+7.InputThe input consists of multiple test cases. The first line contains a single integer t (1\le t\le 2\cdot 10^4) — the number of test cases. The description of the test cases follows.The first line contains an integer n (2\le n\le 10^5) — the number of nodes in the trees T_1 and T_2.Each of the following n-1 lines contain two integers u,v (1\le u,v\le n), representing an undirected edge in T_1. It is guaranteed these edges form a tree.Each of the following n-1 lines contain two integers u,v (1\le u,v\le n), representing an undirected edge in T_2. It is guaranteed these edges form a tree.It is guaranteed that the sum of n does not exceed 2\cdot 10^5.OutputFor each test case, you should output a single line with an integer, representing the number of distinct T_1 after any number of operations, modulo 10^9+7.ExampleInput 321 22 131 32 32 32 141 22 33 44 22 11 3Output 1 2 4 NoteIn the first test case, there is at most one distinct T_1 having the only edge (1,2).In the second test case, you can choose the edge set \{(1,3),(2,3)\} in T_1, the edge set \{(1,2),(2,3)\} in T_2 and swap them. So T_1 can be 1-3-2 or 1-2-3.In the third test case, there are 4 distinct T_1, as the following pictures.
321 22 131 32 32 32 141 22 33 44 22 11 3
1 2 4
2 seconds
1024 megabytes
['dfs and similar', 'graphs', 'trees', '*3500']