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. Hossam and (sub-)palindromic treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam has an unweighted tree G with letters in vertices.Hossam defines s(v, \, u) as a string that is obtained by writing down all the letters on the unique simple path from the vertex v to the vertex u in the tree G.A string a is a subsequence of a string s if a can be obtained from s by deletion of several (possibly, zero) letters. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A palindrome is a string that reads the same from left to right and from right to left. For example, "abacaba" is a palindrome, but "abac" is not.Hossam defines a sub-palindrome of a string s as a subsequence of s, that is a palindrome. For example, "k", "abba" and "abhba" are sub-palindromes of the string "abhbka", but "abka" and "cat" are not.Hossam defines a maximal sub-palindrome of a string s as a sub-palindrome of s, which has the maximal length among all sub-palindromes of s. For example, "abhbka" has only one maximal sub-palindrome — "abhba". But it may also be that the string has several maximum sub-palindromes: the string "abcd" has 4 maximum sub-palindromes.Help Hossam find the length of the longest maximal sub-palindrome among all s(v, \, u) in the tree G.Note that the sub-palindrome is a subsequence, not a substring.InputThe first line contains one integer t (1 \le t \le 200) — the number of test cases.The first line of each test case has one integer number n (1 \le n \le 2 \cdot 10^3) — the number of vertices in the graph.The second line contains a string s of length n, the i-th symbol of which denotes the letter on the vertex i. It is guaranteed that all characters in this string are lowercase English letters.The next n - 1 lines describe the edges of the tree. Each edge is given by two integers v and u (1 \le v, \, u \le n, v \neq u). These two numbers mean that there is an edge (v, \, u) in the tree. It is guaranteed that the given edges form a tree.It is guaranteed that sum of all n doesn't exceed 2 \cdot 10^3.OutputFor each test case output one integer — the length of the longest maximal sub-palindrome among all s(v, \, u).ExampleInput 25abaca1 21 33 44 59caabadedb1 22 32 41 55 65 75 88 9Output 3 5 NoteIn the first example the maximal subpalindromes are "aaa" with letters in vertices 1, \, 3, \, 5, or "aca" with letters in vertices 1, \, 4, \, 5. The tree from the first example. In the second example there is only one maximal palindrome "bacab" with letters in vertices 4, \, 2, \, 1, \, 5, \, 9. The tree from the second example.
25abaca1 21 33 44 59caabadedb1 22 32 41 55 65 75 88 9
3 5
1 second
256 megabytes
['brute force', 'data structures', 'dfs and similar', 'dp', 'strings', 'trees', '*2100']
C. Hossam and Traineestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam has n trainees. He assigned a number a_i for the i-th trainee. A pair of the i-th and j-th (i \neq j) trainees is called successful if there is an integer x (x \geq 2), such that x divides a_i, and x divides a_j.Hossam wants to know if there is a successful pair of trainees.Hossam is very tired now, so he asks you for your help!InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^5), the number of test cases. A description of the test cases follows.The first line of each test case contains an integer number n (2 \le n \le 10^5).The second line of each test case contains n integers, the number of each trainee a_1, a_2, \dots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputPrint the answer — "YES" (without quotes) if there is a successful pair of trainees and "NO" otherwise. You can print each letter in any case.ExampleInput 2332 48 7314 5 9Output YES NO NoteIn the first example, the first trainee and the second trainee make up a successful pair: a_1 = 32, a_2 = 48, you can choose x = 4.
2332 48 7314 5 9
YES NO
3 seconds
256 megabytes
['greedy', 'math', 'number theory', '*1600']
B. Hossam and Friendstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam makes a big party, and he will invite his friends to the party.He has n friends numbered from 1 to n. They will be arranged in a queue as follows: 1, 2, 3, \ldots, n.Hossam has a list of m pairs of his friends that don't know each other. Any pair not present in this list are friends.A subsegment of the queue starting from the friend a and ending at the friend b is [a, a + 1, a + 2, \ldots, b]. A subsegment of the queue is called good when all pairs of that segment are friends.Hossam wants to know how many pairs (a, b) there are (1 \le a \le b \le n), such that the subsegment starting from the friend a and ending at the friend b is good.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. Description of the test cases follows.The first line of each test case contains two integer numbers n and m (2 \le n \le 10^5, 0 \le m \le 10^5) representing the number of friends and the number of pairs, respectively.The i-th of the next m lines contains two integers x_i and y_i (1 \le x_i, y_i\le n, x_i \neq y_i) representing a pair of Hossam's friends that don't know each other.Note that pairs can be repeated.It is guaranteed that the sum of n over all test cases does not exceed 10^5, and the sum of m over all test cases does not exceed 10^5.OutputFor each test case print an integer — the number of good subsegments.ExampleInput 23 21 32 34 21 22 3Output 4 5 NoteIn the first example, the answer is 4.The good subsegments are:[1][2][3][1, 2]In the second example, the answer is 5.The good subsegments are:[1][2][3][4][3, 4]
23 21 32 34 21 22 3
4 5
2 seconds
256 megabytes
['binary search', 'constructive algorithms', 'dp', 'two pointers', '*1400']
A. Hossam and Combinatoricstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputHossam woke up bored, so he decided to create an interesting array with his friend Hazem.Now, they have an array a of n positive integers, Hossam will choose a number a_i and Hazem will choose a number a_j.Count the number of interesting pairs (a_i, a_j) that meet all the following conditions: 1 \le i, j \le n; i \neq j; The absolute difference |a_i - a_j| must be equal to the maximum absolute difference over all the pairs in the array. More formally, |a_i - a_j| = \max_{1 \le p, q \le n} |a_p - a_q|.InputThe input consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100), which denotes the number of test cases. Description of the test cases follows.The first line of each test case contains an integer n (2 \le n \le 10^5).The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^5).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case print an integer — the number of interesting pairs (a_i, a_j).ExampleInput 256 2 3 8 167 2 8 3 2 10Output 2 4 NoteIn the first example, the two ways are: Hossam chooses the fourth number 8 and Hazem chooses the fifth number 1. Hossam chooses the fifth number 1 and Hazem chooses the fourth number 8. In the second example, the four ways are: Hossam chooses the second number 2 and Hazem chooses the sixth number 10. Hossam chooses the sixth number 10 and Hazem chooses the second number 2. Hossam chooses the fifth number 2 and Hazem chooses the sixth number 10. Hossam chooses the sixth number 10 and Hazem chooses the fifth number 2.
256 2 3 8 167 2 8 3 2 10
2 4
2 seconds
256 megabytes
['combinatorics', 'math', 'sortings', '*900']
H. Koxia, Mahiru and Winter Festivaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputWow, what a big face!Kagura MahiruKoxia and Mahiru are enjoying the Winter Festival. The streets of the Winter Festival can be represented as a n \times n undirected grid graph. Formally, the set of vertices is \{(i,j) \; | \; 1 \leq i,j\leq n \} and two vertices (i_1,j_1) and (i_2,j_2) are connected by an edge if and only if |i_1-i_2|+|j_1-j_2|=1. A network with size n = 3. Koxia and Mahiru are planning to visit The Winter Festival by traversing 2n routes. Although routes are not planned yet, the endpoints of the routes are already planned as follows: In the i-th route, they want to start from vertex (1, i) and end at vertex (n, p_i), where p is a permutation of length n. In the (i+n)-th route, they want to start from vertex (i, 1) and end at vertex (q_i, n), where q is a permutation of length n. A network with size n = 3, points to be connected are shown in the same color for p = [3, 2, 1] and q = [3, 1, 2]. Your task is to find a routing scheme — 2n paths where each path connects the specified endpoints. Let's define the congestion of an edge as the number of times it is used (both directions combined) in the routing scheme. In order to ensure that Koxia and Mahiru won't get too bored because of traversing repeated edges, please find a routing scheme that minimizes the maximum congestion among all edges. An example solution — the maximum congestion is 2, which is optimal in this case. InputThe first line contains an integer n (2 \leq n \leq 200) — the size of the network. The second line contains n integers p_1, p_2, \dots, p_n (1 \leq p_i \leq n).The third line contains n integers q_1, q_2, \dots, q_n (1 \leq q_i \leq n).It is guaranteed that both p and q are permutations of length n.OutputOutput 2n lines, each line describing a route.The first n lines should describe the connections from top to bottom. The i-th line should describe the route starting at vertex (1, i) and ending at vertex (n, p_i).The next n lines should describe the connections from left to right. The (i+n)-th line should describe the route starting at vertex (i, 1) and ending at vertex (q_i, n).Each line describing a route should start with an integer k (2 \le k \le 10^5) — the number of vertices the route passes, including the starting and ending vertices. Then output all the vertices on the route in order. In other words, if the route is (x_1, y_1) \rightarrow (x_2, y_2) \rightarrow \dots \rightarrow (x_k, y_k), then output k~x_1~y_1~x_2~y_2 \ldots x_k~y_k. Note that |x_i-x_{i+1}|+|y_i-y_{i+1}| = 1 should holds for 1 \le i < k.If there are multiple solutions that minimize the maximum congestion, you may output any.ExamplesInput 3 3 2 1 3 1 2 Output 5 1 1 2 1 2 2 3 2 3 3 3 1 2 2 2 3 2 5 1 3 1 2 1 1 2 1 3 1 5 1 1 1 2 1 3 2 3 3 3 4 2 1 2 2 2 3 1 3 4 3 1 3 2 3 3 2 3 Input 4 3 4 2 1 2 4 1 3 Output 6 1 1 1 2 2 2 2 3 3 3 4 3 6 1 2 1 3 2 3 2 4 3 4 4 4 5 1 3 2 3 2 2 3 2 4 2 7 1 4 1 3 1 2 2 2 2 1 3 1 4 1 7 1 1 2 1 3 1 3 2 3 3 2 3 2 4 6 2 1 2 2 3 2 4 2 4 3 4 4 6 3 1 3 2 3 3 3 4 2 4 1 4 5 4 1 4 2 4 3 3 3 3 4 Input 3 1 2 3 1 2 3 Output 3 1 1 2 1 3 1 3 1 2 2 2 3 2 3 1 3 2 3 3 3 3 1 1 1 2 1 3 3 2 1 2 2 2 3 3 3 1 3 2 3 3 NoteThe first example corresponds to the figures in the problem statement.The output for examples 2 and 3 respectively are visualized below: Sample output for examples 2 and 3. Maximum congestions are 2 and 1 respectively.
3 3 2 1 3 1 2
5 1 1 2 1 2 2 3 2 3 3 3 1 2 2 2 3 2 5 1 3 1 2 1 1 2 1 3 1 5 1 1 1 2 1 3 2 3 3 3 4 2 1 2 2 2 3 1 3 4 3 1 3 2 3 3 2 3
2 seconds
256 megabytes
['constructive algorithms', '*3500']
G. Koxia and Brackettime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputChiyuu has a bracket sequence^\dagger s of length n. Let k be the minimum number of characters that Chiyuu has to remove from s to make s balanced^\ddagger.Now, Koxia wants you to count the number of ways to remove k characters from s so that s becomes balanced, modulo 998\,244\,353.Note that two ways of removing characters are considered distinct if and only if the set of indices removed is different.^\dagger A bracket sequence is a string containing only the characters "(" and ")".^\ddagger A bracket sequence is called balanced if one can turn it into a valid math expression by adding characters + and 1. For example, sequences (())(), (), (()(())) and the empty string are balanced, while )(, ((), and (()))( are not.InputThe first line of input contains a string s (1 \leq |s| \leq 5 \cdot {10}^5) — the bracket sequence.It is guaranteed that s only contains the characters "(" and ")".OutputOutput a single integer — the number of ways to remove k characters from s so that s becomes balanced, modulo 998\,244\,353.ExamplesInput ())(() Output 4 Input ( Output 1 NoteIn the first test case, it can be proved that the minimum number of characters that Chiyuu has to remove is 2. There are 4 ways to remove 2 characters to make s balanced as follows. Deleted characters are noted as red. \texttt{(} \color{Red}{\texttt{)}} \texttt{)} \color{Red}{\texttt{(}} \texttt{(} \texttt{)}, \texttt{(} \texttt{)} \color{Red}{\texttt{)}} \color{Red}{\texttt{(}} \texttt{(} \texttt{)}, \texttt{(} \color{Red}{\texttt{)}} \texttt{)} \texttt{(} \color{Red}{\texttt{(}} \texttt{)}, \texttt{(} \texttt{)} \color{Red}{\texttt{)}} \texttt{(} \color{Red}{\texttt{(}} \texttt{)}. In the second test case, the only way to make s balanced is by deleting the only character to get an empty bracket sequence, which is considered balanced.
())(()
4
5 seconds
256 megabytes
['divide and conquer', 'fft', 'math', '*3400']
F. Koxia and Sequencetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMari has three integers n, x, and y.Call an array a of n non-negative integers good if it satisfies the following conditions: a_1+a_2+\ldots+a_n=x, and a_1 \, | \, a_2 \, | \, \ldots \, | \, a_n=y, where | denotes the bitwise OR operation. The score of a good array is the value of a_1 \oplus a_2 \oplus \ldots \oplus a_n, where \oplus denotes the bitwise XOR operation.Koxia wants you to find the total bitwise XOR of the scores of all good arrays. If there are no good arrays, output 0 instead.InputThe first line of input contains three integers n, x and y (1 \leq n < 2^{40}, 0 \leq x < 2^{60}, 0 \leq y < 2^{20}).OutputOutput a single integer — the total bitwise XOR of the scores of all good arrays.ExamplesInput 3 5 3 Output 2 Input 100 0 100 Output 0 Input 79877974817 749875791743978 982783 Output 64 NoteIn the first test case, there are 12 good arrays totally as follows. [0,2,3], [0,3,2], [2,0,3], [2,3,0], [3,0,2] and [3,2,0] — the score is 0 \oplus 2 \oplus 3 = 1; [1, 2, 2], [2, 1, 2] and [2, 2, 1] — the score is 1 \oplus 2 \oplus 2 = 1; [1, 1, 3], [1, 3, 1] and [3, 1, 1] — the score is 1 \oplus 1 \oplus 3 = 3. Therefore, the total bitwise xor of the scores is \underbrace{1 \oplus \ldots \oplus 1}_{9\text{ times}} \oplus 3 \oplus 3 \oplus 3 = 2.In the second test case, there are no good sequences. The output should be 0.
3 5 3
2
1 second
256 megabytes
['bitmasks', 'combinatorics', 'dp', 'math', 'number theory', '*3100']
E. Koxia and Treetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputImi has an undirected tree with n vertices where edges are numbered from 1 to n-1. The i-th edge connects vertices u_i and v_i. There are also k butterflies on the tree. Initially, the i-th butterfly is on vertex a_i. All values of a are pairwise distinct.Koxia plays a game as follows: For i = 1, 2, \dots, n - 1, Koxia set the direction of the i-th edge as u_i \rightarrow v_i or v_i \rightarrow u_i with equal probability. For i = 1, 2, \dots, n - 1, if a butterfly is on the initial vertex of i-th edge and there is no butterfly on the terminal vertex, then this butterfly flies to the terminal vertex. Note that operations are sequentially in order of 1, 2, \dots, n - 1 instead of simultaneously. Koxia chooses two butterflies from the k butterflies with equal probability from all possible \frac{k(k-1)}{2} ways to select two butterflies, then she takes the distance^\dagger between the two chosen vertices as her score. Now, Koxia wants you to find the expected value of her score, modulo 998\,244\,353^\ddagger.^\dagger The distance between two vertices on a tree is the number of edges on the (unique) simple path between them.^\ddagger Formally, let M = 998\,244\,353. It can be shown that the answer can be expressed as an irreducible fraction \frac{p}{q}, where p and q are integers and q \not \equiv 0 \pmod{M}. Output the integer equal to p \cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \le x < M and x \cdot q \equiv p \pmod{M}.InputThe first line contains two integers n, k (2 \leq k \leq n \leq 3 \cdot {10}^5) — the size of the tree and the number of butterflies.The second line contains k integers a_1, a_2, \dots, a_k (1 \leq a_i \leq n) — the initial position of butterflies. It's guaranteed that all positions are distinct.The i-th line in following n − 1 lines contains two integers u_i, v_i (1 \leq u_i, v_i \leq n, u_i \neq v_i) — the vertices the i-th edge connects.It is guaranteed that the given edges form a tree.OutputOutput a single integer — the expected value of Koxia's score, modulo 998\,244\,353.ExamplesInput 3 2 1 3 1 2 2 3 Output 748683266Input 5 3 3 4 5 1 2 1 3 2 4 2 5 Output 831870296NoteIn the first test case, the tree is shown below. Vertices containing butterflies are noted as bold. There are only 2 butterflies so the choice of butterflies is fixed. Let's consider the following 4 cases: Edges are 1 \rightarrow 2 and 2 \rightarrow 3: butterfly on vertex 1 moves to vertex 2, but butterfly on vertex 3 doesn't move. The distance between vertices 2 and 3 is 1. Edges are 1 \rightarrow 2 and 3 \rightarrow 2: butterfly on vertex 1 moves to vertex 2, but butterfly on vertex 3 can't move to vertex 2 because it's occupied. The distance between vertices 2 and 3 is 1. Edges are 2 \rightarrow 1 and 2 \rightarrow 3: butterflies on both vertex 1 and vertex 3 don't move. The distance between vertices 1 and 3 is 2. Edges are 2 \rightarrow 1 and 3 \rightarrow 2: butterfly on vertex 1 doesn't move, but butterfly on vertex 3 move to vertex 2. The distance between vertices 1 and 2 is 1. Therefore, the expected value of Koxia's score is \frac {1+1+2+1} {4} = \frac {5} {4}, which is 748\,683\,266 after modulo 998\,244\,353.In the second test case, the tree is shown below. Vertices containing butterflies are noted as bold. The expected value of Koxia's score is \frac {11} {6}, which is 831\,870\,296 after modulo 998\,244\,353.
3 2 1 3 1 2 2 3
748683266
3 seconds
256 megabytes
['combinatorics', 'dfs and similar', 'dp', 'dsu', 'math', 'probabilities', 'trees', '*2400']
D. Koxia and Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKoxia and Mahiru are playing a game with three arrays a, b, and c of length n. Each element of a, b and c is an integer between 1 and n inclusive.The game consists of n rounds. In the i-th round, they perform the following moves: Let S be the multiset \{a_i, b_i, c_i\}. Koxia removes one element from the multiset S by her choice. Mahiru chooses one integer from the two remaining in the multiset S. Let d_i be the integer Mahiru chose in the i-th round. If d is a permutation^\dagger, Koxia wins. Otherwise, Mahiru wins.Currently, only the arrays a and b have been chosen. As an avid supporter of Koxia, you want to choose an array c such that Koxia will win. Count the number of such c, modulo 998\,244\,353.Note that Koxia and Mahiru both play optimally.^\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 contains a single integer t (1 \leq t \leq 2 \cdot 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq {10}^5) — the size of the arrays.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq n).The third line of each test case contains n integers b_1, b_2, \dots, b_n (1 \leq b_i \leq n).It is guaranteed that the sum of n over all test cases does not exceed {10}^5.OutputOutput a single integer — the number of c makes Koxia win, modulo 998\,244\,353.ExampleInput 231 2 21 3 353 3 1 3 44 5 2 5 5Output 6 0 NoteIn the first test case, there are 6 possible arrays c that make Koxia win — [1, 2, 3], [1, 3, 2], [2, 2, 3], [2, 3, 2], [3, 2, 3], [3, 3, 2].In the second test case, it can be proved that no array c makes Koxia win.
231 2 21 3 353 3 1 3 44 5 2 5 5
6 0
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'dfs and similar', 'dsu', 'flows', 'games', 'graph matchings', 'graphs', 'implementation', '*2000']
C. Koxia and Number Theorytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputJoi has an array a of n positive integers. Koxia wants you to determine whether there exists a positive integer x > 0 such that \gcd(a_i+x,a_j+x)=1 for all 1 \leq i < j \leq n.Here \gcd(y, z) denotes the greatest common divisor (GCD) of integers y and z.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains an integer n (2 \leq n \leq 100) — the size of the array.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq {10}^{18}).It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, output "YES" (without quotes) if there exists a positive integer x such that \gcd(a_i+x,a_j+x)=1 for all 1 \leq i < j \leq n, 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 235 7 1033 3 4Output YES NO NoteIn the first test case, we can set x = 4. This is valid because: When i=1 and j=2, \gcd(a_i+x,a_j+x)=\gcd(5+4,7+4)=\gcd(9,11)=1. When i=1 and j=3, \gcd(a_i+x,a_j+x)=\gcd(5+4,10+4)=\gcd(9,14)=1. When i=2 and j=3, \gcd(a_i+x,a_j+x)=\gcd(7+4,10+4)=\gcd(11,14)=1. In the second test case, any choice of x makes \gcd(a_1 + x, a_2 + x) = \gcd(3+x,3+x)=3+x. Therefore, no such x exists.
235 7 1033 3 4
YES NO
1 second
256 megabytes
['brute force', 'chinese remainder theorem', 'math', 'number theory', '*1700']
B. Koxia and Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReve has two integers n and k.Let p be a permutation^\dagger of length n. Let c be an array of length n - k + 1 such that c_i = \max(p_i, \dots, p_{i+k-1}) + \min(p_i, \dots, p_{i+k-1}). Let the cost of the permutation p be the maximum element of c.Koxia wants you to construct a permutation with the minimum possible cost.^\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 contains a single integer t (1 \leq t \leq 2000) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and k (1 \leq k \leq n \leq 2 \cdot 10^5).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output n integers p_1,p_2,\dots,p_n, which is a permutation with minimal cost. If there is more than one permutation with minimal cost, you may output any of them.ExampleInput 35 35 16 6Output 5 1 2 3 4 1 2 3 4 5 3 2 4 1 6 5 NoteIn the first test case, c_1 = \max(p_1,p_2,p_3) + \min(p_1,p_2,p_3) = 5 + 1 = 6. c_2 = \max(p_2,p_3,p_4) + \min(p_2,p_3,p_4) = 3 + 1 = 4. c_3 = \max(p_3,p_4,p_5) + \min(p_3,p_4,p_5) = 4 + 2 = 6. Therefore, the cost is \max(6,4,6)=6. It can be proven that this is the minimal cost.
35 35 16 6
5 1 2 3 4 1 2 3 4 5 3 2 4 1 6 5
1 second
256 megabytes
['constructive algorithms', '*1000']
A. Koxia and Whiteboardstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKiyora has n whiteboards numbered from 1 to n. Initially, the i-th whiteboard has the integer a_i written on it.Koxia performs m operations. The j-th operation is to choose one of the whiteboards and change the integer written on it to b_j.Find the maximum possible sum of integers written on the whiteboards after performing all m operations.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and m (1 \le n,m \le 100).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).The third line of each test case contains m integers b_1, b_2, \ldots, b_m (1 \le b_i \le 10^9).OutputFor each test case, output a single integer — the maximum possible sum of integers written on whiteboards after performing all m operations.ExampleInput 43 21 2 34 52 31 23 4 51 110015 31 1 1 1 11000000000 1000000000 1000000000Output 12 9 1 3000000002 NoteIn the first test case, Koxia can perform the operations as follows: Choose the 1-st whiteboard and rewrite the integer written on it to b_1=4. Choose the 2-nd whiteboard and rewrite to b_2=5. After performing all operations, the numbers on the three whiteboards are 4, 5 and 3 respectively, and their sum is 12. It can be proven that this is the maximum possible sum achievable.In the second test case, Koxia can perform the operations as follows: Choose the 2-nd whiteboard and rewrite to b_1=3. Choose the 1-st whiteboard and rewrite to b_2=4. Choose the 2-nd whiteboard and rewrite to b_3=5. The sum is 4 + 5 = 9. It can be proven that this is the maximum possible sum achievable.
43 21 2 34 52 31 23 4 51 110015 31 1 1 1 11000000000 1000000000 1000000000
12 9 1 3000000002
1 second
256 megabytes
['brute force', 'greedy', '*1000']
D3. Игра в Девятку IIIограничение по времени на тест5 секундограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи нужно найти 26 раскладов с различными значениями важности первого хода.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Помимо того, что каждый игрок стремится избавиться от карт в своей руке, Алиса и Боб также хотят, чтобы в конце игры в руке у их соперника карт осталось как можно больше, а в их руке — как можно меньше. Напомним, что игра заканчивается, как только один из игроков выкладывает на стол последнюю карту из своей руки.Результатом игры назовём совокупность из информации о том, кто из двух игроков выиграет при оптимальной игре, а также о том, сколько карт останется в руке у проигравшего.Пусть Алиса и Боб уже взяли в руки свои 18 карт каждый, но ещё не решили, кто из них будет ходить первым. Величиной важности первого хода для данного расклада назовём абсолютную разность между результатами игры в случае, если первой будет ходить Алиса, и в случае, если первым будет ходить Боб.Например, если в обоих случаях выиграет Боб, но в одном случае у Алисы останется 6 карт в руке в конце игры, а во втором — всего 2, то величина важности первого хода равна 4. Если же в одном случае выиграет Алиса и у Боба останется 5 карт в руке, а во втором случае выиграет Боб и у Алисы останется 3 карты в руке, то величина важности первого хода равна 8.Ребята хотят узнать, насколько разной бывает величина важности первого хода для разных раскладов. По заданному числу k \le 26 помогите им найти такие k раскладов, что величины важности первого хода для всех них — различные целые числа.Входные данныеВ единственной строке задано целое число k (2 \le k \le 26) — число необходимых раскладов.В задаче три теста. В первом тесте k = 2, во втором тесте k = 13, в третьем тесте k = 26.Выходные данныеВыведите k пар строк. Каждая пара строк должна соответствовать некоторому раскладу. Величины важности первого хода для всех выведенных раскладов должны быть различными целыми числами.В первой строке каждой пары выведите 18 строк длины 2 через пробел, описывающих карты Алисы в любом порядке. Первый символ строки должен обозначать достоинство карты — символ из набора 6, 7, 8, 9, T, J, Q, K, A, обозначающий шестёрку, семёрку, восьмёрку, девятку, десятку, валета, даму, короля и туза соответственно. Второй символ строки должен обозначать масть карты — символ из набора C, D, S, H, обозначающий трефы, бубны, пики и черви соответственно.Во второй строке выведите 18 строк длины 2 через пробел, описывающих карты Боба в том же формате.Каждая из 36 возможных карт должна находиться в руке одного из двух игроков в единственном экземпляре.ПримерВходные данные 2 Выходные данные KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C 6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D 7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S ПримечаниеВ первом выведенном раскладе все девятки находятся в руке у Алисы. Даже если Боб будет ходить первым, ему всё равно придётся пропустить первый же свой ход. Следовательно, первый ход при таком раскладе имеет важность 0.Во втором выведенном раскладе вне зависимости от того, чьим будет первый ход, выиграет Алиса. Однако если Алиса будет ходить первой, то у Боба в конце игры в руке останется одна карта, а если же она будет ходить второй, то у Боба останется пять карт. Соответственно, величина важности первого хода при таком раскладе равна 4.
Входные данные 2
Выходные данные KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C 6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D 7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S
ограничение по времени на тест5 секунд
ограничение по памяти на тест512 мегабайт
['*special problem', 'brute force', '*2300']
D2. Игра в Девятку IIограничение по времени на тест5 секундограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи игроки начинают играть не только на победу, но и на оптимизацию результата игры для них. Вводится понятие величины важности первого хода, и нужно найти 13 раскладов с различными значениями этой величины.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Помимо того, что каждый игрок стремится избавиться от карт в своей руке, Алиса и Боб также хотят, чтобы в конце игры в руке у их соперника карт осталось как можно больше, а в их руке — как можно меньше. Напомним, что игра заканчивается, как только один из игроков выкладывает на стол последнюю карту из своей руки.Результатом игры назовём совокупность из информации о том, кто из двух игроков выиграет при оптимальной игре, а также о том, сколько карт останется в руке у проигравшего.Пусть Алиса и Боб уже взяли в руки свои 18 карт каждый, но ещё не решили, кто из них будет ходить первым. Величиной важности первого хода для данного расклада назовём абсолютную разность между результатами игры в случае, если первой будет ходить Алиса, и в случае, если первым будет ходить Боб.Например, если в обоих случаях выиграет Боб, но в одном случае у Алисы останется 6 карт в руке в конце игры, а во втором — всего 2, то величина важности первого хода равна 4. Если же в одном случае выиграет Алиса и у Боба останется 5 карт в руке, а во втором случае выиграет Боб и у Алисы останется 3 карты в руке, то величина важности первого хода равна 8.Ребята хотят узнать, насколько разной бывает величина важности первого хода для разных раскладов. По заданному числу k \le 13 помогите им найти такие k раскладов, что величины важности первого хода для всех них — различные целые числа.Входные данныеВ единственной строке задано целое число k (2 \le k \le 13) — число необходимых раскладов.В задаче два теста. В первом тесте k = 2, во втором тесте k = 13.Выходные данныеВыведите k пар строк. Каждая пара строк должна соответствовать некоторому раскладу. Величины важности первого хода для всех выведенных раскладов должны быть различными целыми числами.В первой строке каждой пары выведите 18 строк длины 2 через пробел, описывающих карты Алисы в любом порядке. Первый символ строки должен обозначать достоинство карты — символ из набора 6, 7, 8, 9, T, J, Q, K, A, обозначающий шестёрку, семёрку, восьмёрку, девятку, десятку, валета, даму, короля и туза соответственно. Второй символ строки должен обозначать масть карты — символ из набора C, D, S, H, обозначающий трефы, бубны, пики и черви соответственно.Во второй строке выведите 18 строк длины 2 через пробел, описывающих карты Боба в том же формате.Каждая из 36 возможных карт должна находиться в руке одного из двух игроков в единственном экземпляре.ПримерВходные данные 2 Выходные данные KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C 6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D 7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S ПримечаниеВ первом выведенном раскладе все девятки находятся в руке у Алисы. Даже если Боб будет ходить первым, ему всё равно придётся пропустить первый же свой ход. Следовательно, первый ход при таком раскладе имеет важность 0.Во втором выведенном раскладе вне зависимости от того, чьим будет первый ход, выиграет Алиса. Однако если Алиса будет ходить первой, то у Боба в конце игры в руке останется одна карта, а если же она будет ходить второй, то у Боба останется пять карт. Соответственно, величина важности первого хода при таком раскладе равна 4.
Входные данные 2
Выходные данные KS QD 8D QC 8S 8C JD 9H AC TH 9S 9D QH 7H 8H TS 7S 9C 6D JS 7D KH QS TC AD AS KC 6C 7C TD AH KD 6S JC JH 6H JC JS 8S TD JD KH 7D 9C KC TH QD 8D 7H TC KD 9H 8C 6D 7S AC QH AD 8H TS 6H JH 6C AH 7C 6S 9D QC AS QS KS 9S
ограничение по времени на тест5 секунд
ограничение по памяти на тест512 мегабайт
['*special problem', 'brute force', '*2200']
D1. Игра в Девятку Iограничение по времени на тест5 секундограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи нужно определить, кто выиграет в карточной игре для двух игроков в заданном раскладе при оптимальной игре обоих соперников.Алиса и Боб решили сыграть в карточную игру «Девятка». Пожалуйста, внимательно прочитайте условие задачи, поскольку правила могут отличаться от известных вам.Для игры нужна стандартная колода из 36 карт — по девять карт (от шестёрки до туза) каждой из четырёх мастей (трефы, бубны, пики и черви). Карты по достоинству от младшей к старшей идут следующим образом: шестёрка, семёрка, восьмёрка, девятка, десятка, валет, дама, король, туз.Перед игрой колода перемешивается, и каждому игроку раздаётся по 18 карт. Карты нужно выкладывать из руки на стол по определённым правилам. Выигрывает игрок, который первым выложит все карты из своей руки.Игроки ходят по очереди. Ход игрока имеет один из следующих видов: выложить на стол из своей руки девятку любой масти; выложить на стол шестёрку, семёрку или восьмёрку любой масти, если на столе уже лежит карта той же масти достоинством на единицу выше; выложить на стол десятку, валета, даму, короля или туза любой масти, если на столе уже лежит карта той же масти достоинством на единицу ниже. Например, девятку пик можно выложить на стол в любой момент, для выкладывания семёрки треф необходимо наличие на столе восьмёрки треф, а для выкладывания туза червей необходимо наличие на столе короля червей.Если игрок не может выложить на стол ни одну карту из своей руки, то ход переходит к сопернику. Обратите внимание: нельзя пропустить ход просто так — всегда необходимо выложить карту на стол корректным образом, если это возможно.Вам дан расклад карт в начале игры. Алиса будет ходить первой. Определите, кто первым избавится от всех своих карт и выиграет, если оба игрока будут пытаться победить и играть оптимально.Входные данныеВ первой строке задано 18 строк длины 2 через пробел, описывающих карты Алисы в случайном порядке. Первый символ строки обозначает достоинство карты — символ из набора 6, 7, 8, 9, T, J, Q, K, A, обозначающий шестёрку, семёрку, восьмёрку, девятку, десятку, валета, даму, короля и туза, соответственно. Второй символ строки обозначает масть карты — символ из набора C, D, S, H, обозначающий трефы, бубны, пики и черви, соответственно.Во второй строке задано 18 строк длины 2 через пробел, описывающих карты Боба в том же формате.Каждая из 36 возможных карт находится в руке одного из двух игроков в единственном экземпляре.В задаче 100 тестов. Все тесты сгенерированы случайным образом.Выходные данныеВыведите Alice, если при оптимальной игре выиграет Алиса, и Bob в противном случае.ПримерыВходные данные JD 7S 9S JS 8S 9D 6D 8C 8D TH KS QD QH TD 6C AD KD AC KH QC 9H 6H KC 9C JC TS 6S QS TC JH 7D 7H AS AH 7C 8H Выходные данные Alice Входные данные 7S KD 8C AH QS AC KS JC 6C 7D 9H TS 7C 6D JH JD 6S KC 8D QD AS TD AD TH KH 9S JS 9C QC 8S 8H 7H TC QH 9D 6H Выходные данные Bob Входные данные 6C 7S 6H KS 9C 6S QS 7C TS JD 8H KC 9D 8C 7H KD JC QC 6D TH TD AD JS 9H TC QD 8D AC JH AH KH AS 7D 8S 9S QH Выходные данные Alice Входные данные JS KS JD TH KH JC KC QD AS JH 6H 9H 7H 6C 9D AC 6D 9S 8D 8H 7C 7S KD 7D 6S QH 8C TS AD TD TC 9C QC 8S QS AH Выходные данные Bob Входные данные 6S KC TD 8S AC 9S KD TS TH 7D 7C KH TC QC JH QD JC JD QH AS 9H 6C 8C 9C 6D AH AD KS JS 7H 6H 8H 9D QS 7S 8D Выходные данные Bob
Входные данные JD 7S 9S JS 8S 9D 6D 8C 8D TH KS QD QH TD 6C AD KD AC KH QC 9H 6H KC 9C JC TS 6S QS TC JH 7D 7H AS AH 7C 8H
Выходные данные Alice
ограничение по времени на тест5 секунд
ограничение по памяти на тест512 мегабайт
['*special problem', 'brute force', 'dp', '*1800']
C2. Подкрутка IIограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи n \le 2 \cdot 10^5 и a_i \le 10^6 (а также есть ограничение на сумму n по наборам входных данных внутри одного теста).Вика за время работы в компании VK уже сделала n коммитов в системе контроля версий. i-й коммит был сделан в a_i-й день работы Вики в компании. В некоторые дни Вика могла сделать несколько коммитов, а в другие — не сделать ни одного.Вику интересуют такие отрезки подряд идущих дней, что в каждый из этих дней у неё есть хотя бы один коммит. Чем длиннее будет самый длинный такой отрезок, тем более продуктивным сотрудником она будет себя ощущать.Недавно Вика нашла способ подкрутить время любого коммита вперёд, но не более чем на сутки. Таким образом, i-й коммит теперь может быть «сделан» либо в a_i-й, либо в (a_i + 1)-й день. Время каждого коммита можно подкрутить независимо от других — в частности, можно как оставить всем коммитам исходное время, так и перенести все коммиты ровно на день вперёд.Найдите длину самого длинного возможного отрезка подряд идущих дней, в каждый из которых у Вики в профиле будет отображаться хотя бы один коммит, после возможной подкрутки времени некоторых коммитов.Входные данныеКаждый тест состоит из нескольких наборов входных данных. В первой строке находится одно целое число t (1 \le t \le 100) — количество наборов входных данных. Далее следует описание наборов входных данных.Первая строка каждого набора входных данных содержит одно целое число n (1 \le n \le 2 \cdot 10^5) — число коммитов.Вторая строка содержит n целых чисел a_1, a_2, \ldots, a_n в неубывающем порядке (1 \le a_1 \le a_2 \le \ldots \le a_n \le 10^6) — номера дней, в которые были сделаны коммиты.Гарантируется, что сумма n по всем наборам входных данных не превосходит 2 \cdot 10^5.Выходные данныеДля каждого набора входных данных выведите одно целое число — максимальную возможную длину отрезка дней, в каждый из которых у Вики в профиле будет отображаться хотя бы один коммит, после возможной подкрутки времени некоторых коммитов вперёд не более чем на сутки.ПримерВходные данные 391 1 3 4 6 6 6 8 1061 2 3 4 5 6510 10 10 10 10Выходные данные 5 6 2 ПримечаниеВ первом наборе входных данных можно поменять дату коммита в день 3 на день 4, дату коммита в день 4 — на день 5, а дату любого из коммитов в день 6 — на день 7. Тогда в каждый из дней 4, 5, 6, 7 и 8 в профиле Вики будет отображаться хотя бы один коммит, и наибольший отрезок из подряд идущих дней с коммитами — [4; 8] — будет иметь длину 5.Во втором наборе входных данных можно либо оставить все коммиты как есть, либо перенести каждый коммит на день вперёд. В любом случае длина отрезка дней составит 6.В третьем наборе входных данных Вика сделала много коммитов, но все в один и тот же день с номером 10. В лучшем случае отрезок дней достигнет длины 2 — если какие-то коммиты оставить на день 10, а другие перенести на день 11.
Входные данные 391 1 3 4 6 6 6 8 1061 2 3 4 5 6510 10 10 10 10
Выходные данные 5 6 2
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'dp', '*1300']
C1. Подкрутка Iограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи n \le 50 и a_i \le 100.Вика за время работы в компании VK уже сделала n коммитов в системе контроля версий. i-й коммит был сделан в a_i-й день работы Вики в компании. В некоторые дни Вика могла сделать несколько коммитов, а в другие — не сделать ни одного.Вику интересуют такие отрезки подряд идущих дней, что в каждый из этих дней у неё есть хотя бы один коммит. Чем длиннее будет самый длинный такой отрезок, тем более продуктивным сотрудником она будет себя ощущать.Недавно Вика нашла способ подкрутить время любого коммита вперёд, но не более чем на сутки. Таким образом, i-й коммит теперь может быть «сделан» либо в a_i-й, либо в (a_i + 1)-й день. Время каждого коммита можно подкрутить независимо от других — в частности, можно как оставить всем коммитам исходное время, так и перенести все коммиты ровно на день вперёд.Найдите длину самого длинного возможного отрезка подряд идущих дней, в каждый из которых у Вики в профиле будет отображаться хотя бы один коммит, после возможной подкрутки времени некоторых коммитов.Входные данныеКаждый тест состоит из нескольких наборов входных данных. В первой строке находится одно целое число t (1 \le t \le 100) — количество наборов входных данных. Далее следует описание наборов входных данных.Первая строка каждого набора входных данных содержит одно целое число n (1 \le n \le 50) — число коммитов.Вторая строка содержит n целых чисел a_1, a_2, \ldots, a_n в неубывающем порядке (1 \le a_1 \le a_2 \le \ldots \le a_n \le 100) — номера дней, в которые были сделаны коммиты.Выходные данныеДля каждого набора входных данных выведите одно целое число — максимальную возможную длину отрезка дней, в каждый из которых у Вики в профиле будет отображаться хотя бы один коммит, после возможной подкрутки времени некоторых коммитов вперёд не более чем на сутки.ПримерВходные данные 391 1 3 4 6 6 6 8 1061 2 3 4 5 6510 10 10 10 10Выходные данные 5 6 2 ПримечаниеВ первом наборе входных данных можно поменять дату коммита в день 3 на день 4, дату коммита в день 4 — на день 5, а дату любого из коммитов в день 6 — на день 7. Тогда в каждый из дней 4, 5, 6, 7 и 8 в профиле Вики будет отображаться хотя бы один коммит, и наибольший отрезок из подряд идущих дней с коммитами — [4; 8] — будет иметь длину 5.Во втором наборе входных данных можно либо оставить все коммиты как есть, либо перенести каждый коммит на день вперёд. В любом случае длина отрезка дней составит 6.В третьем наборе входных данных Вика сделала много коммитов, но все в один и тот же день с номером 10. В лучшем случае отрезок дней достигнет длины 2 — если какие-то коммиты оставить на день 10, а другие перенести на день 11.
Входные данные 391 1 3 4 6 6 6 8 1061 2 3 4 5 6510 10 10 10 10
Выходные данные 5 6 2
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'brute force', 'dp', 'greedy', '*1200']
B2. Копирование файлов IIограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи размеры копируемых файлов не превышают 10^{10} байт.Вы копируете с одного сервера на другой n файлов размером a_1, a_2, \ldots, a_n байт. Файлы копируются последовательно в заданном порядке.При копировании вы видите два прогресс-бара: первый показывает процент скопированных данных в текущем файле, а второй — общий процент скопированных данных по всем n файлам. Оба процента отображаются округлёнными вниз до целого числа. Значения на прогресс-барах обновляются после копирования каждого байта.Формально, после копирования байта номер x из файла номер i первый прогресс-бар показывает \lfloor \frac{100 \cdot x}{a_i} \rfloor процентов, а второй — \lfloor \frac{100 \cdot (a_1 + a_2 + \ldots + a_{i - 1} + x)}{a_1 + a_2 + \ldots + a_n} \rfloor процентов. В самом начале копирования оба прогресс-бара показывают 0 процентов.Найдите все такие целые числа от 0 до 100 включительно, что существует момент времени, в который оба прогресс-бара одновременно показывают это число. Выведите эти числа в порядке возрастания.Входные данныеВ первой строке задано одно целое число n (1 \le n \le 100) — число копируемых файлов.Во второй строке заданы n целых чисел a_1, a_2, \ldots, a_n (1 \le a_i \le 10^{10}) — размеры файлов в байтах в том порядке, в котором они будут копироваться.Выходные данныеВыведите в возрастающем порядке все числа от 0 до 100 включительно такие, что существует момент времени, в который на обоих прогресс-барах одновременно показывается это число.ПримерыВходные данные 1 6 Выходные данные 0 16 33 50 66 83 100 Входные данные 2 100 500 Выходные данные 0 95 96 97 98 99 100 Входные данные 4 10000000000 2 2 9999999998 Выходные данные 0 50 99 100 Входные данные 6 170 130 400 256 30 100 Выходные данные 0 17 43 44 84 90 99 100 ПримечаниеВ первом тесте копируется всего один файл, поэтому оба прогресс-бара всегда показывают одинаковые значения.Во втором тесте первый прогресс-бар сразу же уйдёт вперёд, потом сбросится в ноль и начнёт догонять второй прогресс-бар заново. В конце копирования прогресс-бары некоторое время будут показывать одно и то же число.Обратите внимание, что третий тест в этой версии задачи отличается от третьего теста в предыдущей версии задачи.
Входные данные 1 6
Выходные данные 0 16 33 50 66 83 100
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'binary search', 'brute force', 'math', '*1400']
B1. Копирование файлов Iограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводВ этой версии задачи размеры копируемых файлов не превышают 1000 байт.Вы копируете с одного сервера на другой n файлов размером a_1, a_2, \ldots, a_n байт. Файлы копируются последовательно в заданном порядке.При копировании вы видите два прогресс-бара: первый показывает процент скопированных данных в текущем файле, а второй — общий процент скопированных данных по всем n файлам. Оба процента отображаются округлёнными вниз до целого числа. Значения на прогресс-барах обновляются после копирования каждого байта.Формально, после копирования байта номер x из файла номер i первый прогресс-бар показывает \lfloor \frac{100 \cdot x}{a_i} \rfloor процентов, а второй — \lfloor \frac{100 \cdot (a_1 + a_2 + \ldots + a_{i - 1} + x)}{a_1 + a_2 + \ldots + a_n} \rfloor процентов. В самом начале копирования оба прогресс-бара показывают 0 процентов.Найдите все такие целые числа от 0 до 100 включительно, что существует момент времени, в который оба прогресс-бара одновременно показывают это число. Выведите эти числа в порядке возрастания.Входные данныеВ первой строке задано одно целое число n (1 \le n \le 100) — число копируемых файлов.Во второй строке заданы n целых чисел a_1, a_2, \ldots, a_n (1 \le a_i \le 1000) — размеры файлов в байтах в том порядке, в котором они будут копироваться.Выходные данныеВыведите в возрастающем порядке все числа от 0 до 100 включительно такие, что существует момент времени, в который на обоих прогресс-барах одновременно показывается это число.ПримерыВходные данные 1 6 Выходные данные 0 16 33 50 66 83 100 Входные данные 2 100 500 Выходные данные 0 95 96 97 98 99 100 Входные данные 4 1000 2 2 998 Выходные данные 0 50 99 100 Входные данные 6 170 130 400 256 30 100 Выходные данные 0 17 43 44 84 90 99 100 ПримечаниеВ первом тесте копируется всего один файл, поэтому оба прогресс-бара всегда показывают одинаковые значения.Во втором тесте первый прогресс-бар сразу же уйдёт вперёд, потом сбросится в ноль и начнёт догонять второй прогресс-бар заново. В конце копирования прогресс-бары некоторое время будут показывать одно и то же число.
Входные данные 1 6
Выходные данные 0 16 33 50 66 83 100
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'brute force', 'implementation', 'math', '*1000']
A. Узкая дорогаограничение по времени на тест2 секундыограничение по памяти на тест512 мегабайтвводстандартный вводвыводстандартный выводКолонна из n самокатов едет по узкой односторонней дороге в пункт Б. Самокаты пронумерованы от 1 до n. Для каждого самоката i известно, что текущее расстояние от него до пункта Б равно a_i метров. При этом a_1 < a_2 < \ldots < a_n, в частности, самокат 1 находится ближе всего к пункту Б, а самокат n — дальше всего.Самокат с номером i движется в сторону пункта Б со скоростью i метров в секунду (то есть чем ближе самокат в колонне к пункту Б, тем медленнее он едет). Так как дорога узкая, самокаты не могут обгонять друг друга. Более того, соседние самокаты в колонне должны соблюдать дистанцию хотя бы в 1 метр. Поэтому когда более быстрый самокат догоняет более медленный, более быстрому приходится дальше ехать со скоростью более медленного, причём на расстоянии в 1 метр от него.Определите, на каком расстоянии до пункта Б будет каждый самокат ровно через одну секунду.Входные данныеВ первой строке задано одно целое число n (1 \le n \le 100) — число самокатов в колонне.В i-й из следующих n строк задано одно целое число a_i (1 \le a_i \le 1000; a_1 < a_2 < \ldots < a_n) — текущее расстояние от самоката i до пункта Б в метрах.Выходные данныеВыведите n целых чисел — расстояния от самокатов 1, 2, \ldots, n до пункта Б в метрах через одну секунду.ПримерыВходные данные 4 20 30 50 100 Выходные данные 19 28 47 96 Входные данные 5 1 2 3 4 5 Выходные данные 0 1 2 3 4 Входные данные 8 5 9 10 15 17 18 19 22 Выходные данные 4 7 8 11 12 13 14 15 ПримечаниеВ первом тесте самокаты пока не мешают друг другу ехать, поэтому каждый самокат i продвигается на i метров в сторону пункта Б.Во втором тесте самокаты уже выстроились в колонне на расстоянии 1 метр друг от друга и вынуждены ехать со скоростью самого медленного самоката с номером 1.
Входные данные 4 20 30 50 100
Выходные данные 19 28 47 96
ограничение по времени на тест2 секунды
ограничение по памяти на тест512 мегабайт
['*special problem', 'math', '*800']
F. Wonderful Jumptime limit per test4 secondsmemory limit per test128 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers a_1,a_2,\ldots,a_n of length n. In one operation you can jump from index i to index j (1 \le i \le j \le n) by paying \min(a_i, a_{i + 1}, \ldots, a_j) \cdot (j - i)^2 eris.For all k from 1 to n, find the minimum number of eris needed to get from index 1 to index k.InputThe first line contains a single integer n (2 \le n \le 4 \cdot 10^5).The second line contains n integers a_1,a_2,\ldots a_n (1 \le a_i \le n).OutputOutput n integers — the k-th integer is the minimum number of eris needed to reach index k if you start from index 1.ExamplesInput 3 2 1 3 Output 0 1 2 Input 6 1 4 1 6 3 2 Output 0 1 2 3 6 8 Input 2 1 2 Output 0 1 Input 4 1 4 4 4 Output 0 1 4 8 NoteIn the first example: From 1 to 1: the cost is 0, From 1 to 2: 1 \rightarrow 2 — the cost is \min(2, 1) \cdot (2 - 1) ^ 2=1, From 1 to 3: 1 \rightarrow 2 \rightarrow 3 — the cost is \min(2, 1) \cdot (2 - 1) ^ 2 + \min(1, 3) \cdot (3 - 2) ^ 2 = 1 + 1 = 2. In the fourth example from 1 to 4: 1 \rightarrow 3 \rightarrow 4 — the cost is \min(1, 4, 4) \cdot (3 - 1) ^ 2 + \min(4, 4) \cdot (4 - 3) ^ 2 = 4 + 4 = 8.
3 2 1 3
0 1 2
4 seconds
128 megabytes
['dp', 'greedy', '*2900']
E. Partial Sortingtime limit per test1.5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputConsider a permutation^\dagger p of length 3n. Each time you can do one of the following operations: Sort the first 2n elements in increasing order. Sort the last 2n elements in increasing order. We can show that every permutation can be made sorted in increasing order using only these operations. Let's call f(p) the minimum number of these operations needed to make the permutation p sorted in increasing order.Given n, find the sum of f(p) over all (3n)! permutations p of size 3n.Since the answer could be very large, output it modulo a prime M.^\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).InputThe only line of input contains two numbers n and M (1 \leq n \leq 10^6, 10^8 \leq M \leq 10^9). It is guaranteed that M is a prime number.OutputOutput the answer modulo M.ExamplesInput 1 100009067 Output 9 Input 2 100000357 Output 1689 Input 69 999900997 Output 193862705 NoteIn the first test case, all the permutations are: [1, 2, 3], which requires 0 operations; [1, 3, 2], which requires 1 operation; [2, 1, 3], which requires 1 operation; [2, 3, 1], which requires 2 operations; [3, 1, 2], which requires 2 operations; [3, 2, 1], which requires 3 operations. Therefore, the answer is 0+1+1+2+2+3=9.
1 100009067
9
1.5 seconds
1024 megabytes
['combinatorics', 'math', 'number theory', '*2300']
D. Lucky Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^\dagger p of length n.In one operation, you can choose two indices 1 \le i < j \le n and swap p_i with p_j.Find the minimum number of operations needed to have exactly one inversion^\ddagger in the permutation.^\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).^\ddagger The number of inversions of a permutation p is the number of pairs of indices (i, j) such that 1 \le i < j \le n and p_i > p_j.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers p_1,p_2,\ldots, p_n (1 \le p_i \le n). It is guaranteed that p is a permutation.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output a single integer — the minimum number of operations needed to have exactly one inversion in the permutation. It can be proven that an answer always exists.ExampleInput 422 121 243 4 1 242 4 3 1Output 0 1 3 1 NoteIn the first test case, the permutation already satisfies the condition.In the second test case, you can perform the operation with (i,j)=(1,2), after that the permutation will be [2,1] which has exactly one inversion.In the third test case, it is not possible to satisfy the condition with less than 3 operations. However, if we perform 3 operations with (i,j) being (1,3),(2,4), and (3,4) in that order, the final permutation will be [1, 2, 4, 3] which has exactly one inversion.In the fourth test case, you can perform the operation with (i,j)=(2,4), after that the permutation will be [2,1,3,4] which has exactly one inversion.
422 121 243 4 1 242 4 3 1
0 1 3 1
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*1800']
C. Elemental Decompresstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers.Find two permutations^\dagger p and q of length n such that \max(p_i,q_i)=a_i for all 1 \leq i \leq n or report that such p and q do not exist.^\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).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5).The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq n) — the array a.It is guaranteed that the total sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, if there do not exist p and q that satisfy the conditions, output "NO" (without quotes).Otherwise, output "YES" (without quotes) and then output 2 lines. The first line should contain n integers p_1,p_2,\ldots,p_n and the second line should contain n integers q_1,q_2,\ldots,q_n.If there are multiple solutions, you may output any of them.You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 31155 3 4 2 521 1Output YES 1 1 YES 1 3 4 2 5 5 2 3 1 4 NO NoteIn the first test case, p=q=[1]. It is correct since a_1 = max(p_1,q_1) = 1.In the second test case, p=[1,3,4,2,5] and q=[5,2,3,1,4]. It is correct since: a_1 = \max(p_1, q_1) = \max(1, 5) = 5, a_2 = \max(p_2, q_2) = \max(3, 2) = 3, a_3 = \max(p_3, q_3) = \max(4, 3) = 4, a_4 = \max(p_4, q_4) = \max(2, 1) = 2, a_5 = \max(p_5, q_5) = \max(5, 4) = 5. In the third test case, one can show that no such p and q exist.
31155 3 4 2 521 1
YES 1 1 YES 1 3 4 2 5 5 2 3 1 4 NO
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'sortings', '*1300']
B. Quick Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^\dagger p of length n and a positive integer k \le n.In one operation, you: Choose k distinct elements p_{i_1}, p_{i_2}, \ldots, p_{i_k}. Remove them and then add them sorted in increasing order to the end of the permutation. For example, if p = [2,5,1,3,4] and k = 2 and you choose 5 and 3 as the elements for the operation, then [2, \color{red}{5}, 1, \color{red}{3}, 4] \rightarrow [2, 1, 4, \color{red}{3},\color{red}{5}].Find the minimum number of operations needed to sort the permutation in increasing order. It can be proven that it is always possible to do so.^\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).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers n and k (2 \le n \le 10^5, 1 \le k \le n).The second line of each test case contains n integers p_1,p_2,\ldots, p_n (1 \le p_i \le n). It is guaranteed that p is a permutation.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 operations needed to sort the permutation. It can be proven that it is always possible to do so.ExampleInput 43 21 2 33 13 1 24 21 3 2 44 22 3 1 4Output 0 1 1 2 NoteIn the first test case, the permutation is already sorted.In the second test case, you can choose element 3, and the permutation will become sorted as follows: [\color{red}{3}, 1, 2] \rightarrow [1, 2, \color{red}{3}].In the third test case, you can choose elements 3 and 4, and the permutation will become sorted as follows: [1, \color{red}{3}, 2, \color{red}{4}] \rightarrow [1, 2, \color{red}{3},\color{red}{4}].In the fourth test case, it can be shown that it is impossible to sort the permutation in 1 operation. However, if you choose elements 2 and 1 in the first operation, and choose elements 3 and 4 in the second operation, the permutation will become sorted as follows: [\color{red}{2}, 3, \color{red}{1}, 4] \rightarrow [\color{blue}{3}, \color{blue}{4}, \color{red}{1}, \color{red}{2}] \rightarrow [1,2, \color{blue}{3}, \color{blue}{4}].
43 21 2 33 13 1 24 21 3 2 44 22 3 1 4
0 1 1 2
1 second
256 megabytes
['greedy', 'math', '*900']
A. Greatest Convextime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer k. Find the largest integer x, where 1 \le x < k, such that x! + (x - 1)!^\dagger is a multiple of ^\ddagger k, or determine that no such x exists.^\dagger y! denotes the factorial of y, which is defined recursively as y! = y \cdot (y-1)! for y \geq 1 with the base case of 0! = 1. For example, 5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 \cdot 0! = 120.^\ddagger If a and b are integers, then a is a multiple of b if there exists an integer c such that a = b \cdot c. For example, 10 is a multiple of 5 but 9 is not a multiple of 6.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of test cases follows.The only line of each test case contains a single integer k (2 \le k \le 10^9).OutputFor each test case output a single integer — the largest possible integer x that satisfies the conditions above. If no such x exists, output -1.ExampleInput 436810Output 2 5 7 9 NoteIn the first test case, 2! + 1! = 2 + 1 = 3, which is a multiple of 3.In the third test case, 7! + 6! = 5040 + 720 = 5760, which is a multiple of 8.
436810
2 5 7 9
1 second
256 megabytes
['greedy', 'math', 'number theory', '*800']
F. Two Subtreestime limit per test9 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a rooted tree consisting of n vertices. The vertex 1 is the root. Each vertex has an integer written on it; this integer is val_i for the vertex i.You are given q queries to the tree. The i-th query is represented by two vertices, u_i and v_i. To answer the query, consider all vertices w that lie in the subtree of u_i or v_i (if a vertex is in both subtrees, it is counted twice). For all vertices in these two subtrees, list all integers written on them, and find the integer with the maximum number of occurrences. If there are multiple integers with maximum number of occurrences, the minimum among them is the answer.InputThe first line contains one integer n (1 \le n \le 2 \cdot 10^5) — the number of vertices in the tree.The second line contains n integers val_1, val_2, \dots, val_n (1 \le val_i \le 2 \cdot 10^5) — the numbers written on the vertices.Then n - 1 lines follow, each containing two integers x and y (1 \le x, y \le n) representing an edge between vertices x and y. These edges form a tree.The next line contains one integer q (1 \le q \le 2 \cdot 10^5) — the number of queries to process.Then q lines follow. The i-th of them containing two numbers u_i and v_i (1 \le u_i, v_i \le n) — the roots of subtrees in the i-th query.OutputFor each query, print one integer — the number that has the maximum amount of occurrences in the corresponding pair of subtrees (if there are multiple such numbers, print the minimum one among them).ExampleInput 8 2 1 3 2 3 3 2 4 1 2 1 3 2 4 3 5 3 6 3 7 7 8 6 2 7 3 7 2 3 1 1 5 6 1 3 Output 2 3 3 2 3 3 NoteIn the 1-st query, the pair of subtrees consists of vertices [2, 4, 7, 8], and the numbers written on them are \{1, 2, 2, 4\}. The number 2 occurs twice, all other numbers — at most once, so the answer is 2.In the 2-nd query, the pair of subtrees consists of vertices [3, 5, 6, 7, 7, 8, 8], and the numbers written on them are \{3, 3, 3, 2, 2, 4, 4\}. The number 3 has the maximum number of occurrences.In the 4-th query, the pair of subtrees consists of vertices [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8], and the numbers written on them are \{2, 2, 1, 1, 3, 3, 2, 2, 3, 3, 3, 3, 2, 2, 4, 4\}. The numbers 2 and 3 are the most common, the minimum of them is 2.
8 2 1 3 2 3 3 2 4 1 2 1 3 2 4 3 5 3 6 3 7 7 8 6 2 7 3 7 2 3 1 1 5 6 1 3
2 3 3 2 3 3
9 seconds
1024 megabytes
['data structures', 'trees', '*3100']
E. Algebra Flashtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output Algebra Flash 2.2 has just been released!Changelog: New gamemode! Thank you for the continued support of the game! Huh, is that it? Slightly disappointed, you boot up the game and click on the new gamemode. It says "Colored platforms".There are n platforms, numbered from 1 to n, placed one after another. There are m colors available in the game, numbered from 1 to m. The i-th platform is colored c_i.You start on the platform 1 and want to reach platform n. In one move, you can jump from some platform i to platforms i + 1 or i + 2.All platforms are initially deactivated (including platforms 1 and n). For each color j, you can pay x_j coins to activate all platforms of that color.You want to activate some platforms so that you could start on an activated platform 1, jump through some activated platforms and reach an activated platform n.What's the smallest amount of coins you can spend to achieve that?InputThe first line contains two integers n and m (2 \le n \le 3 \cdot 10^5; 1 \le m \le 40) — the number of platforms and the number of colors, respectively.The second line contains n integers c_1, c_2, \dots, c_n (1 \le c_i \le m) — the colors of the platforms.The third line contains m integers x_1, x_2, \dots, x_m (1 \le x_i \le 10^7) — the cost of activating all platforms of each color.OutputPrint the smallest amount of coins you can spend to activate some platforms so that you could start on an activated platform 1, jump through some activated platforms and reach an activated platform n.ExamplesInput 5 3 1 3 2 3 1 1 10 100 Output 11 Input 5 3 1 3 2 3 1 1 200 20 Output 21 Input 4 2 2 2 1 1 5 5 Output 10 Input 10 10 3 8 6 2 10 5 2 3 7 3 9 7 4 2 1 8 2 6 2 2 Output 15
5 3 1 3 2 3 1 1 10 100
11
2 seconds
256 megabytes
['bitmasks', 'brute force', 'dp', 'graphs', 'math', 'meet-in-the-middle', 'trees', '*2500']
D. Playofftime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output2^n teams participate in a playoff tournament. The tournament consists of 2^n - 1 games. They are held as follows: in the first phase of the tournament, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4, and so on (so, 2^{n-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{n-1} teams remain. If only one team remains, it is declared the champion; otherwise, the second phase begins, where 2^{n-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains. The skill level of the i-th team is p_i, where p is a permutation of integers 1, 2, ..., 2^n (a permutation is an array where each element from 1 to 2^n occurs exactly once).You are given a string s which consists of n characters. These characters denote the results of games in each phase of the tournament as follows: if s_i is equal to 0, then during the i-th phase (the phase with 2^{n-i} games), in each match, the team with the lower skill level wins; if s_i is equal to 1, then during the i-th phase (the phase with 2^{n-i} games), in each match, the team with the higher skill level wins. Let's say that an integer x is winning if it is possible to find a permutation p such that the team with skill x wins the tournament. Find all winning integers.InputThe first line contains one integer n (1 \le n \le 18).The second line contains the string s of length n consisting of the characters 0 and/or 1.OutputPrint all the winning integers x in ascending order.ExamplesInput 3 101 Output 4 5 6 7 Input 1 1 Output 2 Input 2 01 Output 2 3
3 101
4 5 6 7
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'dp', 'greedy', 'math', '*1500']
C. Count Binary Stringstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n. You have to calculate the number of binary (consisting of characters 0 and/or 1) strings s meeting the following constraints.For every pair of integers (i, j) such that 1 \le i \le j \le n, an integer a_{i,j} is given. It imposes the following constraint on the string s_i s_{i+1} s_{i+2} \dots s_j: if a_{i,j} = 1, all characters in s_i s_{i+1} s_{i+2} \dots s_j should be the same; if a_{i,j} = 2, there should be at least two different characters in s_i s_{i+1} s_{i+2} \dots s_j; if a_{i,j} = 0, there are no additional constraints on the string s_i s_{i+1} s_{i+2} \dots s_j. Count the number of binary strings s of length n meeting the aforementioned constraints. Since the answer can be large, print it modulo 998244353.InputThe first line contains one integer n (2 \le n \le 100).Then n lines follow. The i-th of them contains n-i+1 integers a_{i,i}, a_{i,i+1}, a_{i,i+2}, \dots, a_{i,n} (0 \le a_{i,j} \le 2).OutputPrint one integer — the number of strings meeting the constraints, taken modulo 998244353.ExamplesInput 3 1 0 2 1 0 1 Output 6 Input 3 1 1 2 1 0 1 Output 2 Input 3 1 2 1 1 0 1 Output 0 Input 3 2 0 2 0 1 1 Output 0 NoteIn the first example, the strings meeting the constraints are 001, 010, 011, 100, 101, 110.In the second example, the strings meeting the constraints are 001, 110.
3 1 0 2 1 0 1
6
2 seconds
512 megabytes
['data structures', 'dp', '*2100']
B. Block Towerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n block towers, numbered from 1 to n. The i-th tower consists of a_i blocks.In one move, you can move one block from tower i to tower j, but only if a_i > a_j. That move increases a_j by 1 and decreases a_i by 1. You can perform as many moves as you would like (possibly, zero).What's the largest amount of blocks you can have on the tower 1 after the moves?InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of testcases.The first line of each testcase contains a single integer n (2 \le n \le 2 \cdot 10^5) — the number of towers.The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10^9) — the number of blocks on each tower.The sum of n over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print the largest amount of blocks you can have on the tower 1 after you make any number of moves (possibly, zero).ExampleInput 431 2 331 2 221 1000000000103 8 6 7 4 1 2 4 10 1Output 3 2 500000001 9 NoteIn the first testcase, you can move a block from tower 2 to tower 1, making the block counts [2, 1, 3]. Then move a block from tower 3 to tower 1, making the block counts [3, 1, 2]. Tower 1 has 3 blocks in it, and you can't obtain a larger amount.In the second testcase, you can move a block from any of towers 2 or 3 to tower 1, so that it has 2 blocks in it.In the third testcase, you can 500000000 times move a block from tower 2 to tower 1. After that the block countes will be [500000001, 500000000].
431 2 331 2 221 1000000000103 8 6 7 4 1 2 4 10 1
3 2 500000001 9
2 seconds
256 megabytes
['data structures', 'greedy', 'sortings', '*800']
A. Cut the Triangletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a non-degenerate triangle (a non-degenerate triangle is a triangle with positive area). The vertices of the triangle have coordinates (x_1, y_1), (x_2, y_2) and (x_3, y_3).You want to draw a straight line to cut the triangle into two non-degenerate triangles. Furthermore, the line you draw should be either horizontal or vertical.Can you draw the line to meet all the constraints?Here are some suitable ways to draw the line: However, these ways to draw the line are not suitable (the first line cuts the triangle into a triangle and a quadrangle; the second line doesn't cut the triangle at all; the third line is neither horizontal nor vertical): InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of four lines. The first of them is empty. The i-th of the next three lines contains two integers x_i and y_i (1 \le x_i, y_i \le 10^8) — the coordinates of the i-th vertex of the triangle.Additional constraint on the input: in each test case, the triangle formed by three vertices has positive area (i. e. it is non-degenerate).OutputFor each test case, print YES if it is possible to cut the triangle according to the statement, or NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).ExampleInput 44 76 83 54 54 76 85 81 82 53 66 66 3Output YES YES YES NO
44 76 83 54 54 76 85 81 82 53 66 66 3
YES YES YES NO
2 seconds
512 megabytes
['implementation', '*800']
F. MCFtime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a graph consisting of n vertices and m directed arcs. The i-th arc goes from the vertex x_i to the vertex y_i, has capacity c_i and weight w_i. No arc goes into the vertex 1, and no arc goes from the vertex n. There are no cycles of negative weight in the graph (it is impossible to travel from any vertex to itself in such a way that the total weight of all arcs you go through is negative).You have to assign each arc a flow (an integer between 0 and its capacity, inclusive). For every vertex except 1 and n, the total flow on the arcs going to this vertex must be equal to the total flow on the arcs going from that vertex. Let the flow on the i-th arc be f_i, then the cost of the flow is equal to \sum \limits_{i = 1}^{m} f_i w_i. You have to find a flow which minimizes the cost.Sounds classical, right? Well, we have some additional constraints on the flow on every edge: if c_i is even, f_i must be even; if c_i is odd, f_i must be odd. Can you solve this problem?InputThe first line contains two integers n and m (2 \le n \le 100; 1 \le m \le 200).Then m lines follow. The i-th of them contains four integers x_i, y_i, c_i, and w_i (1 \le x_i \le n - 1; 2 \le y_i \le n; x_i \ne y_i; 1 \le c_i \le 100; -100 \le w_i \le 100). These integers describe the i-th arc.Additional constraints on the input: there are no negative cycles in the graph. OutputIf a flow satisfying all of the constraints does not exist, print Impossible.Otherwise, print two lines: the first line should contain one word Possible; the second line should contain m integers f_1, f_2, \dots, f_m. If there are multiple answers, print any of them. Note that the cost of the flow should be minimized.ExamplesInput 3 3 1 2 3 -10 1 2 3 -15 2 3 2 0 Output Possible 1 1 2 Input 3 3 1 2 3 -10 1 2 3 -15 2 3 3 0 Output Impossible Input 3 3 1 2 3 -10 1 2 3 -15 2 3 4 0 Output Possible 1 3 4 Input 6 7 5 6 9 -40 1 2 3 -10 1 4 5 20 4 5 7 30 2 5 1 -15 1 3 3 5 3 5 3 0 Output Possible 5 1 1 1 1 3 3
3 3 1 2 3 -10 1 2 3 -15 2 3 2 0
Possible 1 1 2
4 seconds
512 megabytes
['flows', '*2800']
E. Decompositiontime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputFor a sequence of integers [x_1, x_2, \dots, x_k], let's define its decomposition as follows:Process the sequence from the first element to the last one, maintaining the list of its subsequences. When you process the element x_i, append it to the end of the first subsequence in the list such that the bitwise AND of its last element and x_i is greater than 0. If there is no such subsequence in the list, create a new subsequence with only one element x_i and append it to the end of the list of subsequences.For example, let's analyze the decomposition of the sequence [1, 3, 2, 0, 1, 3, 2, 1]: processing element 1, the list of subsequences is empty. There is no subsequence to append 1 to, so we create a new subsequence [1]; processing element 3, the list of subsequences is [[1]]. Since the bitwise AND of 3 and 1 is 1, the element is appended to the first subsequence; processing element 2, the list of subsequences is [[1, 3]]. Since the bitwise AND of 2 and 3 is 2, the element is appended to the first subsequence; processing element 0, the list of subsequences is [[1, 3, 2]]. There is no subsequence to append 0 to, so we create a new subsequence [0]; processing element 1, the list of subsequences is [[1, 3, 2], [0]]. There is no subsequence to append 1 to, so we create a new subsequence [1]; processing element 3, the list of subsequences is [[1, 3, 2], [0], [1]]. Since the bitwise AND of 3 and 2 is 2, the element is appended to the first subsequence; processing element 2, the list of subsequences is [[1, 3, 2, 3], [0], [1]]. Since the bitwise AND of 2 and 3 is 2, the element is appended to the first subsequence; processing element 1, the list of subsequences is [[1, 3, 2, 3, 2], [0], [1]]. The element 1 cannot be appended to any of the first two subsequences, but can be appended to the third one. The resulting list of subsequences is [[1, 3, 2, 3, 2], [0], [1, 1]].Let f([x_1, x_2, \dots, x_k]) be the number of subsequences the sequence [x_1, x_2, \dots, x_k] is decomposed into.Now, for the problem itself.You are given a sequence [a_1, a_2, \dots, a_n], where each element is an integer from 0 to 3. Let a[i..j] be the sequence [a_i, a_{i+1}, \dots, a_j]. You have to calculate \sum \limits_{i=1}^n \sum \limits_{j=i}^n f(a[i..j]).InputThe first line contains one integer n (1 \le n \le 3 \cdot 10^5).The second line contains n integers a_1, a_2, \dots, a_n (0 \le a_i \le 3).OutputPrint one integer, which should be equal to \sum \limits_{i=1}^n \sum \limits_{j=i}^n f(a[i..j]).ExamplesInput 8 1 3 2 0 1 3 2 1 Output 71 Input 5 0 0 0 0 0 Output 35
8 1 3 2 0 1 3 2 1
71
4 seconds
512 megabytes
['binary search', 'brute force', 'data structures', 'divide and conquer', 'dp', 'two pointers', '*2300']
D. Lucky Chainstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's name a pair of positive integers (x, y) lucky if the greatest common divisor of them is equal to 1 (\gcd(x, y) = 1).Let's define a chain induced by (x, y) as a sequence of pairs (x, y), (x + 1, y + 1), (x + 2, y + 2), \dots, (x + k, y + k) for some integer k \ge 0. The length of the chain is the number of pairs it consists of, or (k + 1).Let's name such chain lucky if all pairs in the chain are lucky.You are given n pairs (x_i, y_i). Calculate for each pair the length of the longest lucky chain induced by this pair. Note that if (x_i, y_i) is not lucky itself, the chain will have the length 0. InputThe first line contains a single integer n (1 \le n \le 10^6) — the number of pairs.Next n lines contains n pairs — one per line. The i-th line contains two integers x_i and y_i (1 \le x_i < y_i \le 10^7) — the corresponding pair.OutputPrint n integers, where the i-th integer is the length of the longest lucky chain induced by (x_i, y_i) or -1 if the chain can be infinitely long.ExampleInput 4 5 15 13 37 8 9 10009 20000 Output 0 1 -1 79 NoteIn the first test case, \gcd(5, 15) = 5 > 1, so it's already not lucky, so the length of the lucky chain is 0.In the second test case, \gcd(13 + 1, 37 + 1) = \gcd(14, 38) = 2. So, the lucky chain consists of the single pair (13, 37).
4 5 15 13 37 8 9 10009 20000
0 1 -1 79
4 seconds
512 megabytes
['math', 'number theory', '*1600']
C. Hamiltonian Walltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSir Monocarp Hamilton is planning to paint his wall. The wall can be represented as a grid, consisting of 2 rows and m columns. Initially, the wall is completely white.Monocarp wants to paint a black picture on the wall. In particular, he wants cell (i, j) (the j-th cell in the i-th row) to be colored black, if c_{i, j} = 'B', and to be left white, if c_{i, j} = 'W'. Additionally, he wants each column to have at least one black cell, so, for each j, the following constraint is satisfied: c_{1, j}, c_{2, j} or both of them will be equal to 'B'.In order for the picture to turn out smooth, Monocarp wants to place down a paint brush in some cell (x_1, y_1) and move it along the path (x_1, y_1), (x_2, y_2), \dots, (x_k, y_k) so that: for each i, (x_i, y_i) and (x_{i+1}, y_{i+1}) share a common side; all black cells appear in the path exactly once; white cells don't appear in the path. Determine if Monocarp can paint the wall.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 m (1 \le m \le 2 \cdot 10^5) — the number of columns in the wall.The i-th of the next two lines contains a string c_i, consisting of m characters, where each character is either 'B' or 'W'. c_{i, j} is 'B', if the cell (i, j) should be colored black, and 'W', if the cell (i, j) should be left white.Additionally, for each j, the following constraint is satisfied: c_{1, j}, c_{2, j} or both of them are equal to 'B'.The sum of m over all testcases doesn't exceed 2 \cdot 10^5.OutputFor each testcase, print "YES" if Monocarp can paint a wall. Otherwise, print "NO".ExampleInput 63WBBBBW1BB5BWBWBBBBBB2BWWB5BBBBWBWBBB6BWBBWBBBBBBBOutput YES YES NO NO NO YES NoteIn the first testcase, Monocarp can follow a path (2, 1), (2, 2), (1, 2), (1, 3) with his brush. All black cells appear in the path exactly once, no white cells appear in the path.In the second testcase, Monocarp can follow a path (1, 1), (2, 1).In the third testcase: the path (1, 1), (2, 1), (2, 2), (2, 3), (1, 3), (2, 4), (2, 5), (1, 5) doesn't suffice because a pair of cells (1, 3) and (2, 4) doesn't share a common side; the path (1, 1), (2, 1), (2, 2), (2, 3), (1, 3), (2, 3), (2, 4), (2, 5), (1, 5) doesn't suffice because cell (2, 3) is visited twice; the path (1, 1), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (1, 5) doesn't suffice because a black cell (1, 3) doesn't appear in the path; the path (1, 1), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (1, 5), (1, 4), (1, 3) doesn't suffice because a white cell (1, 4) appears in the path.
63WBBBBW1BB5BWBWBBBBBB2BWWB5BBBBWBWBBB6BWBBWBBBBBBB
YES YES NO NO NO YES
2 seconds
256 megabytes
['dp', 'implementation', '*1300']
B. Notepad#time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to type the string s, consisting of n lowercase Latin letters, using your favorite text editor Notepad#.Notepad# supports two kinds of operations: append any letter to the end of the string; copy a continuous substring of an already typed string and paste this substring to the end of the string. Can you type string s in strictly less than n operations?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 length of the string s.The second line contains a string s, consisting of n lowercase Latin letters.The sum of n doesn't exceed 2 \cdot 10^5 over all testcases.OutputFor each testcase, print "YES" if you can type string s in strictly less than n operations. Otherwise, print "NO".ExampleInput 610codeforces8labacaba5uohhh16isthissuffixtree1x4momoOutput NO YES NO YES NO YES NoteIn the first testcase, you can start with typing "codef" (5 operations), then copy "o" (1 operation) from an already typed part, then finish with typing "rces" (4 operations). That will be 10 operations, which is not strictly less than n. There exist other ways to type "codeforces". However, no matter what you do, you can't do less than n operations.In the second testcase, you can type "labac" (5 operations), then copy "aba" (1 operation), finishing the string in 6 operations.
610codeforces8labacaba5uohhh16isthissuffixtree1x4momo
NO YES NO YES NO YES
3 seconds
256 megabytes
['implementation', '*1000']
A. Extremely Roundtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputLet's call a positive integer extremely round if it has only one non-zero digit. For example, 5000, 4, 1, 10, 200 are extremely round integers; 42, 13, 666, 77, 101 are not.You are given an integer n. You have to calculate the number of extremely round integers x such that 1 \le x \le n.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Then, t lines follow. The i-th of them contains one integer n (1 \le n \le 999999) — the description of the i-th test case.OutputFor each test case, print one integer — the number of extremely round integers x such that 1 \le x \le n.ExampleInput 594213100111Output 9 13 10 19 19
594213100111
9 13 10 19 19
3 seconds
512 megabytes
['brute force', 'implementation', '*800']
N. Number Reductiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a positive integer x.You can apply the following operation to the number: remove one occurrence of any digit in such a way that the resulting number does not contain any leading zeroes and is still a positive integer. For example, 10142 can be converted to 1142, 1042, 1012 or 1014 (note that 0142 is not a valid outcome); 10 can be converted to 1 (but not to 0 since it is not positive).Your task is to find the minimum positive integer that you can obtain from x if you can apply the aforementioned operation exactly k times.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first line of each test case contains a single integer x (1 \le x < 10^{500000}).The second line contains a single integer k (0 \le k < |x|), where |x| is the length of the number x.The sum of |x| over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print one integer — the minimum positive number that you can obtain from x if you can apply the operation exactly k times.ExampleInput 510000413370987654321666837494128578086523Output 1 1337 321 344128 7052
510000413370987654321666837494128578086523
1 1337 321 344128 7052
2 seconds
512 megabytes
['greedy', '*1500']
M. Minimum LCMtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an integer n.Your task is to find two positive (greater than 0) integers a and b such that a+b=n and the least common multiple (LCM) of a and b is the minimum among all possible values of a and b. If there are multiple answers, you can print any of them.InputThe first line contains a single integer t (1 \le t \le 100) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 10^9).OutputFor each test case, print two positive integers a and b — the answer to the problem. If there are multiple answers, you can print any of them.ExampleInput 429510Output 1 1 3 6 1 4 5 5 NoteIn the second example, there are 8 possible pairs of a and b: a = 1, b = 8, LCM(1, 8) = 8; a = 2, b = 7, LCM(2, 7) = 14; a = 3, b = 6, LCM(3, 6) = 6; a = 4, b = 5, LCM(4, 5) = 20; a = 5, b = 4, LCM(5, 4) = 20; a = 6, b = 3, LCM(6, 3) = 6; a = 7, b = 2, LCM(7, 2) = 14; a = 8, b = 1, LCM(8, 1) = 8. In the third example, there are 5 possible pairs of a and b: a = 1, b = 4, LCM(1, 4) = 4; a = 2, b = 3, LCM(2, 3) = 6; a = 3, b = 2, LCM(3, 2) = 6; a = 4, b = 1, LCM(4, 1) = 4.
429510
1 1 3 6 1 4 5 5
2 seconds
512 megabytes
['math', 'number theory', '*1000']
L. Project Managertime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n employees at Bersoft company, numbered from 1 to n. Each employee works on some days of the week and rests on the other days. You are given the lists of working days of the week for each employee.There are regular days and holidays. On regular days, only those employees work that have the current day of the week on their list. On holidays, no one works. You are provided with a list of days that are holidays. The days are numbered from 1 onwards, day 1 is Monday.The company receives k project offers they have to complete. The projects are numbered from 1 to k in the order of decreasing priority. Each project consists of multiple parts, where the i-th part must be completed by the a_i-th employee. The parts must be completed in order (i. e. the (i+1)-st part can only be started when the i-th part is completed). Each part takes the corresponding employee a day to complete.The projects can be worked on simultaneously. However, one employee can complete a part of only one project during a single day. If they have a choice of what project to complete a part on, they always go for the project with the highest priority (the lowest index).For each project, output the day that project will be completed on.InputThe first line contains three integers n, m and k (1 \le n, m, k \le 2 \cdot 10^5) — the number of employees, the number of holidays and the number of projects.The i-th of the next n lines contains the list of working days of the i-th employee. First, a single integer t (1 \le t \le 7) — the number of working days. Then t days of the week in the increasing order. The possible days are: "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday".The next line contains m integers h_1, h_2, \dots, h_m (1 \le h_1 < h_2 < \dots < h_m \le 10^9) — the list of holidays.The j-th of the next k lines contains a description of the j-th project. It starts with an integer p (1 \le p \le 2 \cdot 10^5) — the number of parts in the project. Then p integers a_1, a_2, \dots, a_p (1 \le a_x \le n) follow, where p_i is the index of the employee that must complete the i-th part.The total number of parts in all projects doesn't exceed 2 \cdot 10^5.OutputPrint k integers — the j-th value should be equal to the day the j-th project is completed on.ExampleInput 3 5 4 2 Saturday Sunday 2 Tuesday Thursday 4 Monday Wednesday Friday Saturday 4 7 13 14 15 5 1 1 3 3 2 3 2 3 2 5 3 3 3 1 1 8 3 3 3 3 3 3 3 3 Output 25 9 27 27
3 5 4 2 Saturday Sunday 2 Tuesday Thursday 4 Monday Wednesday Friday Saturday 4 7 13 14 15 5 1 1 3 3 2 3 2 3 2 5 3 3 3 1 1 8 3 3 3 3 3 3 3 3
25 9 27 27
4 seconds
512 megabytes
['brute force', 'data structures', 'implementation', '*2400']
K. Torus Pathtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a square grid with n rows and n columns, where each cell has a non-negative integer written in it. There is a chip initially placed at the top left cell (the cell with coordinates (1, 1)). You need to move the chip to the bottom right cell (the cell with coordinates (n, n)).In one step, you can move the chip to the neighboring cell, but: you can move only right or down. In other words, if the current cell is (x, y), you can move either to (x, y + 1) or to (x + 1, y). There are two special cases: if the chip is in the last column (cell (x, n)) and you're moving right, you'll teleport to the first column (to the cell (x, 1)); if the chip is in the last row (cell (n, y)) and you're moving down, you'll teleport to the first row (to the cell (1, y)). you cannot visit the same cell twice. The starting cell is counted visited from the beginning (so you cannot enter it again), and you can't leave the finishing cell once you visit it. Your total score is counted as the sum of numbers in all cells you have visited. What is the maximum possible score you can achieve?InputThe first line contains the single integer n (2 \le n \le 200) — the number of rows and columns in the grid.Next n lines contains the description of each row of the grid. The i-th line contains n integers a_{i, 1}, a_{i, 2}, \dots, a_{i, n} (0 \le a_{i, j} \le 10^9) where a_{i, j} is the number written in the cell (i, j).OutputPrint one integer — the maximum possible score you can achieve.ExamplesInput 2 1 2 3 4 Output 8 Input 3 10 10 10 10 0 10 10 10 10 Output 80
2 1 2 3 4
8
2 seconds
512 megabytes
['greedy', 'math', '*1500']
J. Hero to Zerotime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are no heroes in this problem. I guess we should have named it "To Zero".You are given two arrays a and b, each of these arrays contains n non-negative integers.Let c be a matrix of size n \times n such that c_{i,j} = |a_i - b_j| for every i \in [1, n] and every j \in [1, n].Your goal is to transform the matrix c so that it becomes the zero matrix, i. e. a matrix where every element is exactly 0. In order to do so, you may perform the following operations any number of times, in any order: choose an integer i, then decrease c_{i,j} by 1 for every j \in [1, n] (i. e. decrease all elements in the i-th row by 1). In order to perform this operation, you pay 1 coin; choose an integer j, then decrease c_{i,j} by 1 for every i \in [1, n] (i. e. decrease all elements in the j-th column by 1). In order to perform this operation, you pay 1 coin; choose two integers i and j, then decrease c_{i,j} by 1. In order to perform this operation, you pay 1 coin; choose an integer i, then increase c_{i,j} by 1 for every j \in [1, n] (i. e. increase all elements in the i-th row by 1). When you perform this operation, you receive 1 coin; choose an integer j, then increase c_{i,j} by 1 for every i \in [1, n] (i. e. increase all elements in the j-th column by 1). When you perform this operation, you receive 1 coin. You have to calculate the minimum number of coins required to transform the matrix c into the zero matrix. Note that all elements of c should be equal to 0 simultaneously after the operations.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 10^8).The third line contains n integers b_1, b_2, \dots, b_n (0 \le b_j \le 10^8).OutputPrint one integer — the minimum number of coins required to transform the matrix c into the zero matrix.ExamplesInput 3 1 2 3 2 2 2 Output 2 Input 3 3 1 3 1 1 2 Output 5 Input 2 1 0 2 1 Output 2 Input 2 1 4 2 3 Output 4 Input 4 1 3 3 7 6 9 4 2 Output 29 NoteIn the first example, the matrix looks as follows: 111000111 You can turn it into a zero matrix using 2 coins as follows: subtract 1 from the first row, paying 1 coin; subtract 1 from the third row, paying 1 coin. In the second example, the matrix looks as follows: 221001221 You can turn it into a zero matrix using 5 coins as follows: subtract 1 from the first row, paying 1 coin; subtract 1 from the third row, paying 1 coin; subtract 1 from the third row, paying 1 coin; subtract 1 from a_{2,3}, paying 1 coin; add 1 to the third column, receiving 1 coin; subtract 1 from the first row, paying 1 coin; subtract 1 from a_{2,3}, paying 1 coin.
3 1 2 3 2 2 2
2
4 seconds
512 megabytes
['graph matchings', 'math', '*2900']
I. Infinite Chesstime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe black king lives on a chess board with an infinite number of columns (files) and 8 rows (ranks). The columns are numbered with all integer numbers (including negative). The rows are numbered from 1 to 8.Initially, the black king is located on the starting square (x_s, y_s), and he needs to reach some target square (x_t, y_t). Unfortunately, there are also white pieces on the board, and they threaten the black king. After negotiations, the white pieces agreed to let the black king pass to the target square on the following conditions: each turn, the black king makes a move according to the movement rules; the black king cannot move to a square occupied by a white piece; the black king cannot move to a square which is under attack by any white piece. A square is under attack if a white piece can reach it in one move according to the movement rules; the white pieces never move. Help the black king find the minimum number of moves needed to reach the target square while not violating the conditions. The black king cannot leave the board at any time.The black king moves according to the movement rules below. Even though the white pieces never move, squares which they can reach in one move are considered to be under attack, so the black king cannot move into those squares.Below are the movement rules. Note that the pieces (except for the knight) cannot jump over other pieces. a king moves exactly one square horizontally, vertically, or diagonally. a rook moves any number of vacant squares horizontally or vertically. a bishop moves any number of vacant squares diagonally. a queen moves any number of vacant squares horizontally, vertically, or diagonally. a knight moves to one of the nearest squares not on the same rank, file, or diagonal (this can be thought of as moving two squares horizontally then one square vertically, or moving one square horizontally then two squares vertically — i. e. in an "L" pattern). Knights are not blocked by other pieces, they can simply jump over them. There are no pawns on the board. King and knight possible moves, respectively. Dotted line shows that knight can jump over other pieces. Queen, bishop, and rook possible moves, respectively. InputThe first line contains two integers x_s and y_s (1 \le x_s \le 10^8; 1 \le y_s \le 8) — the starting coordinates of the black king.The second line contains two integers x_t and y_t (1 \le x_t \le 10^8; 1 \le y_t \le 8) — the coordinates of the target square for the black king.The third line contains one integer n (0 \le n \le 2000) — the number of white pieces on the board.Then n lines follow, the i-th line contains one character t_i and two integers x_i and y_i (1 \le x_i \le 10^8; 1 \le y_i \le 8) — the type and the coordinates of the i-th white piece. The types of pieces are represented by the following uppercase Latin letters: K — king Q — queen R — rook B — bishop N — knight There can be any number of white pieces of any type listed above on the board, for example, 3 white kings or 4 white queens. There are no pawns on the board.Additional constrains on the input: no square is occupied by more than one white piece; the starting square for the black king is different from the square he wants to reach, and neither of these two squares is occupied or is under attack by any white piece. OutputPrint one integer — the minimum number of moves needed for the black king to reach the target square while not violating the conditions, or -1 if it is impossible.ExamplesInput 1 8 7 8 2 N 4 8 B 4 6 Output 10 Input 1 1 1 5 2 K 1 3 R 2 3 Output 6 Input 2 2 6 4 1 Q 4 3 Output -1 NoteThe image below demonstrates the solution for the second example. Here, the letters K, R, s, and t represent the white king, the white rook, the starting square, and the target square, respectively. Bold crosses mark the squares which are under attack by the white pieces. Bold dots show the shortest path for the black king.
1 8 7 8 2 N 4 8 B 4 6
10
3 seconds
512 megabytes
['implementation', 'shortest paths', '*2800']
H. Hospital Queuetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n people (numbered from 1 to n) signed up for a doctor's appointment. The doctor has to choose in which order he will appoint these people. The i-th patient should be appointed among the first p_i people. There are also m restrictions of the following format: the i-th restriction is denoted by two integers (a_i, b_i) and means that the patient with the index a_i should be appointed earlier than the patient with the index b_i.For example, if n = 4, p = [2, 3, 2, 4], m = 1, a = [3] and b = [1], then the only order of appointment of patients that does not violate the restrictions is [3, 1, 2, 4]. For n =3, p = [3, 3, 3], m = 0, a = [] and b = [], any order of appointment is valid.For each patient, calculate the minimum position in the order that they can have among all possible orderings that don't violate the restrictions.InputThe first line contains two integers n and m (1 \le n \le 2000; 0 \le m \le 2000).The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n).Then m lines follow. The i-th of them contains two integers a_i and b_i (1 \le a_i, b_i \le n; a_i \ne b_i). All pairs of (a_i, b_i) are distinct (i. e. if i \ne j, then either a_i \ne a_j, b_i \ne b_j, or both).Additional constraint on the input: there is at least one valid order of patients.OutputPrint n integers, where i-th integer is equal to the minimum position of i-th patient in the order, among all valid orders. Positions in the order are numbered from 1 to n.ExamplesInput 4 1 2 3 2 4 3 1 Output 2 3 1 4 Input 3 0 3 3 3 Output 1 1 1 Input 5 3 4 3 3 2 5 3 1 1 5 4 2 Output 4 2 1 1 5 NoteIn the first example, [3, 1, 2, 4] the only one valid order, so the minimum position of each patient is equal to their position in this order.In the second example, any order is valid, so any patient can be appointed first.In the third example, there are three valid orders: [4, 2, 3, 1, 5], [3, 4, 2, 1, 5] and [4, 3, 2, 1, 5].
4 1 2 3 2 4 3 1
2 3 1 4
3 seconds
512 megabytes
['binary search', 'graphs', 'greedy', 'implementation', '*2200']
G. Guess the Stringtime limit per test6 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an interactive problem. You have to use flush operation right after printing each line. For example, in C++ you should use the function fflush(stdout), in Java or Kotlin — System.out.flush(), and in Python — sys.stdout.flush().The jury has a string s consisting of characters 0 and/or 1. The first character of this string is 0. The length of this string is n. You have to guess this string. Let's denote s[l..r] as the substring of s from l to r (i. e. s[l..r] is the string s_ls_{l+1} \dots s_r).Let the prefix function of the string s be an array [p_1, p_2, \dots, p_n], where p_i is the greatest integer j \in [0, i-1] such that s[1..j] = s[i-j+1..i]. Also, let the antiprefix function of the string s be an array [q_1, q_2, \dots, q_n], where q_i is the greatest integer j \in [0, i-1] such that s[1..j] differs from s[i-j+1..i] in every position.For example, for the string 011001, its prefix function is [0, 0, 0, 1, 1, 2], and its antiprefix function is [0, 1, 1, 2, 3, 4].You can ask queries of two types to guess the string s: 1 i — "what is the value of p_i?"; 2 i — "what is the value of q_i?". You have to guess the string by asking no more than 789 queries. Note that giving the answer does not count as a query.In every test and in every test case, the string s is fixed beforehand.InteractionInitially, the jury program sends one integer t (1 \le t \le 100) — the number of test cases.At the start of each test case, the jury program sends one integer n (2 \le n \le 1000) — the length of the string.After that, your program can submit queries to the jury program by printing one of the following lines (do not forget to flush the output after printing a line!): 1 i — the query "what is the value of p_i?"; 2 i — the query "what is the value of q_i?". For every query, the jury prints one integer on a separate line. It is either: the answer for your query, if the query is correct and you haven't exceeded the query limit; or the integer -1, if your query is incorrect (for example, the constraint 1 \le i \le n is not met) or if you have asked too many queries while processing the current test case. To submit the answer, your program should send a line in the following format (do not forget to flush the output after printing a line!): 0 s, where s is a sequence of n characters 0 and/or 1. If your guess is correct, the jury program will print one integer 1 on a separate line, indicating that you may proceed to the next test case (or terminate the program, if it was the last test case) and that the number of queries you have asked is reset. If it is not correct, the jury program will print one integer -1 on a separate line.After your program receives -1 as the answer, it should immediately terminate. This will lead to your submission receiving the verdict "Wrong Answer". If your program does not terminate, the verdict of your submission is undefined.ExampleInput 2 // 2 test cases 6 // n = 6 0 // p[3] = 0 1 // q[2] = 1 4 // q[6] = 4 1 // p[4] = 1 1 // answer is correct 5 // n = 5 1 // p[2] = 1 2 // q[4] = 2 2 // q[5] = 2 1 // answer is correct Output 1 3 // what is p[3]? 2 2 // what is q[2]? 2 6 // what is q[6]? 1 4 // what is p[4]? 0 011001 // the guess is 011001 1 2 // what is p[2]? 2 4 // what is q[4]? 2 5 // what is q[5]? 0 00111 // the guess is 00111 NoteThe example contains one possible way of interaction in a test where t = 2, and the strings guessed by the jury are 011001 and 00111. Note that everything after the // sign is a comment that explains which line means what in the interaction. The jury program won't print these comments in the actual problem, and you shouldn't print them. The empty lines are also added for your convenience, the jury program won't print them, and your solution should not print any empty lines.
2 // 2 test cases 6 // n = 6 0 // p[3] = 0 1 // q[2] = 1 4 // q[6] = 4 1 // p[4] = 1 1 // answer is correct 5 // n = 5 1 // p[2] = 1 2 // q[4] = 2 2 // q[5] = 2 1 // answer is correct
1 3 // what is p[3]? 2 2 // what is q[2]? 2 6 // what is q[6]? 1 4 // what is p[4]? 0 011001 // the guess is 011001 1 2 // what is p[2]? 2 4 // what is q[4]? 2 5 // what is q[5]? 0 00111 // the guess is 00111
6 seconds
512 megabytes
['constructive algorithms', 'interactive', 'probabilities', '*2600']
F. Chemistry Labtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp is planning on opening a chemistry lab. During the first month, he's going to distribute solutions of a certain acid.First, he will sign some contracts with a local chemistry factory. Each contract provides Monocarp with an unlimited supply of some solution of the same acid. The factory provides n contract options, numbered from 1 to n. The i-th solution has a concentration of x_i\%, the contract costs w_i burles, and Monocarp will be able to sell it for c_i burles per liter. Monocarp is expecting k customers during the first month. Each customer will buy a liter of a y\%-solution, where y is a real number chosen uniformly at random from 0 to 100 independently for each customer. More formally, the probability of number y being less than or equal to some t is P(y \le t) = \frac{t}{100}.Monocarp can mix the solution that he signed the contracts with the factory for, at any ratio. More formally, if he has contracts for m solutions with concentrations x_1, x_2, \dots, x_m, then, for these solutions, he picks their volumes a_1, a_2, \dots, a_m so that \sum \limits_{i=1}^{m} a_i = 1 (exactly 1 since each customer wants exactly one liter of a certain solution).The concentration of the resulting solution is \sum \limits_{i=1}^{m} x_i \cdot a_i. The price of the resulting solution is \sum \limits_{i=1}^{m} c_i \cdot a_i.If Monocarp can obtain a solution of concentration y\%, then he will do it while maximizing its price (the cost for the customer). Otherwise, the customer leaves without buying anything, and the price is considered equal to 0.Monocarp wants to sign some contracts with a factory (possibly, none or all of them) so that the expected profit is maximized — the expected total price of the sold solutions for all k customers minus the total cost of signing the contracts from the factory.Print the maximum expected profit Monocarp can achieve.InputThe first line contains two integers n and k (1 \le n \le 5000; 1 \le k \le 10^5) — the number of contracts the factory provides and the number of customers.The i-th of the next n lines contains three integers x_i, w_i and c_i (0 \le x_i \le 100; 1 \le w_i \le 10^9; 1 \le c_i \le 10^5) — the concentration of the solution, the cost of the contract and the cost per liter for the customer, for the i-th contract.OutputPrint a single real number — the maximum expected profit Monocarp can achieve.Your answer is considered correct if its absolute or relative error does not exceed 10^{-6}.Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if \frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}.ExamplesInput 2 10 0 10 20 100 15 20 Output 175.000000000000000 Input 2 10 0 100 20 100 150 20 Output 0.000000000000000 Input 6 15 79 5 35 30 13 132 37 3 52 24 2 60 76 18 14 71 17 7 Output 680.125000000000000 Input 10 15 46 11 11 4 12 170 69 2 130 2 8 72 82 7 117 100 5 154 38 9 146 97 1 132 0 12 82 53 1 144 Output 2379.400000000000000
2 10 0 10 20 100 15 20
175.000000000000000
2 seconds
512 megabytes
['dp', 'geometry', 'probabilities', '*2200']
E. Exchangetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp is playing a MMORPG. There are two commonly used types of currency in this MMORPG — gold coins and silver coins. Monocarp wants to buy a new weapon for his character, and that weapon costs n silver coins. Unfortunately, right now, Monocarp has no coins at all.Monocarp can earn gold coins by completing quests in the game. Each quest yields exactly one gold coin. Monocarp can also exchange coins via the in-game trading system. Monocarp has spent days analyzing the in-game economy; he came to the following conclusion: it is possible to sell one gold coin for a silver coins (i. e. Monocarp can lose one gold coin to gain a silver coins), or buy one gold coin for b silver coins (i. e. Monocarp can lose b silver coins to gain one gold coin).Now Monocarp wants to calculate the minimum number of quests that he has to complete in order to have at least n silver coins after some abuse of the in-game economy. Note that Monocarp can perform exchanges of both types (selling and buying gold coins for silver coins) any number of times.InputThe first line contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line containing three integers n, a and b (1 \le n \le 10^7; 1 \le a, b \le 50).OutputFor each test case, print one integer — the minimum possible number of quests Monocarp has to complete.ExampleInput 4100 25 309999997 25 5052 50 4849 50 1Output 4 400000 1 1 NoteIn the first test case of the example, Monocarp should complete 4 quests, and then sell 4 gold coins for 100 silver coins.In the second test case, Monocarp should complete 400000 quests, and then sell 400000 gold coins for 10 million silver coins.In the third test case, Monocarp should complete 1 quest, sell the gold coin for 50 silver coins, buy a gold coin for 48 silver coins, and then sell it again for 50 coins. So, he will have 52 silver coins.In the fourth test case, Monocarp should complete 1 quest and then sell the gold coin he has obtained for 50 silver coins.
4100 25 309999997 25 5052 50 4849 50 1
4 400000 1 1
2 seconds
512 megabytes
['brute force', 'math', '*1000']
D. Watch the Videostime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputMonocarp wants to watch n videos. Each video is only one minute long, but its size may be arbitrary. The i-th video has the size a_i megabytes. All videos are published on the Internet. A video should be downloaded before it can be watched. Monocarp has poor Internet connection — it takes exactly 1 minute to download 1 megabyte of data, so it will require a_i minutes to download the i-th video.Monocarp's computer has a hard disk of m megabytes. The disk is used to store the downloaded videos. Once Monocarp starts the download of a video of size s, the s megabytes are immediately reserved on a hard disk. If there are less than s megabytes left, the download cannot be started until the required space is freed. Each single video can be stored on the hard disk, since a_i \le m for all i. Once the download is started, it cannot be interrupted. It is not allowed to run two or more downloads in parallel.Once a video is fully downloaded to the hard disk, Monocarp can watch it. Watching each video takes exactly 1 minute and does not occupy the Internet connection, so Monocarp can start downloading another video while watching the current one.When Monocarp finishes watching a video, he doesn't need it on the hard disk anymore, so he can delete the video, instantly freeing the space it occupied on a hard disk. Deleting a video takes negligible time.Monocarp wants to watch all n videos as quickly as possible. The order of watching does not matter, since Monocarp needs to watch all of them anyway. Please calculate the minimum possible time required for that.InputThe first line contains two integers n and m (1 \le n \le 2 \cdot 10^5; 1 \le m \le 10^9) — the number of videos Monocarp wants to watch and the size of the hard disk, respectively. The second line contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le m) — the sizes of the videos.OutputPrint one integer — the minimum time required to watch all n videos.ExamplesInput 5 6 1 2 3 4 5 Output 16 Input 5 5 1 2 3 4 5 Output 17 Input 4 3 1 3 2 3 Output 12
5 6 1 2 3 4 5
16
1 second
512 megabytes
['binary search', 'constructive algorithms', 'two pointers', '*1700']
C. Card Guessingtime limit per test15 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputConsider a deck of cards. Each card has one of 4 suits, and there are exactly n cards for each suit — so, the total number of cards in the deck is 4n. The deck is shuffled randomly so that each of (4n)! possible orders of cards in the deck has the same probability of being the result of shuffling. Let c_i be the i-th card of the deck (from top to bottom).Monocarp starts drawing the cards from the deck one by one. Before drawing a card, he tries to guess its suit. Monocarp remembers the suits of the k last cards, and his guess is the suit that appeared the least often among the last k cards he has drawn. So, while drawing the i-th card, Monocarp guesses that its suit is the suit that appears the minimum number of times among the cards c_{i-k}, c_{i-k+1}, \dots, c_{i-1} (if i \le k, Monocarp considers all previously drawn cards, that is, the cards c_1, c_2, \dots, c_{i-1}). If there are multiple suits that appeared the minimum number of times among the previous cards Monocarp remembers, he chooses a random suit out of those for his guess (all suits that appeared the minimum number of times have the same probability of being chosen).After making a guess, Monocarp draws a card and compares its suit to his guess. If they match, then his guess was correct; otherwise it was incorrect.Your task is to calculate the expected number of correct guesses Monocarp makes after drawing all 4n cards from the deck.InputThe first (and only) line contains two integers n (1 \le n \le 500) and k (1 \le k \le 4 \cdot n).OutputLet the expected value you have to calculate be an irreducible fraction \dfrac{x}{y}. Print one integer — the value of x \cdot y^{-1} \bmod 998244353, where y^{-1} is the inverse to y (i. e. an integer such that y \cdot y^{-1} \bmod 998244353 = 1).ExamplesInput 1 1 Output 748683266 Input 3 2 Output 567184295 Input 2 7 Output 373153250 Input 2 8 Output 373153250
1 1
748683266
15 seconds
1024 megabytes
['combinatorics', 'dp', 'probabilities', '*2600']
B. Broken Keyboardtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputRecently, Mishka started noticing that his keyboard malfunctions — maybe it's because he was playing rhythm games too much. Empirically, Mishka has found out that every other time he presses a key, it is registered as if the key was pressed twice. For example, if Mishka types text, the first time he presses a key, exactly one letter is printed; the second time he presses a key, two same letters are printed; the third time he presses a key, one letter is printed; the fourth time he presses a key, two same letters are printed, and so on. Note that the number of times a key was pressed is counted for the whole keyboard, not for each key separately. For example, if Mishka tries to type the word osu, it will be printed on the screen as ossu.You are given a word consisting of n lowercase Latin letters. You have to determine if it can be printed on Mishka's keyboard or not. You may assume that Mishka cannot delete letters from the word, and every time he presses a key, the new letter (or letters) is appended to the end of the word.InputThe first line of the input contains one integer t (1 \le t \le 100) — the number of test cases.The first line of the test case contains one integer n (1 \le n \le 100) — the length of the word.The second line of the test case contains a string s consisting of n lowercase Latin letters — the word that should be checked.OutputFor each test case, print YES if the word s can be printed on Mishka's keyboard, and NO otherwise.ExampleInput 44ossu2aa6addonn3qweOutput YES NO YES NO NoteIn the first test case, Mishka can type the word as follows: press o (one letter o appears at the end of the word), then presses s (two letters s appear at the end of the word), and, finally, press u (one letter appears at the end of the word, making the resulting word ossu).In the second test case, Mishka can try typing the word as follows: press a (one letter a appears at the end of the word). But if he tries to press a one more time, two letters a will appear at the end of the word, so it is impossible to print the word using his keyboard.In the fourth test case, Mishka has to start by pressing q. Then, if he presses w, two copies of w will appear at the end of the word, but the third letter should be e instead of w, so the answer is NO.
44ossu2aa6addonn3qwe
YES NO YES NO
1 second
512 megabytes
['greedy', '*800']
A. Access Levelstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBerSoft is the biggest IT corporation in Berland, and Monocarp is the head of its security department. This time, he faced the most difficult task ever. Basically, there are n developers working at BerSoft, numbered from 1 to n. There are m documents shared on the internal network, numbered from 1 to m. There is a table of access requirements a such that a_{i,j} (the j-th element of the i-th row) is 1 if the i-th developer should have access to the j-th document, and 0 if they should have no access to it.In order to restrict the access, Monocarp is going to perform the following actions: choose the number of access groups k \ge 1; assign each document an access group (an integer from 1 to k) and the required access level (an integer from 1 to 10^9); assign each developer k integer values (from 1 to 10^9) — their access levels for each of the access groups. The developer i has access to the document j if their access level for the access group of the document is greater than or equal to the required access level of the document.What's the smallest number of access groups Monocarp can choose so that it's possible to assign access groups and access levels in order to satisfy the table of access requirements?InputThe first line contains two integers n and m (1 \le n, m \le 500) — the number of developers and the number of documents.Each of the next n lines contains a binary string of length m — the table of access requirements. The j-th element of the i-th row is 1 if the i-th developer should have access to the j-th document, and 0 if they should have no access to it.OutputThe first line should contain a single integer k — the smallest number of access groups Monocarp can choose so that it's possible to assign access groups and access levels in order to satisfy the table of access requirements.The second line should contain m integers from 1 to k — the access groups of the documents.The third line should contain m integers from 1 to 10^9 — the required access levels of the documents.The i-th of the next n lines should contain k integers from 1 to 10^9 — the access level of the i-th developer on each of the access groups.If there are multiple solutions, print any of them.ExamplesInput 3 2 01 11 10 Output 2 1 2 2 2 1 2 2 2 2 1 Input 2 3 101 100 Output 1 1 1 1 1 10 5 8 3 NoteIn the first example, we assign the documents to different access groups. Both documents have level 2 in their access group. This way, we can assign the developers, who need the access, level 2, and the developers, who have to have no access, level 1.If they had the same access group, it would be impossible to assign access levels to developers 1 and 3. Developer 1 should've had a lower level than developer 3 in this group to not be able to access document 1. At the same time, developer 3 should've had a lower level than developer 1 in this group to not be able to access document 2. Since they can't both have lower level than each other, it's impossible to have only one access group.In the second example, it's possible to assign all documents to the same access group.
3 2 01 11 10
2 1 2 2 2 1 2 2 2 2 1
2 seconds
512 megabytes
['bitmasks', 'dsu', 'flows', 'graph matchings', '*2400']
H. Doremy's Paint 2time limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoremy has n buckets of paint which is represented by an array a of length n. Bucket i contains paint with color a_i. Initially, a_i=i.Doremy has m segments [l_i,r_i] (1 \le l_i \le r_i \le n). Each segment describes an operation. Operation i is performed as follows: For each j such that l_i < j \leq r_i, set a_j := a_{l_i}. Doremy also selects an integer k. She wants to know for each integer x from 0 to m-1, the number of distinct colors in the array after performing operations x \bmod m +1, (x+1) \bmod m + 1, \ldots, (x+k-1) \bmod m +1. Can you help her calculate these values? Note that for each x individually we start from the initial array and perform only the given k operations in the given order.InputThe first line of input contains three integers n, m, and k (1\le n,m\le 2\cdot 10^5, 1 \le k \le m) — the length of the array a, the total number of operations, and the integer that Doremy selects.The i-th line of the following m lines contains two integers l_i, r_i (1\le l_i\le r_i\le n) — the bounds of the i-th segment.OutputOutput m integers. The (x+1)-th integer should be the number of distinct colors in the array if we start from the initial array and perform operations x \bmod m +1, (x+1) \bmod m + 1, \ldots, (x+k-1) \bmod m +1.ExamplesInput 7 5 5 3 5 2 3 4 6 5 7 1 2 Output 3 3 3 3 2 Input 10 9 4 1 1 2 3 3 4 7 9 6 8 5 7 2 4 9 10 1 3 Output 6 6 7 6 5 5 7 7 7 NoteIn the first test case, the picture below shows the resulting array for the values of x=0,1,2 respectively.
7 5 5 3 5 2 3 4 6 5 7 1 2
3 3 3 3 2
4 seconds
256 megabytes
['data structures', '*3400']
G3. Doremy's Perfect DS Class (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{20} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 \leq l \leq r \leq m and 1 \leq k \leq m, which returns the number of distinct integers in the array \left[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, \ldots, \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 \leq l \leq r \leq n, 1 \leq k \leq n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 \leq y \leq n) such that p_y=1 in at most \mathbf{20} queries?Note that the permutation p is fixed before any queries are made.InteractionYou begin the interaction by reading an integer n (3 \le n \le 1024) in the first line — the length of the permutation.To make a query, you should output "? l\ r\ k" (1 \leq l \leq r \leq n, 1 \leq k \leq n) in a separate line. After each query, you should read an integer x — the value of Q(l,r,k) for p. In this version of the problem, you can make at most 20 such queries.To give the answer, you should output "! y" (1 \leq y \leq n) in a separate line, where p_y=1.After printing a query or the answer, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hacks FormatThe first line of the hack contains an integer n (3 \le n \le 1024) — the length of the permutation.The second line of the hack contains n distinct integers p_1,p_2,\ldots,p_n (1 \le p_i\le n) — the permutation.ExampleInput 5 2 2 1 3Output ? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4NoteThe permutation in the example is [3,5,2,1,4].The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).In this interaction process: For the first query, \lfloor\frac{3}{4}\rfloor=0,\lfloor\frac{5}{4}\rfloor=1,\lfloor\frac{2}{4}\rfloor=0, so the answer is 2. For the second query, \lfloor\frac{2}{3}\rfloor=0,\lfloor\frac{1}{3}\rfloor=0,\lfloor\frac{4}{3}\rfloor=1, so the answer is still 2. For the third query, \lfloor\frac{2}{5}\rfloor=0,\lfloor\frac{1}{5}\rfloor=0, so the answer is 1. For the fourth query, \lfloor\frac{2}{2}\rfloor=1,\lfloor\frac{1}{2}\rfloor=0,\lfloor\frac{4}{2}\rfloor=2, so the answer is 3. The correct answer is got after 4 queries, so this process will be judged correct.
5 2 2 1 3
? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4
1 second
256 megabytes
['binary search', 'interactive', '*3300']
G2. Doremy's Perfect DS Class (Medium Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{25} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 \leq l \leq r \leq m and 1 \leq k \leq m, which returns the number of distinct integers in the array \left[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, \ldots, \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 \leq l \leq r \leq n, 1 \leq k \leq n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 \leq y \leq n) such that p_y=1 in at most \mathbf{25} queries?Note that the permutation p is fixed before any queries are made.InteractionYou begin the interaction by reading an integer n (3 \le n \le 1024) in the first line — the length of the permutation.To make a query, you should output "? l\ r\ k" (1 \leq l \leq r \leq n, 1 \leq k \leq n) in a separate line. After each query, you should read an integer x — the value of Q(l,r,k) for p. In this version of the problem, you can make at most 25 such queries.To give the answer, you should output "! y" (1 \leq y \leq n) in a separate line, where p_y=1.After printing a query or the answer, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hacks FormatThe first line of the hack contains an integer n (3 \le n \le 1024) — the length of the permutation.The second line of the hack contains n distinct integers p_1,p_2,\ldots,p_n (1 \le p_i\le n) — the permutation.ExampleInput 5 2 2 1 3Output ? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4NoteThe permutation in the example is [3,5,2,1,4].The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).In this interaction process: For the first query, \lfloor\frac{3}{4}\rfloor=0,\lfloor\frac{5}{4}\rfloor=1,\lfloor\frac{2}{4}\rfloor=0, so the answer is 2. For the second query, \lfloor\frac{2}{3}\rfloor=0,\lfloor\frac{1}{3}\rfloor=0,\lfloor\frac{4}{3}\rfloor=1, so the answer is still 2. For the third query, \lfloor\frac{2}{5}\rfloor=0,\lfloor\frac{1}{5}\rfloor=0, so the answer is 1. For the fourth query, \lfloor\frac{2}{2}\rfloor=1,\lfloor\frac{1}{2}\rfloor=0,\lfloor\frac{4}{2}\rfloor=2, so the answer is 3. The correct answer is got after 4 queries, so this process will be judged correct.
5 2 2 1 3
? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4
1 second
256 megabytes
['binary search', 'interactive', '*3000']
G1. Doremy's Perfect DS Class (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe only difference between this problem and the other two versions is the maximum number of queries. In this version, you are allowed to ask at most \mathbf{30} queries. You can make hacks only if all versions of the problem are solved.This is an interactive problem."Everybody! Doremy's Perfect Data Structure Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's Data Structure class, Doremy is teaching everyone a powerful data structure — Doremy tree! Now she gives you a quiz to prove that you are paying attention in class.Given an array a of length m, Doremy tree supports the query Q(l,r,k), where 1 \leq l \leq r \leq m and 1 \leq k \leq m, which returns the number of distinct integers in the array \left[\lfloor\frac{a_l}{k} \rfloor, \lfloor\frac{a_{l+1}}{k} \rfloor, \ldots, \lfloor\frac{a_r}{k} \rfloor\right].Doremy has a secret permutation p of integers from 1 to n. You can make queries, in one query, you give 3 integers l,r,k (1 \leq l \leq r \leq n, 1 \leq k \leq n) and receive the value of Q(l,r,k) for the array p. Can you find the index y (1 \leq y \leq n) such that p_y=1 in at most \mathbf{30} queries?Note that the permutation p is fixed before any queries are made.InteractionYou begin the interaction by reading an integer n (3 \le n \le 1024) in the first line — the length of the permutation.To make a query, you should output "? l\ r\ k" (1 \leq l \leq r \leq n, 1 \leq k \leq n) in a separate line. After each query, you should read an integer x — the value of Q(l,r,k) for p. In this version of the problem, you can make at most 30 such queries.To give the answer, you should output "! y" (1 \leq y \leq n) in a separate line, where p_y=1.After printing a query or the answer, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hacks FormatThe first line of the hack contains an integer n (3 \le n \le 1024) — the length of the permutation.The second line of the hack contains n distinct integers p_1,p_2,\ldots,p_n (1 \le p_i\le n) — the permutation.ExampleInput 5 2 2 1 3Output ? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4NoteThe permutation in the example is [3,5,2,1,4].The input and output for example illustrate possible interaction on that test (empty lines are inserted only for clarity).In this interaction process: For the first query, \lfloor\frac{3}{4}\rfloor=0,\lfloor\frac{5}{4}\rfloor=1,\lfloor\frac{2}{4}\rfloor=0, so the answer is 2. For the second query, \lfloor\frac{2}{3}\rfloor=0,\lfloor\frac{1}{3}\rfloor=0,\lfloor\frac{4}{3}\rfloor=1, so the answer is still 2. For the third query, \lfloor\frac{2}{5}\rfloor=0,\lfloor\frac{1}{5}\rfloor=0, so the answer is 1. For the fourth query, \lfloor\frac{2}{2}\rfloor=1,\lfloor\frac{1}{2}\rfloor=0,\lfloor\frac{4}{2}\rfloor=2, so the answer is 3. The correct answer is got after 4 queries, so this process will be judged correct.
5 2 2 1 3
? 1 3 4 ? 3 5 3 ? 3 4 5 ? 3 5 2 ! 4
1 second
256 megabytes
['binary search', 'interactive', '*2900']
F. Doremy's Experimental Treetime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoremy has an edge-weighted tree with n vertices whose weights are integers between 1 and 10^9. She does \frac{n(n+1)}{2} experiments on it.In each experiment, Doremy chooses vertices i and j such that j \leq i and connects them directly with an edge with weight 1. Then, there is exactly one cycle (or self-loop when i=j) in the graph. Doremy defines f(i,j) as the sum of lengths of shortest paths from every vertex to the cycle.Formally, let \mathrm{dis}_{i,j}(x,y) be the length of the shortest path between vertex x and y when the edge (i,j) of weight 1 is added, and S_{i,j} be the set of vertices that are on the cycle when edge (i,j) is added. Then, f(i,j)=\sum_{x=1}^{n}\left(\min_{y\in S_{i,j}}\mathrm{dis}_{i,j}(x,y)\right). Doremy writes down all values of f(i,j) such that 1 \leq j \leq i \leq n, then goes to sleep. However, after waking up, she finds that the tree has gone missing. Fortunately, the values of f(i,j) are still in her notebook, and she knows which i and j they belong to. Given the values of f(i,j), can you help her restore the tree?It is guaranteed that at least one suitable tree exists.InputThe first line of input contains a single integer n (2 \le n \le 2000) — the number of vertices in the tree.The following n lines contain a lower-triangular matrix with i integers on the i-th line; the j-th integer on the i-th line is f(i,j) (0 \le f(i,j) \le 2\cdot 10^{15}).It is guaranteed that there exists a tree whose weights are integers between 1 and 10^9 such that the values of f(i,j) of the tree match those given in the input.OutputPrint n-1 lines describing the tree. In the i-th line of the output, output three integers u_i, v_i, w_i (1 \le u_i,v_i \le n, 1 \le w_i \le 10^9), representing an edge (u_i,v_i) whose weight is w_i.If there are multiple answers, you may output any.All edges must form a tree and all values of f(i,j) must match those given in the input.ExamplesInput 3 7 3 5 0 2 8 Output 2 3 3 1 2 2 Input 9 8081910646 8081902766 8081903751 8081902555 8081903540 8081905228 3090681001 3090681986 3090681775 7083659398 7083657913 7083658898 7083658687 2092437133 15069617722 1748216295 1748217280 1748217069 5741194692 749972427 10439821163 2377558289 2377559274 2377559063 6370536686 1379314421 5028071980 8866466178 1746983932 1746984917 1746984706 5739962329 748740064 10438588800 5026839617 10448447704 2341942133 2341943118 2341942907 6334920530 1343698265 4992455824 8830850022 4991223461 9115779270 Output 1 2 985 2 3 211 2 4 998244353 2 5 998244853 4 6 671232353 6 8 1232363 4 7 356561356 7 9 35616156 NoteIn the first test case, the picture below, from left to right, from top to bottom, shows the graph when pairs (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) are connected with an edge, respectively. The nodes colored yellow are on the cycle.
3 7 3 5 0 2 8
2 3 3 1 2 2
2.5 seconds
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'dsu', 'sortings', 'trees', '*2500']
E. Doremy's Number Linetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoremy has two arrays a and b of n integers each, and an integer k.Initially, she has a number line where no integers are colored. She chooses a permutation p of [1,2,\ldots,n] then performs n moves. On the i-th move she does the following: Pick an uncolored integer x on the number line such that either: x \leq a_{p_i}; or there exists a colored integer y such that y \leq a_{p_i} and x \leq y+b_{p_i}. Color integer x with color p_i. Determine if the integer k can be colored with color 1.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 two integers n and k (1 \le n \le 10^5, 1 \le k \le 10^9).Each of the following n lines contains two integers a_i and b_i (1 \le a_i,b_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output "YES" (without quotes) if the point k can be colored with color 1. Otherwise, output "NO" (without quotes).You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).ExampleInput 64 165 38 1210 715 14 168 1210 715 15 34 1610 715 15 38 124 1615 15 38 1210 71 1000000000500000000 5000000002 10000000001 9999999991 1Output NO YES YES YES NO YES NoteFor the first test case, it is impossible to color point 16 with color 1.For the second test case, p=[2,1,3,4] is one possible choice, the detail is shown below. On the first move, pick x=8 and color it with color 2 since x=8 is uncolored and x \le a_2. On the second move, pick x=16 and color it with color 1 since there exists a colored point y=8 such that y\le a_1 and x \le y + b_1. On the third move, pick x=0 and color it with color 3 since x=0 is uncolored and x \le a_3. On the forth move, pick x=-2 and color it with color 4 since x=-2 is uncolored and x \le a_4. In the end, point -2,0,8,16 are colored with color 4,3,2,1, respectively. For the third test case, p=[2,1,4,3] is one possible choice.For the fourth test case, p=[2,3,4,1] is one possible choice.
64 165 38 1210 715 14 168 1210 715 15 34 1610 715 15 38 124 1615 15 38 1210 71 1000000000500000000 5000000002 10000000001 9999999991 1
NO YES YES YES NO YES
2 seconds
256 megabytes
['dp', 'greedy', 'sortings', '*2400']
D. Doremy's Pegging Gametime limit per test1.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDoremy has n+1 pegs. There are n red pegs arranged as vertices of a regular n-sided polygon, numbered from 1 to n in anti-clockwise order. There is also a blue peg of slightly smaller diameter in the middle of the polygon. A rubber band is stretched around the red pegs.Doremy is very bored today and has decided to play a game. Initially, she has an empty array a. While the rubber band does not touch the blue peg, she will: choose i (1 \leq i \leq n) such that the red peg i has not been removed; remove the red peg i; append i to the back of a. Doremy wonders how many possible different arrays a can be produced by the following process. Since the answer can be big, you are only required to output it modulo p. p is guaranteed to be a prime number. game with n=9 and a=[7,5,2,8,3,9,4] and another game with n=8 and a=[3,4,7,1,8,5,2] InputThe first line contains two integers n and p (3 \leq n \leq 5000, 10^8 \le p \le 10^9) — the number of red pegs and the modulo respectively.p is guaranteed to be a prime number.OutputOutput a single integer, the number of different arrays a that can be produced by the process described above modulo p.ExamplesInput 4 100000007 Output 16 Input 1145 141919831 Output 105242108 NoteIn the first test case, n=4, some possible arrays a that can be produced are [4,2,3] and [1,4]. However, it is not possible for a to be [1] or [1,4,3].
4 100000007
16
1.5 seconds
512 megabytes
['combinatorics', 'dp', 'math', '*2000']
C. Doremy's City Constructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoremy's new city is under construction! The city can be regarded as a simple undirected graph with n vertices. The i-th vertex has altitude a_i. Now Doremy is deciding which pairs of vertices should be connected with edges.Due to economic reasons, there should be no self-loops or multiple edges in the graph.Due to safety reasons, there should not be pairwise distinct vertices u, v, and w such that a_u \leq a_v \leq a_w and the edges (u,v) and (v,w) exist.Under these constraints, Doremy would like to know the maximum possible number of edges in the graph. Can you help her?Note that the constructed graph is allowed to be disconnected.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 of each test case contains a single integer n (2 \le n \le 2\cdot 10^5) — the number of vertices.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1\le a_i\le 10^6) — the altitudes of each vertex.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the maximum possible number of edges in the graph.ExampleInput 442 2 3 165 2 3 1 5 2127 2 4 9 1 4 6 3 7 4 2 341000000 1000000 1000000 1000000Output 3 9 35 2 NoteIn the first test case, there can only be at most 3 edges in the graph. A possible construction is to connect (1,3), (2,3), (3,4). In the picture below the red number above node i is a_i.The following list shows all such u, v, w that the edges (u,v) and (v,w) exist. u=1, v=3, w=2; u=1, v=3, w=4; u=2, v=3, w=1; u=2, v=3, w=4; u=4, v=3, w=1; u=4, v=3, w=2. Another possible construction is to connect (1,4), (2,4), (3,4).An unacceptable construction is to connect (1,3), (2,3), (2,4), (3,4). Because when u=4, v=2, w=3, a_u\le a_v \le a_w holds, and the respective edges exist.
442 2 3 165 2 3 1 5 2127 2 4 9 1 4 6 3 7 4 2 341000000 1000000 1000000 1000000
3 9 35 2
1 second
256 megabytes
['graphs', 'greedy', '*1400']
B. Doremy's Perfect Math Classtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output"Everybody! Doremy's Perfect Math Class is about to start! Come and do your best if you want to have as much IQ as me!" In today's math class, Doremy is teaching everyone subtraction. Now she gives you a quiz to prove that you are paying attention in class.You are given a set S containing positive integers. You may perform the following operation some (possibly zero) number of times: choose two integers x and y from the set S such that x > y and x - y is not in the set S. add x-y into the set S. You need to tell Doremy the maximum possible number of integers in S if the operations are performed optimally. It can be proven that this number is finite.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 an integer n (2 \le n\le 10^5) — the size of the set S.The second line contains n integers a_1,a_2,\dots,a_n (1\le a_1 < a_2 < \cdots < a_n \le 10^9) — the positive integers in S.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, you need to output the maximum possible number of integers in S. It can be proven that this value is finite.ExampleInput 221 235 10 25Output 2 5 NoteIn the first test case, no such x and y exist. The maximum possible number of integers in S is 2.In the second test case, S=\{5,10,25\} at first. You can choose x=25, y=10, then add x-y=15 to the set. S=\{5,10,15,25\} now. You can choose x=25, y=5, then add x-y=20 to the set. S=\{5,10,15,20,25\} now. You can not perform any operation now. After performing all operations, the number of integers in S is 5. It can be proven that no other sequence of operations allows S to contain more than 5 integers.
221 235 10 25
2 5
1 second
256 megabytes
['math', 'number theory', '*900']
A. Doremy's Painttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDoremy has n buckets of paint which is represented by an array a of length n. Bucket i contains paint with color a_i. Let c(l,r) be the number of distinct elements in the subarray [a_l,a_{l+1},\ldots,a_r]. Choose 2 integers l and r such that l \leq r and r-l-c(l,r) is maximized.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 of each test case contains a single integer n (1 \le n \le 10^5) — the length of the array a.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le n).It is guaranteed that the sum of n does not exceed 10^5.OutputFor each test case, output l and r such that l \leq r and r-l-c(l,r) is maximized.If there are multiple solutions, you may output any.ExampleInput 751 3 2 2 451 2 3 4 542 1 2 132 3 322 21199 8 5 2 1 1 2 3 3Output 2 4 1 5 1 4 2 3 1 2 1 1 3 9 NoteIn the first test case, a=[1,3,2,2,4]. When l=1 and r=3, c(l,r)=3 (there are 3 distinct elements in [1,3,2]). When l=2 and r=4, c(l,r)=2 (there are 2 distinct elements in [3,2,2]). It can be shown that choosing l=2 and r=4 maximizes the value of r-l-c(l,r) at 0.For the second test case, a=[1,2,3,4,5]. When l=1 and r=5, c(l,r)=5 (there are 5 distinct elements in [1,2,3,4,5]). When l=3 and r=3, c(l,r)=1 (there is 1 distinct element in [3]). It can be shown that choosing l=1 and r=5 maximizes the value of r-l-c(l,r) at -1. Choosing l=3 and r=3 is also acceptable.
751 3 2 2 451 2 3 4 542 1 2 132 3 322 21199 8 5 2 1 1 2 3 3
2 4 1 5 1 4 2 3 1 2 1 1 3 9
1 second
256 megabytes
['greedy', '*800']
F. Edge Queriestime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an undirected, connected graph of n nodes and m edges. All nodes u of the graph satisfy the following: Let S_u be the set of vertices in the longest simple cycle starting and ending at u. Let C_u be the union of the sets of vertices in any simple cycle starting and ending at u. S_u = C_u. You need to answer q queries.For each query, you will be given node a and node b. Out of all the edges that belong to any simple path from a to b, count the number of edges such that if you remove that edge, a and b are reachable from each other.InputThe first line contains two integers n and m (2 \le n \le 2 \cdot 10^5, 1 \le m \le \min(2 \cdot 10^5, (n \cdot (n-1))/2)) — the total number of nodes and edges in the graph, respectively.The next m lines contain two integers u and v (1 \le u, v \le n, u \neq v) — describing an edge, implying that nodes u and v are connected to each other.It is guaranteed that there is at most one edge between any pair of vertices in the graph and the given graph is connected.The next line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of queries.Then q lines follow, each representing a query. Each query contains two integers a and b (1 \le a, b \le n).OutputFor each query, output a single integer — answer to the query.ExamplesInput 10 11 1 2 2 3 3 4 4 5 5 3 2 7 7 9 9 10 10 6 6 7 1 8 5 1 4 5 10 3 5 2 8 7 10 Output 3 7 3 0 4 Input 13 15 1 2 2 3 3 4 4 1 2 4 3 5 5 6 6 7 6 8 7 9 9 10 8 7 10 11 10 12 10 13 6 9 11 1 5 1 8 5 2 5 12 12 13 Output 0 5 8 5 3 0 NoteThe graph in the first sample is : The first query is (1, 4). There are 5 total edges that belong to any simple path from 1 to 4. Edges (3, 4), (4, 5), (5, 3) will be counted in the answer to the query.The fourth query is (2, 8). There is only one simple path from 2 to 8, thus none of the edges will be counted in the answer to the query.The fifth query is (7, 10). There are 4 total edges that belong to any simple path from 7 to 10, all of them will be counted in the answer to the query.
10 11 1 2 2 3 3 4 4 5 5 3 2 7 7 9 9 10 10 6 6 7 1 8 5 1 4 5 10 3 5 2 8 7 10
3 7 3 0 4
3 seconds
256 megabytes
['data structures', 'dfs and similar', 'dp', 'dsu', 'graphs', 'trees', '*3000']
E. Node Pairstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call an ordered pair of nodes (u, v) in a directed graph unidirectional if u \neq v, there exists a path from u to v, and there are no paths from v to u.A directed graph is called p-reachable if it contains exactly p ordered pairs of nodes (u, v) such that u < v and u and v are reachable from each other. Find the minimum number of nodes required to create a p-reachable directed graph.Also, among all such p-reachable directed graphs with the minimum number of nodes, let G denote a graph which maximizes the number of unidirectional pairs of nodes. Find this number.InputThe first and only line contains a single integer p (0 \le p \le 2 \cdot 10^5) — the number of ordered pairs of nodes.OutputPrint a single line containing two integers — the minimum number of nodes required to create a p-reachable directed graph, and the maximum number of unidirectional pairs of nodes among all such p-reachable directed graphs with the minimum number of nodes.ExamplesInput 3 Output 3 0 Input 4 Output 5 6 Input 0 Output 0 0 NoteIn the first test case, the minimum number of nodes required to create a 3-reachable directed graph is 3. Among all 3-reachable directed graphs with 3 nodes, the following graph G is one of the graphs with the maximum number of unidirectional pairs of nodes, which is 0.
3
3 0
2 seconds
256 megabytes
['dp', 'graphs', 'math', 'number theory', '*2200']
D. Valid Bitonic Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given five integers n, i, j, x, and y. Find the number of bitonic permutations B, of the numbers 1 to n, such that B_i=x, and B_j=y. Since the answer can be large, compute it modulo 10^9+7.A bitonic permutation is a permutation of numbers, such that the elements of the permutation first increase till a certain index k, 2 \le k \le n-1, and then decrease till the end. Refer to notes for further clarification.InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The only line of each test case contains five integers, n, i, j, x, and y (3 \le n \le 100 and 1 \le i,j,x,y \le n). It is guaranteed that i < j and x \ne y.OutputFor each test case, output a single line containing the number of bitonic permutations satisfying the above conditions modulo 10^9+7.ExampleInput 73 1 3 2 33 2 3 3 24 3 4 3 15 2 5 2 45 3 4 5 49 3 7 8 620 6 15 8 17Output 0 1 1 1 3 0 4788 NoteA permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).An array of n \ge 3 elements is bitonic if its elements are first increasing till an index k, 2 \le k \le n-1, and then decreasing till the end. For example, [2,5,8,6,1] is a bitonic array with k=3, but [2,5,8,1,6] is not a bitonic array (elements first increase till k=3, then decrease, and then increase again).A bitonic permutation is a permutation in which the elements follow the above-mentioned bitonic property. For example, [2,3,5,4,1] is a bitonic permutation, but [2,3,5,1,4] is not a bitonic permutation (since it is not a bitonic array) and [2,3,4,4,1] is also not a bitonic permutation (since it is not a permutation).Sample Test Case DescriptionFor n=3, possible permutations are [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. Among the given permutations, the bitonic permutations are [1,3,2] and [2,3,1].In the first test case, the expected permutation must be of the form [2,?,3], which does not satisfy either of the two bitonic permutations with n=3, therefore the answer is 0.In the second test case, the expected permutation must be of the form [?,3,2], which only satisfies the bitonic permutation [1,3,2], therefore, the answer is 1.
73 1 3 2 33 2 3 3 24 3 4 3 15 2 5 2 45 3 4 5 49 3 7 8 620 6 15 8 17
0 1 1 1 3 0 4788
1 second
256 megabytes
['combinatorics', 'dp', 'implementation', 'math', 'number theory', '*2200']
C. Another Array Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of n integers. You are allowed to perform the following operation on it as many times as you want (0 or more times): Choose 2 indices i,j where 1 \le i < j \le n and replace a_k for all i \leq k \leq j with |a_i - a_j| Print the maximum sum of all the elements of the final array that you can obtain in such a way.InputThe first line contains a single integer t (1 \le t \le 10^5) — the number of test cases.The first line of each test case contains a single integer n (2 \le n \le 2 \cdot 10^5) — the 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^9) — the elements of array a.It's guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the sum of the final array.ExampleInput 331 1 129 134 9 5Output 3 16 18 NoteIn the first test case, it is not possible to achieve a sum > 3 by using these operations, therefore the maximum sum is 3.In the second test case, it can be shown that the maximum sum achievable is 16. By using operation (1,2) we transform the array from [9,1] into [8,8], thus the sum of the final array is 16. In the third test case, it can be shown that it is not possible to achieve a sum > 18 by using these operations, therefore the maximum sum is 18.
331 1 129 134 9 5
3 16 18
2 seconds
256 megabytes
['brute force', 'constructive algorithms', 'greedy', '*2000']
B. Incineratetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo destroy humanity, The Monster Association sent n monsters to Earth's surface. The i-th monster has health h_i and power p_i.With his last resort attack, True Spiral Incineration Cannon, Genos can deal k damage to all monsters alive. In other words, Genos can reduce the health of all monsters by k (if k > 0) with a single attack. However, after every attack Genos makes, the monsters advance. With their combined efforts, they reduce Genos' attack damage by the power of the ^\daggerweakest monster ^\ddaggeralive. In other words, the minimum p_i among all currently living monsters is subtracted from the value of k after each attack.^\daggerThe Weakest monster is the one with the least power.^\ddaggerA monster is alive if its health is strictly greater than 0.Will Genos be successful in killing all the monsters?InputThe first line of the input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of test cases follows.The first line of each test case contains two integers, n and k (1 \le n, k \le 10^5) — the number of monsters and Genos' initial attack damage. Then two lines follow, each containing n integers describing the arrays h and p (1 \le h_i, p_i \le 10^9).It's guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the answer — "YES" (without quotes) if Genos could kill all monsters and "NO" otherwise.ExampleInput 36 718 5 13 9 10 12 7 2 1 2 63 45 5 54 4 43 22 1 31 1 1Output YES NO YES NoteIn the first example, after Genos' first attack, h and k will update to: h: [11,0,6,2,3,0] k: 7-1 = 6 After second attack: h: [5,0,0,0,0,0] k: 6-2 = 4 After third attack: h: [1,0,0,0,0,0] k: 4-2 = 2 After fourth attack: h: [0,0,0,0,0,0] As Genos could kill all monsters, the answer is YES.
36 718 5 13 9 10 12 7 2 1 2 63 45 5 54 4 43 22 1 31 1 1
YES NO YES
1 second
256 megabytes
['binary search', 'brute force', 'data structures', 'implementation', 'math', 'sortings', '*1200']
A. Absolute Maximizationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n. You can perform the following operation several (possibly, zero) times: Choose i, j, b: Swap the b-th digit in the binary representation of a_i and a_j. Find the maximum possible value of \max(a) - \min(a).In a binary representation, bits are numbered from right (least significant) to left (most significant). Consider that there are an infinite number of leading zero bits at the beginning of any binary representation.For example, swap the 0-th bit for 4=100_2 and 3=11_2 will result 101_2=5 and 10_2=2. Swap the 2-nd bit for 4=100_2 and 3=11_2 will result 000_2=0_2=0 and 111_2=7. Here, \max(a) denotes the maximum element of array a and \min(a) denotes the minimum element of array a.The binary representation of x is x written in base 2. For example, 9 and 6 written in base 2 are 1001 and 110, respectively.InputThe first line contains a single integer t (1 \le t \le 128) — the number of testcases.The first line of each test case contains a single integer n (3 \le n \le 512) — the length of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 1024) — the elements of array a.It's guaranteed that the sum of n over all testcases does not exceed 512.OutputFor each testcase, print one integer — the maximum possible value of \max(a) - \min(a).ExampleInput 431 0 145 5 5 551 2 3 4 5720 85 100 41 76 49 36Output 1 0 7 125 NoteIn the first example, it can be shown that we do not need to perform any operations — the maximum value of \max(a) - \min(a) is 1 - 0 = 1.In the second example, no operation can change the array — the maximum value of \max(a) - \min(a) is 5 - 5 = 0.In the third example, initially a = [1, 2, 3, 4, 5], we can perform one operation taking i = 2, j = 5, b = 1. The array now becomes a = [1, 0, 3, 4, 7]. It can be shown that any further operations do not lead to a better answer — therefore the answer is \max(a) - \min(a) = 7 - 0 = 7.
431 0 145 5 5 551 2 3 4 5720 85 100 41 76 49 36
1 0 7 125
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'greedy', 'math', '*800']
G. Unequal Adjacent Elementstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n positive integers. Find any permutation p of [1,2,\dots,n] such that: p_{i-2} < p_i for all i, where 3 \leq i \leq n, and a_{p_{i-1}} \neq a_{p_i} for all i, where 2 \leq i \leq n. Or report that no such permutation exists.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 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 (3 \leq n \leq 3 \cdot 10^5) — the length of the array a.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq n) — representing the array a.It is guaranteed that the sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output "NO" if no such permutation exists, otherwise output "YES" in the first line and print the permutation p in the next line.In case there are multiple permutations, print any one of them.You can output "YES" and "NO" in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).ExampleInput 431 2 141 2 3 431 1 171 2 1 1 3 1 4Output YES 1 2 3 YES 3 1 4 2 NO YES 1 2 3 5 4 7 6 NoteIn the first test case, p=[1,2,3] is the only permutation of [1,2,3] that satisfy the given constraints.In the second test case, [1,3,2,4], [2,1,4,3] and some other permutations are also acceptable.In the third test case, it can be proved that there does not exist any permutation of [1,2,3] satisfying the given constraints.
431 2 141 2 3 431 1 171 2 1 1 3 1 4
YES 1 2 3 YES 3 1 4 2 NO YES 1 2 3 5 4 7 6
2 seconds
256 megabytes
['constructive algorithms', 'sortings', '*3100']
F. Good Pairs time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a consisting of n integers and an integer k.A pair (l,r) is good if there exists a sequence of indices i_1, i_2, \dots, i_m such that i_1=l and i_m=r; i_j < i_{j+1} for all 1 \leq j < m; and |a_{i_j}-a_{i_{j+1}}| \leq k for all 1 \leq j < m. Find the number of pairs (l,r) (1 \leq l \leq r \leq n) that are good.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^5) — the number of test cases. The description of the test cases follows.The first line of each test case contains two space-separated integers n and k (1 \leq n \leq 5 \cdot 10^5; 0 \leq k \leq 10^5) — the length of the array a and the integer k.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^5) — representing the array a.It is guaranteed that the sum of n over all test cases does not exceed 5 \cdot 10^5.OutputFor each test case, print the number of good pairs.ExampleInput 43 01 1 14 24 8 6 86 47 2 5 8 3 820 23110 57 98 14 20 1 60 82 108 37 82 73 8 46 38 35 106 115 58 112Output 6 9 18 92 NoteIn the first test case, good pairs are (1,1), (1,2), (1,3), (2,2), (2,3), and (3,3).In the second test case, good pairs are (1,1), (1,3), (1,4), (2,2), (2,3), (2,4), (3,3), (3,4) and (4,4). Pair (1,4) is good because there exists a sequence of indices 1, 3, 4 which satisfy the given conditions.
43 01 1 14 24 8 6 86 47 2 5 8 3 820 23110 57 98 14 20 1 60 82 108 37 82 73 8 46 38 35 106 115 58 112
6 9 18 92
3 seconds
256 megabytes
['binary search', 'data structures', 'dp', '*2600']
E. Tree Sumtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet us call an edge-weighted tree with n vertices numbered from 1 to n good if the weight of each edge is either 1 or -1 and for each vertex i, the product of the edge weights of all edges having i as one endpoint is -1.You are given a positive integer n. There are n^{n-2} \cdot 2^{n-1} distinct^\dagger edge-weighted trees with n vertices numbered from 1 to n such that each edge is either 1 or -1. Your task is to find the sum of d(1,n)^\ddagger of all such trees that are good. Since the answer can be quite large, you only need to find it modulo 998\,244\,353.^\dagger Two trees are considered to be distinct if either: there exists two vertices such that there is an edge between them in one of the trees, and not in the other. there exists two vertices such that there is an edge between them in both trees but the weight of the edge between them in one tree is different from the one in the other tree. Note that by Cayley's formula, the number of trees on n labeled vertices is n^{n-2}. Since we have n-1 edges, there are 2^{n-1} possible assignment of weights(weight can either be 1 or -1). That is why total number of distinct edge-weighted tree is n^{n-2} \cdot 2^{n-1}.^\ddagger d(u,v) denotes the sum of the weight of all edges on the unique simple path from u to v.InputThe first and only line of input contains a single integer n (1 \leq n \leq 5 \cdot 10^5).OutputThe only line of output should contain a single integer, the required answer, modulo 998\,244\,353.ExamplesInput 2 Output 998244352 Input 1 Output 0Input 4 Output 998244343 Input 10 Output 948359297 Input 43434 Output 86232114 NoteIn the first test case, there is only 1 distinct good tree. The value of d(1,2) for that tree is -1, which is 998\,244\,352 under modulo 998\,244\,353.In the second test case, the value of d(1,1) for any tree is 0, so the answer is 0.In the third test case, there are 16 distinct good trees. The value of d(1,4) is: -2 for 2 trees; -1 for 8 trees; 0 for 4 trees; 1 for 2 trees. The sum of d(1,4) over all trees is 2 \cdot (-2) + 8 \cdot (-1) + 4 \cdot (0) + 2 \cdot (1) = -10, which is 998\,244\,343 under modulo 998\,244\,353.
2
998244352
3 seconds
256 megabytes
['combinatorics', 'math', 'trees', '*2600']
D. GCD Queries time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.There is a secret permutation p of [0,1,2,\ldots,n-1]. Your task is to find 2 indices x and y (1 \leq x, y \leq n, possibly x=y) such that p_x=0 or p_y=0. In order to find it, you are allowed to ask at most 2n queries.In one query, you give two integers i and j (1 \leq i, j \leq n, i \neq j) and receive the value of \gcd(p_i,p_j)^\dagger.Note that the permutation p is fixed before any queries are made and does not depend on the queries.^\dagger \gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y. Note that \gcd(x,0)=\gcd(0,x)=x for all positive integers x.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \leq t \leq 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 2 \cdot 10^4).After reading the integer n for each test case, you should begin the interaction.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^4.InteractionThe interaction for each test case begins by reading the integer n.To make a query, output "? i j" (1 \leq i, j \leq n, i \neq j) without quotes. Afterwards, you should read a single integer — the answer to your query \gcd(p_i,p_j). You can make at most 2n such queries in each test case.If you want to print the answer, output "! x y" (1 \leq x, y \leq n) without quotes. After doing that, read 1 or -1. If p_x=0 or p_y=0, you'll receive 1, otherwise you'll receive -1. If you receive -1, 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.If you receive the integer -1 instead of an answer or a valid value of n, it means your program has made an invalid query, has exceeded the limit of queries, or has given an incorrect answer on the previous test case. Your program must terminate immediately to receive a Wrong Answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.After printing a query or the answer, do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. HacksTo hack, use the following format.The first line should contain a single integer t (1 \leq t \leq 10^4).The first line of each test case should contain a single integer n (2 \leq n \leq 2 \cdot 10^4).The second line of each test case should contain n space separated integers p_1,p_2,\ldots,p_n. p should be a permutation of [0,1,2,\ldots,n-1].The sum of n should not exceed 2 \cdot 10^4.ExampleInput 2 2 1 1 5 2 4 1 Output ? 1 2 ! 1 2 ? 1 2 ? 2 3 ! 3 3 NoteIn the first test, the interaction proceeds as follows. SolutionJuryExplanation\texttt{2}There are 2 test cases.\texttt{2}In the first test case, the hidden permutation is [1,0], with length 2.\texttt{? 1 2}\texttt{1}The solution requests \gcd(p_1,p_2), and the jury responds with 1.\texttt{! 1 2}\texttt{1}The solution knows that either p_1=0 or p_2=0, and prints the answer. Since the output is correct, the jury responds with 1 and continues to the next test case.\texttt{5}In the second test case, the hidden permutation is [2,4,0,1,3], with length 5.\texttt{? 1 2}\texttt{2}The solution requests \gcd(p_1,p_2), and the jury responds with 2.\texttt{? 2 3}\texttt{4}The solution requests \gcd(p_2,p_3), and the jury responds with 4.\texttt{! 3 3}\texttt{1}The solution has somehow determined that p_3=0, and prints the answer. Since the output is correct, the jury responds with 1. Note that the empty lines in the example input and output are for the sake of clarity, and do not occur in the real interaction.After each test case, make sure to read 1 or -1.
2 2 1 1 5 2 4 1
? 1 2 ! 1 2 ? 1 2 ? 2 3 ! 3 3
3 seconds
256 megabytes
['constructive algorithms', 'interactive', 'number theory', '*2100']
C. Binary Strings are Funtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string^\dagger b of odd length m is good if b_i is the median^\ddagger of b[1,i]^\S for all odd indices i (1 \leq i \leq m).For a binary string a of length k, a binary string b of length 2k-1 is an extension of a if b_{2i-1}=a_i for all i such that 1 \leq i \leq k. For example, 1001011 and 1101001 are extensions of the string 1001. String x=1011011 is not an extension of string y=1001 because x_3 \neq y_2. Note that there are 2^{k-1} different extensions of a.You are given a binary string s of length n. Find the sum of the number of good extensions over all prefixes of s. In other words, find \sum_{i=1}^{n} f(s[1,i]), where f(x) gives number of good extensions of string x. Since the answer can be quite large, you only need to find it modulo 998\,244\,353.^\dagger A binary string is a string whose elements are either \mathtt{0} or \mathtt{1}.^\ddagger For a binary string a of length 2m-1, the median of a is the (unique) element that occurs at least m times in a.^\S a[l,r] denotes the string of length r-l+1 which is formed by the concatenation of a_l,a_{l+1},\ldots,a_r in that order.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5), where n is the length of the binary string s.The second line of each test case contains the binary string s of length n.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print the answer modulo 998\,244\,353.ExampleInput 6111021130109101101111371011011111011010000011011111111011111Output 1 1 3 3 21 365 NoteIn the first and second test cases, f(s[1,1])=1.In the third test case, the answer is f(s[1,1])+f(s[1,2])=1+2=3. In the fourth test case, the answer is f(s[1,1])+f(s[1,2])+f(s[1,3])=1+1+1=3.f(\mathtt{11})=2 because two good extensions are possible: 101 and 111.f(\mathtt{01})=1 because only one good extension is possible: 011.
6111021130109101101111371011011111011010000011011111111011111
1 1 3 3 21 365
1 second
256 megabytes
['combinatorics', 'math', '*1400']
B. Make Array Goodtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array b of m positive integers is good if for all pairs i and j (1 \leq i,j \leq m), \max(b_i,b_j) is divisible by \min(b_i,b_j).You are given an array a of n positive integers. You can perform the following operation: Select an index i (1 \leq i \leq n) and an integer x (0 \leq x \leq a_i) and add x to a_i, in other words, a_i := a_i+x. After this operation, a_i \leq 10^{18} should be satisfied. You have to construct a sequence of at most n operations that will make a good. It can be proven that under the constraints of the problem, such a sequence of operations always exists.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 10^5) — the length of the array a.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^9) — representing the array a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test, output a single integer p (0 \leq p \leq n) — denoting the number of operations in your solution. In each of the following p lines, output two space-separated integers — i and x.You do not need to minimize the number of operations. It can be proven that a solution always exists.ExampleInput 442 3 5 524 853 4 343 5 6331 5 17Output 4 1 2 1 1 2 2 3 0 0 5 1 3 1 4 2 1 5 4 3 7 3 1 29 2 5 3 3 NoteIn the first test case, array a becomes [5,5,5,5] after the operations. It is easy to see that [5,5,5,5] is good.In the second test case, array a is already good.In the third test case, after performing the operations, array a becomes [10,5,350,5,10], which is good.In the fourth test case, after performing the operations, array a becomes [60,10,20], which is good.
442 3 5 524 853 4 343 5 6331 5 17
4 1 2 1 1 2 2 3 0 0 5 1 3 1 4 2 1 5 4 3 7 3 1 29 2 5 3 3
1 second
256 megabytes
['constructive algorithms', 'implementation', 'number theory', 'sortings', '*1100']
A. Divide and Conquertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array b is good if the sum of elements of b is even. You are given an array a consisting of n positive integers. In one operation, you can select an index i and change a_i := \lfloor \frac{a_i}{2} \rfloor. ^\daggerFind the minimum number of operations (possibly 0) needed to make a good. It can be proven that it is always possible to make a good.^\dagger \lfloor x \rfloor denotes the floor function — the largest integer less than or equal to x. For example, \lfloor 2.7 \rfloor = 2, \lfloor \pi \rfloor = 3 and \lfloor 5 \rfloor =5.InputEach test contains multiple test cases. The first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (1 \leq n \leq 50) — the length of the array a.The second line of each test case contains n space-separated integers a_1,a_2,\ldots,a_n (1 \leq a_i \leq 10^6) — representing the array a.Do note that the sum of n over all test cases is not bounded.OutputFor each test case, output the minimum number of operations needed to make a good.ExampleInput 441 1 1 127 431 2 4115Output 0 2 1 4 NoteIn the first test case, array a is already good.In the second test case, we can perform on index 2 twice. After the first operation, array a becomes [7,2]. After performing on index 2 again, a becomes [7,1], which is good. It can be proved that it is not possible to make a good in less number of operations.In the third test case, a becomes [0,2,4] if we perform the operation on index 1 once. As [0,2,4] is good, answer is 1.In the fourth test case, we need to perform the operation on index 1 four times. After all operations, a becomes [0]. It can be proved that it is not possible to make a good in less number of operations.
441 1 1 127 431 2 4115
0 2 1 4
1 second
256 megabytes
['greedy', 'math', 'number theory', '*800']
G. Centroid Guesstime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis in an interactive problem.There is an unknown tree consisting of n nodes, which has exactly one centroid. You only know n at first, and your task is to find the centroid of the tree.You can ask the distance between any two vertices for at most 2\cdot10^5 times. Note that the interactor is not adaptive. That is, the tree is fixed in each test beforehand and does not depend on your queries.A vertex is called a centroid if its removal splits the tree into subtrees with at most \lfloor\frac{n}{2}\rfloor vertices each.InputThe only line of the input contains an integer n (3\le n\le 7.5\cdot10^4) — the number of nodes in the tree.InteractionStart interaction by reading n.To ask a query about the distance between two nodes u, v (1 \le u, v \le n), output "? u v".If you determine that the centroid of the tree is x, use "! x" to report.After printing a query, do not forget to output the end of a line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. Hacks are disabled in this problem.It's guaranteed that there are at most 500 tests in this problem.ExampleInput 5 2 1 2 3 1 1 1 Output ? 1 2 ? 1 3 ? 1 4 ? 1 5 ? 2 3 ? 3 4 ? 4 5 ! 3 NoteHere is an image of the tree from the sample.
5 2 1 2 3 1 1 1
? 1 2 ? 1 3 ? 1 4 ? 1 5 ? 2 3 ? 3 4 ? 4 5 ! 3
4 seconds
512 megabytes
['interactive', 'probabilities', 'trees', '*3500']
F2. Anti-median (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 n. You can make hacks only if all versions of the problem are solved.Let's call an array a of odd length 2m+1 (with m \ge 1) bad, if element a_{m+1} is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at m+1-st position remains the same.Let's call a permutation p of integers from 1 to n anti-median, if every its subarray of odd length \ge 3 is not bad.You are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an anti-median permutation. As this number can be very large, find it modulo 10^9+7.InputThe first line contains a single integer t (1 \le t \le 10^4)  — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 10^6)  — the length of the permutation.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, or p_i = -1)  — the elements of the permutation. If p_i \neq -1, it's given, else it's unknown. It's guaranteed that if for some i \neq j holds p_i \neq -1, p_j \neq -1, then p_i \neq p_j.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, output a single integer  — the number of ways to set unknown values to obtain an anti-median permutation, modulo 10^9+7.ExampleInput 52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1Output 2 4 0 1 316 NoteIn the first test case, both [1, 2] and [2, 1] are anti-median.In the second test case, permutations [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] are anti-median. The remaining two permutations, [1, 2, 3], [3, 2, 1], are bad arrays on their own, as their median, 2, is in their middle.In the third test case, [1, 2, 3, 4] isn't anti-median, as it contains bad subarray [1, 2, 3].In the fourth test case, the only anti-median array you can get is [5, 6, 3, 4, 1, 2].
52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1
2 4 0 1 316
2 seconds
256 megabytes
['combinatorics', 'dp', 'math', '*3500']
F1. Anti-median (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. You can make hacks only if all versions of the problem are solved.Let's call an array a of odd length 2m+1 (with m \ge 1) bad, if element a_{m+1} is equal to the median of this array. In other words, the array is bad if, after sorting it, the element at m+1-st position remains the same.Let's call a permutation p of integers from 1 to n anti-median, if every its subarray of odd length \ge 3 is not bad.You are already given values of some elements of the permutation. Find the number of ways to set unknown values to obtain an anti-median permutation. As this number can be very large, find it modulo 10^9+7.InputThe first line contains a single integer t (1 \le t \le 10^4)  — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2 \le n \le 1000)  — the length of the permutation.The second line of each test case contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n, or p_i = -1)  — the elements of the permutation. If p_i \neq -1, it's given, else it's unknown. It's guaranteed that if for some i \neq j holds p_i \neq -1, p_j \neq -1, then p_i \neq p_j.It is guaranteed that the sum of n^2 over all test cases does not exceed 10^6.OutputFor each test case, output a single integer  — the number of ways to set unknown values to obtain an anti-median permutation, modulo 10^9+7.ExampleInput 52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1Output 2 4 0 1 316 NoteIn the first test case, both [1, 2] and [2, 1] are anti-median.In the second test case, permutations [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2] are anti-median. The remaining two permutations, [1, 2, 3], [3, 2, 1], are bad arrays on their own, as their median, 2, is in their middle.In the third test case, [1, 2, 3, 4] isn't anti-median, as it contains bad subarray [1, 2, 3].In the fourth test case, the only anti-median array you can get is [5, 6, 3, 4, 1, 2].
52-1 -13-1 -1 -141 2 3 46-1 -1 3 4 -1 -18-1 -1 -1 -1 -1 -1 -1 -1
2 4 0 1 316
2 seconds
256 megabytes
['dp', 'math', '*3100']
E. Make It Connectedtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a simple undirected graph consisting of n vertices. The graph doesn't contain self-loops, there is at most one edge between each pair of vertices. Your task is simple: make the graph connected.You can do the following operation any number of times (possibly zero): Choose a vertex u arbitrarily. For each vertex v satisfying v\ne u in the graph individually, if v is adjacent to u, remove the edge between u and v, otherwise add an edge between u and v. Find the minimum number of operations required to make the graph connected. Also, find any sequence of operations with the minimum length that makes the graph connected.InputEach test contains multiple test cases. The first line contains a single integer t (1\leq t\leq 800) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2\leq n\leq 4000) — the number of vertices in the graph.Then n lines follow. The i-th row contains a binary string s_i of length n, where s_{i,j} is '1' if there is an edge between vertex i and j initially, otherwise s_{i,j} is '0'.It is guaranteed that s_{i,i} is always '0' and s_{i,j}=s_{j,i} for 1\leq i,j\leq n.It is guaranteed that the sum of n over all test cases does not exceed 4000.OutputFor each test case, in the first line, output an integer m  — the minimum number of operations required.If m is greater than zero, then print an extra line consisting of m integers — the vertices chosen in the operations in your solution. If there are multiple solutions with the minimum number of operations, print any.ExampleInput 430111001003000001010401001000000100106001100000011100100101000010001010010Output 0 1 1 2 3 4 3 2 5 6 NoteIn the first test case, the graph is connected at the beginning, so the answer is 0.In the second test case, if we do the operation with vertex 1, we will get the following graph represented by an adjacency matrix: \begin{bmatrix} 0&1&1\\ 1&0&1\\ 1&1&0 \end{bmatrix} It's obvious that the graph above is connected.In the third test case, if we do the operation with vertex 3 and 4, we will get the following graph represented by an adjacency matrix: \begin{bmatrix} 0&1&1&1\\ 1&0&1&1\\ 1&1&0&1\\ 1&1&1&0 \end{bmatrix} It's obvious that the graph above is connected, and it can be proven that we can't perform less than 2 operations to make the graph connected.
430111001003000001010401001000000100106001100000011100100101000010001010010
0 1 1 2 3 4 3 2 5 6
1 second
512 megabytes
['binary search', 'brute force', 'constructive algorithms', 'dsu', 'graphs', 'greedy', 'matrices', 'trees', 'two pointers', '*2400']
D. Carry Bittime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet f(x,y) be the number of carries of x+y in binary (i. e. f(x,y)=g(x)+g(y)-g(x+y), where g(x) is the number of ones in the binary representation of x).Given two integers n and k, find the number of ordered pairs (a,b) such that 0 \leq a,b < 2^n, and f(a,b) equals k. Note that for a\ne b, (a,b) and (b,a) are considered as two different pairs. As this number may be large, output it modulo 10^9+7.InputThe only line of each test contains two integers n and k (0\leq k<n\leq 10^6).OutputOutput a single integer  — the answer modulo 10^9+7.ExamplesInput 3 1 Output 15 Input 3 0 Output 27 Input 998 244 Output 573035660 NoteHere are some examples for understanding carries: \begin{aligned} &\begin{array}{r} 1_{\ \ }1_{\ \ }1\\ +\ _{1}1_{\ \ }0_{\ \ }0\\ \hline \ 1_{\ \ }0_{\ \ }1_{\ \ }1 \end{array} &\begin{array}{r} \ 1_{\ \ }0_{\ \ }1\\ +\ _{\ \ }0_{\ \ }0_{1}1\\ \hline \ 0_{\ \ }1_{\ \ }1_{\ \ }0 \end{array} & &\begin{array}{r} \ 1_{\ \ }0_{\ \ }1\\ +\ _{1}0_{1}1_{1}1\\ \hline \ 1_{\ \ }0_{\ \ }0_{\ \ }0 \end{array} \end{aligned} So f(7,4)=1, f(5,1)=1 and f(5,3)=3.In the first test case, all the pairs meeting the constraints are (1,1),(1,5),(2,2),(2,3),(3,2),(4,4),(4,5),(4,6),(4,7),(5,1),(5,4),(5,6),(6,4),(6,5),(7,4).
3 1
15
1 second
256 megabytes
['combinatorics', 'math', '*2100']
C. Set Constructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary matrix b (all elements of the matrix are 0 or 1) of n rows and n columns.You need to construct a n sets A_1, A_2, \ldots, A_n, for which the following conditions are satisfied: Each set is nonempty and consists of distinct integers between 1 and n inclusive. All sets are distinct. For all pairs (i,j) satisfying 1\leq i, j\leq n, b_{i,j}=1 if and only if A_i\subsetneq A_j. In other words, b_{i, j} is 1 if A_i is a proper subset of A_j and 0 otherwise. Set X is a proper subset of set Y, if X is a nonempty subset of Y, and X \neq Y.It's guaranteed that for all test cases in this problem, such n sets exist. Note that it doesn't mean that such n sets exist for all possible inputs.If there are multiple solutions, you can output any of them.InputEach test contains multiple test cases. The first line contains a single integer t (1\le t\le 1000) — the number of test cases. The description of test cases follows.The first line contains a single integer n (1\le n\le 100).The following n lines contain a binary matrix b, the j-th character of i-th line denotes b_{i,j}.It is guaranteed that the sum of n over all test cases does not exceed 1000.It's guaranteed that for all test cases in this problem, such n sets exist. OutputFor each test case, output n lines.For the i-th line, first output s_i (1 \le s_i \le n)  — the size of the set A_i. Then, output s_i distinct integers from 1 to n  — the elements of the set A_i.If there are multiple solutions, you can output any of them.It's guaranteed that for all test cases in this problem, such n sets exist. ExampleInput 2 4 0001 1001 0001 0000 3 011 001 000 Output 3 1 2 3 2 1 3 2 2 4 4 1 2 3 4 1 1 2 1 2 3 1 2 3 NoteIn the first test case, we have A_1 = \{1, 2, 3\}, A_2 = \{1, 3\}, A_3 = \{2, 4\}, A_4 = \{1, 2, 3, 4\}. Sets A_1, A_2, A_3 are proper subsets of A_4, and also set A_2 is a proper subset of A_1. No other set is a proper subset of any other set.In the second test case, we have A_1 = \{1\}, A_2 = \{1, 2\}, A_3 = \{1, 2, 3\}. A_1 is a proper subset of A_2 and A_3, and A_2 is a proper subset of A_3.
2 4 0001 1001 0001 0000 3 011 001 000
3 1 2 3 2 1 3 2 2 4 4 1 2 3 4 1 1 2 1 2 3 1 2 3
1 second
256 megabytes
['constructive algorithms', 'dfs and similar', 'graphs', 'greedy', '*1400']
B. Elimination of a Ringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDefine a cyclic sequence of size n as an array s of length n, in which s_n is adjacent to s_1.Muxii has a ring represented by a cyclic sequence a of size n.However, the ring itself hates equal adjacent elements. So if two adjacent elements in the sequence are equal at any time, one of them will be erased immediately. The sequence doesn't contain equal adjacent elements initially.Muxii can perform the following operation until the sequence becomes empty: Choose an element in a and erase it. For example, if ring is [1, 2, 4, 2, 3, 2], and Muxii erases element 4, then ring would erase one of the elements equal to 2, and the ring will become [1, 2, 3, 2].Muxii wants to find the maximum number of operations he could perform.Note that in a ring of size 1, its only element isn't considered adjacent to itself (so it's not immediately erased).InputEach test contains multiple test cases. The first line contains a single integer t (1\leq t\leq 100) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1\leq n\leq 100) — the size of the cyclic sequence.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1\leq a_i\leq n) — the sequence itself.It's guaranteed that a_i\ne a_{i+1} for 1\leq i<n.It's guaranteed that a_n\ne a_1 when n>1.OutputFor each test case, output a single integer — the maximum number of operations Muxii can perform.ExampleInput 341 2 3 241 2 1 211Output 4 3 1 NoteIn the first test case, you can erase the second element first, then erase the remaining elements one by one in any order. In total, you can perform the operation 4 times. Note that if you erase the first element first, then the sequence will be turned into [2,3,2] and then immediately become [2,3].In the second test case, you can erase the first element first, then the sequence becomes [2,1]. Then you can erase all remaining elements one by one in any order.
341 2 3 241 2 1 211
4 3 1
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', '*1000']
A. Two Permutationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers n, a, and b. Determine if there exist two permutations p and q of length n, for which the following conditions hold: The length of the longest common prefix of p and q is a. The length of the longest common suffix of p and q is b. A permutation of length n is an array containing each integer from 1 to n exactly once. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array), and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).InputEach test contains multiple test cases. The first line contains a single integer t (1\leq t\leq 10^4) — the number of test cases. The description of test cases follows.The only line of each test case contains three integers n, a, and b (1\leq a,b\leq n\leq 100).OutputFor each test case, if such a pair of permutations exists, output "Yes"; otherwise, output "No". You can output each letter in any case (upper or lower).ExampleInput 41 1 12 1 23 1 14 1 1Output Yes No No Yes NoteIn the first test case, [1] and [1] form a valid pair.In the second test case and the third case, we can show that such a pair of permutations doesn't exist.In the fourth test case, [1,2,3,4] and [1,3,2,4] form a valid pair.
41 1 12 1 23 1 14 1 1
Yes No No Yes
1 second
256 megabytes
['brute force', 'constructive algorithms', '*800']
G. SlavicG's Favorite Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a weighted tree with n vertices. Recall that a tree is a connected graph without any cycles. A weighted tree is a tree in which each edge has a certain weight. The tree is undirected, it doesn't have a root.Since trees bore you, you decided to challenge yourself and play a game on the given tree.In a move, you can travel from a node to one of its neighbors (another node it has a direct edge with).You start with a variable x which is initially equal to 0. When you pass through edge i, x changes its value to x ~\mathsf{XOR}~ w_i (where w_i is the weight of the i-th edge). Your task is to go from vertex a to vertex b, but you are allowed to enter node b if and only if after traveling to it, the value of x will become 0. In other words, you can travel to node b only by using an edge i such that x ~\mathsf{XOR}~ w_i = 0. Once you enter node b the game ends and you win.Additionally, you can teleport at most once at any point in time to any vertex except vertex b. You can teleport from any vertex, even from a.Answer with "YES" if you can reach vertex b from a, and "NO" otherwise.Note that \mathsf{XOR} represents the bitwise XOR operation.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains three integers n, a, and b (2 \leq n \leq 10^5), (1 \leq a, b \leq n; a \ne b) — the number of vertices, and the starting and desired ending node respectively.Each of the next n-1 lines denotes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i  — the labels of vertices it connects (1 \leq u_i, v_i \leq n; u_i \ne v_i; 1 \leq w_i \leq 10^9) and the weight of the respective edge.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case output "YES" if you can reach vertex b, and "NO" otherwise.ExampleInput 35 1 41 3 12 3 24 3 33 5 12 1 21 2 26 2 31 2 12 3 13 4 14 5 35 6 5Output YES NO YES NoteFor the first test case, we can travel from node 1 to node 3, x changing from 0 to 1, then we travel from node 3 to node 2, x becoming equal to 3. Now, we can teleport to node 3 and travel from node 3 to node 4, reaching node b, since x became equal to 0 in the end, so we should answer "YES".For the second test case, we have no moves, since we can't teleport to node b and the only move we have is to travel to node 2 which is impossible since x wouldn't be equal to 0 when reaching it, so we should answer "NO".
35 1 41 3 12 3 24 3 33 5 12 1 21 2 26 2 31 2 12 3 13 4 14 5 35 6 5
YES NO YES
2 seconds
256 megabytes
['bitmasks', 'dfs and similar', 'graphs', '*1700']
F. Queststime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n quests. If you complete the i-th quest, you will gain a_i coins. You can only complete at most one quest per day. However, once you complete a quest, you cannot do the same quest again for k days. (For example, if k=2 and you do quest 1 on day 1, then you cannot do it on day 2 or 3, but you can do it again on day 4.)You are given two integers c and d. Find the maximum value of k such that you can gain at least c coins over d days. If no such k exists, output Impossible. If k can be arbitrarily large, output Infinity.InputThe input consists of 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 three integers n,c,d (2 \leq n \leq 2\cdot10^5; 1 \leq c \leq 10^{16}; 1 \leq d \leq 2\cdot10^5) — the number of quests, the number of coins you need, and the number of days.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \leq a_i \leq 10^9) — the rewards for the quests.The sum of n over all test cases does not exceed 2\cdot10^5, and the sum of d over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output one of the following. If no such k exists, output Impossible. If k can be arbitrarily large, output Infinity. Otherwise, output a single integer — the maximum value of k such that you can gain at least c coins over d days. Please note, the checker is case-sensitive, and you should output strings exactly as they are given.ExampleInput 62 5 41 22 20 10100 103 100 37 2 64 20 34 5 6 74 100000000000 20228217734 927368 26389746 6278969742 20 45 1Output 2 Infinity Impossible 1 12 0 NoteIn the first test case, one way to earn 5 coins over 4 days with k=2 is as follows: Day 1: do quest 2, and earn 2 coins. Day 2: do quest 1, and earn 1 coin. Day 3: do nothing. Day 4: do quest 2, and earn 2 coins. In total, we earned 2+1+2=5 coins.In the second test case, we can make over 20 coins on the first day itself by doing the first quest to earn 100 coins, so the value of k can be arbitrarily large, since we never need to do another quest.In the third test case, no matter what we do, we can't earn 100 coins over 3 days.
62 5 41 22 20 10100 103 100 37 2 64 20 34 5 6 74 100000000000 20228217734 927368 26389746 6278969742 20 45 1
2 Infinity Impossible 1 12 0
3 seconds
256 megabytes
['binary search', 'greedy', 'sortings', '*1500']
E. Binary Inversionstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary array^{\dagger} of length n. You are allowed to perform one operation on it at most once. In an operation, you can choose any element and flip it: turn a 0 into a 1 or vice-versa.What is the maximum number of inversions^{\ddagger} the array can have after performing at most one operation?^\dagger A binary array is an array that contains only zeroes and ones.^\ddagger The number of inversions in an array is the number of pairs of indices i,j such that i<j and a_i > a_j.InputThe input consists of 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 an integer n (1 \leq n \leq 2\cdot10^5) — the length of the array.The following line contains n space-separated positive integers a_1, a_2,..., a_n (0 \leq a_i \leq 1) — the elements of the array.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output a single integer  — the maximum number of inversions the array can have after performing at most one operation.ExampleInput 541 0 1 060 1 0 0 1 020 081 0 1 1 0 0 0 131 1 1Output 3 7 1 13 2 NoteFor the first test case, the inversions are initially formed by the pairs of indices (1, 2), (1, 4), (3, 4), being a total of 3, which already is the maximum possible.For the second test case, the inversions are initially formed by the pairs of indices (2, 3), (2, 4), (2, 6), (5, 6), being a total of four. But, by flipping the first element, the array becomes {1, 1, 0, 0, 1, 0}, which has the inversions formed by the pairs of indices (1, 3), (1, 4), (1, 6), (2, 3), (2, 4), (2, 6), (5, 6) which total to 7 inversions which is the maximum possible.
541 0 1 060 1 0 0 1 020 081 0 1 1 0 0 0 131 1 1
3 7 1 13 2
2 seconds
256 megabytes
['data structures', 'greedy', 'math', '*1100']
D. Challenging Valleystime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a[0 \dots n-1] of n integers. This array is called a "valley" if there exists exactly one subarray a[l \dots r] such that: 0 \le l \le r \le n-1, a_l = a_{l+1} = a_{l+2} = \dots = a_r, l = 0 or a_{l-1} > a_{l}, r = n-1 or a_r < a_{r+1}. Here are three examples: The first image shows the array [3, 2, 2, 1, 2, 2, 3], it is a valley because only subarray with indices l=r=3 satisfies the condition.The second image shows the array [1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6], it is a valley because only subarray with indices l=0, r=2 satisfies the codition.The third image shows the array [1, 2, 3, 4, 3, 2, 1], it is not a valley because two subarrays l=r=0 and l=r=6 that satisfy the condition.You are asked whether the given array is a valley or not.Note that we consider the array to be indexed from 0.InputThe first line contains a single integer t (1 \leq t \leq 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 2\cdot10^5) — the length of the array.The second line of each test case contains n integers a_i (1 \leq a_i \leq 10^9) — the elements of the array.It is guaranteed that the sum of n over all test cases is smaller than 2\cdot10^5.OutputFor each test case, output "YES" (without quotes) if the array is a valley, and "NO" (without quotes) otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 673 2 2 1 2 2 3111 1 1 2 3 3 4 5 6 6 671 2 3 4 3 2 179 7 4 6 9 9 101100000000089 4 4 5 9 4 9 10Output YES YES NO YES YES NO NoteThe first three test cases are explained in the statement.
673 2 2 1 2 2 3111 1 1 2 3 3 4 5 6 6 671 2 3 4 3 2 179 7 4 6 9 9 101100000000089 4 4 5 9 4 9 10
YES YES NO YES YES NO
2 seconds
256 megabytes
['implementation', 'two pointers', '*1000']
C. Advantagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n participants in a competition, participant i having a strength of s_i. Every participant wonders how much of an advantage they have over the other best participant. In other words, each participant i wants to know the difference between s_i and s_j, where j is the strongest participant in the competition, not counting i (a difference can be negative).So, they ask you for your help! For each i (1 \leq i \leq n) output the difference between s_i and the maximum strength of any participant other than participant i.InputThe input consists of multiple test cases. The first line contains an integer t (1 \leq t \leq 1000) — the number of test cases. The descriptions of the test cases follow.The first line of each test case contains an integer n (2 \leq n \leq 2\cdot10^5) — the length of the array.The following line contains n space-separated positive integers s_1, s_2, ..., s_n (1 \leq s_i \leq 10^9) — the strengths of the participants.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot10^5.OutputFor each test case, output n space-separated integers. For each i (1 \leq i \leq n) output the difference between s_i and the maximum strength of any other participant.ExampleInput 544 7 3 521 251 2 3 4 534 9 444 4 4 4Output -3 2 -4 -2 -1 1 -4 -3 -2 -1 1 -5 5 -5 0 0 0 0 NoteFor the first test case: The first participant has a strength of 4 and the largest strength of a participant different from the first one is 7, so the answer for the first participant is 4 - 7 = -3. The second participant has a strength of 7 and the largest strength of a participant different from the second one is 5, so the answer for the second participant is 7 - 5 = 2. The third participant has a strength of 3 and the largest strength of a participant different from the third one is 7, so the answer for the third participant is 3 - 7 = -4. The fourth participant has a strength of 5 and the largest strength of a participant different from the fourth one is 7, so the answer for the fourth participant is 5 - 7 = -2.
544 7 3 521 251 2 3 4 534 9 444 4 4 4
-3 2 -4 -2 -1 1 -4 -3 -2 -1 1 -5 5 -5 0 0 0 0
2 seconds
256 megabytes
['data structures', 'implementation', 'sortings', '*800']
B. Atilla's Favorite Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn order to write a string, Atilla needs to first learn all letters that are contained in the string.Atilla needs to write a message which can be represented as a string s. He asks you what is the minimum alphabet size required so that one can write this message.The alphabet of size x (1 \leq x \leq 26) contains only the first x Latin letters. For example an alphabet of size 4 contains only the characters \texttt{a}, \texttt{b}, \texttt{c} and \texttt{d}.InputThe first line contains a single integer t (1 \leq t \leq 1000) — the number of test cases.The first line of each test case contains a single integer n (1 \leq n \leq 100) — the length of the string.The second line of each test case contains a string s of length n, consisting of lowercase Latin letters.OutputFor each test case, output a single integer — the minimum alphabet size required to so that Atilla can write his message s.ExampleInput 51a4down10codeforces3bcf5zzzzzOutput 1 23 19 6 26 NoteFor the first test case, Atilla needs to know only the character \texttt{a}, so the alphabet of size 1 which only contains \texttt{a} is enough.For the second test case, Atilla needs to know the characters \texttt{d}, \texttt{o}, \texttt{w}, \texttt{n}. The smallest alphabet size that contains all of them is 23 (such alphabet can be represented as the string \texttt{abcdefghijklmnopqrstuvw}).
51a4down10codeforces3bcf5zzzzz
1 23 19 6 26
1 second
256 megabytes
['greedy', 'implementation', 'strings', '*800']
A. Medium Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven three distinct integers a, b, and c, find the medium number between all of them.The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of 5,2,6 is 5, since the minimum is 2 and the maximum is 6.InputThe first line contains a single integer t (1 \leq t \leq 6840) — the number of test cases.The description of each test case consists of three distinct integers a, b, c (1 \leq a, b, c \leq 20).OutputFor each test case, output a single integer — the medium number of the three numbers.ExampleInput 95 2 614 3 420 2 11 2 311 19 1210 8 206 20 34 1 319 8 4Output 5 4 2 2 12 10 6 3 8
95 2 614 3 420 2 11 2 311 19 1210 8 206 20 34 1 319 8 4
5 4 2 2 12 10 6 3 8
1 second
256 megabytes
['implementation', 'sortings', '*800']
G. Restore the Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of n numbers is called permutation if it contains all numbers from 1 to n exactly once. For example, the sequences [3, 1, 4, 2], [1] and [2,1] are permutations, but [1,2,1], [0,1] and [1,3,4] — are not.For a permutation p of even length n you can make an array b of length \frac{n}{2} such that: b_i = \max(p_{2i - 1}, p_{2i}) for 1 \le i \le \frac{n}{2} For example, if p = [2, 4, 3, 1, 5, 6], then: b_1 = \max(p_1, p_2) = \max(2, 4) = 4 b_2 = \max(p_3, p_4) = \max(3,1)=3 b_3 = \max(p_5, p_6) = \max(5,6) = 6 As a result, we made b = [4, 3, 6].For a given array b, find the lexicographically minimal permutation p such that you can make the given array b from it.If b = [4,3,6], then the lexicographically minimal permutation from which it can be made is p = [1,4,2,3,5,6], since: b_1 = \max(p_1, p_2) = \max(1, 4) = 4 b_2 = \max(p_3, p_4) = \max(2, 3) = 3 b_3 = \max(p_5, p_6) = \max(5, 6) = 6 A permutation x_1, x_2, \dots, x_n is lexicographically smaller than a permutation y_1, y_2 \dots, y_n if and only if there exists such i (1 \le i \le n) that x_1=y_1, x_2=y_2, \dots, x_{i-1}=y_{i-1} and x_i<y_i.InputThe first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases.The description of the test cases follows.The first line of each test case contains one even integer n (2 \le n \le 2 \cdot 10^5).The second line of each test case contains exactly \frac{n}{2} integers b_i (1 \le b_i \le n) — elements of array b.It is guaranteed that the sum of n values over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print on a separate line: lexicographically minimal permutation p such that you can make an array b from it; or a number -1 if the permutation you are looking for does not exist. ExampleInput 664 3 642 488 7 2 366 4 244 488 7 4 5Output 1 4 2 3 5 6 1 2 3 4 -1 5 6 3 4 1 2 -1 1 8 6 7 2 4 3 5 NoteThe first test case is parsed in the problem statement.
664 3 642 488 7 2 366 4 244 488 7 4 5
1 4 2 3 5 6 1 2 3 4 -1 5 6 3 4 1 2 -1 1 8 6 7 2 4 3 5
1 second
256 megabytes
['binary search', 'constructive algorithms', 'data structures', 'greedy', 'math', '*1900']
F. All Possible Digitstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA positive number x of length n in base p (2 \le p \le 10^9) is written on the blackboard. The number x is given as a sequence a_1, a_2, \dots, a_n (0 \le a_i < p) — the digits of x in order from left to right (most significant to least significant).Dmitry is very fond of all the digits of this number system, so he wants to see each of them at least once.In one operation, he can: take any number x written on the board, increase it by 1, and write the new value x + 1 on the board. For example, p=5 and x=234_5. Initially, the board contains the digits 2, 3 and 4; Dmitry increases the number 234_5 by 1 and writes down the number 240_5. On the board there are digits 0, 2, 3, 4; Dmitry increases the number 240_5 by 1 and writes down the number 241_5. Now the board contains all the digits from 0 to 4. Your task is to determine the minimum number of operations required to make all the digits from 0 to p-1 appear on the board at least once.InputThe first line of the input contains a single integer t (1 \le t \le 2 \cdot 10^3) — the number of test cases. The descriptions of the input test cases follow.The first line of description of each test case contains two integers n (1 \le n \le 100) and p (2 \le p \le 10^9) — the length of the number and the base of the number system.The second line of the description of each test case contains n integers a_1, a_2, \dots, a_n (0 \le a_i < p) — digits of x in number system with base pIt is guaranteed that the number x does not contain leading zeros (that is, a_1>0).OutputFor each test case print a single integer — the minimum number of operations required for Dmitry to get all the digits on the board from 0 to p-1.It can be shown that this always requires a finite number of operations.ExampleInput 112 31 24 21 1 1 16 61 2 3 4 5 05 21 0 1 0 13 101 2 35 10004 1 3 2 53 52 3 44 43 2 3 01 325 51 2 2 2 43 41 0 1Output 1 1 0 0 7 995 2 1 1 1 2
112 31 24 21 1 1 16 61 2 3 4 5 05 21 0 1 0 13 101 2 35 10004 1 3 2 53 52 3 44 43 2 3 01 325 51 2 2 2 43 41 0 1
1 1 0 0 7 995 2 1 1 1 2
3 seconds
256 megabytes
['binary search', 'data structures', 'greedy', 'math', 'number theory', '*1800']
E. The Humanoidtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n astronauts working on some space station. An astronaut with the number i (1 \le i \le n) has power a_i.An evil humanoid has made his way to this space station. The power of this humanoid is equal to h. Also, the humanoid took with him two green serums and one blue serum.In one second , a humanoid can do any of three actions: to absorb an astronaut with power strictly less humanoid power; to use green serum, if there is still one left; to use blue serum, if there is still one left. When an astronaut with power a_i is absorbed, this astronaut disappears, and power of the humanoid increases by \lfloor \frac{a_i}{2} \rfloor, that is, an integer part of \frac{a_i}{2}. For example, if a humanoid absorbs an astronaut with power 4, its power increases by 2, and if a humanoid absorbs an astronaut with power 7, its power increases by 3.After using the green serum, this serum disappears, and the power of the humanoid doubles, so it increases by 2 times.After using the blue serum, this serum disappears, and the power of the humanoid triples, so it increases by 3 times.The humanoid is wondering what the maximum number of astronauts he will be able to absorb if he acts optimally.InputThe first line of each test contains an integer t (1 \le t \le 10^4) — number of test cases.The first line of each test case contains integers n (1 \le n \le 2 \cdot 10^5) — number of astronauts and h (1 \le h \le 10^6) — the initial power of the humanoid.The second line of each test case contains n integers a_i (1 \le a_i \le 10^8) — powers of astronauts.It is guaranteed that the sum of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, in a separate line, print the maximum number of astronauts that a humanoid can absorb.ExampleInput 84 12 1 8 93 36 2 604 55 1 100 53 238 6 31 1124 612 12 36 1004 12 1 1 153 515 1 13Output 4 3 3 3 0 4 4 3 NoteIn the first case, you can proceed as follows: use green serum. h = 1 \cdot 2 = 2 absorb the cosmonaut 2. h = 2 + \lfloor \frac{1}{2} \rfloor = 2 use green serum. h = 2 \cdot 2 = 4 absorb the spaceman 1. h = 4 + \lfloor \frac{2}{2} \rfloor = 5 use blue serum. h = 5 \cdot 3 = 15 absorb the spaceman 3. h = 15 + \lfloor \frac{8}{2} \rfloor = 19 absorb the cosmonaut 4. h = 19 + \lfloor \frac{9}{2} \rfloor = 23
84 12 1 8 93 36 2 604 55 1 100 53 238 6 31 1124 612 12 36 1004 12 1 1 153 515 1 13
4 3 3 3 0 4 4 3
2 seconds
256 megabytes
['brute force', 'dp', 'sortings', '*1500']
D. Make It Roundtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputInflation has occurred in Berlandia, so the store needs to change the price of goods.The current price of good n is given. It is allowed to increase the price of the good by k times, with 1 \le k \le m, k is an integer. Output the roundest possible new price of the good. That is, the one that has the maximum number of zeros at the end.For example, the number 481000 is more round than the number 1000010 (three zeros at the end of 481000 and only one at the end of 1000010).If there are several possible variants, output the one in which the new price is maximal.If it is impossible to get a rounder price, output n \cdot m (that is, the maximum possible price).InputThe first line contains a single integer t (1 \le t \le 10^4) —the number of test cases in the test.Each test case consists of one line.This line contains two integers: n and m (1 \le n, m \le 10^9). Where n is the old price of the good, and the number m means that you can increase the price n no more than m times.OutputFor each test case, output on a separate line the roundest integer of the form n \cdot k (1 \le k \le m, k — an integer).If there are several possible variants, output the one in which the new price (value n \cdot k) is maximal.If it is impossible to get a more rounded price, output n \cdot m (that is, the maximum possible price).ExampleInput 106 115 4313 54 1610050 123452 64 3025 102 811 7Output 60 200 65 60 120600000 10 100 200 100 7 NoteIn the first case n = 6, m = 11. We cannot get a number with two zeros or more at the end, because we need to increase the price 50 times, but 50 > m = 11. The maximum price multiple of 10 would be 6 \cdot 10 = 60.In the second case n = 5, m = 43. The maximum price multiple of 100 would be 5 \cdot 40 = 200.In the third case, n = 13, m = 5. All possible new prices will not end in 0, then you should output n \cdot m = 65.In the fourth case, you should increase the price 15 times.In the fifth case, increase the price 12000 times.
106 115 4313 54 1610050 123452 64 3025 102 811 7
60 200 65 60 120600000 10 100 200 100 7
1 second
256 megabytes
['brute force', 'number theory', '*1400']
C. Thermostattime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVlad came home and found out that someone had reconfigured the old thermostat to the temperature of a.The thermostat can only be set to a temperature from l to r inclusive, the temperature cannot change by less than x. Formally, in one operation you can reconfigure the thermostat from temperature a to temperature b if |a - b| \ge x and l \le b \le r.You are given l, r, x, a and b. Find the minimum number of operations required to get temperature b from temperature a, or say that it is impossible.InputThe first line of input data contains the single integer t (1 \le t \le 10^4) — the number of test cases in the test.The descriptions of the test cases follow.The first line of each case contains three integers l, r and x (-10^9 \le l \le r \le 10^9, 1 \le x \le 10^9) — range of temperature and minimum temperature change.The second line of each case contains two integers a and b (l \le a, b \le r) — the initial and final temperatures.OutputOutput t numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature b, output -1, otherwise output the minimum number of operations.ExampleInput 103 5 63 30 15 54 50 10 53 73 5 63 4-10 10 11-5 6-3 3 41 0-5 10 89 21 5 12 5-1 4 30 2-6 3 6-1 -4Output 0 2 3 -1 1 -1 3 1 3 -1 NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: 4 \rightarrow 10 \rightarrow 5.In the third example, you can achieve the desired temperature as follows: 3 \rightarrow 8 \rightarrow 2 \rightarrow 7.In the fourth test, it is impossible to make any operation.
103 5 63 30 15 54 50 10 53 73 5 63 4-10 10 11-5 6-3 3 41 0-5 10 89 21 5 12 5-1 4 30 2-6 3 6-1 -4
0 2 3 -1 1 -1 3 1 3 -1
1 second
256 megabytes
['greedy', 'math', 'shortest paths', '*1100']
B. Lost Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputA sequence of n numbers is called a permutation if it contains all integers from 1 to n exactly once. For example, the sequences [3, 1, 4, 2], [1] and [2,1] are permutations, but [1,2,1], [0,1] and [1,3,4] — are not.Polycarp lost his favorite permutation and found only some of its elements — the numbers b_1, b_2, \dots b_m. He is sure that the sum of the lost elements equals s.Determine whether one or more numbers can be appended to the given sequence b_1, b_2, \dots b_m such that the sum of the added numbers equals s, and the resulting new array is a permutation?InputThe first line of input contains a single integer t (1 \le t \le 100) —the number of test cases. Then the descriptions of the test cases follow.The first line of each test set contains two integers m and s (1 \le m \le 50, 1 \le s \le 1000)—-the number of found elements and the sum of forgotten numbers.The second line of each test set contains m different integers b_1, b_2 \dots b_m (1 \le b_i \le 50) — the elements Polycarp managed to find.OutputPrint t lines, each of which is the answer to the corresponding test set. Print as the answer YES if you can append several elements to the array b, that their sum equals s and the result will be a permutation. Output NO otherwise.You can output the answer in any case (for example, yEs, yes, Yes and YES will be recognized as positive answer).ExampleInput 53 133 1 41 113 31 4 22 14 35 61 2 3 4 5Output YES NO YES NO YES NoteIn the test case of the example, m=3, s=13, b=[3,1,4]. You can append to b the numbers 6,2,5, the sum of which is 6+2+5=13. Note that the final array will become [3,1,4,6,2,5], which is a permutation.In the second test case of the example, m=1, s=1, b=[1]. You cannot append one or more numbers to [1] such that their sum equals 1 and the result is a permutation.In the third test case of the example, m=3, s=3, b=[1,4,2]. You can append the number 3 to b. Note that the resulting array will be [1,4,2,3], which is a permutation.
53 133 1 41 113 31 4 22 14 35 61 2 3 4 5
YES NO YES NO YES
1 second
256 megabytes
['math', '*800']
A. Yes-Yes?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string s is a substring of YesYesYes... (Yes repeated many times in a row).InputThe first line of input data contains the singular t (1 \le t \le 1000) — the number of test cases in the test.Each test case is described by a single string of Latin letters s (1 \le |s| \le 50) — the part of Polycarp's answer that you heard, where |s| — is the length of the string s.OutputOutput t lines, each of which is the answer to the corresponding test case. As an answer, output "YES" if the specified string s is a substring of the string YesYesYes...Yes (the number of words Yes is arbitrary), and "NO" otherwise.You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).ExampleInput 12YESesYescodeforcesesseYesYesYesYesYesYesYesYeseYYesssYoYesOutput NO YES NO YES NO YES YES NO NO YES NO YES
12YESesYescodeforcesesseYesYesYesYesYesYesYesYeseYYesssYoYes
NO YES NO YES NO YES YES NO NO YES NO YES
1 second
256 megabytes
['implementation', 'strings', '*800']
F. Decent Divisiontime limit per test5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA binary string is a string where every character is \texttt{0} or \texttt{1}. Call a binary string decent if it has an equal number of \texttt{0}s and \texttt{1}s.Initially, you have an infinite binary string t whose characters are all \texttt{0}s. You are given a sequence a of n updates, where a_i indicates that the character at index a_i will be flipped (\texttt{0} \leftrightarrow \texttt{1}). You need to keep and modify after each update a set S of disjoint ranges such that: for each range [l,r], the substring t_l \dots t_r is a decent binary string, and for all indices i such that t_i = \texttt{1}, there exists [l,r] in S such that l \leq i \leq r. You only need to output the ranges that are added to or removed from S after each update. You can only add or remove ranges from S at most \mathbf{10^6} times.More formally, let S_i be the set of ranges after the i-th update, where S_0 = \varnothing (the empty set). Define X_i to be the set of ranges removed after update i, and Y_i to be the set of ranges added after update i. Then for 1 \leq i \leq n, S_i = (S_{i - 1} \setminus X_i) \cup Y_i. The following should hold for all 1 \leq i \leq n: \forall a,b \in S_i, (a \neq b) \rightarrow (a \cap b = \varnothing); X_i \subseteq S_{i - 1}; (S_{i-1} \setminus X_i) \cap Y_i = \varnothing; \displaystyle\sum_{i = 1}^n {(|X_i| + |Y_i|)} \leq 10^6. InputThe first line contains a single integer n (1 \leq n \leq 2 \cdot 10^5) — the number of updates.The next n lines each contain a single integer a_i (1 \leq a_i \leq 2 \cdot 10^5) — the index of the i-th update to the string.OutputAfter the i-th update, first output a single integer x_i — the number of ranges to be removed from S after update i.In the following x_i lines, output two integers l and r (1 \leq l < r \leq 10^6), which denotes that the range [l,r] should be removed from S. Each of these ranges should be distinct and be part of S.In the next line, output a single integer y_i — the number of ranges to be added to S after update i.In the following y_i lines, output two integers l and r (1 \leq l < r \leq 10^6), which denotes that the range [l,r] should be added to S. Each of these ranges should be distinct and not be part of S.The total number of removals and additions across all updates must not exceed \mathbf{10^6}.After processing the removals and additions for each update, all the ranges in S should be disjoint and cover all ones.It can be proven that an answer always exists under these constraints.ExampleInput 5 1 6 5 5 6 Output 0 1 1 2 0 1 5 6 1 5 6 2 6 7 4 5 1 4 5 0 1 6 7 0NoteLine breaks are provided in the sample only for the sake of clarity, and you don't need to print them in your output.After the first update, the set of indices where a_i = 1 is \{1\}. The interval [1, 2] is added, so S_1 = \{[1, 2]\}, which has one \texttt{0} and one \texttt{1}.After the second update, the set of indices where a_i = 1 is \{1, 6\}. The interval [5, 6] is added, so S_2 = \{[1, 2], [5, 6]\}, each of which has one \texttt{0} and one \texttt{1}.After the third update, the set of indices where a_i = 1 is \{1, 5, 6\}. The interval [5, 6] is removed and the intervals [4, 5] and [6, 7] are added, so S_3 = \{[1, 2], [4, 5], [6, 7]\}, each of which has one \texttt{0} and one \texttt{1}.After the fourth update, the set of indices where a_i = 1 is \{1, 6\}. The interval [4, 5] is removed, so S_4 = \{[1, 2], [6, 7]\}, each of which has one \texttt{0} and one \texttt{1}.After the fifth update, the set of indices where a_i = 1 is \{1\}. The interval [6, 7] is removed, so S_5 = \{[1, 2]\}, which has one \texttt{0} and one \texttt{1}.
5 1 6 5 5 6
0 1 1 2 0 1 5 6 1 5 6 2 6 7 4 5 1 4 5 0 1 6 7 0
5 seconds
256 megabytes
['constructive algorithms', 'data structures', '*3000']
E. Tick, Tocktime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTannhaus, the clockmaker in the town of Winden, makes mysterious clocks that measure time in h hours numbered from 0 to h-1. One day, he decided to make a puzzle with these clocks. The puzzle consists of an n \times m grid of clocks, and each clock always displays some hour exactly (that is, it doesn't lie between two hours). In one move, he can choose any row or column and shift all clocks in that row or column one hour forward^\dagger.The grid of clocks is called solvable if it is possible to make all the clocks display the same time.While building his puzzle, Tannhaus suddenly got worried that it might not be possible to make the grid solvable. Some cells of the grid have clocks already displaying a certain initial time, while the rest of the cells are empty.Given the partially completed grid of clocks, find the number of ways^\ddagger to assign clocks in the empty cells so that the grid is solvable. The answer can be enormous, so compute it modulo 10^9 + 7.^\dagger If a clock currently displays hour t and is shifted one hour forward, then the clock will instead display hour (t+1) \bmod h.^\ddagger Two assignments are different if there exists some cell with a clock that displays a different time in both arrangements.InputThe first line of input contains t (1 \leq t \leq 5 \cdot 10^4) — the number of test cases.The first line of each test case consists of 3 integers n, m, and h (1 \leq n, m \leq 2 \cdot 10^5; 1 \leq h \leq 10^9) — the number of rows in the grid, the number of columns in the grid, and the number of the hours in the day respectively.The next n lines each contain m integers, describing the clock grid. The integer x (-1 \leq x < h) in the i-th row and the j-th column represents the initial hour of the corresponding clock, or if x = -1, an empty cell.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output the number of ways to assign clocks in the empty cells so that the grid is solvable. The answer can be huge, so output it modulo 10^9 + 7.ExampleInput 52 3 41 0 -1-1 -1 22 2 101 23 54 5 10241 -1 -1 -1 -1-1 -1 -1 1000 -1-1 -1 -1 -1 69420 -1 -1 999 -13 3 3-1 -1 12 -1 12 -1 23 3 31 -1 2-1 0 -1-1 1 0Output 4 0 73741817 0 1 NoteFor the first sample, this is a possible configuration for the clocks: 103032This is solvable since we can: Move the middle column forward one hour. Move the third column forward one hour. Move the third column forward one hour. Move the second row forward one hour. After that all the clocks show one hour.For the second test case, it can be shown that there are no possible solvable clock configurations.
52 3 41 0 -1-1 -1 22 2 101 23 54 5 10241 -1 -1 -1 -1-1 -1 -1 1000 -1-1 -1 -1 -1 69420 -1 -1 999 -13 3 3-1 -1 12 -1 12 -1 23 3 31 -1 2-1 0 -1-1 1 0
4 0 73741817 0 1
1 second
256 megabytes
['combinatorics', 'dfs and similar', 'dsu', 'graphs', '*2500']
D. Range = √Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer n. Find a sequence of n distinct integers a_1, a_2, \dots, a_n such that 1 \leq a_i \leq 10^9 for all i and \max(a_1, a_2, \dots, a_n) - \min(a_1, a_2, \dots, a_n)= \sqrt{a_1 + a_2 + \dots + a_n}.It can be proven that there exists a sequence of distinct integers that satisfies all the conditions above.InputThe first line of input contains t (1 \leq t \leq 10^4) — the number of test cases.The first and only line of each test case contains one integer n (2 \leq n \leq 3 \cdot 10^5) — the length of the sequence you have to find.The sum of n over all test cases does not exceed 3 \cdot 10^5.OutputFor each test case, output n space-separated distinct integers a_1, a_2, \dots, a_n satisfying the conditions in the statement. If there are several possible answers, you can output any of them. Please remember that your integers must be distinct!ExampleInput 3254Output 3 1 20 29 18 26 28 25 21 23 31 NoteIn the first test case, the maximum is 3, the minimum is 1, the sum is 4, and 3 - 1 = \sqrt{4}.In the second test case, the maximum is 29, the minimum is 18, the sum is 121, and 29-18 = \sqrt{121}.For each test case, the integers are all distinct.
3254
3 1 20 29 18 26 28 25 21 23 31
1 second
256 megabytes
['binary search', 'brute force', 'constructive algorithms', 'math', 'two pointers', '*1800']