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
F. LIS?time limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputEntering senior high school life, Tom is attracted by LIS problems, not only the Longest Increasing Subsequence problem, but also the Largest Interval Sum problem. Now he gets a really interesting problem from his friend Daniel. However, it seems too hard for him to solve it, so he asks you for help.Given an array a consisting of n integers.In one operation, you do the following: Select an interval [l,r] (1\le l\le r\le n), such that the sum of the interval is the largest among all intervals in the array a. More formally, \displaystyle\sum_{i=l}^r a_i=\max_{1\le l'\le r'\le n}\sum_{i=l'}^{r'} a_i. Then subtract 1 from all elements a_l,a_{l+1},\ldots,a_r. Find the minimum number of operations you need to perform to make a_i<0 for every 1\le i\le n.InputThe first line of input contains a single integer n (1 \le n \le 5 \cdot 10^5) — the length of the array a.The second line contains n integers a_1,a_2,\ldots,a_n (-10^6\le a_i\le 10^6) — the elements of the array a.OutputPrint a single integer — the minimum number of operations.ExamplesInput 5 1 2 3 4 5 Output 6 Input 6 -1 -5 -4 -1 -4 -7 Output 0 Input 11 0 1000000 1 -50000 2 998353 3 -100007 4 200943 0 Output 1936973 NoteIn the first example, you can do operations on intervals [1,5],[1,5],[2,5],[3,5],[4,5],[5,5] in such order. You may also do operations on intervals [1,5],[2,5],[3,5],[4,5],[5,5],[1,5] in such order.In the second example, it's already satisfied that a_i<0 for every 1\le i\le n. So you do not need to perform any operations.
5 1 2 3 4 5
6
5 seconds
1024 megabytes
['data structures', 'greedy', 'implementation', '*3500']
E. Min-Sum-Maxtime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputTom is waiting for his results of Zhongkao examination. To ease the tense atmosphere, his friend, Daniel, decided to play a game with him. This game is called "Divide the Array".The game is about the array a consisting of n integers. Denote [l,r] as the subsegment consisting of integers a_l,a_{l+1},\ldots,a_r.Tom will divide the array into contiguous subsegments [l_1,r_1],[l_2,r_2],\ldots,[l_m,r_m], such that each integer is in exactly one subsegment. More formally: For all 1\le i\le m, 1\le l_i\le r_i\le n; l_1=1, r_m=n; For all 1< i\le m, l_i=r_{i-1}+1. Denote s_{i}=\sum_{k=l_i}^{r_i} a_k, that is, s_i is the sum of integers in the i-th subsegment. For all 1\le i\le j\le m, the following condition must hold: \min_{i\le k\le j} s_k \le \sum_{k=i}^j s_k \le \max_{i\le k\le j} s_k. Tom believes that the more subsegments the array a is divided into, the better results he will get. So he asks Daniel to find the maximum number of subsegments among all possible ways to divide the array a. You have to help him find it.InputThe first line of input contains a single integer t (1\le t\le 50) — 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 300) — the length of the array a.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (-10^9\le a_i\le 10^9) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case, output a single integer — the maximum number of subsegments among all possible ways to divide the array a.ExampleInput 83-1 5 422023 204361 4 7 -1 5 -45-4 0 3 -18 10199824485310-4 2 5 -10 4 8 2 9 -15 77-7 3 8 -9 -2 2 44-5 5 -2 -5Output 2 1 3 2 1 6 5 3 NoteIn the first test case, Daniel can divide the array into [-1] and [5,4], and s=[-1,9]. It can be shown that for any i=j, the condition in the statement is already satisfied, and for i=1,j=2, we have \min(-1,9)\le (-1)+9\le \max(-1,9).In the second test case, if Daniel divides the array into [2023] and [2043], then for i=1,j=2 we have 2023+2043>\max(2023,2043), so the maximum number of subsegments is 1.In the third test case, the optimal way to divide the array is [1,4,7],[-1],[5,-4].In the fourth test case, the optimal to divide the array way is [-4,0,3,-18],[10].In the fifth test case, Daniel can only get one subsegment.
83-1 5 422023 204361 4 7 -1 5 -45-4 0 3 -18 10199824485310-4 2 5 -10 4 8 2 9 -15 77-7 3 8 -9 -2 2 44-5 5 -2 -5
2 1 3 2 1 6 5 3
5 seconds
1024 megabytes
['constructive algorithms', 'dp', 'greedy', '*3500']
D. Flower-like Pseudotreetime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA pseudotree is a connected graph which has exactly one cycle and no self-loops. Note that a pseudotree may contain multiple-edges. It can be shown that a pseudotree with n vertices always contains n edges.After deleting all edges on the cycle in the pseudotree, a forest^{\dagger} will be formed. It can be shown that each tree in the forest will contain exactly one vertex which is on cycle before removing the edges. If all trees in the forest have the same depth^{\ddagger} when picking the vertex on cycle as root, we call the original pseudotree flower-like.Our friend sszcdjr, had a flower-like pseudotree with n vertices and n edges. However, he forgot all the edges in the pseudotree. Fortunately, he still remembers the degrees of vertices. Specifically, the degree of the i-th vertex is d_i.You have to help sszcdjr construct a possible flower-like pseudotree with n vertices, where the degree of the i-th vertex is exactly d_i, or tell him that it is impossible.^{\dagger} A forest is a graph in which all connectivity components are trees. A connected graph without cycles and self-loops is called a tree.^{\ddagger} The depth of a tree with a root is the maximum distance from the root to the vertex of this tree.InputThe first line of the input contains a single integer t (1\leq t\leq 10^5) — 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 10^6) — the number of vertices.The second line of each test case contains n integers d_1,d_2,\ldots,d_n (1\leq d_i\leq n) — the degree of each vertex.It is guaranteed that the sum of n over all test cases does not exceed 10^6.OutputFor each test case, if there exist a possible flower-like pseudotree: Print "Yes" (without quotes) in the first line. Then, output n lines, in each line print two integers u_i and v_i — the two vertices that the i-th edge connects. If there are multiple answers, you may output any of them.Otherwise, print "No" (without quotes) in the only line of output.You can output the first line of each test case in any case (upper or lower). For example, the strings "yEs", "yes", "Yes", and "YES" will be recognized as positive responses.ExampleInput 632 2 241 2 3 474 3 3 1 1 1 161 1 2 2 3 3101 1 5 2 1 1 1 1 1 691 1 3 1 1 4 1 1 5Output Yes 1 2 2 3 3 1 No Yes 1 2 2 3 3 1 1 4 1 5 2 6 3 7 Yes 5 6 6 5 1 3 2 4 3 5 4 6 No Yes 3 6 6 9 9 3 1 3 2 6 4 6 5 9 7 9 8 9 NoteIn the first test case, the only possible flower-like psuedotree is: After deleting all edges on the cycle in the pseudotree, each tree has depth 0.In the second test case, it can be proven that there's no such flower-like psuedotree.In the third test case, one of the possible flower-like psuedotrees is:
632 2 241 2 3 474 3 3 1 1 1 161 1 2 2 3 3101 1 5 2 1 1 1 1 1 691 1 3 1 1 4 1 1 5
Yes 1 2 2 3 3 1 No Yes 1 2 2 3 3 1 1 4 1 5 2 6 3 7 Yes 5 6 6 5 1 3 2 4 3 5 4 6 No Yes 3 6 6 9 9 3 1 3 2 6 4 6 5 9 7 9 8 9
3 seconds
512 megabytes
['constructive algorithms', 'graphs', 'greedy', 'implementation', 'trees', '*3000']
C. Travel Plantime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputDuring the summer vacation after Zhongkao examination, Tom and Daniel are planning to go traveling.There are n cities in their country, numbered from 1 to n. And the traffic system in the country is very special. For each city i (1 \le i \le n), there is a road between city i and 2i, if 2i\le n; a road between city i and 2i+1, if 2i+1\le n. Making a travel plan, Daniel chooses some integer value between 1 and m for each city, for the i-th city we denote it by a_i.Let s_{i,j} be the maximum value of cities in the simple^\dagger path between cities i and j. The score of the travel plan is \sum_{i=1}^n\sum_{j=i}^n s_{i,j}. Tom wants to know the sum of scores of all possible travel plans. Daniel asks you to help him find it. You just need to tell him the answer modulo 998\,244\,353.^\dagger A simple path between cities x and y is a path between them that passes through each city at most once.InputThe first line of input contains a single integer t (1\le t\le 200) — the number of test cases. The description of test cases follows.The only line of each test case contains two integers n and m (1\leq n\leq 10^{18}, 1\leq m\leq 10^5) — the number of the cities and the maximum value of a city.It is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputFor each test case output one integer — the sum of scores of all possible travel plans, modulo 998\,244\,353.ExampleInput 53 12 210 943 20154 147Output 6 19 583217643 68816635 714002110 NoteIn the first test case, there is only one possible travel plan: Path 1\rightarrow 1: s_{1,1}=a_1=1.Path 1\rightarrow 2: s_{1,2}=\max(1,1)=1.Path 1\rightarrow 3: s_{1,3}=\max(1,1)=1.Path 2\rightarrow 2: s_{2,2}=a_2=1.Path 2\rightarrow 1\rightarrow 3: s_{2,3}=\max(1,1,1)=1.Path 3\rightarrow 3: s_{3,3}=a_3=1.The score is 1+1+1+1+1+1=6.In the second test case, there are four possible travel plans: Score of plan 1: 1+1+1=3.Score of plan 2: 1+2+2=5.Score of plan 3: 2+2+1=5.Score of plan 4: 2+2+2=6.Therefore, the sum of score is 3+5+5+6=19.
53 12 210 943 20154 147
6 19 583217643 68816635 714002110
2 seconds
512 megabytes
['combinatorics', 'dp', 'implementation', 'math', 'trees', '*2400']
B2. Candy Party (Hard Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference is that in this version everyone must give candies to no more than one person and receive candies from no more than one person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.There will be n people at the party. Initially, the i-th person has a_i candies. During the party, they will swap their candies. To do this, they will line up in an arbitrary order and everyone will do the following no more than once: Choose an integer p (1 \le p \le n) and a non-negative integer x, then give his 2^{x} candies to the p-th person. Note that one cannot give more candies than currently he has (he might receive candies from someone else before) and he cannot give candies to himself. Daniel likes fairness, so he will be happy if and only if everyone receives candies from no more than one person. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.InputThe first line of input contains a single integer t (1\le t\le 1000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2\le n\le 2\cdot 10^5) — the number of people at the party.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 number of candies each person has.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print "Yes" (without quotes) if exists a way to swap candies to make both Daniel and Tom happy, and print "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 632 4 351 2 3 4 561 4 7 1 5 4220092043 20092043129 9 8 2 4 4 3 5 1 1 1 162 12 7 16 11 12Output Yes Yes No Yes No Yes NoteIn the first test case, the second person gives 1 candy to the first person, then all people have 3 candies. In the second test case, the fourth person gives 1 candy to the second person, the fifth person gives 2 candies to the first person, the third person does nothing. And after the swaps everyone has 3 candies.In the third test case, it's impossible for all people to have the same number of candies.In the fourth test case, the two people do not need to do anything.
632 4 351 2 3 4 561 4 7 1 5 4220092043 20092043129 9 8 2 4 4 3 5 1 1 1 162 12 7 16 11 12
Yes Yes No Yes No Yes
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'dp', 'greedy', 'implementation', 'math', '*2100']
B1. Candy Party (Easy Version)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The only difference is that in this version everyone must give candies to exactly one person and receive candies from exactly one person. Note that a submission cannot pass both versions of the problem at the same time. You can make hacks only if both versions of the problem are solved.After Zhongkao examination, Daniel and his friends are going to have a party. Everyone will come with some candies.There will be n people at the party. Initially, the i-th person has a_i candies. During the party, they will swap their candies. To do this, they will line up in an arbitrary order and everyone will do the following exactly once: Choose an integer p (1 \le p \le n) and a non-negative integer x, then give his 2^{x} candies to the p-th person. Note that one cannot give more candies than currently he has (he might receive candies from someone else before) and he cannot give candies to himself. Daniel likes fairness, so he will be happy if and only if everyone receives candies from exactly one person. Meanwhile, his friend Tom likes average, so he will be happy if and only if all the people have the same number of candies after all swaps.Determine whether there exists a way to swap candies, so that both Daniel and Tom will be happy after the swaps.InputThe first line of input contains a single integer t (1\le t\le 1000) — the number of test cases. The description of test cases follows.The first line of each test case contains a single integer n (2\le n\le 2\cdot 10^5) — the number of people at the party.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 number of candies each person has.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, print "Yes" (without quotes) if exists a way to swap candies to make both Daniel and Tom happy, and print "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 632 4 351 2 3 4 561 4 7 1 5 4220092043 20092043129 9 8 2 4 4 3 5 1 1 1 162 12 7 16 11 12Output Yes Yes No Yes No No NoteIn the first test case: The first person gives 1 candy to the third person; The second person gives 2 candies to the first person; The third person gives 1 candy to the second person. Then all people have 3 candies.In the second test case: The fifth person gives 4 candies to the first person, from now on the first person has 5 candies; The first person gives 2 candies to the third person; The third person gives 2 candies to the fifth person; The fourth person gives 2 candies to the second person; The second person gives 1 candy to the fourth person. Then all people have 3 candies. Note that at first the first person cannot give 2 candies to the third person, since he only has a_1=1 candy. But after the fifth person gives him 4 candies, he can do this, because he currently has 1+4=5 candies.In the third test case, it's impossible for all people to have the same number of candies.In the fourth test case, the first person gives 1024 candies to the second person, and the second person gives 1024 candies to the first person as well.
632 4 351 2 3 4 561 4 7 1 5 4220092043 20092043129 9 8 2 4 4 3 5 1 1 1 162 12 7 16 11 12
Yes Yes No Yes No No
2 seconds
256 megabytes
['bitmasks', 'constructive algorithms', 'graphs', 'greedy', 'implementation', 'math', '*1700']
A. Fill in the Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an empty matrix M of size n\times m.Zhongkao examination is over, and Daniel would like to do some puzzle games. He is going to fill in the matrix M using permutations of length m. That is, each row of M must be a permutation of length m^\dagger.Define the value of the i-th column in M as v_i=\operatorname{MEX}(M_{1,i},M_{2,i},\ldots,M_{n,i})^\ddagger. Since Daniel likes diversity, the beauty of M is s=\operatorname{MEX}(v_1,v_2,\cdots,v_m).You have to help Daniel fill in the matrix M and maximize its beauty.^\dagger A permutation of length m is an array consisting of m distinct integers from 0 to m-1 in arbitrary order. For example, [1,2,0,4,3] is a permutation, but [0,1,1] is not a permutation (1 appears twice in the array), and [0,1,3] is also not a permutation (m-1=2 but there is 3 in the array).^\ddagger The \operatorname{MEX} of an array is the smallest non-negative integer that does not belong to the array. For example, \operatorname{MEX}(2,2,1)=0 because 0 does not belong to the array, and \operatorname{MEX}(0,3,1,2)=4 because 0, 1, 2 and 3 appear in the array, but 4 does not.InputThe first line of input contains a single integer t (1\le t\le 1000) — the number of test cases. The description of test cases follows.The only line of each test case contains two integers n and m (1\le n,m\le 2\cdot 10^5) — the size of the matrix.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, in the first line output a single integer — the maximum beauty of M.Then output the matrix M of size n\times m — the matrix you find.If there are multiple solutions, you may output any of them.ExampleInput 44 31 166 62 1Output 3 1 0 2 0 2 1 1 0 2 0 2 1 2 14 7 15 4 10 0 8 6 1 2 3 5 9 11 12 13 6 3 0 1 4 2 5 5 2 1 0 4 3 1 3 2 4 5 0 4 1 3 2 5 0 4 2 5 3 0 1 2 4 0 5 1 3 0 0 0NoteIn the first test case: v_1=\operatorname{MEX}(1,0,1,0)=2; v_2=\operatorname{MEX}(0,2,0,2)=1; v_3=\operatorname{MEX}(2,1,2,1)=0. Therefore, s=\operatorname{MEX}(2,1,0)=3. It can be shown that 3 is the maximum possible beauty of M.In the second test case, any permutation will make s=2.In the third test case: v_1=\operatorname{MEX}(3,5,1,4,4,2)=0; v_2=\operatorname{MEX}(0,2,3,1,2,4)=5; v_3=\operatorname{MEX}(1,1,2,3,5,0)=4; v_4=\operatorname{MEX}(4,0,4,2,3,5)=1; v_5=\operatorname{MEX}(2,4,5,5,0,1)=3; v_6=\operatorname{MEX}(5,3,0,0,1,3)=2. Therefore, s=\operatorname{MEX}(0,5,4,1,3,2)=6.
44 31 166 62 1
3 1 0 2 0 2 1 1 0 2 0 2 1 2 14 7 15 4 10 0 8 6 1 2 3 5 9 11 12 13 6 3 0 1 4 2 5 5 2 1 0 4 3 1 3 2 4 5 0 4 1 3 2 5 0 4 2 5 3 0 1 2 4 0 5 1 3 0 0 0
2 seconds
256 megabytes
['constructive algorithms', 'implementation', '*1300']
F. Most Different Treetime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a tree with n vertices rooted at vertex 1, denote it as G. Also denote P(G) as the multiset of subtrees of all vertices in tree G. You need to find a tree G' of size n rooted at vertex 1 such that the number of subtrees in P(G') that are isomorphic to any subtree in P(G) is minimized.A subtree of vertex v is a graph that contains all vertices for which vertex v lies on the path from the root of the tree to itself, as well as all edges between these vertices.Two rooted trees are considered isomorphic if it is possible to relabel the vertices of one of them so that it becomes equal to the other, with the root of the first tree receiving the number of the root of the second tree.InputThe first line contains a single integer n (2 \le n \le 10^6) - the number of vertices in tree G. Each of the next n-1 lines contains two integers a and b (1 \leq a,b \leq n), indicating that there is an edge between vertices a and b in the tree.OutputOutput n-1 lines, each line containing two numbers a, b (1 \leq a,b \leq n) - the edges of tree G'. If there are multiple optimal answers, output any.ExamplesInput 2 1 2 Output 1 2 Input 3 1 2 1 3 Output 1 2 2 3 Input 4 1 2 1 3 3 4 Output 1 2 2 3 3 4
2 1 2
1 2
4 seconds
512 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'greedy', 'hashing', '*2700']
E2. Salyg1n and Array (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 57 queries. You can make hacks only if both versions of the problem are solved.This is an interactive problem!salyg1n has given you a positive integer k and wants to play a game with you. He has chosen an array of n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9). You must print a_1 \oplus a_2 \oplus \ldots \oplus a_n, where \oplus denotes the bitwise XOR operation. You can make queries of the following type: ? i: in response to this query, you will receive a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}. Also, after this query, the subarray a_i, a_{i + 1}, \ldots, a_{i + k - 1} will be reversed, i.e., the chosen array a will become: a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n. You can make no more than 57 queries to answer the problem.InputThe first line contains a single integer t (1 \leq t \leq 1000) – the number of test cases.InteractionThe interaction between your program and the jury's program begins with reading two positive even integers n and k (1 \leq k \leq n \leq k^2 \leq 2500) – the length of the chosen array and the length of the query subarray, respectively.To find the value of a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}, print the query in the format ? i (1 \leq i \leq n - k + 1). Then read a single integer – the answer to your query.You can make no more than 57 queries. When you are ready to print the answer, output it in the format ! x. After that, proceed to process the next test case or terminate the program if it was the last test case. Printing the answer does not count as one of the 57 queries.If your program makes more than 57 queries for one set of input data, or makes an invalid query, then the response to the query will be -1. After receiving such a response, your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, it may receive any other verdict.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. It is guaranteed that the sum of n over all test cases does not exceed 10000. The interactor in this problem is not adaptive.Hacks:To perform a hack, use the following format:The first line contains a single integer t – the number of test cases.The description of each test case should consist of two lines. The first line contains the numbers n and k – the length of the chosen array and the length of the query subarray, respectively. The second line contains n numbers a_1, a_2, \ldots, a_n – the array that the jury should choose for this test case.ExampleInput 2 4 2 6 4 6 6 4Output ? 1 ? 3 ! 2 ? 1 ! 4NoteIn the first test case, the jury has chosen the array a = [4, 2, 5, 1]In the second test case, the jury has chosen the array a = [5, 7, 1, 3, 3, 7]
2 4 2 6 4 6 6 4
? 1 ? 3 ! 2 ? 1 ! 4
1 second
256 megabytes
['constructive algorithms', 'interactive', '*2200']
E1. Salyg1n and Array (simple version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is the simple version of the problem. The only difference between the versions is the limit on the number of queries. In this version, you can make no more than 100 queries. You can make hacks only if both versions of the problem are solved.This is an interactive problem!salyg1n has given you a positive integer k and wants to play a game with you. He has chosen an array of n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9). You must print a_1 \oplus a_2 \oplus \ldots \oplus a_n, where \oplus denotes the bitwise XOR operation. You can make queries of the following type: ? i: in response to this query, you will receive a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}. Also, after this query, the subarray a_i, a_{i + 1}, \ldots, a_{i + k - 1} will be reversed, i.e., the chosen array a will become: a_1, a_2, \ldots a_{i - 1}, a_{i + k - 1}, a_{i + k - 2}, \ldots, a_{i + 1}, a_i, a_{i + k}, \ldots, a_n. You can make no more than 100 queries to answer the problem.InputThe first line contains a single integer t (1 \leq t \leq 1000) – the number of test cases.InteractionThe interaction between your program and the jury's program begins with reading two positive even integers n and k (1 \leq k \leq n \leq k^2 \leq 2500) – the length of the chosen array and the length of the query subarray, respectively.To find the value of a_i \oplus a_{i + 1} \oplus \ldots \oplus a_{i + k - 1}, print the query in the format ? i (1 \leq i \leq n - k + 1). Then read a single integer – the answer to your query.You can make no more than 100 queries. When you are ready to print the answer, output it in the format ! x. After that, proceed to process the next test case or terminate the program if it was the last test case. Printing the answer does not count as one of the 100 queries.If your program makes more than 100 queries for one set of input data, or makes an invalid query, then the response to the query will be -1. After receiving such a response, your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, it may receive any other verdict.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. It is guaranteed that the sum of n over all test cases does not exceed 10000. The interactor in this problem is not adaptive.Hacks:To perform a hack, use the following format:The first line contains a single integer t – the number of test cases.The description of each test case should consist of two lines. The first line contains the numbers n and k – the length of the chosen array and the length of the query subarray, respectively. The second line contains n numbers a_1, a_2, \ldots, a_n – the array that the jury should choose for this test case.ExampleInput 2 4 2 6 4 6 6 4Output ? 1 ? 3 ! 2 ? 1 ! 4NoteIn the first test case, the jury has chosen the array a = [4, 2, 5, 1]In the second test case, the jury has chosen the array a = [5, 7, 1, 3, 3, 7]
2 4 2 6 4 6 6 4
? 1 ? 3 ! 2 ? 1 ! 4
1 second
256 megabytes
['constructive algorithms', 'interactive', 'math', '*2000']
D. Cyclic Operationstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEgor has an array a of length n, initially consisting of zeros. However, he wanted to turn it into another array b of length n.Since Egor doesn't take easy paths, only the following operation can be used (possibly zero or several times): choose an array l of length k (1 \leq l_i \leq n, all l_i are distinct) and change each element a_{l_i} to l_{(i\%k)+1} (1 \leq i \leq k). He became interested in whether it is possible to get the array b using only these operations. Since Egor is still a beginner programmer, he asked you to help him solve this problem.The operation \% means taking the remainder, that is, a\%b is equal to the remainder of dividing the number a by the number b.InputThe first line of the input contains an integer t (1 \leq t \leq 10^5) - the number of test cases.Each test case consists of two lines. The first line contains two integers n and k (1 \leq k \leq n \leq 10^5).The second line contains the array b_1, b_2, \ldots, b_n (1 \leq b_i \leq n).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" (without quotes) if there is a way to get the array b using only the given operation. Otherwise, output "NO" (without quotes). You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes" and "YES" will be accepted as a positive answer.ExampleInput 65 32 3 5 3 44 22 4 3 11 113 11 2 35 35 4 3 2 16 11 2 3 1 5 6Output YES NO YES YES NO NO NoteLet's consider the first example: Apply the operation with l = [1,2,3]. Now a = [2,3,1,0,0]. Apply the operation with l = [3,5,4]. Now a = [2,3,5,3,4] = b. We see that it is possible to get the array b. Therefore, the answer is YES.In the second example, it can be proven that the array b cannot be obtained, therefore the answer is NO.
65 32 3 5 3 44 22 4 3 11 113 11 2 35 35 4 3 2 16 11 2 3 1 5 6
YES NO YES YES NO NO
1 second
256 megabytes
['brute force', 'constructive algorithms', 'dfs and similar', 'graphs', 'greedy', 'implementation', '*1800']
C. Salyg1n and the MEX Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem!salyg1n gave Alice a set S of n distinct integers s_1, s_2, \ldots, s_n (0 \leq s_i \leq 10^9). Alice decided to play a game with this set against Bob. The rules of the game are as follows: Players take turns, with Alice going first. In one move, Alice adds one number x (0 \leq x \leq 10^9) to the set S. The set S must not contain the number x at the time of the move. In one move, Bob removes one number y from the set S. The set S must contain the number y at the time of the move. Additionally, the number y must be strictly smaller than the last number added by Alice. The game ends when Bob cannot make a move or after 2 \cdot n + 1 moves (in which case Alice's move will be the last one). The result of the game is \operatorname{MEX}\dagger(S) (S at the end of the game). Alice aims to maximize the result, while Bob aims to minimize it. Let R be the result when both players play optimally. In this problem, you play as Alice against the jury program playing as Bob. Your task is to implement a strategy for Alice such that the result of the game is always at least R.\dagger \operatorname{MEX} of a set of integers c_1, c_2, \ldots, c_k is defined as the smallest non-negative integer x which does not occur in the set c. For example, \operatorname{MEX}(\{0, 1, 2, 4\}) = 3.InputThe first line contains an integer t (1 \leq t \leq 10^5) - the number of test cases.InteractionThe interaction between your program and the jury program begins with reading an integer n (1 \leq n \leq 10^5) - the size of the set S before the start of the game.Then, read one line - n distinct integers s_i (0 \leq s_1 < s_2 < \ldots < s_n \leq 10^9) - the set S given to Alice.To make a move, output an integer x (0 \leq x \leq 10^9) - the number you want to add to the set S. S must not contain x at the time of the move. Then, read one integer y (-2 \leq y \leq 10^9). If 0 \leq y \leq 10^9 - Bob removes the number y from the set S. It's your turn! If y = -1 - the game is over. After this, proceed to handle the next test case or terminate the program if it was the last test case. Otherwise, y = -2. This means that you made an invalid query. Your program should immediately terminate to receive the verdict Wrong Answer. Otherwise, it may receive any other verdict. After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. It is guaranteed that the sum of n over all test cases does not exceed 10^5.Do not attempt to hack this problem.ExampleInput 3 5 1 2 3 5 7 7 5 -1 3 0 1 2 0 -1 3 5 7 57 -1Output 8 57 0 3 0 0NoteIn the first test case, the set S changed as follows:{1, 2, 3, 5, 7} \to {1, 2, 3, 5, 7, 8} \to {1, 2, 3, 5, 8} \to {1, 2, 3, 5, 8, 57} \to {1, 2, 3, 8, 57} \to {0, 1, 2, 3, 8, 57}. In the end of the game, \operatorname{MEX}(S) = 4, R = 4.In the second test case, the set S changed as follows:{0, 1, 2} \to {0, 1, 2, 3} \to {1, 2, 3} \to {0, 1, 2, 3}. In the end of the game, \operatorname{MEX}(S) = 4, R = 4.In the third test case, the set S changed as follows:{5, 7, 57} \to {0, 5, 7, 57}. In the end of the game, \operatorname{MEX}(S) = 1, R = 1.
3 5 1 2 3 5 7 7 5 -1 3 0 1 2 0 -1 3 5 7 57 -1
8 57 0 3 0 0
3 seconds
256 megabytes
['constructive algorithms', 'data structures', 'games', 'greedy', 'interactive', '*1300']
B. XOR Palindromestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s of length n (a string that consists only of 0 and 1). A number x is good if there exists a binary string l of length n, containing x ones, such that if each symbol s_i is replaced by s_i \oplus l_i (where \oplus denotes the bitwise XOR operation), then the string s becomes a palindrome.You need to output a binary string t of length n+1, where t_i (0 \leq i \leq n) is equal to 1 if number i is good, and 0 otherwise.A palindrome is a string that reads the same from left to right as from right to left. For example, 01010, 1111, 0110 are palindromes.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains a single integer n (1 \le n \le 10^5).The second line of each test case contains a binary string s of length n.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output a single line containing a binary string t of length n+1 - the answer to the problem.ExampleInput 561010115000009100100011310011Output 0010100 111111 0011111100 0110 11 NoteConsider the first example. t_2 = 1 because we can choose l = 010100, then the string s becomes 111111, which is a palindrome. t_4 = 1 because we can choose l = 101011. It can be shown that for all other i, there is no answer, so the remaining symbols are 0.
561010115000009100100011310011
0010100 111111 0011111100 0110 11
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'strings', '*1100']
A. green_gold_dog, array and permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputgreen_gold_dog has an array a of length n, and he wants to find a permutation b of length n such that the number of distinct numbers in the element-wise difference between array a and permutation b is maximized.A permutation of length n is an array consisting of n distinct integers from 1 to n in any order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (as 2 appears twice in the array) and [1,3,4] is also not a permutation (as n=3, but 4 appears in the array).The element-wise difference between two arrays a and b of length n is an array c of length n, where c_i = a_i - b_i (1 \leq i \leq n).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 4 \cdot 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 4 \cdot 10^4).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9).It is guaranteed that the sum of n over all test cases does not exceed 4 \cdot 10^4.OutputFor each test case, output n numbers - a suitable permutation b. If there are multiple solutions, print any of them.ExampleInput 3110000021 1310 3 3Output 1 2 1 1 3 2 NoteIn the first set of input data, the element-wise difference of the arrays is [99999]. Here, there is one distinct number, and it is obvious that in an array of length one, there cannot be more than one different element.In the second set of input data, the element-wise difference of the arrays is [-1, 0]. Here, there are two distinct numbers, and it is obvious that in an array of length two, there cannot be more than two different elements.In the third set of input data, the element-wise difference of the arrays is [9, 0, 1]. Here, there are three distinct numbers, and it is obvious that in an array of length three, there cannot be more than three different elements.
3110000021 1310 3 3
1 2 1 1 3 2
1 second
256 megabytes
['constructive algorithms', 'sortings', '*800']
M. Mighty Rock Towertime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek comes up with an idea in the midst of boredom to play a game. The game is a rock tower game. There is a big rock that is used as a base. There are also N small identical rocks that Pak Chanek will use to build a rock tower with a height of N above the base rock.Initially, there are no small rocks that are located above the base rock. In other words, the height of the tower above the base rock is initially 0. In one move, Pak Chanek can place one small rock onto the top of the tower which makes the height of the tower above the base rock increase by 1. Each time Pak Chanek place one small rock, the following will happen after the small rock is placed: Let's say x is the height of the tower above the base rock right after the small rock is placed. There is a probability of P_x percent that the topmost rock falls. If x \geq 2 and the topmost rock falls, then there is another probability of P_x percent that the 2-nd topmost rock also falls. If x \geq 3 and the 2-nd topmost rock falls, then there is another probability of P_x percent that the 3-rd topmost rock also falls. If x \geq 4 and the 3-rd topmost rock falls, then there is another probability of P_x percent that the 4-th topmost rock also falls. And so on. If the tower successfully reaches a height of N without any rocks falling after that, then the game is ended.If given an integer array [P_1, P_2, \ldots, P_N], what is the expected value of the number of moves that Pak Chanek needs to do to end the game? It can be proven that the expected value can be represented as an simple fraction \frac{P}{Q} where Q is coprime to 998\,244\,353. Output the value of P \times Q^{-1} modulo 998\,244\,353.InputThe first line contains a single integer N (1 \leq N \leq 2\cdot10^5) — the required height of the rock tower.The second line contains N integers P_1, P_2, P_3, \ldots, P_N (0 \leq P_i \leq 99).OutputAn integer representing the expected value of the number of moves that Pak Chanek needs to do to end the game, modulo 998\,244\,353.ExamplesInput 2 80 50 Output 499122186 Input 3 25 16 20 Output 879786027 NoteIn the first example, the expected value of the number of moves that Pak Chanek needs to do to end the game is \frac{19}{2}.
2 80 50
499122186
2 seconds
512 megabytes
['brute force', 'combinatorics', 'dp', 'math', 'probabilities', '*2400']
L. Lihmuf Ballingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter working at a factory (Lihmuf Sorting), Lihmuf wants to play a game with his good friend, Pak Chanek. There are N boxes numbered from 1 to N. The i-th box contains i balls. Pak Chanek and Lihmuf will play a game using those boxes.There will be N turns numbered from 1 to N. On each turn, Pak Chanek chooses one box and takes all balls from that box, then Lihmuf does the same thing for one box he chooses (it is possible that the two chosen boxes are the same).Given an integer M. Before the game begins, Lihmuf must choose an integer K satisfying 1 \leq K \leq M. It is known that on the j-th turn, Pak Chanek will choose the j-th box, while Lihmuf will choose the y-th box, with y=((j \times K - 1) \bmod N) + 1. Help Lihmuf choose the correct value of K so that he will get as many balls as possible! If there are more than one possible values of K that result in the maximum total balls, find the minimum such value of K.Keep in mind that each box can be chosen more than once, but after a box is chosen for the first time, the box becomes empty.InputThe only line contains two integers N and M (1 \leq N \leq 10^9; 1 \leq M \leq 2000) — the number of boxes and the maximum limit for the value of K.OutputAn integer representing the value of K that will make Lihmuf get as many balls as possible. If there are more than one possible value of K that result in the maximum total balls, find the minimum such value of K.ExamplesInput 3 1 Output 1 Input 5 4 Output 3 NoteIn the first example, if Lihmuf chooses K=1, the game will go as follows: Pak Chanek chooses the 1-st box and gets 1 ball, then Lihmuf chooses the 1-st box and gets 0 balls. Pak Chanek chooses the 2-nd box and gets 2 balls, then Lihmuf chooses the 2-nd box and gets 0 balls. Pak Chanek chooses the 3-rd box and gets 3 balls, then Lihmuf chooses the 3-rd box and gets 0 balls. In total, Lihmuf gets 0+0+0=0 balls.The maximum total balls that can be earned by Lihmuf is 0 because he can only choose K=1. Therefore, K=1 is the minimum possible value of K that results in the maximum total balls.In the second example, if Lihmuf chooses K=3, the game will go as follows: Pak Chanek chooses the 1-st box and gets 1 ball, then Lihmuf chooses the 3-rd box and gets 3 balls. Pak Chanek chooses the 2-nd box and gets 2 balls, then Lihmuf chooses the 1-st box and gets 0 balls. Pak Chanek chooses the 3-rd box and gets 0 balls, then Lihmuf chooses the 4-th box and gets 4 balls. Pak Chanek chooses the 4-th box and gets 0 balls, then Lihmuf chooses the 2-nd box and gets 0 balls. Pak Chanek chooses the 5-th box and gets 5 balls, then Lihmuf chooses the 5-th box and gets 0 balls. In total, Lihmuf gets 3+0+4+0+0=7 balls.It can be obtained that 7 is the maximum total balls that can be earned by Lihmuf. The possible values of K that result in 7 total balls are 3 and 4. Therefore, K=3 is the minimum possible value of K that results in the maximum total balls.
3 1
1
2 seconds
256 megabytes
['binary search', 'brute force', 'math', '*2400']
K. Keen Tree Calculationtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a tree of N vertices and N-1 edges. The i-th edge connects vertices U_i and V_i and has a length of W_i.Chaneka, the owner of the tree, asks you Q times. For the j-th question, the following is the question format: X_j K_j – If each edge that contains vertex X_j has its length multiplied by K_j, what is the diameter of the tree? Notes: Each of Chaneka's question is independent, which means the changes in edge length do not influence the next questions. The diameter of a tree is the maximum possible distance between two different vertices in the tree. InputThe first line contains a single integer N (2\leq N\leq10^5) — the number of vertices in the tree.The i-th of the next N-1 lines contains three integers U_i, V_i, and W_i (1 \leq U_i,V_i \leq N; 1\leq W_i\leq10^9) — an edge that connects vertices U_i and V_i with a length of W_i. The edges form a tree.The (N+1)-th line contains a single integer Q (1\leq Q\leq10^5) — the number of questions.The j-th of the next Q lines contains two integers X_j and K_j as described (1 \leq X_j \leq N; 1 \leq K_j \leq 10^9).OutputOutput Q lines with an integer in each line. The integer in the j-th line represents the diameter of the tree on the j-th question.ExamplesInput 7 5 1 2 1 4 2 3 4 1 2 5 3 6 1 6 4 7 2 2 4 3 3 2 Output 18 11 Input 3 1 2 1000000000 2 3 1000000000 1 2 1000000000 Output 2000000000000000000 NoteIn the first example, the following is the tree without any changes.The following is the tree on the 1-st question.The maximum distance is between vertices 6 and 7, which is 6+6+6=18, so the diameter is 18.The following is the tree on the 2-nd question.The maximum distance is between vertices 2 and 6, which is 3+2+6=11, so the diameter is 11.
7 5 1 2 1 4 2 3 4 1 2 5 3 6 1 6 4 7 2 2 4 3 3 2
18 11
2 seconds
512 megabytes
['binary search', 'data structures', 'dp', 'geometry', 'graphs', 'implementation', 'trees', '*2500']
J. Jackets and Packetstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek has N jackets that are stored in a wardrobe. Pak Chanek's wardrobe has enough room for two stacks of jackets, namely the left stack and the right stack. Initially, all N jackets are in the left stack, while the right stack is empty. Initially, the i-th jacket from the top of the left stack has colour C_i.Pak Chanek wants to pack all of those jackets into some packets, such that the jackets in the same packet has the same colour. However, it is possible for two jackets with the same colour to be in different packets.Pak Chanek can do two kinds of operations: Pak Chanek can pick any number of jackets from the top from one stack as long as the colour is the same, then take those jackets out of the stack and pack them into a packet. This packing operation takes X minutes, no matter how many jackets are packed. Pak Chanek can move one topmost jacket from one stack to the top of the other stack (possibly right to left or left to right). This moving operation takes Y minutes. Determine the minimum time to pack all jackets!InputThe first line contains three integers N, X, and Y (1 \leq N \leq 400; 1\leq X,Y\leq10^9) — the number of jackets, the time to do a packing operation, and the time to do a movement operation.The second line contains N integers C_1, C_2, C_3, \ldots, C_N (1 \leq C_i \leq N) — the colour of each jacket.OutputAn integer representing the minimum time to pack all jackets.ExampleInput 8 7 2 4 4 2 4 1 2 2 1 Output 38 NoteLet's denote the contents of the two stacks using arrays that represent the colours of the jackets in the stack from top to bottom. Initially, the two stacks form [4, 4, 2, 4, 1, 2, 2, 1] and [].Pak Chanek can do the following sequence of operations: Movement from left to right. The two stacks become [4, 2, 4, 1, 2, 2, 1] and [4]. Movement from left to right. The two stacks become [2, 4, 1, 2, 2, 1] and [4, 4]. Packing for 1 jacket from the top of the left stack. The two stacks become [4, 1, 2, 2, 1] and [4, 4]. Movement from left to right. The two stacks become [1, 2, 2, 1] and [4, 4, 4]. Movement from left to right. The two stacks become [2, 2, 1] and [1, 4, 4, 4]. Packing for 2 jackets from the top of the left stack. The two stacks become [1] and [1, 4, 4, 4]. Movement from right to left. The two stacks become [1, 1] and [4, 4, 4]. Packing for 3 jackets from the top of the right stack. The two stacks become [1, 1] and []. Packing for 2 jackets from the top of the left stack. The two stacks become [] and []. In total, it requires a time of 2+2+7+2+2+7+2+7+7=38 minutes to pack all jackets. It can be proven that there are no other ways that are faster.
8 7 2 4 4 2 4 1 2 2 1
38
2 seconds
512 megabytes
['dp', '*2800']
I. Imagination Castletime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGiven a chessboard of size N \times M (N rows and M columns). Each row is numbered from 1 to N from top to bottom and each column is numbered from 1 to M from left to right. The tile in row r and column c is denoted as (r,c). There exists K distinct special tiles on the chessboard with the i-th special tile being tile (X_i,Y_i). It is guaranteed that tile (1,1) is not a special tile.A new chess piece has been invented, which is the castle. The castle moves similarly to a rook in regular chess, but slightly differently. In one move, a castle that is on some tile can only move to another tile in the same row or in the same column, but only in the right direction or the down direction. Formally, in one move, the castle on tile (r,c) can only move to tile (r',c') if and only if one of the following two conditions is satisfied: r'=r and c'>c. c'=c and r'>r. Chaneka and Bhinneka will play a game. In the beginning of the game, there is a castle in tile (1,1). The two players will play alternatingly with Chaneka going first. In one turn, the player on that turn must move the castle following the movement rules of the castle.If a player moves the castle to a special tile on her turn, then that player wins the game and the game ends. If on a turn, the castle cannot be moved, the player on that turn loses and the game ends.Given the size of the board and the locations of each special tile. Determine the winner of this game if Chaneka and Bhinneka plays optimally.InputThe first line contains three integers N, M, and K (1 \leq N,M \leq 2 \cdot 10^5; 0 \leq K \leq \min(N \times M - 1, 2\cdot10^5)) — the size of the chessboard and the number of special tiles.The i-th of the next K lines contains two integers X_i and Y_i (1\leq X_i\leq N; 1\leq Y_i\leq M; (X_i, Y_i) \neq (1,1)) — the location of each special tile. The special tiles are pairwise distinct.OutputOutput Chaneka if Chaneka is the winner, output Bhinneka if Bhinneka is the winner.ExamplesInput 4 5 3 1 3 4 4 1 5 Output Chaneka Input 2 2 0 Output Bhinneka NoteIn the first example, the following is an illustration of the chessboard in the beginning of the game. Chaneka can move the castle to special tile (1,3) or (1,5) directly on her first turn. Therefore, Chaneka is the winner.In the second example, the following is an illustration of the chessboard in the beginning of the game. Chaneka can only move the castle to tile (1, 2) or (2, 1) on her first turn. Whatever Chaneka does, Bhinneka will be able to directly move the castle to tile (2, 2). After that, on Chaneka's turn, she cannot move the castle, so Chaneka loses. Therefore, Bhinneka is the winner.
4 5 3 1 3 4 4 1 5
Chaneka
2 seconds
512 megabytes
['dp', 'games', 'two pointers', '*2300']
H. Happy Setstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDefine a set A as a child of set B if and only if for each element of value x that is in A, there exists an element of value x+1 that is in B.Given integers N and K. In order to make Chaneka happy, you must find the number of different arrays containing N sets [S_1, S_2, S_3, \ldots, S_N] such that: - Each set can only contain zero or more different integers from 1 to K. - There exists a way to rearrange the order of the array of sets into [S'_1, S'_2, S'_3, \ldots, S'_N] such that S'_i is a child of S'_{i+1} for each 1\leq i\leq N-1.Print the answer modulo 998\,244\,353.Two sets are considered different if and only if there is at least one value that only occurs in one of the two sets.Two arrays of sets are considered different if and only if there is at least one index i such that the sets at index i in the two arrays are different.InputThe only line contains two integers N and K (1 \leq N,K \leq 2\cdot10^5) — the number of sets in the array and the maximum limit for the values in the sets.OutputAn integer representing the number of different arrays of sets that satisfy the problem condition, modulo 998\,244\,353.ExamplesInput 2 2 Output 11 Input 1 3 Output 8 Input 3 1 Output 4 NoteIn the first example, there are 11 different arrays of sets possible, which are: [\{\}, \{\}] [\{\}, \{1\}] [\{\}, \{1, 2\}] [\{\}, \{2\}] [\{1\}, \{\}] [\{1\}, \{1, 2\}] [\{1\}, \{2\}] [\{1, 2\}, \{\}] [\{1, 2\}, \{1\}] [\{2\}, \{\}] [\{2\}, \{1\}]
2 2
11
1 second
256 megabytes
['combinatorics', '*2100']
G. Grouped Carriagestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek observes that the carriages of a train is always full on morning departure hours and afternoon departure hours. Therefore, the balance between carriages is needed so that it is not too crowded in only a few carriages.A train contains N carriages that are numbered from 1 to N from left to right. Carriage i initially contains A_i passengers. All carriages are connected by carriage doors, namely for each i (1\leq i\leq N-1), carriage i and carriage i+1 are connected by a two-way door.Each passenger can move between carriages, but train regulation regulates that for each i, a passenger that starts from carriage i cannot go through more than D_i doors.Define Z as the most number of passengers in one same carriage after moving. Pak Chanek asks, what is the minimum possible value of Z?InputThe first line contains a single integer N (1 \leq N \leq 2\cdot10^5) — the number of carriages.The second line contains N integers A_1, A_2, A_3, \ldots, A_N (0 \leq A_i \leq 10^9) — the initial number of passengers in each carriage.The third line contains N integers D_1, D_2, D_3, \ldots, D_N (0 \leq D_i \leq N-1) — the maximum limit of the number of doors for each starting carriage.OutputAn integer representing the minimum possible value of Z.ExampleInput 7 7 4 2 0 5 8 3 4 0 0 1 3 1 3 Output 5 NoteOne strategy that is optimal is as follows: 5 people in carriage 1 move to carriage 4 (going through 3 doors). 3 people in carriage 5 move to carriage 3 (going through 2 doors). 2 people in carriage 6 move to carriage 5 (going through 1 door). 1 person in carriage 6 moves to carriage 7 (going through 1 door). The number of passengers in each carriage becomes [2,4,5,5,4,5,4].
7 7 4 2 0 5 8 3 4 0 0 1 3 1 3
5
3 seconds
512 megabytes
['binary search', 'data structures', 'dp', 'flows', 'greedy', '*2100']
F. Freak Joker Processtime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAfter the success of the basketball teams formed and trained by Pak Chanek last year (Basketball Together), Pak Chanek wants to measure the performance of each player that is considered as a superstar.There are N superstar players that have been trained by Pak Chanek. At the end of the season, some calculations will be made on the performance of the N players using an international method. Each player has two values A_i and B_i where each represents the offensive and defensive value of that player.Define \text{RankA}(i) as the offensive ranking of the i-th player, whose value is c+1 with c here representing the number of j (1 \leq j \leq N) such that A_j>A_i. Define \text{RankB}(i) as the defensive ranking of the i-th player, whose value is c+1 with c here representing the number of j (1 \leq j \leq N) such that B_j>B_i.Define \text{RankOverall}(i) as the overall ranking of the i-th player, whose value is c+1 with c here representing the number of j (1 \leq j \leq N) such that \text{RankA}(j)+\text{RankB}(j)<\text{RankA}(i)+\text{RankB}(i).During the next Q days, exactly one event will happen on each day. Each event is one of the three following possibilities: 1 k c – If c is +, then A_k increases by 1. If c is -, then A_k decreases by 1. (1\leq k\leq N; c is + or -) 2 k c – If c is +, then B_k increases by 1. If c is -, then B_k decreases by 1. (1\leq k\leq N; c is + or -) 3 k – Pak Chanek wants to know the value of \text{RankOverall}(k) at that moment. (1\leq k\leq N) InputThe first line contains a single integer N (1\leq N\leq10^5) — the number of superstar players.The second line contains N integers A_1, A_2, A_3 \ldots, A_N (1 \leq A_i \leq 10^5) — the offensive value of each player.The third line contains N integers B_1, B_2, B_3 \ldots, B_N (1 \leq B_i \leq 10^5) — the defensive value of each player.The fourth line contains a single integer Q (1\leq Q\leq10^5) — the number of events.The j-th of the next Q lines contains the j-th event as described. At any moment, each value of A_i and B_i is always between 1 and 10^5 inclusive. There is at least one event of type 3.OutputFor each event of type 3, output a line containing an integer representing the value of \text{RankOverall}(k) at that moment.ExampleInput 5 3 3 1 3 2 3 7 1 3 1 8 3 1 3 2 2 4 + 1 2 - 3 2 3 3 2 2 - 3 1 Output 2 1 2 5 2 NoteAt the 8-th event, A=[3,2,1,3,2] and B=[3,6,1,4,1]. It can be obtained that the values of \text{RankA} and \text{RankB} for each player are as follows: \text{RankA}(1)=1, \text{RankB}(1)=3 \text{RankA}(2)=3, \text{RankB}(2)=1 \text{RankA}(3)=5, \text{RankB}(3)=4 \text{RankA}(4)=1, \text{RankB}(4)=2 \text{RankA}(5)=3, \text{RankB}(5)=4 So it can be obtained that \text{RankOverall}(1)=2.
5 3 3 1 3 2 3 7 1 3 1 8 3 1 3 2 2 4 + 1 2 - 3 2 3 3 2 2 - 3 1
2 1 2 5 2
5 seconds
1024 megabytes
['binary search', 'data structures', 'sortings', '*3100']
E. Elevators of Tamemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a building named Taman Membeku (shortened as Tamem). The building has N floors numbered from 1 to N from bottom to top. The only way to move between floors in the building is to use elevators. There are 3 elevators available in Tamem, namely elevators 1, 2, and 3.Pak Chanek works as an elevator operator in Tamem. Pak Chanek will work for Q days. Initially, each elevator is in floor 1 and all elevators are on. On each day, exactly one of the following will happen: 1 x y – There is a person currently in floor x who wants to go to floor y. (1\leq x,y\leq N; x\neq y) 2 p – Elevator p changes state at the start of the day. If previously it is on, then it will turn off. If previously it is off, then it will turn on. (1\leq p\leq3) For each day, Pak Chanek can control the movement of all elevators as he pleases. However, for each day where there is a person currently in floor x who wants to go to floor y, among all elevator movements done by Pak Chanek, the following must happen: One elevator moves to floor x. The person gets into the elevator. The elevator moves to floor y. The person gets out of the elevator. For each day, Pak Chanek can only move the elevators that are currently on. Note that, since a change in state happens at the start of the day, this means that an elevator that turns off on some day starts becoming unusable from that day itself. Conversely, an elevator that turns on on some day starts becoming usable from that day itself.It is known that the electricity fee for each day is different. More specifically, on the j-th day, the fee needed to move one elevator up or down by one floor is A_j.From the start, Pak Chanek already knows the electricity fees and the sequence of events that will happen on the Q days, so Pak Chanek can operate the elevators strategically. What is the minimum possible electricity fee to fulfill all needs of the people who want to move between floors in Tamem? Note: in the end, each elevator does not have to go back to floor 1.InputThe first line contains two integers N and Q (2\leq N\leq10^5; 1\leq Q\leq300) — the number of floors and the number of days.The second line contains Q integers A_1, A_2, A_3 \ldots, A_Q (1 \leq A_j \leq 10^5) — the electricity fee for each day.The j-th of the next Q lines contains the j-th event as described. At any moment, there will always be at least one elevator that is on.OutputAn integer representing the minimum possible electricity fee to fulfill all needs of the people who want to move between floors in Tamem.ExampleInput 9 8 3 4 4 3 4 2 7 6 1 2 7 1 3 9 2 2 1 4 5 1 3 5 2 2 1 7 3 1 2 1 Output 114 NoteThe following is an example of an optimal strategy: On the 1-st day: Elevator 2 moves to floor 3. Elevator 3 moves to floor 2, picks the person up, moves to floor 7, then drops the person off. On the 2-nd day: Elevator 2 picks the person up, moves to floor 9, then drops the person off. On the 3-rd day: Elevator 2 turns off. On the 4-th day: Elevator 3 moves to floor 4, picks the person up, moves to floor 5, drops the person off, then moves to floor 3. On the 5-th day: Elevator 3 picks the person up, moves to floor 5, then drops the person off. On the 6-th day: Elevator 2 turns on. Elevator 1 moves to floor 2. Elevator 2 moves to floor 7. On the 7-th day: Elevator 2 picks the person up, moves to floor 3, then drops the person off. On the 8-th day: Elevator 1 picks the person up, moves to floor 1, then drops the person off. The total electricity fee for each day from the 1-st day to the 8-th day are 24, 24, 0, 18, 8, 6, 28, and 6 respectively. Therefore, the total electricity fee for the entire Q days is 24+24+0+18+8+6+28+6=114.It can be obtained that there is no strategy that requires a smaller electricity fee.
9 8 3 4 4 3 4 2 7 6 1 2 7 1 3 9 2 2 1 4 5 1 3 5 2 2 1 7 3 1 2 1
114
5 seconds
512 megabytes
['dp', '*2700']
D. Digital Wallettime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are N arrays, each array has M positive integer elements The j-th element of the i-th array is A_{i,j}.Initially, Chaneka's digital wallet contains 0 money. Given an integer K. Chaneka will do M-K+1 operations. In the p-th operation, Chaneka does the following procedure: Choose any array. Let's say Chaneka chooses the x-th array. Choose an index y in that array such that p \leq y \leq p+K-1. Add the value of A_{x, y} to the total money in the wallet. Change the value of A_{x, y} into 0. Determine the maximum total money that can be earned!InputThe first line contains three integers N, M, and K (1 \leq N \leq 10; 1 \leq M \leq 10^5; 1 \leq K \leq \min(10, M)) — the number of arrays, the size of each array, and the constant that describes the operation constraints.The i-th of the next N lines contains M integers A_{i,1}, A_{i,2}, \ldots, A_{i,M} (1 \leq A_{i,j} \leq 10^6) — the elements of the i-th array.OutputOutput an integer representing the maximum total money that can be earned.ExamplesInput 3 3 1 10 4 2 8 1 9 4 8 2 Output 27 Input 3 3 2 5 9 4 1 3 1 2 8 7 Output 17 Input 3 4 3 5 9 10 1 1 3 1 5 2 5 7 2 Output 19 NoteIn the first example, the following is a sequence of operations of one optimal strategy: Choosing element A_{1, 1} with a value of 10. Choosing element A_{3, 2} with a value of 8. Choosing element A_{2, 3} with a value of 9. So the total money earned is 10+8+9=27.In the second example, the following is a sequence of operations of one optimal strategy: Choosing element A_{3, 2} with a value of 8. Choosing element A_{1, 2} with a value of 9. So the total money earned is 8+9=17.In the third example, the following is a sequence of operations of one optimal strategy: Choosing element A_{1, 3} with a value of 10. Choosing element A_{1, 2} with a value of 9. So the total money earned is 10+9=19.
3 3 1 10 4 2 8 1 9 4 8 2
27
2 seconds
512 megabytes
['dp', 'greedy', '*2300']
C. Completely Searching for Inversionstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputPak Chanek has a directed acyclic graph (a directed graph that does not have any cycles) containing N vertices. Vertex i has S_i edges directed away from that vertex. The j-th edge of vertex i that is directed away from it, is directed towards vertex L_{i,j} and has an integer W_{i,j} (0\leq W_{i,j}\leq1). Another information about the graph is that the graph is shaped in such a way such that each vertex can be reached from vertex 1 via zero or more directed edges.Pak Chanek has an array Z that is initially empty.Pak Chanek defines the function dfs as follows:// dfs from vertex ivoid dfs(int i) { // iterate each edge of vertex i that is directed away from it for(int j = 1; j <= S[i]; j++) { Z.push_back(W[i][j]); // add the integer in the edge to the end of Z dfs(L[i][j]); // recurse to the next vertex }}Note that the function does not keep track of which vertices have been visited, so each vertex can be processed more than once.Let's say Pak Chanek does dfs(1) once. After that, Pak Chanek will get an array Z containing some elements 0 or 1. Define an inversion in array Z as a pair of indices (x, y) (x < y) such that Z_x > Z_y. How many different inversions in Z are there if Pak Chanek does dfs(1) once? Since the answer can be very big, output the answer modulo 998\,244\,353.InputThe first line contains a single integer N (2 \leq N \leq 10^5) — the number of vertices in the graph. The following lines contain the description of each vertex from vertex 1 to vertex N.The first line of each vertex i contains a single integer S_i (0 \leq S_i \leq N-1) — the number of edges directed away from vertex i.The j-th of the next S_i lines of each vertex i contains two integers L_{i,j} and W_{i,j} (1 \leq L_{i,j} \leq N; 0 \leq W_{i,j} \leq 1) — an edge directed away from vertex i that is directed towards vertex L_{i,j} and has an integer W_{i,j}. For each i, the values of L_{i,1}, L_{i,2}, ..., L_{i,S_i} are pairwise distinct. It is guaranteed that the sum of S_i over all vertices does not exceed 2 \cdot 10^5. There are no cycles in the graph. Each vertex can be reached from vertex 1 via zero or more directed edges.OutputAn integer representing the number of inversions in Z if Pak Chanek does dfs(1) once. Since the answer can be very big, output the answer modulo 998\,244\,353.ExampleInput 5 2 4 0 3 1 0 1 2 0 2 3 1 5 1 0 Output 4 NoteThe following is the dfs(1) process on the graph. In the end, Z=[0,1,0,1,1,0]. All of its inversions are (2,3), (2,6), (4,6), and (5,6).
5 2 4 0 3 1 0 1 2 0 2 3 1 5 1 0
4
2 seconds
512 megabytes
['dfs and similar', 'dp', 'graphs', '*1900']
B. Battling with Numberstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputOn the trip to campus during the mid semester exam period, Chaneka thinks of two positive integers X and Y. Since the two integers can be very big, both are represented using their prime factorisations, such that: X=A_1^{B_1}\times A_2^{B_2}\times\ldots\times A_N^{B_N} (each A_i is prime, each B_i is positive, and A_1<A_2<\ldots<A_N) Y=C_1^{D_1}\times C_2^{D_2}\times\ldots\times C_M^{D_M} (each C_j is prime, each D_j is positive, and C_1<C_2<\ldots<C_M) Chaneka ponders about these two integers for too long throughout the trip, so Chaneka's friend commands her "Gece, deh!" (move fast) in order to not be late for the exam.Because of that command, Chaneka comes up with a problem, how many pairs of positive integers p and q such that \text{LCM}(p, q) = X and \text{GCD}(p, q) = Y. Since the answer can be very big, output the answer modulo 998\,244\,353.Notes: \text{LCM}(p, q) is the smallest positive integer that is simultaneously divisible by p and q. \text{GCD}(p, q) is the biggest positive integer that simultaneously divides p and q. InputThe first line contains a single integer N (1 \leq N \leq 10^5) — the number of distinct primes in the prime factorisation of X.The second line contains N integers A_1, A_2, A_3, \ldots, A_N (2 \leq A_1 < A_2 < \ldots < A_N \leq 2 \cdot 10^6; each A_i is prime) — the primes in the prime factorisation of X.The third line contains N integers B_1, B_2, B_3, \ldots, B_N (1 \leq B_i \leq 10^5) — the exponents in the prime factorisation of X.The fourth line contains a single integer M (1 \leq M \leq 10^5) — the number of distinct primes in the prime factorisation of Y.The fifth line contains M integers C_1, C_2, C_3, \ldots, C_M (2 \leq C_1 < C_2 < \ldots < C_M \leq 2 \cdot 10^6; each C_j is prime) — the primes in the prime factorisation of Y.The sixth line contains M integers D_1, D_2, D_3, \ldots, D_M (1 \leq D_j \leq 10^5) — the exponents in the prime factorisation of Y.OutputAn integer representing the number of pairs of positive integers p and q such that \text{LCM}(p, q) = X and \text{GCD}(p, q) = Y, modulo 998\,244\,353.ExamplesInput 4 2 3 5 7 2 1 1 2 2 3 7 1 1 Output 8 Input 2 1299721 1999993 100000 265 2 1299721 1999993 100000 265 Output 1 Input 2 2 5 1 1 2 2 3 1 1 Output 0 NoteIn the first example, the integers are as follows: X=2^2\times3^1\times5^1\times7^2=2940 Y=3^1\times7^1=21 The following are all possible pairs of p and q: p=21, q=2940 p=84, q=735 p=105, q=588 p=147, q=420 p=420, q=147 p=588, q=105 p=735, q=84 p=2940, q=21 In the third example, the integers are as follows: X=2^1\times5^1=10 Y=2^1\times3^1=6 There is no pair p and q that simultaneously satisfies \text{LCM}(p,q)=10 and \text{GCD}(p,q)=6.
4 2 3 5 7 2 1 1 2 2 3 7 1 1
8
1 second
256 megabytes
['combinatorics', 'math', 'number theory', '*1400']
A. Ambitious Kidtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputChaneka, Pak Chanek's child, is an ambitious kid, so Pak Chanek gives her the following problem to test her ambition.Given an array of integers [A_1, A_2, A_3, \ldots, A_N]. In one operation, Chaneka can choose one element, then increase or decrease the element's value by 1. Chaneka can do that operation multiple times, even for different elements.What is the minimum number of operations that must be done to make it such that A_1 \times A_2 \times A_3 \times \ldots \times A_N = 0?InputThe first line contains a single integer N (1 \leq N \leq 10^5).The second line contains N integers A_1, A_2, A_3, \ldots, A_N (-10^5 \leq A_i \leq 10^5).OutputAn integer representing the minimum number of operations that must be done to make it such that A_1 \times A_2 \times A_3 \times \ldots \times A_N = 0.ExamplesInput 3 2 -6 5 Output 2 Input 1 -3 Output 3 Input 5 0 -1 0 1 0 Output 0 NoteIn the first example, initially, A_1\times A_2\times A_3=2\times(-6)\times5=-60. Chaneka can do the following sequence of operations: Decrease the value of A_1 by 1. Then, A_1\times A_2\times A_3=1\times(-6)\times5=-30 Decrease the value of A_1 by 1. Then, A_1\times A_2\times A_3=0\times(-6)\times5=0 In the third example, Chaneka does not have to do any operations, because from the start, it already holds that A_1\times A_2\times A_3\times A_4\times A_5=0\times(-1)\times0\times1\times0=0
3 2 -6 5
2
1 second
256 megabytes
['math', '*800']
I. Future Dominatorstime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDhruvil and amenotiomoi are sitting in different countries and chatting online. Initially, amenotiomoi has an empty board of size n \times n, and Dhruvil has a sequence of integers 1, 2, \ldots, n^2, each number occurring exactly once. The numbers may be placed in the cells of the board, each cell is either empty or contains exactly one number.The current state of the board is called good, if there is a way of placing the remaining numbers in empty cells so that all numbers except 1 have a neighbor with a smaller value. Two cells are neighbors if they share an edge.The rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. The cell at the intersection of the x-th row and the y-th column is denoted as (x, y).To chat, amenotiomoi asks q queries to Dhruvil. Each time he provides Dhruvil with an empty cell (x, y). Dhruvil has to place one of the remaining numbers in this cell so that the board is still good. Among all ways to do this, he chooses the largest possible number he can place and sends this number to amenotiomoi as the answer to the query.Since amenotiomoi knows the correct answer every time, he tells Dhruvil (x \oplus k,y \oplus k) instead of (x, y), where k is the answer for the previous query. If amenotiomoi is sending the first query, he considers k = 0. Each time Dhruvil has to decode the query and send the answer to amenotiomoi. Here \oplus denotes the bitwise XOR operation.Help Dhruvil reply to all amenotiomoi's queries.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains two integers n and q (1 \le n \le 10^3, 1 \le q \le n^2).The i-th of the following q lines contains two integers x_i' and y_i'. The corresponding cell is (x_i, y_i), where x_i'=x_i \oplus k and y_i' = y_i \oplus k, where k is the correct answer for the previous query. If i = 1, then k = 0 is used. It is guaranteed that 1 \le x_i, y_i \le n and that (x_i, y_i) is an empty cell at the moment of i-th query.It is guaranteed that the sum of n^2 over all test cases does not exceed 10^6.OutputFor each test case, output one line, containing the answers to all queries, separated by spaces.ExampleInput 32 41 16 63 01 23 92 18 114 44 42 04 411 101 33 21 11 1Output 4 2 3 1 9 7 6 3 5 8 2 1 4 1 NoteIn the first test case, the first query is (1, 1), Dhruvil puts 4 in that cell.The second query is (6, 6), Dhruvil decode it as (2, 2) using the previous answer (2 \oplus 4 = 6). If Dhruvil places 3 to the cell (2, 2), the board stops being good. So, Dhruvil places 2 in this cell.The third query is (3, 0), Dhruvil decodes it as (1, 2) using the previous answer (1 \oplus 2 = 3, 2 \oplus 2 = 0). Dhruvil can place 3 in this cell.The fourth query is (1, 2), Dhruvil decodes it as (2, 1) using the previous answer (2 \oplus 3 = 1, 1 \oplus 3 = 2). Now, only 1 remains in the sequence, and after Dhruvil places 1 in this cell, the board becomes full and remains good.Here you can see the entire history of the board: In the second test case, the final state of the board is: 875934126
32 41 16 63 01 23 92 18 114 44 42 04 411 101 33 21 11 1
4 2 3 1 9 7 6 3 5 8 2 1 4 1
4 seconds
256 megabytes
['graphs', 'greedy', '*3500']
H. Asterism Streamtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBogocubic is playing a game with amenotiomoi. First, Bogocubic fixed an integer n, and then he gave amenotiomoi an integer x which is initially equal to 1.In one move amenotiomoi performs one of the following operations with the same probability: increase x by 1; multiply x by 2. Bogocubic wants to find the expected number of moves amenotiomoi has to do to make x greater than or equal to n. Help him find this number modulo 998\,244\,353.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 y that 0 \le y < M and y \cdot q \equiv p \pmod{M}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The only line of each test case contains one integer n (1 \le n \le 10^{18}).OutputFor each test case, output a single integer — the expected number of moves modulo 998\,244\,353.ExampleInput 714815998244353296574916252563317494288321850420024Output 0 499122179 717488133 900515847 93715054 44488799 520723508 NoteIn the first test case, n\le x without any operations, so the answer is 0.In the second test case, for n = 4, here is the list of all possible sequences of operations and their probabilities: 1\stackrel{+1}{\longrightarrow}2\stackrel{+1}{\longrightarrow}3\stackrel{+1}{\longrightarrow}4, the probability is \frac{1}{8}; 1\stackrel{\times 2}{\longrightarrow}2\stackrel{+1}{\longrightarrow}3\stackrel{+1}{\longrightarrow}4, the probability is \frac{1}{8}; 1\stackrel{+1}{\longrightarrow}2\stackrel{+1}{\longrightarrow}3\stackrel{\times 2}{\longrightarrow}6, the probability is \frac{1}{8}; 1\stackrel{\times 2}{\longrightarrow}2\stackrel{+1}{\longrightarrow}3\stackrel{\times 2}{\longrightarrow}6, the probability is \frac{1}{8}; 1\stackrel{+1}{\longrightarrow}2\stackrel{\times 2}{\longrightarrow}4, the probability is \frac{1}{4}; 1\stackrel{\times 2}{\longrightarrow}2\stackrel{\times 2}{\longrightarrow}4, the probability is \frac{1}{4}. So the expected number of moves is 4 \cdot \left(3 \cdot \frac{1}{8}\right) + 2 \cdot \left(2 \cdot \frac{1}{4} \right) =\frac{5}{2} \equiv 499122179 \pmod{998244353}. In the third test case, for n = 8, the expected number of moves is \frac{137}{32}\equiv 717488133\pmod{998244353}. In the fourth test case, for n = 15, the expected number of moves is \frac{24977}{4096} \equiv 900515847 \pmod{998244353}.
714815998244353296574916252563317494288321850420024
0 499122179 717488133 900515847 93715054 44488799 520723508
3 seconds
256 megabytes
['dp', 'math', 'matrices', '*3200']
G. Magic Squaretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAquamoon has a Rubik's Square which can be seen as an n \times n matrix, the elements of the matrix constitute a permutation of numbers 1, \ldots, n^2.Aquamoon can perform two operations on the matrix: Row shift, i.e. shift an entire row of the matrix several positions (at least 1 and at most n-1) to the right. The elements that come out of the right border of the matrix are moved to the beginning of the row. For example, shifting a row \begin{pmatrix} a & b & c \end{pmatrix} by 2 positions would result in \begin{pmatrix} b & c & a \end{pmatrix}; Column shift, i.e. shift an entire column of the matrix several positions (at least 1 and at most n-1) downwards. The elements that come out of the lower border of the matrix are moved to the beginning of the column. For example, shifting a column \begin{pmatrix} a \\ b \\ c \end{pmatrix} by 2 positions would result in \begin{pmatrix} b\\c\\a \end{pmatrix}. The rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. The cell at the intersection of the x-th row and the y-th column is denoted as (x, y).Aquamoon can perform several (possibly, zero) operations, but she has to obey the following restrictions: each row and each column can be shifted at most once; each integer of the matrix can be moved at most twice; the offsets of any two integers moved twice cannot be the same. Formally, if integers a and b have been moved twice, assuming a has changed its position from (x_1,y_1) to (x_2,y_2), and b has changed its position from (x_3,y_3) to (x_4,y_4), then x_2-x_1 \not\equiv x_4-x_3 \pmod{n} or y_2-y_1 \not\equiv y_4-y_3 \pmod{n}.Aquamoon wonders in how many ways she can transform the Rubik's Square from the given initial state to a given target state. Two ways are considered different if the sequences of applied operations are different. Since the answer can be very large, print the result modulo 998\,244\,353.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 2\cdot 10^4). The description of the test cases follows.The first line of each test case contains an integer n (3\le n \le 500).The i-th of the following n lines contains n integers a_{i1}, \ldots, a_{in}, representing the i-th row of the initial matrix (1 \le a_{ij} \le n^2).The i-th of the following n lines contains n integers b_{i1}, \ldots, b_{in}, representing the i-th row of the target matrix (1 \le b_{ij} \le n^2).It is guaranteed that both the elements of the initial matrix and the elements of the target matrix constitute a permutation of numbers 1, \ldots, n^2.It is guaranteed that the sum of n^2 over all test cases does not exceed 250\,000.OutputFor each test case, if it is possible to convert the initial state to the target state respecting all the restrictions, output one integer — the number of ways to do so, modulo 998\,244\,353.If there is no solution, print a single integer 0.ExampleInput 431 2 34 5 67 8 97 2 31 4 56 8 931 2 34 5 67 8 93 2 16 5 49 7 831 2 34 5 67 8 97 8 12 3 45 6 931 2 34 5 67 8 93 8 45 1 97 6 2Output 1 0 0 4 NoteIn the first test case, the only way to transform the initial matrix to the target one is to shift the second row by 1 position to the right, and then shift the first column by 1 position downwards.In the second test case, it can be shown that there is no correct way to transform the matrix, thus, the answer is 0.
431 2 34 5 67 8 97 2 31 4 56 8 931 2 34 5 67 8 93 2 16 5 49 7 831 2 34 5 67 8 97 8 12 3 45 6 931 2 34 5 67 8 93 8 45 1 97 6 2
1 0 0 4
2 seconds
256 megabytes
['combinatorics', 'constructive algorithms', 'implementation', '*3100']
F. Exotic Queriestime limit per test4 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputAquaMoon gives RiverHamster a sequence of integers a_1,a_2,\dots,a_n, and RiverHamster gives you q queries. Each query is expressed by two integers l and r. For each query independently, you can take any continuous segment of the sequence and subtract an identical non-negative value from all the numbers of this segment. You can do so multiple (possibly, zero) times. However, you may not choose two intersecting segments which are not included in one another. Your goal is to convert to 0 all numbers whose initial value was within the range [l, r]. You must do so in the minimum number of operations.Please note that the queries are independent, the numbers in the array are restored to their initial values between the queries.Formally, for each query, you are to find the smallest m such that there exists a sequence \{(x_j,y_j,z_j)\}_{j=1}^{m} satisfying the following conditions: for any 1 \le j \leq m, z_j \ge 0 and 1 \le x_j \le y_j \leq n (here [x_j, y_j] correspond to the segment of the sequence); for any 1 \le j < k \le m, it is true that [x_j,y_j]\subseteq[x_{k},y_{k}], or [x_k,y_k]\subseteq[x_{j},y_{j}], or [x_j,y_j]\cap[x_{k},y_{k}]=\varnothing; for any 1 \le i \le n, such that l \le a_i \leq r, it is true that {\large a_i = \sum\limits_{\substack {1 \le j \le m \\ x_j \le i \le y_j}} z_j. } InputThe first line contains two integers n and q (1\le n,q\le 10^6).The second line contains n integers integers a_1, a_2, \ldots, a_n (1 \le a_i \le n).Each of the next q lines contains two integers l and r (1\le l\le r\le n), representing a query.OutputFor each query, output the answer for this query on a separate line.ExamplesInput 10 8 1 6 2 3 2 6 3 10 1 2 1 10 2 2 3 3 2 3 1 3 3 6 4 6 5 5 Output 8 1 1 3 5 3 1 0 Input 3 1 1 3 2 1 3 Output 3 NoteIn the first test case, consider the second query, when l = 2, r = 2. The elements to be manipulated are [a_3, a_5, a_{10}] = [2, 2, 2]. It is sufficient to apply the operation sequence \{(2, 10, 2)\}.Consider the fourth query, when l = 2, r = 3. The elements to be manipulated are [a_3, a_4, a_5, a_7, a_{10}] = [2, 3, 2, 3, 2]. It is sufficient to apply the operation sequence \{(1, 10, 2), (4, 4, 1), (7, 7, 1)\}.In the second test case, note that the operation sequence \{(1, 2, 1), (2, 3, 2)\} is invalid because the two segments intersect but neither is contained inside the other.
10 8 1 6 2 3 2 6 3 10 1 2 1 10 2 2 3 3 2 3 1 3 3 6 4 6 5 5
8 1 1 3 5 3 1 0
4 seconds
1024 megabytes
['data structures', 'implementation', 'sortings', '*2300']
E. Guess Gametime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputCarol has a sequence s of n non-negative integers. She wants to play the "Guess Game" with Alice and Bob.To play the game, Carol will randomly select two integer indices i_a and i_b within the range [1, n], and set a=s_{i_a}, b=s_{i_b}. Please note that i_a and i_b may coincide.Carol will tell: the value of a to Alice; the value of b to Bob; the value of a \mid b to both Alice and Bob, where | denotes the bitwise OR operation. Please note that Carol will not tell any information about s to either Alice or Bob.Then the guessing starts. The two players take turns making guesses, with Alice starting first. The goal of both players is to establish which of the following is true: a < b, a > b, or a = b.In their turn, a player can do one of the following two things: say "I don't know", and pass the turn to the other player; say "I know", followed by the answer "a<b", "a>b", or "a=b"; then the game ends. Alice and Bob hear what each other says, and can use this information to deduce the answer. Both Alice and Bob are smart enough and only say "I know" when they are completely sure.You need to calculate the expected value of the number of turns taken by players in the game. Output the answer modulo 998\,244\,353.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}.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each testcase contains a single integer n (1 \le n \le 2\cdot 10^5).The second line of each testcase contains n integers s_1,s_2,\ldots, s_n (0 \le s_i < 2^{30}).It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, print a single integer — the answer to the problem modulo 998\,244\,353.ExampleInput 422 330 0 039 9 6834124838 0 113193378 8 321939321 113193378 9463828 99Output 499122179 1 332748120 77987843 NoteIn the first test case, there are only 4 possible situations: i_a=1, i_b=1, a=2, b=2, the number of turns is 2; i_a=1, i_b=2, a=2, b=3, the number of turns is 3; i_a=2, i_b=1, a=3, b=2, the number of turns is 2; i_a=2, i_b=2, a=3, b=3, the number of turns is 3. The expected number of turns is \frac{2+3+2+3}{4}=\frac{5}{2}=499122179\pmod{998244353}.Consider the first case, when a=2, b=2. The guessing process is as follows.In the first turn, Alice thinks, "I know that a=2, a\mid b=2. I can infer that b=0 or b=2, but I am not sure which one". Thus, she says, "I don't know".In the second turn, Bob thinks, "I know that b=2, a\mid b=2. I can infer that a=0 or a=2. But if a=0, then Alice would have already said that a<b in the first turn, but she hasn't. So a=2". Thus, he says, "I know, a=b". The game ends. In the second test case, for a=0, b=0, Alice knows that a=b immediately. The expected number of turns equals 1.
422 330 0 039 9 6834124838 0 113193378 8 321939321 113193378 9463828 99
499122179 1 332748120 77987843
3 seconds
256 megabytes
['bitmasks', 'data structures', 'games', 'math', 'probabilities', 'sortings', 'strings', 'trees', '*2100']
D. Matrix Cascadetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere is a matrix of size n \times n which consists of 0s and 1s. The rows are numbered from 1 to n from top to bottom, the columns are numbered from 1 to n from left to right. The cell at the intersection of the x-th row and the y-th column is denoted as (x, y).AquaMoon wants to turn all elements of the matrix to 0s. In one step she can perform the following operation: Select an arbitrary cell, let it be (i, j), then invert the element in (i, j) and also invert all elements in cells (x, y) for x > i and x - i \ge \left|y - j\right|. To invert a value means to change it to the opposite: 0 changes to 1, 1 changes to 0. Help AquaMoon determine the minimum number of steps she need to perform to turn all elements of the matrix to 0s. We can show that an answer always exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains an integer n (2 \le n \le 3000).The i-th of the following n lines contains a binary string only of characters 0 and 1, of length n.It is guaranteed that the sum of n^2 over all test cases does not exceed 9\,000\,000.OutputFor each test case, print the minimum number of steps.ExampleInput 35001000111011111111111111131001101106010101111101011110000000111010001110Output 1 2 15 NoteIn the first test case, we can use the following scheme: perform the operation on the cell (1, 3). Clearly, the elements of the initial matrix are not all 0, so at least one operation is required. Thus, 1 is the answer.In the second test case, we use the following scheme: perform the operation on the cell (3, 3); perform the operation on the cell (1, 1). It can be shown that there is no way to convert all elements to 0s in 0 or 1 steps, so the answer is exactly 2.
35001000111011111111111111131001101106010101111101011110000000111010001110
1 2 15
2 seconds
512 megabytes
['brute force', 'constructive algorithms', 'data structures', 'dp', 'greedy', 'math', '*1700']
C. Divisor Chaintime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an integer x. Your task is to reduce x to 1.To do that, you can do the following operation: select a divisor d of x, then change x to x-d, i.e. reduce x by d. (We say that d is a divisor of x if d is an positive integer and there exists an integer q such that x = d \cdot q.) There is an additional constraint: you cannot select the same value of d more than twice.For example, for x=5, the following scheme is invalid because 1 is selected more than twice: 5\xrightarrow{-1}4\xrightarrow{-1}3\xrightarrow{-1}2\xrightarrow{-1}1. The following scheme is however a valid one: 5\xrightarrow{-1}4\xrightarrow{-2}2\xrightarrow{-1}1.Output any scheme which reduces x to 1 with at most 1000 operations. It can be proved that such a scheme always exists.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The only line of each test case contains a single integer x (2\le x \le 10^{9}).OutputFor each test case, output two lines.The first line should contain an integer k (1 \le k \le 1001).The next line should contain k integers a_1,a_2,\ldots,a_k, which satisfy the following: a_1=x; a_k=1; for each 2 \le i \le k, the value (a_{i-1}-a_i) is a divisor of a_{i-1}. Each number may occur as a divisor at most twice. ExampleInput 33514Output 3 3 2 1 4 5 4 2 1 6 14 12 6 3 2 1 NoteIn the first test case, we use the following scheme: 3\xrightarrow{-1}2\xrightarrow{-1}1.In the second test case, we use the following scheme: 5\xrightarrow{-1}4\xrightarrow{-2}2\xrightarrow{-1}1.In the third test case, we use the following scheme: 14\xrightarrow{-2}12\xrightarrow{-6}6\xrightarrow{-3}3\xrightarrow{-1}2\xrightarrow{-1}1.
33514
3 3 2 1 4 5 4 2 1 6 14 12 6 3 2 1
1 second
256 megabytes
['bitmasks', 'constructive algorithms', 'math', 'number theory', '*1300']
B. Swap and Reversetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string s of length n consisting of lowercase English letters, and an integer k. In one step you can perform any one of the two operations below: Pick an index i (1 \le i \le n - 2) and swap s_{i} and s_{i+2}. Pick an index i (1 \le i \le n-k+1) and reverse the order of letters formed by the range [i,i+k-1] of the string. Formally, if the string currently is equal to s_1\ldots s_{i-1}s_is_{i+1}\ldots s_{i+k-2}s_{i+k-1}s_{i+k}\ldots s_{n-1}s_n, change it to s_1\ldots s_{i-1}s_{i+k-1}s_{i+k-2}\ldots s_{i+1}s_is_{i+k}\ldots s_{n-1}s_n. You can make as many steps as you want (possibly, zero). Your task is to find the lexicographically smallest string you can obtain after some number of steps. A string a is lexicographically smaller than a string b of the same length if and only if the following holds: in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^4). The description of the test cases follows.The first line of each test case contains two integers n and k (1 \le k < n \le 10^5).The second line of each test case contains the string s of length n consisting of lowercase English letters.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print the lexicographically smallest string after doing some (possibly, zero) steps.ExampleInput 54 2nima5 3panda9 2theforces7 3amirfar6 4roundsOutput aimn aandp ceefhorst aafmirr dnorsu NoteIn the first test case, we can obtain the string "aimn" using the following operations: Reverse the range [3,4]. The string turns into "niam". Swap s_1 and s_3. The string turns into "ainm". Reverse the range [3,4]. The string turns into "aimn". It can be proven that we cannot obtain any string lexicographically smaller than "aimn". Therefore, "aimn" is the answer.In the second test case, we can obtain the string "aandp" using the following operations: Swap s_3 and s_5. The string turns into "paadn". Swap s_1 and s_3. The string turns into "aapdn". Swap s_3 and s_5. The string turns into "aandp". It can be proven that we cannot obtain any string lexicographically smaller than "aandp". Therefore, "aandp" is the answer.
54 2nima5 3panda9 2theforces7 3amirfar6 4rounds
aimn aandp ceefhorst aafmirr dnorsu
1 second
256 megabytes
['constructive algorithms', 'greedy', 'sortings', 'strings', '*1100']
A. Increasing and Decreasingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers x, y, and n.Your task is to construct an array a consisting of n integers which satisfies the following conditions: a_1=x, a_n=y; a is strictly increasing (i.e. a_1 < a_2 < \ldots < a_n); if we denote b_i=a_{i+1}-a_{i} for 1 \leq i \leq n-1, then b is strictly decreasing (i.e. b_1 > b_2 > \ldots > b_{n-1}). If there is no such array a, print a single integer -1.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The only line of each test case contains three integers x, y, n (1 \le x < y \le 1000,3 \le n \le 1000).OutputFor each test case, output n integers a_1,a_2,\ldots,a_n. If there are multiple solutions, print any of them.If there is no solution, print a single integer -1.ExampleInput 31 4 31 3 3100 200 4Output 1 3 4 -1 100 150 180 200 NoteIn the first test case, a=[1,3,4], which is strictly increasing. Next, b_1=a_2-a_1=3-1=2, b_2=a_3-a_2=4-3=1, thus b=[2,1], which is strictly decreasing.In the second test case, there is no array a that satisfies all the conditions above.
31 4 31 3 3100 200 4
1 3 4 -1 100 150 180 200
1 second
256 megabytes
['constructive algorithms', 'greedy', 'implementation', 'math', '*800']
I. Redundant Routestime limit per test5 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputYou are given a tree with n vertices labeled 1, 2, \ldots, n. The length of a simple path in the tree is the number of vertices in it.You are to select a set of simple paths of length at least 2 each, but you cannot simultaneously select two distinct paths contained one in another. Find the largest possible size of such a set.Formally, a set S of vertices is called a route if it contains at least two vertices and coincides with the set of vertices of a simple path in the tree. A collection of distinct routes is called a timetable. A route S in a timetable T is called redundant if there is a different route S' \in T such that S \subset S'. A timetable is called efficient if it contains no redundant routes. Find the largest possible number of routes in an efficient timetable.InputThe first line contains a single integer n (2 \le n \le 3000).The i-th of the following n - 1 lines contains two integers u_i and v_i (1 \le u_i, v_i \le n, u_i \neq v_i) — the numbers of vertices connected by the i-th edge.It is guaranteed that the given edges form a tree.OutputPrint a single integer — the answer to the problem.ExamplesInput 4 1 2 1 3 1 4 Output 3 Input 7 2 1 3 2 4 3 5 3 6 4 7 4 Output 7 NoteIn the first example, possible efficient timetables are \{\{1, 2\}, \{1, 3\}, \{1, 4\}\} and \{\{1, 2, 3\}, \{1, 2, 4\}, \{1, 3, 4\}\}.In the second example, we can choose \{ \{1, 2, 3\}, \{2, 3, 4\}, \{3, 4, 6\}, \{2, 3, 5\}, \{3, 4, 5\}, \{3, 4, 7\}, \{4, 6, 7\}\}.
4 1 2 1 3 1 4
3
5 seconds
1024 megabytes
['constructive algorithms', 'dp', 'trees', '*3500']
H. Goldberg Machine 3time limit per test8 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThere is a complete rooted binary tree, that is, a rooted tree in which each vertex has either 0 or 2 children. The root of the tree is vertex 1. A node without children is called a leaf. Each leaf has a hunger value, we denote the hunger value of leaf v by h_v.Each inner vertex of the tree has a selector pointing to one of the children of the vertex.This tree accepts cookies. Before launching the process you can choose the initial state of each selector individually. The process is as follows: Initially there are no cookies in vertices. You insert cookies into the root one by one. As long as the cookie is not in a leaf, it falls to the child defined by the selector in the current vertex. This selector then changes its state to the opposite one, i. e. it starts pointing to the other child of the vertex. You stop inserting cookies when each leaf v has at least h_v cookies in it. In this case, we say that the tree is filled up. You have q queries. Each query changes the value of h_v for some leaf v. You need to print q + 1 numbers, the i-th of them being the minimum number of cookies required to fill up the machine after (i - 1) updates if you can pick any initial state for every selector. Since these numbers may be very large, print the answers modulo 998\,244\,353.Please note that you can choose the initial state of all selectors independently between queries. However, the queries themselves are not independent: when answering the i-th query, you should also consider the effect of queries 1, 2, \ldots, i - 1.InputThe first line contains a single integer n (1\le n < 200\,000) — the number of vertices in the tree.The second line contains n - 1 integers p_2, p_3, \ldots, p_n (1\le p_i < i), meaning that the parent of vertex i is p_i.The third line contains n integers h_1, h_2, \ldots, h_n (0\le h_i\le 10^9) — the hunger values of vertices. If vertex i is not a leaf, then h_i = 0 and this value is irrelevant. However, h_i = 0 may also hold if i is a leaf.The fourth line contains a single integer q (0\le q\le 200\,000) — the number of queries.Each of the next q lines contains two integers v and x (1\le v\le n, 0\le x\le 10^9), meaning that the hunger value of vertex v is set to x.It is guaranteed that the tree in the input is a full binary tree rooted at vertex 1. It is also guaranteed that in each query v is a leaf.OutputOutput q + 1 integers, i-th of them being the minimum number of cookies needed to fill up the machine after (i - 1) updates, modulo 998\,244\,353.ExampleInput 5 1 1 2 2 0 0 0 0 0 5 3 1 4 1 5 1 3 4 4 1000000000 Output 0 1 2 3 7 7022585 NoteConsider the example. Before any queries are made, no cookies need to be inserted, since all hunger values of zero are trivially satisfied.After the first query, we can choose the selector in vertex 1 pointing to vertex 3. Then one cookie will immediately descend to 3.After the second query, we choose the selector in vertex 1 pointing to vertex 3 and the selector in vertex 2 pointing to vertex 4. The first cookie will drop down to 3 and change the state of the selector in vertex 1: now it is pointing to 2. The second cookie will go via the path 1 \to 2 \to 4.After the third query, we choose the selector in vertex 1 pointing to vertex 2 and the selector in vertex 2 pointing to vertex 4. Then the three cookies will descend via the paths 1 \to 2 \to 4, 1 \to 3, 1 \to 2 \to 5.After the fourth query, we choose the selector in vertex 1 pointing to vertex 3. Regardless of the initial state of the selector in vertex 2, after seven cookies are inserted, four of them will be in leaf 3, and one or two cookies will be in each of the leaves 4 and 5 (note that exceeding the hunger value is allowed).The answer after the fifth query is 3\,999\,999\,997. Do not forget to print the answer modulo 998\,244\,353.
5 1 1 2 2 0 0 0 0 0 5 3 1 4 1 5 1 3 4 4 1000000000
0 1 2 3 7 7022585
8 seconds
1024 megabytes
['dp', 'trees', '*3500']
G. Swapstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a_1, a_2, \dots, a_n (1 \le a_i \le n). You can perform the following operation several (possibly, zero) times: pick an arbitrary i and perform swap(a_i, a_{a_i}). How many distinct arrays is it possible to attain? Output the answer modulo (10^9 + 7).InputThe first line contains an integer n (1 \le n \le 10^6).The second line contains n integers a_1, a_2, \dots, a_n (1\le a_i\le n).OutputOutput the number of attainable arrays modulo (10^9 + 7).ExamplesInput 31 1 2Output 2 Input 42 1 4 3Output 4 Input 62 3 1 1 1 2Output 18 NoteIn the first example, the initial array is [1, 1, 2]. If we perform the operation with i = 3, we swap a_3 and a_2, obtaining [1, 2, 1]. One can show that there are no other attainable arrays.In the second example, the four attainable arrays are [2, 1, 4, 3], [1, 2, 4, 3], [1, 2, 3, 4], [2, 1, 3, 4]. One can show that there are no other attainable arrays.
31 1 2
2
2 seconds
256 megabytes
['combinatorics', 'dp', 'graphs', 'math', '*2800']
F. Divide, XOR, and Conquertime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of n integers a_1, a_2, \ldots, a_n.In one operation you split the array into two parts: a non-empty prefix and a non-empty suffix. The value of each part is the bitwise XOR of all elements in it. Next, discard the part with the smaller value. If both parts have equal values, you can choose which one to discard. Replace the array with the remaining part.The operations are being performed until the length of the array becomes 1. For each i (1 \le i \le n), determine whether it is possible to achieve the state when only the i-th element (with respect to the original numbering) remains.Formally, you have two numbers l and r, initially l = 1 and r = n. The current state of the array is [a_l, a_{l+1}, \ldots, a_r].As long as l < r, you apply the following operation: Choose an arbitrary k from the set \{l, l + 1, \ldots, r - 1\}. Denote x = a_l \oplus a_{l + 1} \oplus \ldots \oplus a_k and y = a_{k + 1} \oplus a_{k + 2} \oplus \ldots \oplus a_{r}, where \oplus denotes the bitwise XOR operation. If x < y, set l = k + 1. If x > y, set r = k. If x = y, either set l = k + 1, or set r = k. For each i (1 \le i \le n), determine whether it is possible to achieve l = r = i.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). The description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 10\,000).The second line of each test case contains n integers a_1, a_2, \ldots, a_n (0 \le a_i < 2^{60}).It is guaranteed that the sum of n over all test cases does not exceed 10\,000.OutputFor each test case, output a single string of length n where the i-th element is equal to 1 if it is possible to achieve l = r = i and is equal to 0 otherwise.ExampleInput 663 2 1 3 7 451 1 1 1 1101 2 4 8 4 1 2 3 4 550 0 0 0 051 2 3 0 11100500Output 111111 10101 0001000000 11111 11001 1 NoteIn the first test case, it is possible to achieve l = r = i for any i from 1 to n: for i=1: [1; 6] \rightarrow [1; 4] \rightarrow [1; 1]; for i=2: [1; 6] \rightarrow [1; 3] \rightarrow [2; 3] \rightarrow [2; 2]; for i=3: [1; 6] \rightarrow [1; 3] \rightarrow [3; 3]; for i=4: [1; 6] \rightarrow [1; 4] \rightarrow [4; 4]; for i=5: [1; 6] \rightarrow [5; 6] \rightarrow [5; 5]; for i=6: [1; 6] \rightarrow [6; 6]. Let's take a closer look at i = 2. Initially l = 1, r = 6. We can choose k = 3 and set r = k = 3 since (3 \oplus 2 \oplus 1) = 0 \ge 0 = (3 \oplus 7 \oplus 4); Next, we can choose k = 1 and set l = k + 1 = 2 since 3 \le 3 = (2 \oplus 1); Finally, we can choose k = 2 and set r = k = 2 since 2 \ge 1.
663 2 1 3 7 451 1 1 1 1101 2 4 8 4 1 2 3 4 550 0 0 0 051 2 3 0 11100500
111111 10101 0001000000 11111 11001 1
2 seconds
256 megabytes
['bitmasks', 'dp', 'math', '*2600']
E. Speedruntime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are playing a video game. The game has n quests that need to be completed. However, the j-th quest can only be completed at the beginning of hour h_j of a game day. The game day is k hours long. The hours of each game day are numbered 0, 1, \ldots, k - 1. After the first day ends, a new one starts, and so on.Also, there are dependencies between the quests, that is, for some pairs (a_i, b_i) the b_i-th quest can only be completed after the a_i-th quest. It is guaranteed that there are no circular dependencies, as otherwise the game would be unbeatable and nobody would play it.You are skilled enough to complete any number of quests in a negligible amount of time (i. e. you can complete any number of quests at the beginning of the same hour, even if there are dependencies between them). You want to complete all quests as fast as possible. To do this, you can complete the quests in any valid order. The completion time is equal to the difference between the time of completing the last quest and the time of completing the first quest in this order.Find the least amount of time you need to complete the game.InputEach test contains multiple test cases. The first line contains the number of test cases t (1\le t\le 100\,000). The description of the test cases follows.The first line of each test case contains three integers n, m, and k (1\le n\le 200\,000, 0\le m\le 200\,000, 1\le k\le 10^9) — the number of quests, the number of dependencies between them, and the number of hours in a game day, respectively.The next line contains n integers h_1, h_2, \ldots, h_n (0\le h_i < k).The next m lines describe the dependencies. The i-th of these lines contains two integers a_i and b_i (1\le a_i < b_i\le n) meaning that quest b_i can only be completed after quest a_i. It is guaranteed that all dependencies are pairwise distinct.It is guaranteed that the sum of n over all test cases does not exceed 200\,000.It is guaranteed that the sum of m over all test cases does not exceed 200\,000.OutputFor each test case, output a single integer — the minimum completion time.ExampleInput 64 4 2412 16 18 121 21 32 43 44 3 102 6 5 91 42 43 42 1 105 51 25 0 10008 800 555 35 355 0 103 2 5 4 73 2 54 3 21 22 3Output 24 7 0 480 5 8 NoteIn the first test case, quests 1 and 4 must be completed at the beginning of the 12-th hour of the day, but they cannot be completed during the same hour, because you also need to complete quests 2 and 3 between them. You can do all this in 24 hours, though. To do so, you start at 12 hours of the first game day by completing the first quest. At 16 hours you complete quest 2. At 18 hours you complete quest 3. Finally at 12 hours of the second day you can complete quest 4. The total time elapsed (from the moment you completed the first quest and the moment you completed the last) is 24 hours.In the third test case, you can complete the first quest and then complete the remaining quest right after. You start at 5 hours of the first day by completing the first quest. After this the second quest becomes available, you complete it as well. The total time elapsed is 0.In the fourth test case, you can start with the third quest. You start at 555 hours of the first day and you can finish at 35 hours of the second day. The total time elapsed is 1035-555=480.
64 4 2412 16 18 121 21 32 43 44 3 102 6 5 91 42 43 42 1 105 51 25 0 10008 800 555 35 355 0 103 2 5 4 73 2 54 3 21 22 3
24 7 0 480 5 8
2 seconds
256 megabytes
['brute force', 'dfs and similar', 'dp', 'graphs', 'greedy', 'math', 'sortings', 'two pointers', '*2100']
D. Two-Colored Dominoestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is an n\times m board divided into cells. There are also some dominoes on this board. Each domino covers two adjacent cells (that is, two cells that share a side), and no two dominoes overlap.Piet thinks that this board is too boring and it needs to be painted. He will paint the cells of the dominoes black and white. He calls the painting beautiful if all of the following conditions hold: for each domino, one of its cells is painted white and the other is painted black; for each row, the number of black cells in this row equals the number of white cells in this row; for each column, the number of black cells in this column equals the number of white cells in this column. Note that the cells that are not covered by dominoes are not painted at all, they are counted as neither black nor white.Help Piet produce a beautiful painting or tell that it is impossible.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10\,000). The description of the test cases follows.The first line of each test case contains two integers n and m (2\le n, m\le 500).The next n lines describe the tiling of the board, row by row from top to bottom. Each of these lines contains m characters, describing the cells in the corresponding row from left to right. Each character is one of U, D, L, R, or ., meaning that the cell is covered with a top, bottom, left, right half of a domino or nothing, respectively. The tiling is guaranteed to be valid.It is guaranteed that the sum of n \cdot m over all test cases does not exceed 250\,000.OutputFor each test case, output a single integer -1 if a beautiful painting does not exist. Otherwise, print n lines, each containing m characters, describing the colors in the corresponding row of a beautiful painting. Every character corresponding to a cell not covered by a domino must be . (a dot), and all other characters must be B if the corresponding cell is black or W if it is white.If there are multiple solutions, print any of them.ExampleInput 34 6..LR..ULRU..DLRDUU..LRDD5 4.LR..UU.UDDUD..DLR..2 2....Output ..WB.. WWBB.. BBWWWB ..BWBW -1 .. .. NoteIn the first test case, the answer is illustrated below: In the second test case, it is impossible to paint all cells the right way.
34 6..LR..ULRU..DLRDUU..LRDD5 4.LR..UU.UDDUD..DLR..2 2....
..WB.. WWBB.. BBWWWB ..BWBW -1 .. ..
1 second
256 megabytes
['constructive algorithms', 'greedy', '*1400']
C. MEX Repetitiontime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a_1,a_2,\ldots, a_n of pairwise distinct integers from 0 to n. Consider the following operation: consecutively for each i from 1 to n in this order, replace a_i with \operatorname{MEX}(a_1, a_2, \ldots, a_n). Here \operatorname{MEX} of a collection of integers c_1, c_2, \ldots, c_m is defined as the smallest non-negative integer x which does not occur in the collection c. For example, \operatorname{MEX}(0, 2, 2, 1, 4) = 3 and \operatorname{MEX}(1, 2) = 0.Print the array after applying k such operations.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 10^5). The description of the test cases follows.The first line of each test case contains two integers n and k (1\le n\le 10^5, 1\le k\le 10^9).The second line contains n pairwise distinct integers a_1,a_2,\ldots, a_n (0\le a_i\le n) representing the elements of the array before applying the operations.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, print all n elements of the array after applying k operations.ExampleInput 51 213 10 1 32 20 25 51 2 3 4 510 1005 3 0 4 2 1 6 9 10 8Output 1 2 0 1 2 1 2 3 4 5 0 7 5 3 0 4 2 1 6 9 10 NoteIn the first test case, here is the entire process: On the first operation, the array changes from [1] to [0], since \operatorname{MEX}(1) = 0. On the second operation, the array changes from [0] to [1], since \operatorname{MEX}(0) = 1. Thus, the array becomes [1] after two operations.In the second test case, the array changes as follows during one operation: [{\mkern3mu\underline{\mkern-3mu {\bf 0}\mkern-3mu}\mkern3mu}, 1, 3] \rightarrow [2, {\mkern3mu\underline{\mkern-3mu {\bf 1}\mkern-3mu}\mkern3mu}, 3] \rightarrow [2, 0, {\mkern3mu\underline{\mkern-3mu {\bf 3}\mkern-3mu}\mkern3mu}] \rightarrow [2, 0, 1].In the third test case, the array changes as follows during one operation: [{\mkern3mu\underline{\mkern-3mu {\bf 0}\mkern-3mu}\mkern3mu}, 2] \rightarrow [1, {\mkern3mu\underline{\mkern-3mu {\bf 2}\mkern-3mu}\mkern3mu}] \rightarrow [1, 0]. And during the second operation: [{\mkern3mu\underline{\mkern-3mu {\bf 1}\mkern-3mu}\mkern3mu}, 0] \rightarrow [2, {\mkern3mu\underline{\mkern-3mu {\bf 0}\mkern-3mu}\mkern3mu}] \rightarrow [2, 1].
51 213 10 1 32 20 25 51 2 3 4 510 1005 3 0 4 2 1 6 9 10 8
1 2 0 1 2 1 2 3 4 5 0 7 5 3 0 4 2 1 6 9 10
2 seconds
256 megabytes
['implementation', 'math', '*1100']
B. Split Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation^{\dagger} p_1, p_2, \ldots, p_n of integers 1 to n.You can change the current permutation by applying the following operation several (possibly, zero) times: choose some x (2 \le x \le n); create a new permutation by: first, writing down all elements of p that are less than x, without changing their order; second, writing down all elements of p that are greater than or equal to x, without changing their order; replace p with the newly created permutation. For example, if the permutation used to be [6, 4, 3, 5, 2, 1] and you choose x = 4, then you will first write down [3, 2, 1], then append this with [6, 4, 5]. So the initial permutation will be replaced by [3, 2, 1, 6, 4, 5].Find the minimum number of operations you need to achieve p_i = i for i = 1, 2, \ldots, n. We can show 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).InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line of each test case contains one integer n (1 \le n \le 100\,000).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_1, p_2, \ldots, p_n is a permutation.It is guaranteed that the sum of n over all test cases does not exceed 100\,000.OutputFor each test case, output the answer on a separate line.ExampleInput 51122 166 4 3 5 2 133 1 21910 19 7 1 17 11 8 5 12 9 4 18 14 2 6 15 3 16 13Output 0 1 4 1 7 NoteIn the first test case, n = 1 and p_1 = 1, so there is nothing left to do.In the second test case, we can choose x = 2 and we immediately obtain p_1 = 1, p_2 = 2.In the third test case, we can achieve the minimum number of operations in the following way: x = 4: [6, 4, 3, 5, 2, 1] \rightarrow [3, 2, 1, 6, 4, 5]; x = 6: [3, 2, 1, 6, 4, 5] \rightarrow [3, 2, 1, 4, 5, 6]; x = 3: [3, 2, 1, 4, 5, 6] \rightarrow [2, 1, 3, 4, 5, 6]; x = 2: [2, 1, 3, 4, 5, 6] \rightarrow [1, 2, 3, 4, 5, 6].
51122 166 4 3 5 2 133 1 21910 19 7 1 17 11 8 5 12 9 4 18 14 2 6 15 3 16 13
0 1 4 1 7
1 second
256 megabytes
['greedy', 'math', 'sortings', '*1100']
A. Channeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPetya is an administrator of a channel in one of the messengers. A total of n people are subscribed to his channel, and Petya is not considered a subscriber.Petya has published a new post on the channel. At the moment of the publication, there were a subscribers online. We assume that every subscriber always reads all posts in the channel if they are online.After this, Petya starts monitoring the number of subscribers online. He consecutively receives q notifications of the form "a subscriber went offline" or "a subscriber went online". Petya does not know which exact subscriber goes online or offline. It is guaranteed that such a sequence of notifications could have indeed been received.Petya wonders if all of his subscribers have read the new post. Help him by determining one of the following: it is impossible that all n subscribers have read the post; it is possible that all n subscribers have read the post; it is guaranteed that all n subscribers have read the post. InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line of each test case contains three integers n, a, and q (1 \le n \le 100, 0 \le a \le n, 1 \le q \le 100) — the number of subscribers of the channel, the initial number of subscribers online, and the number of notifications.The second line of each test case contains a string of length q, consisting of characters '+' and '-'. The i-th of these characters is '+', if the i-th notification tells that a subscriber goes online, and it is '-' otherwise.OutputFor each test case, output a single line: "YES" if all n subscribers are guaranteed to have read the post, "NO" if it is impossible for all n subscribers to have read the post, and "MAYBE" otherwise.ExampleInput 45 5 3--+5 2 3++-5 4 2-+5 0 7++++-++Output YES NO MAYBE YES NoteIn the first test case, there are 5 out of 5 subscribers online in the very beginning, so they will all read the post no matter what. The answer is "YES".In the second test case, the number of subscribers online becomes 4 after the first two notifications, next someone goes offline, and thus the fifth subscriber has no chance of reading the post. It is impossible for all the subscribers to read the post, so the answer is "NO".In the third test case, on the one hand, the same person may have gone offline and online (in this case only 4 out of 5 subscribers have read the post), on the other hand, the last notification may have told that the fifth subscriber has gone online (in this case all subscribers have read the post). We cannot deduce which of the two holds, so the answer is "MAYBE".In the fourth test case, there have to be five subscribers online after all the notifications. All of them will read the post, so the answer is "YES".
45 5 3--+5 2 3++-5 4 2-+5 0 7++++-++
YES NO MAYBE YES
1 second
256 megabytes
['greedy', 'implementation', '*800']
G. The Great Equalizertime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTema bought an old device with a small screen and a worn-out inscription "The Great Equalizer" on the side.The seller said that the device needs to be given an array a of integers as input, after which "The Great Equalizer" will work as follows: Sort the current array in non-decreasing order and remove duplicate elements leaving only one occurrence of each element. If the current length of the array is equal to 1, the device stops working and outputs the single number in the array — output value of the device. Add an arithmetic progression {n,\ n - 1,\ n - 2,\ \ldots,\ 1} to the current array, where n is the length of the current array. In other words, n - i is added to the i-th element of the array, when indexed from zero. Go to the first step. To test the operation of the device, Tema came up with a certain array of integers a, and then wanted to perform q operations on the array a of the following type: Assign the value x (1 \le x \le 10^9) to the element a_i (1 \le i \le n). Give the array a as input to the device and find out the result of the device's operation, while the array a remains unchanged during the operation of the device. Help Tema find out the output values of the device after each operation.InputThe first line of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases.Then follows the description of each test case.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the size of the array a that Tema initially came up with.The second line of each test case contains n integers a_1, a_2, a_3, \ldots, a_n (1 \le a_i \le 10^9) — the elements of the array a.The third line of a set contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of operations.Each of the next q lines of a test case contains two integers i (1 \le i \le n) and x (1 \le x \le 10^9) - the descriptions of the operations.It is guaranteed that the sum of the values of n and the sum of the values of q for all test cases do not exceed 2 \cdot 10^5.OutputFor each test case, output q integers — the output values of the device after each operation.ExampleInput 432 4 831 62 103 151 2 2 2 215 325 671 21 71 72 51 22 72 252 5 1 10 6101 74 82 51 42 83 41 93 73 43 1Output 10 12 15 4 10 8 8 9 8 12 2 14 12 12 11 11 10 11 10 11 14 NoteLet's consider the first example of the input.Initially, the array of numbers given as input to the device will be [6, 4, 8]. It will change as follows: [6, 4, 8] \rightarrow [4, 6, 8] \rightarrow [7, 8, 9] \rightarrow [10, 10, 10] \rightarrow [10]Then, the array of numbers given as input to the device will be [6, 10, 8]. It will change as follows: [6, 10, 8] \rightarrow [6, 8, 10] \rightarrow [9, 10, 11] \rightarrow [12, 12, 12] \rightarrow [12]The last array of numbers given as input to the device will be [6, 10, 1]. It will change as follows: [6, 10, 1] \rightarrow [1, 6, 10] \rightarrow [4, 8, 11] \rightarrow [7, 10, 12] \rightarrow [10, 12, 13] \rightarrow [13, 14, 14] \rightarrow [13, 14] \rightarrow [15, 15] \rightarrow [15]
432 4 831 62 103 151 2 2 2 215 325 671 21 71 72 51 22 72 252 5 1 10 6101 74 82 51 42 83 41 93 73 43 1
10 12 15 4 10 8 8 9 8 12 2 14 12 12 11 11 10 11 10 11 14
4 seconds
256 megabytes
['binary search', 'data structures', 'math', 'sortings', '*2000']
F. Magic Will Save the Worldtime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA portal of dark forces has opened at the border of worlds, and now the whole world is under a terrible threat. To close the portal and save the world, you need to defeat n monsters that emerge from the portal one after another.Only the sorceress Vika can handle this. She possesses two magical powers — water magic and fire magic. In one second, Vika can generate w units of water mana and f units of fire mana. She will need mana to cast spells. Initially Vika have 0 units of water mana and 0 units of fire mana.Each of the n monsters that emerge from the portal has its own strength, expressed as a positive integer. To defeat the i-th monster with strength s_i, Vika needs to cast a water spell or a fire spell of at least the same strength. In other words, Vika can spend at least s_i units of water mana on a water spell, or at least s_i units of fire mana on a fire spell.Vika can create and cast spells instantly. Vika can cast an unlimited number of spells every second as long she has enough mana for that.The sorceress wants to save the world as quickly as possible, so tell her how much time she will need.InputEach test consists of several test cases. The first line of each test contains a single integer t (1 \le t \le 100) — the number of test cases. This is followed by a description of the test cases.The first line of each test case contains two integers w, f (1 \le w, f \le 10^9) — the amount of water and fire mana that Vika can generate per second.The second line of each test case contains a single integer n (1 \le n \le 100) — the number of monsters.The third line of each test case contains n integers s_1, s_2, s_3, \dots, s_n (1 \le s_i \le 10^4) — the strengths of the monsters.It is guaranteed that the sum of n over all test cases does not exceed 100.OutputFor each test case, output a single integer — the minimum time in seconds that Vika will need to defeat all the monsters.ExampleInput 42 332 6 737 58193190 90223 9713 4410 10 2 45Output 3 2 1 5 NoteIn the first sample, after the first second, Vika can spend 2 units of fire mana to kill the first monster. Then she has 2 units of water mana and 1 unit of fire mana. After the third second, she will have 6 units of water mana and 7 units of fire mana at her disposal. This will be enough to immediately kill the second and third monsters.
42 332 6 737 58193190 90223 9713 4410 10 2 45
3 2 1 5
4 seconds
256 megabytes
['binary search', 'bitmasks', 'brute force', 'dp', '*1800']
E. Kolya and Movie Theatretime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Kolya found out that a new movie theatre is going to be opened in his city soon, which will show a new movie every day for n days. So, on the day with the number 1 \le i \le n, the movie theatre will show the premiere of the i-th movie. Also, Kolya found out the schedule of the movies and assigned the entertainment value to each movie, denoted by a_i.However, the longer Kolya stays without visiting a movie theatre, the larger the decrease in entertainment value of the next movie. That decrease is equivalent to d \cdot cnt, where d is a predetermined value and cnt is the number of days since the last visit to the movie theatre. It is also known that Kolya managed to visit another movie theatre a day before the new one opened — the day with the number 0. So if we visit the movie theatre the first time on the day with the number i, then cnt — the number of days since the last visit to the movie theatre will be equal to i.For example, if d = 2 and a = [3, 2, 5, 4, 6], then by visiting movies with indices 1 and 3, cnt value for the day 1 will be equal to 1 - 0 = 1 and cnt value for the day 3 will be 3 - 1 = 2, so the total entertainment value of the movies will be a_1 - d \cdot 1 + a_3 - d \cdot 2 = 3 - 2 \cdot 1 + 5 - 2 \cdot 2 = 2.Unfortunately, Kolya only has time to visit at most m movies. Help him create a plan to visit the cinema in such a way that the total entertainment value of all the movies he visits is maximized.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains three integers n, m, and d (1 \le n \le 2 \cdot 10^5, 1 \le m \le n, 1 \le d \le 10^9).The second line of each set of input data contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the entertainment values of the movies.It is guaranteed that the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single integer — the maximum total entertainment value that Kolya can get.ExampleInput 65 2 23 2 5 4 64 3 21 1 1 16 6 6-82 45 1 -77 39 115 2 23 2 5 4 82 1 1-1 26 3 2-8 8 -2 -1 9 0Output 2 0 60 3 0 7 NoteThe first test case is explained in the problem statement.In the second test case, it is optimal not to visit any movies.In the third test case, it is optimal to visit movies with numbers 2, 3, 5, 6, so the total entertainment value of the visited movies will be 45 - 6 \cdot 2 + 1 - 6 \cdot 1 + 39 - 6 \cdot 2 + 11 - 6 \cdot 1 = 60.
65 2 23 2 5 4 64 3 21 1 1 16 6 6-82 45 1 -77 39 115 2 23 2 5 4 82 1 1-1 26 3 2-8 8 -2 -1 9 0
2 0 60 3 0 7
2 seconds
256 megabytes
['constructive algorithms', 'data structures', 'greedy', '*1600']
D. Ice Cream Ballstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTema decided to improve his ice cream making skills. He has already learned how to make ice cream in a cone using exactly two balls.Before his ice cream obsession, Tema was interested in mathematics. Therefore, he is curious about the minimum number of balls he needs to have in order to make exactly n different types of ice cream.There are plenty possible ice cream flavours: 1, 2, 3, \dots. Tema can make two-balls ice cream with any flavours (probably the same).Two ice creams are considered different if their sets of ball flavours are different. For example, \{1, 2\} = \{2, 1\}, but \{1, 1\} \neq \{1, 2\}.For example, having the following ice cream balls: \{1, 1, 2\}, Tema can make only two types of ice cream: \{1, 1\} and \{1, 2\}.Note, that Tema do not need to make all the ice cream cones at the same time. This means that he making ice cream cones independently. Also in order to make a following cone \{x, x\} for some x, Tema needs at least 2 balls of type x.Help Tema answer this question. It can be shown that answer always exist.InputEach test consists of multiple test cases. The first line of input contains a single integer t (1 \le t \le 10^4) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains a single integer n (1 \le n \le 10^{18}) — the number of ice cream types that Tema wants to make.OutputFor each test case, output a single integer — the minimum number of balls Tema needs to buy.ExampleInput 51361791000000000000000000Output 2 3 4 27 2648956421 NoteIn the first sample, it is enough to have following balls types: \{1, 1\}. Note, that set \{1\} if not enough since we need at least 2 balls of a type 1 in order to make such cone \{1, 1\}.In the second sample, it is not possible to make it with 2 balls, but it can be done with these balls: \{1, 2, 3\}.In the third sample, \{1, 2, 3, 4\} is optimal answer, so we can get following ice cream cones: \{1, 2\}, \{1, 3\}, \{1, 4\}, \{2, 3\}, \{2, 4\}, \{3, 4\}.
51361791000000000000000000
2 3 4 27 2648956421
1 second
256 megabytes
['binary search', 'combinatorics', 'constructive algorithms', 'math', '*1300']
C. Flower City Fencetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnya lives in the Flower City. By order of the city mayor, she has to build a fence for herself.The fence consists of n planks, each with a height of a_i meters. According to the order, the heights of the planks must not increase. In other words, it is true that a_i \ge a_j for all i < j.Anya became curious whether her fence is symmetrical with respect to the diagonal. In other words, will she get the same fence if she lays all the planks horizontally in the same order.For example, for n = 5, a = [5, 4, 3, 2, 1], the fence is symmetrical. Because if all the planks are laid horizontally, the fence will be [5, 4, 3, 2, 1], as shown in the diagram. On the left is the fence [5, 4, 3, 2, 1], on the right is the same fence laid horizontally But for n = 3, a = [4, 2, 1], the fence is not symmetrical. Because if all the planks are laid horizontally, the fence will be [3, 2, 1, 1], as shown in the diagram. On the left is the fence [4, 2, 1], on the right is the same fence laid horizontally Help Anya and determine whether her fence is symmetrical.InputThe first line of the input contains an integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of a test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the fence.The second line of a test case contains n integers a_1 \ge a_2 \ge a_3 \ge \dots \ge a_n (1 \le a_i \le 10^9) — the heights of the planks.The sum of the values of n for all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output "YES" if the fence is symmetrical, otherwise output "NO".You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes" and "YES" will be accepted as a positive answer.ExampleInput 755 4 3 2 133 1 134 2 11255 3 3 1 155 5 5 3 326 1Output YES YES NO NO YES YES NO NoteIn the first and second test cases of the example, the fence is symmetrical.In the third test case of the example, the fence is not symmetrical. If the planks are laid horizontally, the fence will be [3, 2, 1, 1].In the fourth test case of the example, the fence is not symmetrical. If the planks are laid horizontally, the fence will be [1, 1].In the fifth and sixth test cases of the example, the fence is symmetrical.In the seventh test case of the example, the fence is not symmetrical. If the planks are laid horizontally, the fence will be [2, 1, 1, 1, 1, 1].
755 4 3 2 133 1 134 2 11255 3 3 1 155 5 5 3 326 1
YES YES NO NO YES YES NO
2 seconds
256 megabytes
['binary search', 'data structures', 'implementation', 'sortings', '*1100']
B. Sequence Gametime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTema and Vika are playing the following game.First, Vika comes up with a sequence of positive integers a of length m and writes it down on a piece of paper. Then she takes a new piece of paper and writes down the sequence b according to the following rule: First, she writes down a_1. Then, she writes down only those a_i (2 \le i \le m) such that a_{i - 1} \le a_i. Let the length of this sequence be denoted as n. For example, from the sequence a=[4, 3, 2, 6, 3, 3], Vika will obtain the sequence b=[4, 6, 3].She then gives the piece of paper with the sequence b to Tema. He, in turn, tries to guess the sequence a.Tema considers winning in such a game highly unlikely, but still wants to find at least one sequence a that could have been originally chosen by Vika. Help him and output any such sequence.Note that the length of the sequence you output should not exceed the input sequence length by more than two times.InputEach test consists of multiple test cases. The first line of input data contains a single integer t (1 \le t \le 10^4) — the number of test cases. This is followed by a description of the test cases.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the length of the sequence b.The second line of each test case contains n integers b_1, b_2, b_3, \dots, b_n (1 \le b_i \le 10^9) — the elements of the sequence.The sum of the values of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output two lines. In the first line, output a single integer m — the length of the sequence (n \le m \le 2 \cdot n). In the second line, output m integers a_1, a_2, a_3, \dots, a_m (1 \le a_i \le 10^9) — the assumed sequence that Vika could have written on the first piece of paper.If there are multiple suitable sequences, you can output any of them.ExampleInput 634 6 331 2 351 7 9 5 7114421 151 2 2 1 1Output 6 4 3 2 6 3 3 3 1 2 3 6 1 7 9 3 5 7 1 144 2 1 1 6 1 2 2 1 1 1NoteThe first sample is explained in the problem statement.In the second sample, Vika could have chosen the original sequence.
634 6 331 2 351 7 9 5 7114421 151 2 2 1 1
6 4 3 2 6 3 3 3 1 2 3 6 1 7 9 3 5 7 1 144 2 1 1 6 1 2 2 1 1 1
2 seconds
256 megabytes
['constructive algorithms', '*800']
A. Gift Carpettime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecently, Tema and Vika celebrated Family Day. Their friend Arina gave them a carpet, which can be represented as an n \cdot m table of lowercase Latin letters.Vika hasn't seen the gift yet, but Tema knows what kind of carpets she likes. Vika will like the carpet if she can read her name on. She reads column by column from left to right and chooses one or zero letters from current column.Formally, the girl will like the carpet if it is possible to select four distinct columns in order from left to right such that the first column contains "v", the second one contains "i", the third one contains "k", and the fourth one contains "a".Help Tema understand in advance whether Vika will like Arina's gift.InputEach test consists of multiple test cases. The first line of input contains a single integer t (1 \le t \le 100) — the number of test cases. Then follows the description of the test cases.The first line of each test case contains two integers n, m (1 \le n, m \le 20) — the sizes of the carpet.The next n lines contain m lowercase Latin letters each, describing the given carpet.OutputFor each set of input data, output "YES" if Vika will like the carpet, otherwise output "NO".You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be accepted as a positive answer.ExampleInput 51 4vika3 3badcarpet4 4vvvviiiikkkkaaaa4 4vkakiiaiavvkviaa4 7vbickdavbickdavbickdavbickdaOutput YES NO YES NO YES NoteIn the first sample, Vika can read her name from left to right.In the second sample, Vika cannot read the character "v", so she will not like the carpet.
51 4vika3 3badcarpet4 4vvvviiiikkkkaaaa4 4vkakiiaiavvkviaa4 7vbickdavbickdavbickdavbickda
YES NO YES NO YES
1 second
256 megabytes
['dp', 'greedy', 'implementation', 'strings', '*800']
F. Four Suitstime limit per test6 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputThe game of Berland poker is played as follows. There are n+1 people: n players, numbered from 1 to n, and the dealer. The dealer has a deck which contains cards of four different suits (the number of cards of each suit is not necessarily the same); the number of cards in the deck is divisible by n. The dealer gives all cards to the players, so that every player receives the same number of cards, and the whole deck is used.After the cards are dealt, every player chooses one of four suits (independently) and discards all cards from their hand which do not belong to their chosen suit. The winner of the game is the player with the maximum number of cards left in their hand. The number of points the winner receives is x - y, where x is the number of cards in the winner's hand, and y is the maximum number of cards among all other players; everyone else receives 0 points. Note that it means that if there are multiple players with the maximum number of cards, everyone receives 0 points.Since every player wants to maximize their odds to win, they will choose a suit with the maximum number of cards in their hand.Monocarp is the dealer. He has already given some cards to the players; the i-th player received a_{i,j} cards of suit j. Note that the number of cards in players' hands don't have to be the same at this moment. Monocarp has b_1, b_2, b_3, b_4 cards of suit 1, 2, 3, 4 respectively left in his deck. He has to give them to the players so that, after all cards are dealt, every player has the same number of cards.For each player, calculate the maximum number of points they can receive among all ways to deal the remaining cards according to the rules of the game.InputThe first line of the input contains one integer n (2 \le n \le 5 \cdot 10^4) — the number of players.Then n lines follow. The i-th of them contains four integers a_{i,1}, a_{i,2}, a_{i,3}, a_{i,4} (0 \le a_{i,j} \le 10^6), where a_{i,j} is the number of cards of the j-th suit that the i-th player currently has.The last line contains 4 integers b_1, b_2, b_3, b_4 (0 \le b_j \le 10^6), where b_j is the number of cards of the j-th suit Monocarp has to deal yet.Additional constraint on the input: it is possible to deal all of the remaining cards so that every player has the same number of cards.OutputPrint n integers. The i-th of them should be the maximum number of points the i-th player can get among all possible ways to deal the remaining cards.ExamplesInput 2 3 1 1 1 1 1 1 1 2 2 0 0 Output 1 0 Input 4 0 0 0 0 0 0 0 1 2 2 0 0 0 1 0 0 3 2 3 2 Output 1 1 1 1 Input 7 2 1 0 1 0 0 2 1 4 4 1 2 0 0 1 0 1 1 0 1 0 2 1 1 0 2 0 0 15 10 10 14 Output 5 6 1 7 5 5 7
2 3 1 1 1 1 1 1 1 2 2 0 0
1 0
6 seconds
1024 megabytes
['binary search', 'bitmasks', 'flows', 'greedy', '*3200']
E. Non-Intersecting Subpermutationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given two integers n and k.For an array of length n, let's define its cost as the maximum number of contiguous subarrays of this array that can be chosen so that: each element belongs to at most one subarray; the length of each subarray is exactly k; each subarray contains each integer from 1 to k exactly once. For example, if n = 10, k = 3 and the array is [1, 2, 1, 3, 2, 3, 2, 3, 1, 3], its cost is 2 because, for example, we can choose the subarrays from the 2-nd element to the 4-th element and from the 7-th element to the 9-th element, and we can show that it's impossible to choose more than 2 subarrays.Calculate the sum of costs over all arrays of length n consisting of integers from 1 to k, and print it modulo 998244353.InputThe only line of the input contains two integers n and k (2 \le k \le n \le 4000).OutputPrint one integer — the sum of costs of all arrays of length n consisting of integers from 1 to k taken modulo 998244353.ExamplesInput 10 3 Output 71712 Input 2 2 Output 2 Input 1337 42 Output 524933698
10 3
71712
2 seconds
512 megabytes
['combinatorics', 'dp', 'implementation', 'math', '*2300']
D. Sorting By Multiplicationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n, consisting of positive integers. You can perform the following operation on this array any number of times (possibly zero): choose three integers l, r and x such that 1 \le l \le r \le n, and multiply every a_i such that l \le i \le r by x. Note that you can choose any integer as x, it doesn't have to be positive.You have to calculate the minimum number of operations to make the array a sorted in strictly ascending order (i. e. the condition a_1 < a_2 < \dots < a_n must be satisfied).InputThe first line contains a single integer t (1 \le t \le 10^4)  — the number of test cases.The first line of each test case contains one integer n (1 \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, \dots, a_n (1 \le a_i \le 10^9) — the array a.Additional constraint on the input: the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, print one integer — the minimum number of operations required to make a sorted in strictly ascending order.ExampleInput 351 1 2 2 265 4 3 2 5 131 2 3Output 3 2 0 NoteIn the first test case, we can perform the operations as follows: l = 2, r = 4, x = 3; l = 4, r = 4, x = 2; l = 5, r = 5, x = 10. After these operations, the array a becomes [1, 3, 6, 12, 20].In the second test case, we can perform one operation as follows: l = 1, r = 4, x = -2; l = 6, r = 6, x = 1337. After these operations, the array a becomes [-10, -8, -6, -4, 5, 1337].In the third test case, the array a is already sorted.
351 1 2 2 265 4 3 2 5 131 2 3
3 2 0
2 seconds
256 megabytes
['dp', 'greedy', '*1800']
C. Queries for the Arraytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp had an array a consisting of integers. Initially, this array was empty.Monocarp performed three types of queries to this array: choose an integer and append it to the end of the array. Each time Monocarp performed a query of this type, he wrote out a character +; remove the last element from the array. Each time Monocarp performed a query of this type, he wrote out a character -. Monocarp never performed this query on an empty array; check if the array is sorted in non-descending order, i.,e. a_1 \le a_2 \le \dots \le a_k, where k is the number of elements in the array currently. Every array with less than 2 elements is considered sorted. If the array was sorted by the time Monocarp was performing that query, he wrote out a character 1. Otherwise, he wrote out a character 0. You are given a sequence s of q characters 0, 1, + and/or -. These are the characters that were written out by Monocarp, given in the exact order he wrote them out.You have to check if this sequence is consistent, i. e. it was possible for Monocarp to perform the queries so that the sequence of characters he wrote out is exactly s.InputThe first line of the input contains one integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line containing the string s (1 \le |s| \le 2 \cdot 10^5). This string consists of characters 0, 1, + and/or -. This is the sequence of characters written by Monocarp, in the order he wrote them.Additional constraints on the input: for every prefix of s, the number of characters + on it is not less than the number of characters - on it. In other words, if Monocarp actually performed these queries, he would never try to remove the last element from the empty array; the sum of |s| over all test cases does not exceed 2 \cdot 10^5. OutputFor each test case, print YES if it was possible for Monocarp to perform the queries so that the sequence of characters he wrote is exactly s. Otherwise, print NO.You can print each letter in any register.ExampleInput 7++1+++1--0+00++0-+1-+0++0+-1+-0+1-+0Output YES NO NO NO YES NO NO NoteIn the first test case, Monocarp could perform the following sequence of queries: add the integer 13; add the integer 37; check that the current array [13, 37] is sorted in non-descending order (and it is sorted). In the fifth test case, Monocarp could perform the following sequence of queries: add the integer 3; add the integer 2; check that the current array [3, 2] is sorted (it is not); remove the last element; add the integer 3; check that the current array [3, 3] is sorted (it is); remove the last element; add the integer -5; check that the current array [3, -5] is sorted (it is not). In all other test cases of the example test, it is impossible for Monocarp to write the sequence s when performing the queries according to the statement.
7++1+++1--0+00++0-+1-+0++0+-1+-0+1-+0
YES NO NO NO YES NO NO
2 seconds
256 megabytes
['data structures', 'dfs and similar', 'implementation', 'strings', 'trees', '*1600']
B. Two Binary Stringstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings a and b of equal length, consisting of only characters 0 and/or 1; both strings start with character 0 and end with character 1. You can perform the following operation any number of times (possibly zero): choose one of the strings and two equal characters in it; then turn all characters between them into those characters. Formally, you choose one of these two strings (let the chosen string be s), then pick two integers l and r such that 1 \le l < r \le |s| and s_l = s_r, then replace every character s_i such that l < i < r with s_l.For example, if the chosen string is 010101, you can transform it into one of the following strings by applying one operation: 000101 if you choose l = 1 and r = 3; 000001 if you choose l = 1 and r = 5; 010001 if you choose l = 3 and r = 5; 010111 if you choose l = 4 and r = 6; 011111 if you choose l = 2 and r = 6; 011101 if you choose l = 2 and r = 4. You have to determine if it's possible to make the given strings equal by applying this operation any number of times.InputThe first line contains a single integer t (1 \le t \le 2000)  — the number of test cases.Each test case consists of two lines: the first line contains the string a (2 \le |a| \le 5000), consisting of only characters 0 and/or 1. the second line contains the string b (2 \le |b| \le 5000), consisting of only characters 0 and/or 1. Additional constraints on the input: in each test case, |a| = |b| (the strings have equal length); in each test case, both strings start with 0 and end with 1; the total length of all strings a in all test cases does not exceed 5000. OutputFor each test case, print YES if it is possible to make the strings equal. Otherwise, print NO. You can print each letter in any register.ExampleInput 7010100010111010101001010010001010101110000101111011001001001011011010001011011Output YES YES YES NO NO NO YES NoteIn the first test case, we can perform the following operations: choose the string a, l = 2, r = 4; after this operation, a is 01110001, b is 01110101; choose the string b, l = 5, r = 7; after this operation, a is 01110001, b is 01110001. In the second test case, the strings are already equal.In the third test case, we can perform the following operations: choose the string a, l = 4, r = 6; after this operation, a is 000111, b is 010111; choose the string b, l = 1, r = 3; after this operation, a is 000111, b is 000111; In the fourth and fifth test cases, it's impossible to make the given strings equal.
7010100010111010101001010010001010101110000101111011001001001011011010001011011
YES YES YES NO NO NO YES
2 seconds
256 megabytes
['constructive algorithms', 'dp', 'greedy', '*1000']
A. Prime Deletiontime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputA prime number is a positive integer that has exactly two different positive divisors: 1 and the integer itself. For example, 2, 3, 13 and 101 are prime numbers; 1, 4, 6 and 42 are not.You are given a sequence of digits from 1 to 9, in which every digit from 1 to 9 appears exactly once.You are allowed to do the following operation several (maybe zero) times: choose any digit from the sequence and delete it. However, you cannot perform this operation if the sequence consists of only two digits.Your goal is to obtain a sequence which represents a prime number. Note that you cannot reorder the digits in the sequence.Print the resulting sequence, or report that it is impossible to perform the operations so that the resulting sequence is a prime number.InputThe first line contains one integer t (1 \le t \le 5000) — the number of test cases.Each test case consists of one line containing a string of 9 digits (without any characters between them). Each digit from 1 to 9 appears in this string exactly once.OutputFor each test case, print the answer on a separate line as follows: if it is impossible to perform the described operations, print -1; otherwise, print any sequence that represents a prime number, which can be obtained from the given string performing several (maybe zero) operations described in the statement. If there are multiple such sequences, you can print any one of them. ExampleInput 4123456789987654321243567918576318429Output 167 53 3571 57638429
4123456789987654321243567918576318429
167 53 3571 57638429
2 seconds
512 megabytes
['constructive algorithms', 'math', '*800']
F. Evaluate RBStime limit per test10 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given 2n tuples of values (a, b, c), where a and b are positive integers and c is a bracket '(' or ')'. Exactly n tuples have c = '(' and the other n tuples have c = ')'.You are asked to choose two positive values x and y (x > 0 and y > 0; not necessarily integers) and sort the tuples in the increasing value of a \cdot x + b \cdot y. If several tuples have the same value, you can place them in any order among themselves.Is it possible to choose such x and y that taking brackets c from the tuples in the resulting order produces a regular bracket sequence?A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence.InputThe first line contains a single integer t (1 \le t \le 1500) — the number of testcases.The first line of each testcase contains a single integer n (1 \le n \le 1500).The i-th of the next 2n lines contains two integers a_i and b_i (1 \le a_i, b_i \le 10^6) and a character c_i (c_i = '(' or c_i = ')'). Exactly n tuples have c_i = '(' and the other n tuples have c_i = ')'.The sum of n over all testcases doesn't exceed 1500.OutputFor each testcase, print "YES" if it's possible to choose such x and y that taking brackets c from the tuples in the resulting order produces a regular bracket sequence. Otherwise, print "NO".ExampleInput 411 4 (2 3 )11 2 )3 4 (416 5 (12 3 (19 6 )4 10 )3 10 )19 11 (19 7 )7 14 (416 8 (11 9 )20 10 )20 19 )2 13 (18 7 (15 19 )5 6 (Output YES NO NO YES NoteIn the first testcase, you can choose x = 10, y = 0.1. The values for tuples will be 10 \cdot 1 + 0.1 \cdot 4 = 10.4 and 10 \cdot 2 + 0.1 \cdot 3 = 20.3. Thus, the first tuple will go first, then the second one, making the bracket sequence "()", which is regular.In the second testcase, you can't choose positive x and y such that the opening brackets gets assigned a value less or equal to the value of the closing bracket.In the fourth testcase, you can choose x = 0.6, y = 0.55. The bracket sequence is "(()(()))".
411 4 (2 3 )11 2 )3 4 (416 5 (12 3 (19 6 )4 10 )3 10 )19 11 (19 7 )7 14 (416 8 (11 9 )20 10 )20 19 )2 13 (18 7 (15 19 )5 6 (
YES NO NO YES
10 seconds
512 megabytes
['data structures', 'geometry', 'implementation', 'math', 'sortings', '*2900']
E. Fast Travel Text Editortime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given a string s, consisting of lowercase Latin letters.There's a cursor, initially placed between two adjacent letters of the string. The cursor can't be placed before the first or after the last letter.In one move, you can perform one of three actions: move a cursor one position to the left (if that doesn't place it before the first letter); move a cursor one position to the right (if that doesn't place it after the last letter); let x be the letter immediately to the left of the cursor, and y be the letter immediately to the right of the cursor. Choose any pair of adjacent letters in the string such that the left of them is x and the right of them is y, and move the cursor to the position between these two letters. You are asked m queries. In each query, you are given two integers f and t, which correspond to two valid positions of the cursor in the string. In response to the query, you have to calculate the minimum number of operations required to move the cursor from position f to position t.InputThe first line contains a string s (2 \le |s| \le 5 \cdot 10^4), consisting of lowercase Latin letters.The second line contains a single integer m (1 \le m \le 5 \cdot 10^4) — the number of queries.The i-th of the next m lines contains two integers f and t (1 \le f, t \le |s| - 1) — the initial and the target positions of the cursor in the i-th query. Position x means that the cursor is between the x-th and the (x+1)-st letters of the string (1-indexed).OutputFor each query, print the minimum number of actions required to move the cursor from position f to position t.ExamplesInput codecode 3 1 7 3 5 3 6 Output 3 2 2 Input abcdefghij 3 1 9 9 1 5 5 Output 8 8 0 Input aaaaaaaaaaaa 4 10 8 3 7 6 1 11 11 Output 1 1 1 0
codecode 3 1 7 3 5 3 6
3 2 2
5 seconds
512 megabytes
['data structures', 'dfs and similar', 'graphs', 'shortest paths', '*2400']
D. Balanced Stringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a binary string s (a binary string is a string consisting of characters 0 and/or 1).Let's call a binary string balanced if the number of subsequences 01 (the number of indices i and j such that 1 \le i < j \le n, s_i=0 and s_j=1) equals to the number of subsequences 10 (the number of indices k and l such that 1 \le k < l \le n, s_k=1 and s_l=0) in it.For example, the string 1000110 is balanced, because both the number of subsequences 01 and the number of subsequences 10 are equal to 6. On the other hand, 11010 is not balanced, because the number of subsequences 01 is 1, but the number of subsequences 10 is 5. You can perform the following operation any number of times: choose two characters in s and swap them. Your task is to calculate the minimum number of operations to make the string s balanced.InputThe only line contains the string s (3 \le |s| \le 100) consisting of characters 0 and/or 1. Additional constraint on the input: the string s can be made balanced.OutputPrint a single integer — the minimum number of swap operations to make the string s balanced.ExamplesInput 101 Output 0 Input 1000110 Output 0 Input 11010 Output 1 Input 11001100 Output 2 NoteIn the first example, the string is already balanced, the number of both 01 and 10 is equal to 1.In the second example, the string is already balanced, the number of both 01 and 10 is equal to 6.In the third example, one of the possible answers is the following one: 11010 \rightarrow 01110. After that, the number of both 01 and 10 is equal to 3.In the fourth example, one of the possible answers is the following one: 11001100 \rightarrow 11001010 \rightarrow 11000011. After that, the number of both 01 and 10 is equal to 8.
101
0
2 seconds
256 megabytes
['dp', '*2200']
C. Game on Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice and Bob are playing a game. They have a permutation p of size n (a permutation of size n is an array of size n where each element from 1 to n occurs exactly once). They also have a chip, which can be placed on any element of the permutation.Alice and Bob make alternating moves: Alice makes the first move, then Bob makes the second move, then Alice makes the third move, and so on. During the first move, Alice chooses any element of the permutation and places the chip on that element. During each of the next moves, the current player has to move the chip to any element that is simultaneously to the left and strictly less than the current element (i. e. if the chip is on the i-th element, it can be moved to the j-th element if j < i and p_j < p_i). If a player cannot make a move (it is impossible to move the chip according to the rules of the game), that player wins the game.Let's say that the i-th element of the permutation is lucky if the following condition holds: if Alice places the chip on the i-th element during her first move, she can win the game no matter how Bob plays (i. e. she has a winning strategy). You have to calculate the number of lucky elements in the permutation.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The first line of each test case contains a single integer n (1 \le n \le 3 \cdot 10^5) – the number of elements in the permutation.The second line contains n integers p_1, p_2, \dots, p_n (1 \le p_i \le n). All p_i are distinct. The sum of n over all test cases doesn't exceed 3 \cdot 10^5.OutputFor each test case, print a single integer — the number of lucky elements in the permutation.ExampleInput 432 1 322 131 2 342 1 4 3Output 1 0 1 2 NoteIn the first test case of the example, the 3-rd element of the permutation is lucky.In the second test case of the example, there are no lucky elements.In the third test case of the example, the 2-nd element of the permutation is lucky.In the fourth test case of the example, the 3-rd and the 4-th element of the permutation are lucky.
432 1 322 131 2 342 1 4 3
1 0 1 2
2 seconds
256 megabytes
['data structures', 'dp', 'games', 'greedy', '*1400']
B. Fancy Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMonocarp is going to make a purchase with cost of exactly m burles.He has two types of coins, in the following quantities: coins worth 1 burle: a_1 regular coins and infinitely many fancy coins; coins worth k burles: a_k regular coins and infinitely many fancy coins. Monocarp wants to make his purchase in such a way that there's no change — the total worth of provided coins is exactly m. He can use both regular and fancy coins. However, he wants to spend as little fancy coins as possible.What's the smallest total number of fancy coins he can use to make a purchase?InputThe first line contains a single integer t (1 \le t \le 3 \cdot 10^4) — the number of testcases.The only line of each testcase contains four integers m, k, a_1 and a_k (1 \le m \le 10^8; 2 \le k \le 10^8; 0 \le a_1, a_k \le 10^8) — the cost of the purchase, the worth of the second type of coin and the amounts of regular coins of both types, respectively.OutputFor each testcase, print a single integer — the smallest total number of fancy coins Monocarp can use to make a purchase.ExampleInput 411 3 0 011 3 20 2011 3 6 1100000000 2 0 0Output 5 0 1 50000000 NoteIn the first testcase, there are no regular coins of either type. Monocarp can use 2 fancy coins worth 1 burle and 3 fancy coins worth 3 (since k=3) burles to get 11 total burles with 5 total fancy coins.In the second testcase, Monocarp has a lot of regular coins of both types. He can use 11 regular coins worth 1 burle, for example. Notice that Monocarp doesn't have to minimize the total number of used coins. That way he uses 0 fancy coins.In the third testcase, Monocarp can use 5 regular coins worth 1 burle and 1 regular coin worth 3 burles. That will get him to 8 total burles when he needs 11. So, 1 fancy coin worth 3 burles is enough.
411 3 0 011 3 20 2011 3 6 1100000000 2 0 0
5 0 1 50000000
2 seconds
256 megabytes
['binary search', 'brute force', 'greedy', 'math', '*1200']
A. Not a Substringtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA bracket sequence is a string consisting of characters '(' and/or ')'. A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example: bracket sequences "()()" and "(())" are regular (they can be transformed into "(1)+(1)" and "((1+1)+1)", respectively); bracket sequences ")(", "(" and ")" are not regular. You are given a bracket sequence s; let's define its length as n. Your task is to find a regular bracket sequence t of length 2n such that s does not occur in t as a contiguous substring, or report that there is no such sequence.InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The only line of each test case contains a string s (2 \le |s| \le 50), consisting of characters "(" and/or ")".OutputFor each test case, print the answer to it. If there is no required regular bracket sequence, print NO in a separate line. Otherwise, print YES in the first line, and the required regular bracket sequence t itself in the second line. If there are multiple answers — you may print any of them.ExampleInput 4)((()()))()Output YES (()) YES ()()() NO YES ()(()())
4)((()()))()
YES (()) YES ()()() NO YES ()(()())
2 seconds
256 megabytes
['constructive algorithms', 'strings', '*900']
F. Teleportation in Bytelandtime limit per test8 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are n cities in Byteland, some of which are connected by roads, which can be traversed in any direction. The i-th road has its own hardness parameter w_i. Time spent on traversing a road with its hardness equal to w_i is \lceil\frac{w_i}{c}\rceil, where c is the current driving skill.The travel network of Byteland is a tree. In other words, between any pair of cities, there is exactly one path that passes through each city at most once.In some cities you can visit driving courses. A single course takes T time to complete, and after completing the course the driver's skill c is increased by 2 times. Notice that the time T required to complete a course is the same in all cities, and courses can be completed in the same city more than once.You need to answer the q queries: what is the minimum time it takes to get from the city a to city b if you start the travelling with driving skill c = 1?InputEach test contains multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and T (1 \le n \le 10^5, 1 \le T \le 10^6) - the number of cities and time required to complete a single driving course.The following n - 1 lines each contain three integers u_i, v_i and w_i (1 \le u_i, v_i \le n, 1 \le w_i \le 10^6, u_i \neq v_i), which mean that there exists a road connecting towns u_i and v_i with hardness equal to w_i .The next line contains a binary string s of length n, consisting only of symbols 0 and 1. If s_i = 1 (1 \le i \le n), then you can visit driving courses in the i-th city. If s_i = 0 (1 \le i \le n), then you cannot visit driving courses in the i-th city.The next line contains a single integer q (1 \le q \le 10^5) — the number of queries you are required to answer.The next q lines contain two integers a_j, b_j (1 \le a_j, b_j \le n, 1 \le j \le q) — the cities you are required to process in the j-th query.It is guaranteed that the given graph is a tree. It is guaranteed that the sum of n and the sum of q over all test cases does not exceed 10^5.OutputFor each query, print one integer in a separate line — the minimum time it takes to get in the corresponding query.ExampleInput 2 2 3 1 2 1 11 1 1 2 5 3 1 4 5 1 3 8 2 3 8 4 5 10 11001 5 1 5 2 5 5 1 3 4 4 2 Output 1 11 14 11 13 15 NoteIn the only query of the first test case, it is optimal to ignore the driving courses. Then the minimum time required is equal to the distance between vertexes 1 and 2, which is 1.In the first query of the second test case, we can spend 3 time in city number 1 visiting the driving courses, then go to vertex 5. Then the minimum time required is 3 + \lceil\frac{5}{2}\rceil + \lceil\frac{10}{2}\rceil = 11.
2 2 3 1 2 1 11 1 1 2 5 3 1 4 5 1 3 8 2 3 8 4 5 10 11001 5 1 5 2 5 5 1 3 4 4 2
1 11 14 11 13 15
8 seconds
512 megabytes
['data structures', 'dfs and similar', 'divide and conquer', 'graphs', 'shortest paths', 'trees', '*3200']
E. Maximum Monogonositytime limit per test2.5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array a of length n and an array b of length n. The cost of a segment [l, r], 1 \le l \le r \le n, is defined as |b_l - a_r| + |b_r - a_l|.Recall that two segments [l_1, r_1], 1 \le l_1 \le r_1 \le n, and [l_2, r_2], 1 \le l_2 \le r_2 \le n, are non-intersecting if one of the following conditions is satisfied: r_1 < l_2 or r_2 < l_1.The length of a segment [l, r], 1 \le l \le r \le n, is defined as r - l + 1.Find the maximum possible sum of costs of non-intersecting segments [l_j, r_j], 1 \le l_j \le r_j \le n, whose total length is equal to k.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 1000) — the number of sets of input data. The description of the test cases follows.The first line of each test case contains two integers n and k (1 \le k \le n \le 3000) — the length of array a and the total length of segments.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (-10^9 \le a_i \le 10^9) — the elements of array a.The third line of each test case contains n integers b_1, b_2, \ldots, b_n (-10^9 \le b_i \le 10^9) — the elements of array b.It is guaranteed that the sum of n over all test case does not exceed 3000.OutputFor each test case, output a single number — the maximum possible sum of costs of such segments.ExampleInput 54 41 1 1 11 1 1 13 21 3 25 2 35 11 2 3 4 51 2 3 4 57 21 3 7 6 4 7 21 5 3 2 7 4 54 217 3 5 816 2 5 9Output 0 10 0 16 28 NoteIn the first test case, the cost of any segment is 0, so the total cost is 0.In the second test case, we can take the segment [1, 1] with a cost of 8 and the segment [3, 3] with a cost of 2 to get a total sum of 10. It can be shown that this is the optimal solution.In the third test case, we are only interested in segments of length 1, and the cost of any such segment is 0.In the fourth test case, it can be shown that the optimal sum is 16. For example, we can take the segments [3, 3] and [4, 4].
54 41 1 1 11 1 1 13 21 3 25 2 35 11 2 3 4 51 2 3 4 57 21 3 7 6 4 7 21 5 3 2 7 4 54 217 3 5 816 2 5 9
0 10 0 16 28
2.5 seconds
512 megabytes
['brute force', 'dp', 'math', '*2500']
D. Andrey and Escape from Capygradtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn incident occurred in Capygrad, the capital of Tyagoland, where all the capybaras in the city went crazy and started throwing mandarins. Andrey was forced to escape from the city as far as possible, using portals.Tyagoland is represented by a number line, and the city of Capygrad is located at point 0. There are n portals all over Tyagoland, each of which is characterised by four integers l_i, r_i, a_i and b_i (1 \le l_i \le a_i \le b_i \le r_i \le 10^9). Note that the segment [a_i, b_i] is contained in the segment [l_i, r_i].If Andrey is on the segment [l_i, r_i], then the portal can teleport him to any point on the segment [a_i, b_i]. Andrey has a pass that allows him to use the portals an unlimited number of times.Andrey thinks that the point x is on the segment [l, r] if the inequality l \le x \le r is satisfied.Andrey has q options for where to start his escape, each option is characterized by a single integer x_i — the starting position of the escape. He wants to escape from Capygrad as far as possible (to the point with the maximum possible coordinate). Help Andrey determine how far he could escape from Capygrad, starting at each of the q positions.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 10^4) — the number of sets of test cases. The description of test cases follows.The first line of each test case contains a single integer n (1 \le n \le 2 \cdot 10^5) — the number of portals.Each of the next n lines contains four integers l_i, r_i, a_i, and b_i (1 \le l_i \le a_i \le b_i \le r_i \le 10^9) — the characteristics of the portals.The next line contains a single integer q (1 \le q \le 2 \cdot 10^5) — the number of positions.The following line contains q integers x_1, x_2, \ldots, x_q (1 \le x_i \le 10^9) — the position from which Andrey will start his escape in the i-th options.It is guaranteed that the sum of n and the sum of q over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case, output a single line of q integers, containing the answers to Andrey's questions.ExampleInput 536 17 7 141 12 3 816 24 20 22610 2 23 15 28 1833 14 7 1016 24 20 221 16 3 1492 4 6 8 18 23 11 13 1521 4 2 33 9 6 734 8 1518 24 18 241 8 2 411 16 14 1426 32 28 305 10 6 8915 14 13 27 22 17 31 1 769 22 14 2011 26 13 2421 33 22 2321 33 25 321 6 3 418 29 20 21811 23 16 5 8 33 2 21Output 14 14 23 15 28 22 14 14 14 14 22 23 14 14 15 7 8 7 15 14 14 30 24 17 31 4 8 32 32 32 5 8 33 4 32 NoteIn the first test case: Optimal actions when starting from each position: Use portal 1 and teleport to point b_1 = 14. Use portal 2 first and teleport to point 6, which is on the segment [l_1, r_1] = [6, 17], then use portal 1 and teleport to point b_1 = 14. Stay at point x_3=23 without using any portals. Stay at point x_4=15 without using any portals. Point x_5=28 is not on any segment, so Andrey won't be able to teleport anywhere. Point x_6=18 is only on the segment [l_3, r_3] = [16, 24], use portal 3 and teleport to point b_3 = 22. In the fifth test case: Optimal actions when starting from each position: Use portal 1 first and teleport to point 15 on the segment [a_1, b_1] = [14, 20], then use portal 2 and teleport to point 21, which is on the segment [l_4, r_4] = [21, 33] and on the segment [a_2, b_2] = [13, 24], then teleport to point b_4 = 32. Use portal 6 first and teleport to point 20 on the segment [a_6, b_6] = [20, 21], then use portal 2 and teleport to point 22, which is simultaneously on the segment [l_4, r_4] = [21, 33] and on the segment [a_2, b_2] = [13, 24], then teleport to point b_4 = 32. Perform the same actions as from the first position. Stay at point x_4=5 without using any portals. Point 8 is not on any segment, so Andrey won't be able to teleport anywhere. Stay at point x_6=33 without using any portals. Use portal 5 and teleport to point b_5 = 4. Perform the same actions as from the first position.
536 17 7 141 12 3 816 24 20 22610 2 23 15 28 1833 14 7 1016 24 20 221 16 3 1492 4 6 8 18 23 11 13 1521 4 2 33 9 6 734 8 1518 24 18 241 8 2 411 16 14 1426 32 28 305 10 6 8915 14 13 27 22 17 31 1 769 22 14 2011 26 13 2421 33 22 2321 33 25 321 6 3 418 29 20 21811 23 16 5 8 33 2 21
14 14 23 15 28 22 14 14 14 14 22 23 14 14 15 7 8 7 15 14 14 30 24 17 31 4 8 32 32 32 5 8 33 4 32
2 seconds
256 megabytes
['binary search', 'data structures', 'dp', 'dsu', 'greedy', 'sortings', '*1800']
C. Another Permutation Problemtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAndrey is just starting to come up with problems, and it's difficult for him. That's why he came up with a strange problem about permutations^{\dagger} and asks you to solve it. Can you do it?Let's call the cost of a permutation p of length n the value of the expression: (\sum_{i = 1}^{n} p_i \cdot i) - (\max_{j = 1}^{n} p_j \cdot j). Find the maximum cost among all permutations of length n.^{\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 \le t \le 30) — the number of test cases. The description of the test cases follows.The only line of each test case contains a single integer n (2 \le n \le 250) — the length of the permutation.It is guaranteed that the sum of n over all test cases does not exceed 500.OutputFor each test case, output a single integer — the maximum cost among all permutations of length n.ExampleInput 52431020Output 2 17 7 303 2529 NoteIn the first test case, the permutation with the maximum cost is [2, 1]. The cost is equal to 2 \cdot 1 + 1 \cdot 2 - \max (2 \cdot 1, 1 \cdot 2)= 2 + 2 - 2 = 2.In the second test case, the permutation with the maximum cost is [1, 2, 4, 3]. The cost is equal to 1 \cdot 1 + 2 \cdot 2 + 4 \cdot 3 + 3 \cdot 4 - 4 \cdot 3 = 17.
52431020
2 17 7 303 2529
3 seconds
256 megabytes
['brute force', 'dp', 'greedy', 'math', '*1200']
B. Olya and Game with Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputArtem suggested a game to the girl Olya. There is a list of n arrays, where the i-th array contains m_i \ge 2 positive integers a_{i,1}, a_{i,2}, \ldots, a_{i,m_i}.Olya can move at most one (possibly 0) integer from each array to another array. Note that integers can be moved from one array only once, but integers can be added to one array multiple times, and all the movements are done at the same time.The beauty of the list of arrays is defined as the sum \sum_{i=1}^n \min_{j=1}^{m_i} a_{i,j}. In other words, for each array, we find the minimum value in it and then sum up these values.The goal of the game is to maximize the beauty of the list of arrays. Help Olya win this challenging game!InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 25000) — 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 25000) — the number of arrays in the list.This is followed by descriptions of the arrays. Each array description consists of two lines.The first line contains a single integer m_i (2 \le m_i \le 50000) — the number of elements in the i-th array.The next line contains m_i integers a_{i, 1}, a_{i, 2}, \ldots, a_{i, m_i} (1 \le a_{i,j} \le 10^9) — the elements of the i-th array.It is guaranteed that the sum of m_i over all test cases does not exceed 50000.OutputFor each test case, output a single line containing a single integer — the maximum beauty of the list of arrays that Olya can achieve.ExampleInput 3221 224 313100 1 6341001 7 1007 538 11 622 9Output 5 1 19 NoteIn the first test case, we can move the integer 3 from the second array to the first array. Then the beauty is \min(1, 2, 3) + \min(4) = 5. It can be shown that this is the maximum possible beauty.In the second test case, there is only one array, so regardless of the movements, the beauty will be \min(100, 1, 6) = 1.
3221 224 313100 1 6341001 7 1007 538 11 622 9
5 1 19
1 second
256 megabytes
['constructive algorithms', 'greedy', 'math', 'sortings', '*1000']
A. United We Standtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array a of length n, containing integers. And there are two initially empty arrays b and c. You need to add each element of array a to exactly one of the arrays b or c, in order to satisfy the following conditions: Both arrays b and c are non-empty. More formally, let l_b be the length of array b, and l_c be the length of array c. Then l_b, l_c \ge 1. For any two indices i and j (1 \le i \le l_b, 1 \le j \le l_c), c_j is not a divisor of b_i. Output the arrays b and c that can be obtained, or output -1 if they do not exist.InputEach test consists of multiple test cases. The first line contains a single integer t (1 \le t \le 500) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 100) — the length of array a.The second line of each test case contains n integers a_1, a_2, \ldots, a_n (1 \le a_i \le 10^9) — the elements of array a.OutputFor each test case, output a single integer -1 if a solution does not exist.Otherwise, in the first line, output two integers l_b and l_c — the lengths of arrays b and c respectively.In the second line, output l_b integers b_1, b_2, \ldots, b_{l_b} — the elements of array b.In the third line, output l_c integers c_1, c_2, \ldots, c_{l_c} — the elements of array c.If there are multiple solutions, output any of them. You can output the elements of the arrays in any order.ExampleInput 532 2 251 2 3 4 531 3 571 7 7 2 9 1 454 8 12 12 4Output -1 3 2 1 3 5 2 4 1 2 1 3 5 2 5 1 1 2 4 7 7 9 3 2 4 8 4 12 12 NoteIn the first test case, a solution does not exist.In the second test case, we can obtain b = [1, 3, 5] and c = [2, 4]. Then elements 2 and 4 do not divide elements 1, 3 and 5.In the fifth test case, we can obtain b = [4, 8, 4] and c = [12, 12].
532 2 251 2 3 4 531 3 571 7 7 2 9 1 454 8 12 12 4
-1 3 2 1 3 5 2 4 1 2 1 3 5 2 5 1 1 2 4 7 7 9 3 2 4 8 4 12 12
1 second
256 megabytes
['constructive algorithms', 'math', 'number theory', '*800']
E2. Rollbacks (Hard Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved.You have an array a, which is initially empty. You need to process queries of the following types: + x — add the integer x to the end of the array a. - k — remove the last k numbers from the array a. ! — roll back the last active change (i.e., make the array a the way it was before the change). In this problem, only queries of the first two types (+ and -) are considered as changes. ? — find the number of distinct numbers in the array a. InputThe first line contains an integer q (1 \leq q \leq 10^6) — the number of queries.The next q lines contain the queries as described above.It is guaranteed that in the queries of the first type, 1 \le x \le 10^6; in the queries of the second type, k \ge 1 and k does not exceed the current length of the array a; at the moment of the queries of the third type, there is at least one query of the first or of the second type that can be rolled back. It is also guaranteed that the number of queries of the fourth type (?) does not exceed 10^5.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program.OutputFor each query of the fourth type output one integer — the number of distinct elements in array a at the moment of query.ExamplesInput 10 + 1 + 2 + 2 ? ! + 3 - 2 ? + 1 ? Output 2 1 1 Input 6 + 1 + 1000000 ? ! ! ? Output 2 0 NoteIn the first example array a changes as follows: After the first query, a=[1]. After the second query, a=[1,2]. After the third query, a=[1,2,2]. At the moment of the fourth query, there are 2 distinct intergers in the array a: 1 and 2. After the fifth query, a=[1,2] (rolled back the change + 2). After the sixth query, a=[1,2,3]. After the seventh query, a=[1]. At the moment of the eigth query, there is only one 1 in the array a. After the ninth query, a=[1,1]. At the moment of the tenth query, there are only two 1 in the array a. In the second example array a changes as follows: After the first query, a=[1]. After the second query, a=[1, 1\,000\,000]. At the moment of the third query, there are 2 distinct intergers in the array a: 1 and 1\,000\,000. After the fourth query, a=[1] (rolled back the change + 1000000). After the fifth query, a=[] (rolled back the change + 1). At the moment of the sixth query, there are no integers in the array a, so the answer to this query is 0.
10 + 1 + 2 + 2 ? ! + 3 - 2 ? + 1 ?
2 1 1
3 seconds
256 megabytes
['data structures', 'interactive', 'trees', '*2600']
E1. Rollbacks (Easy Version)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of this problem. The only difference between the versions is that you have to solve the hard version in online mode. You can make hacks only if both versions of the problem are solved.You have an array a, which is initially empty. You need to process queries of the following types: + x — add the integer x to the end of the array a. - k — remove the last k numbers from the array a. ! — roll back the last active change (i.e., make the array a the way it was before the change). In this problem, only queries of the first two types (+ and -) are considered as changes. ? — find the number of distinct numbers in the array a. InputThe first line contains an integer q (1 \leq q \leq 10^6) — the number of queries.The next q lines contain the queries as described above.It is guaranteed that in the queries of the first type, 1 \le x \le 10^6; in the queries of the second type, k \ge 1 and k does not exceed the current length of the array a; at the moment of the queries of the third type, there is at least one query of the first or of the second type that can be rolled back. It is also guaranteed that the number of queries of the fourth type (?) does not exceed 10^5.OutputFor each query of the fourth type output one integer — the number of distinct elements in array a at the moment of query.ExamplesInput 10 + 1 + 2 + 2 ? ! + 3 - 2 ? + 1 ? Output 2 1 1 Input 6 + 1 + 1000000 ? ! ! ? Output 2 0 NoteIn the first example array a changes as follows: After the first query, a=[1]. After the second query, a=[1,2]. After the third query, a=[1,2,2]. At the moment of the fourth query, there are 2 distinct intergers in the array a: 1 and 2. After the fifth query, a=[1,2] (rolled back the change + 2). After the sixth query, a=[1,2,3]. After the seventh query, a=[1]. At the moment of the eigth query, there is only one 1 in the array a. After the ninth query, a=[1,1]. At the moment of the tenth query, there are only two 1 in the array a. In the second example array a changes as follows: After the first query, a=[1]. After the second query, a=[1,1\,000\,000]. At the moment of the third query, there are 2 distinct intergers in the array a: 1 and 1\,000\,000. After the fourth query, a=[1] (rolled back the change + 1000000). After the fifth query, a=[] (rolled back the change + 1). At the moment of the sixth query, there are no integers in the array a, so the answer to this query is 0.
10 + 1 + 2 + 2 ? ! + 3 - 2 ? + 1 ?
2 1 1
3 seconds
256 megabytes
['brute force', 'data structures', 'dfs and similar', 'trees', '*2500']
D. Trees and Segmentstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe teachers of the Summer Informatics School decided to plant n trees in a row, and it was decided to plant only oaks and firs. To do this, they made a plan, which can be represented as a binary string s of length n. If s_i = 0, then the i-th tree in the row should be an oak, and if s_i = 1, then the i-th tree in the row should be a fir.The day of tree planting is tomorrow, and the day after tomorrow an inspector will come to the School. The inspector loves nature very much, and he will evaluate the beauty of the row as follows: First, he will calculate l_0 as the maximum number of consecutive oaks in the row (the maximum substring consisting of zeros in the plan s). If there are no oaks in the row, then l_0 = 0. Then, he will calculate l_1 as the maximum number of consecutive firs in the row (the maximum substring consisting of ones in the plan s). If there are no firs in the row, then l_1 = 0. Finally, he will calculate the beauty of the row as a \cdot l_0 + l_1 for some a — the inspector's favourite number. The teachers know the value of the parameter a, but for security reasons they cannot tell it to you. They only told you that a is an integer from 1 to n.Since the trees have not yet been planted, the teachers decided to change the type of no more than k trees to the opposite (i.e., change s_i from 0 to 1 or from 1 to 0 in the plan) in order to maximize the beauty of the row of trees according to the inspector.For each integer j from 1 to n answer the following question independently: What is the maximum beauty of the row of trees that the teachers can achieve by changing the type of no more than k trees if the inspector's favourite number a is equal to j? InputThe first line contains a single integer t (1 \le t \le 1000) — the number of test cases.The first line of each test case contains two integers n and k (1 \le n \le 3000, 0 \le k \le n) — the number of trees in the row and the maximum number of changes.The second line contains a string s of length n, consisting of zeros and ones — the plan description.It is guaranteed that the sum of all n values for all test cases does not exceed 3000.OutputFor each test case, print n integers, the j-th (1 \le j \le n) of which is the maximum beauty of the row of trees after no more than k changes if a = j is used to calculate the beauty.ExampleInput 53 01114 101105 0100006 21011017 10001101Output 3 3 3 4 5 7 9 5 9 13 17 21 6 9 13 17 21 25 7 10 13 17 21 25 29 NoteIn the first test case no changes are allowed, so l_0 = 0 and l_1 = 3 always hold. Thus, regardless of the value of a, the beauty of the row of trees will be 3.In the second test case for a \in \{1, 2\} the teachers can, for example, change the plan s to 0111 (by changing s_4), and for a \in \{3, 4\} — to 0010 (by changing s_2). In this case, the beauty of the row for each a is calculated as follows: For a = 1: l_0 = 1, l_1 = 3. The beauty of the row is 1\cdot 1 + 3 = 4. For a = 2: l_0 = 1, l_1 = 3. The beauty of the row is 2\cdot 1 + 3 = 5. For a = 3: l_0 = 2, l_1 = 1. The beauty of the row is 3\cdot 2 + 1 = 7. For a = 4: l_0 = 2, l_1 = 1. The beauty of the row is 4\cdot 2 + 1 = 9. It can be shown that the changes described above are optimal for all a from 1 to 4.
53 01114 101105 0100006 21011017 10001101
3 3 3 4 5 7 9 5 9 13 17 21 6 9 13 17 21 25 7 10 13 17 21 25 29
3 seconds
256 megabytes
['brute force', 'data structures', 'dp', 'greedy', 'two pointers', '*2200']
C. Yet Another Permutation Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlex got a new game called "GCD permutations" as a birthday present. Each round of this game proceeds as follows: First, Alex chooses a permutation^{\dagger} a_1, a_2, \ldots, a_n of integers from 1 to n. Then, for each i from 1 to n, an integer d_i = \gcd(a_i, a_{(i \bmod n) + 1}) is calculated. The score of the round is the number of distinct numbers among d_1, d_2, \ldots, d_n. Alex has already played several rounds so he decided to find a permutation a_1, a_2, \ldots, a_n such that its score is as large as possible.Recall that \gcd(x, y) denotes the greatest common divisor (GCD) of numbers x and y, and x \bmod y denotes the remainder of dividing x by y.^{\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 of the input contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of one line containing a single integer n (2 \le n \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 n distinct integers a_{1},a_{2},\ldots,a_{n} (1 \le a_i \le n) — the permutation with the largest possible score.If there are several permutations with the maximum possible score, you can print any one of them.ExampleInput 452710Output 1 2 4 3 5 1 2 1 2 3 6 4 5 7 1 2 3 4 8 5 10 6 9 7 NoteIn the first test case, Alex wants to find a permutation of integers from 1 to 5. For the permutation a=[1,2,4,3,5], the array d is equal to [1,2,1,1,1]. It contains 2 distinct integers. It can be shown that there is no permutation of length 5 with a higher score.In the second test case, Alex wants to find a permutation of integers from 1 to 2. There are only two such permutations: a=[1,2] and a=[2,1]. In both cases, the array d is equal to [1,1], so both permutations are correct.In the third test case, Alex wants to find a permutation of integers from 1 to 7. For the permutation a=[1,2,3,6,4,5,7], the array d is equal to [1,1,3,2,1,1,1]. It contains 3 distinct integers so its score is equal to 3. It can be shown that there is no permutation of integers from 1 to 7 with a score higher than 3.
452710
1 2 4 3 5 1 2 1 2 3 6 4 5 7 1 2 3 4 8 5 10 6 9 7
2 seconds
256 megabytes
['constructive algorithms', 'greedy', 'math', 'number theory', '*1000']
B. The Walkwaytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are n benches near the Main Walkway in Summer Infomatics School. These benches are numbered by integers from 1 to n in order they follow. Also there are m cookie sellers near the Walkway. The i-th (1 \le i \le m) cookie sellers is located near the s_i-th bench.Petya is standing in the beginning of the Walkway. He will pass near all benches starting from the 1-st bench and ending with the n-th bench. Petya passes the distance between two consecutive benches in 1 minute. He has a knapsack with an infinite amount of cookies. Petya is going to eat cookies from his knapsack and buy them from cookie sellers during the walk.Petya eats cookies only near the benches according to the following rule: he will eat the cookie near the i-th (1 \le i \le n) bench if and only if at least one of the following conditions holds: There is a cookie seller near the i-th bench. Then Petya will buy a cookie from cookie seller and eat it immediately. Petya has not yet eaten a cookie. Then Petya will take a cookie from his knapsack and eat it immediately. At least d minutes passed since Petya ate the previous cookie. In other words, Petya has not eaten a cookie near the benches i-1, i-2, \ldots, \max(i-d+1, 1). Then Petya will take a cookie from his knapsack and eat it immediately. You may assume that Petya eats cookies instantly. Petya will not eat two or more cookies near the same bench.You want to minimize the number of cookies Petya will eat during his walk. In order to do this, you will ask the administration of the Summer Informatics School to remove exactly one cookie seller from the Walkway before Petya starts his walk.Please determine the minimum possible number of cookies Petya can eat after removing exactly one cookie seller. Also determine the number of cookie sellers, such that if you remove one of them, Petya will eat the minimum possible number of cookies.InputThe first line contains a single integer t (1 \le t \le 10^3) — the number of test cases.The first line of each test case contains three integers n, m and d (2 \le d \le n \le 10^9, 2 \le m \le \min(10^{5}, n)) — the number of benches, the number of cookie sellers and the value of parameter d from the statement, respectively.The second line of each test case contains m integers s_1, s_2, \ldots, s_m (1 \le s_i \le n) — the locations of the cookie sellers. It is guaranteed that s_{i} < s_{i+1} for all 1 \leq i \leq m - 1.It is guaranteed that the sum of m over all test cases does not exceed 10^5.OutputFor each test case print two integers — the minimum number of cookies that Petya can eat if exactly one cookie seller is removed, and the number of cookie sellers such that if one of them is removed, Petya will eat the minimum possible number of cookies.ExampleInput 86 2 22 58 3 23 5 810 4 92 8 9 1030 5 86 8 15 24 2930 5 86 8 12 20 278 8 31 2 3 4 5 6 7 82 2 21 21000000000 3 2000000057008429 66778899 837653445Output 3 1 4 1 4 4 6 4 5 2 7 7 1 1 51 1 NoteIn the first test case n=6, m=2, d=2 and s=[2, 5]. If no cookie seller is removed, then Petya will eat 4 cookies during his walk (note that you have to remove exactly one cookie seller; this case is explained only to show how Petya decides whether to eat a cookie): Petya will eat a cookie near the 1-st bench since he has not yet eaten a cookie. Petya will eat a cookie near the 2-nd bench since there is a cookie seller near this bench. Petya will not eat a cookie near the 3-rd bench since only 1<d minute passed since he ate a cookie. Petya will eat a cookie near the 4-th bench since 2\ge d minutes passed since he ate a cookie. Petya will eat a cookie near the 5-th bench since there is a cookie seller near this bench. Petya will not eat a cookie near the 6-th bench since only 1<d minute passed since he ate a cookie. If the 1-st cookie seller is removed, Petya will eat 3 cookies (near the benches 1, 3 and 5). If the 2-nd cookie seller is removed, Petya will eat 4 cookies (near the benches 1, 2, 4 and 6).Thus, the minimum number of cookies Petya will eat is 3; there is only one cookie seller such that removing it results in minimizing the number of cookies Petya will eat.In the second test case the removal of the 1-st or the 2-nd cookie seller results in Petya eating 5 cookies near the benches 1, 3, 5, 7, 8; the removal of the 3-rd cookie seller results in Petya eating 4 cookies near the benches 1, 3, 5, 7. Note that the second integer you should output is the number of (that is, amount) cookie sellers, not the index of a cookie seller to remove. Thus, the answer to the second test case is 4 1 because there is only one cookie seller such that removing it results in Petya eating four cookies, which is the minimum possible.In the third test case Petya will eat 4 cookies no matter what cookie seller is removed.Note that Petya is not interested in minimizing the number of cookies he will eat, so he eats cookies whenever it is possible under the rule from the statement.
86 2 22 58 3 23 5 810 4 92 8 9 1030 5 86 8 15 24 2930 5 86 8 12 20 278 8 31 2 3 4 5 6 7 82 2 21 21000000000 3 2000000057008429 66778899 837653445
3 1 4 1 4 4 6 4 5 2 7 7 1 1 51 1
1 second
256 megabytes
['brute force', 'dp', 'greedy', 'math', 'number theory', '*1500']
A. Buttonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnna and Katie ended up in a secret laboratory.There are a+b+c buttons in the laboratory. It turned out that a buttons can only be pressed by Anna, b buttons can only be pressed by Katie, and c buttons can be pressed by either of them. Anna and Katie decided to play a game, taking turns pressing these buttons. Anna makes the first turn. Each button can be pressed at most once, so at some point, one of the girls will not be able to make her turn.The girl who cannot press a button loses. Determine who will win if both girls play optimally.InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.Each test case consists of three integers a, b, and c (1 \le a, b, c \le 10^9) — the number of buttons that can only be pressed by Anna, the number of buttons that can only be pressed by Katie, and the number of buttons that can be pressed by either of them, respectively.OutputFor each test case, output First if Anna wins, or Second if Katie wins.ExampleInput 51 1 19 3 31 2 36 6 92 2 8Output First First Second First Second NoteFor the simplicity of the explanation, we will numerate the buttons by the numbers from 1 to a+b+c: the first a buttons can only be pressed by Anna, the next b buttons can only be pressed by Katie, and the last c buttons can be pressed by either of them.In the first test case, Anna can press the 3-rd button on the first turn. Then Katie will press the 2-nd button (since it is the only possible turn for her). Then Anna will press the 1-st button. Katie won't have a button to press, so Anna will win.In the second test case, Anna can press the first nine buttons in some order on her turns. No matter what buttons Katie will press, all the buttons from the 10-th to the 15-th will be pressed after 12 turns. On the 13-th turn, Anna will press one of the first nine buttons and Katie will not have a button to press on her turn. Thus, Anna will win.In the third test case, the game can proceed as follows: On the 1-st turn Anna presses the 5-th button. On the 2-st turn Katie presses the 4-th button. On the 3-st turn Anna presses the 6-th button. On the 4-st turn Katie presses the 3-th button. On the 5-st turn Anna presses the 1-th button. On the 6-st turn Katie presses the 2-th button. Anna cannot make the turn, so Katie wins. It can be shown that Katie can win no matter what moves Anna takes.
51 1 19 3 31 2 36 6 92 2 8
First First Second First Second
1 second
256 megabytes
['games', 'greedy', 'math', '*800']
G. Counting Graphstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a tree consisting of n vertices. A tree is a connected undirected graph without cycles. Each edge of the tree has its weight, w_i.Your task is to count the number of different graphs that satisfy all four conditions: The graph does not have self-loops and multiple edges. The weights on the edges of the graph are integers and do not exceed S. The graph has exactly one minimum spanning tree. The minimum spanning tree of the graph is the given tree. Two graphs are considered different if their sets of edges are different, taking into account the weights of the edges.The answer can be large, output it modulo 998244353.InputThe first line contains an integer t (1\le t\le 10^4) — the number of test cases.The first line of each test case contains two integers n and S (2 \le n \le 2 \cdot 10^5, 1\le S\le 10^9) — the number of vertices and the upper bound of the weights.Then follow n-1 lines describing the tree, the i-th line contains three integers u_i, v_i, and w_i (1\le u_i,v_i\le n, u_i \ne v_i, 1\le w_i\le S) — an edge in the tree with weight w_i.It is guaranteed that the sum of n for all tests does not exceed 2\cdot 10^5.OutputFor each test, output the number of different graphs that satisfy the conditions, modulo 998244353.ExampleInput 42 51 2 44 51 2 22 3 43 4 35 61 2 31 3 23 4 63 5 110 2001 2 32 3 333 4 2001 5 1325 6 15 7 297 8 1877 9 207 10 4Output 1 8 80 650867886 NoteIn the first sample, there is only one graph, which is the given tree.In the second samle, the given tree looks like this: All possible graphs for the second sample are shown below, the minimum spanning tree is highlighted in red:
42 51 2 44 51 2 22 3 43 4 35 61 2 31 3 23 4 63 5 110 2001 2 32 3 333 4 2001 5 1325 6 15 7 297 8 1877 9 207 10 4
1 8 80 650867886
2 seconds
256 megabytes
['combinatorics', 'divide and conquer', 'dsu', 'graphs', 'greedy', 'sortings', 'trees', '*2000']
F. Sum and Producttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have an array a of length n.Your task is to answer q queries: given x,y, find the number of pairs i and j (1 \le i < j \le n) that both a_i + a_j = x and a_i \cdot a_j = y.That is, for the array [1,3,2] and asking for x=3,y=2 the answer is 1: i=1 and j=2 fail because 1 + 3 = 4 and not 3, also 1 \cdot 3=3 and not 2; i=1 and j=3 satisfies both conditions; i=2 and j=3 fail because 3 + 2 = 5 and not 3, also 3 \cdot 2=6 and not 2; InputThe first line contains one integer t (1\le t\le 10^4) — the number of test cases.The second line of each test case contains one integer n (1 \le n \le 2\cdot 10^5) — the length of the array a.The third line of each test case contains n integers a_1,a_2,\dots,a_n (1 \le |a_i| \le 10^9) — array a.The fourth line of each test case contains the integer q (1 \le q \le 2\cdot 10^5) — the number of requests.The next q lines contain two numbers each x and y (1 \le |x|\le 2\cdot 10^9,1\le |y|\le 10^{18}) — request.It is guaranteed that the sum of n over all test cases does not exceed 2\cdot 10^5. This is also guaranteed for the sum of q values.OutputFor each test case print a line with q numbers — the answers to the queries.ExampleInput 331 3 243 25 63 15 541 1 1 112 161 4 -2 3 3 332 -8-1 -27 12Output 1 1 0 0 6 1 1 3 NoteFor the first test case, let's analyze each pair of numbers separately: pair (a_1,a_2): a_1 + a_2 = 4, a_1 \cdot a_2 = 3 pair (a_1,a_3): a_1 + a_3 = 3, a_1 \cdot a_3 = 2 pair (a_2,a_3): a_2 + a_3 = 5, a_2 \cdot a_3 = 6 From this, we can see that for the first query, the pair (a_1,a_3) is suitable, for the second query, it is (a_2,a_3), and there are no suitable pairs for the third and fourth queries.In the second test case, all combinations of pairs are suitable.
331 3 243 25 63 15 541 1 1 112 161 4 -2 3 3 332 -8-1 -27 12
1 1 0 0 6 1 1 3
4 seconds
256 megabytes
['binary search', 'data structures', 'math', '*1600']
E. Power of Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given n points with integer coordinates x_1,\dots x_n, which lie on a number line.For some integer s, we construct segments [s,x_1], [s,x_2], \dots, [s,x_n]. Note that if x_i<s, then the segment will look like [x_i,s]. The segment [a, b] covers all integer points a, a+1, a+2, \dots, b.We define the power of a point p as the number of segments that intersect the point with coordinate p, denoted as f_p.Your task is to compute \sum\limits_{p=1}^{10^9}f_p for each s \in \{x_1,\dots,x_n\}, i.e., the sum of f_p for all integer points from 1 to 10^9.For example, if the initial coordinates are [1,2,5,7,1] and we choose s=5, then the segments will be: [1,5],[2,5],[5,5],[5,7],[1,5]. And the powers of the points will be: f_1=2, f_2=3, f_3=3, f_4=3, f_5=5, f_6=1, f_7=1, f_8=0, \dots, f_{10^9}=0. Their sum is 2+3+3+3+5+1+1=18.InputThe first line contains an integer t (1\le t\le 10^4) — the number of test cases.The first line of each test case contains an integer n (1 \le n \le 2\cdot 10^5) — the number of points.The second line contains n integers x_1,x_2 \dots x_n (1 \le x_i \le 10^9) — the coordinates of the points.It is guaranteed that the sum of the values of n over all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output n integers, where the i-th integer is equal to the sum of the powers of all points for s=x_i.ExampleInput 331 4 351 2 5 7 141 10 100 1000Output 8 7 6 16 15 18 24 16 1111 1093 1093 2893 NoteIn the first test case we first choose s=x_1=1, then the following segments are formed: [1,1],[1,4],[1,3]. The powers of the points will be as follows: f_1=3, f_2=2, f_3=2, f_4=1, f_5=0 \dots The sum of powers of the points: 3+2+2+1+0+\dots+0=8. After that we choose s=x_2=4. Then there will be such segments: [1,4],[4,4],[3,4], and powers of the points are f_1=1, f_2=1, f_3=2, f_4=3. At the end we take s=x_3=3 and the segments look like this: [1,3],[3,4],[3,3], the powers of the points are f_1=1, f_2=1, f_3=3, f_4=1.
331 4 351 2 5 7 141 10 100 1000
8 7 6 16 15 18 24 16 1111 1093 1093 2893
2 seconds
256 megabytes
['math', 'sortings', '*1500']
D. Strong Verticestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven two arrays a and b, both of length n. Elements of both arrays indexed from 1 to n. You are constructing a directed graph, where edge from u to v (u\neq v) exists if a_u-a_v \ge b_u-b_v.A vertex V is called strong if there exists a path from V to all other vertices.A path in a directed graph is a chain of several vertices, connected by edges, such that moving from the vertex u, along the directions of the edges, the vertex v can be reached.Your task is to find all strong vertices.For example, if a=[3,1,2,4] and b=[4,3,2,1], the graph will look like this: The graph has only one strong vertex with number 4 InputThe first line contains an integer t (1\le t\le 10^4) — the number of test cases.The first line of each test case contains an integer n (2 \le n \le 2\cdot 10^5) — the length of a and b.The second line of each test case contains n integers a_1,a_2 \dots a_n (-10^9 \le a_i \le 10^9) — the array a.The third line of each test case contains n integers b_1,b_2 \dots b_n (-10^9 \le b_i \le 10^9) — the array b.It is guaranteed that the sum of n for all test cases does not exceed 2\cdot 10^5.OutputFor each test case, output two lines: in the first line, output the number of strong vertices, and in the second line, output all strong vertices in ascending order.ExampleInput 543 1 2 44 3 2 151 2 4 1 25 2 3 3 121 22 130 2 11 3 235 7 4-2 -3 -6Output 1 4 2 3 5 1 2 3 1 2 3 2 2 3 NoteThe first sample is covered in the problem statement.For the second sample, the graph looks like this: The graph has two strong vertices with numbers 3 and 5. Note that there is a bidirectional edge between vertices 3 and 5. In the third sample, the vertices are connected by a single directed edge from vertex 2 to vertex 1, so the only strong vertex is 2.In the fourth sample, all vertices are connected to each other by bidirectional edges, so there is a path from every vertex to any other vertex.
543 1 2 44 3 2 151 2 4 1 25 2 3 3 121 22 130 2 11 3 235 7 4-2 -3 -6
1 4 2 3 5 1 2 3 1 2 3 2 2 3
2 seconds
256 megabytes
['math', 'sortings', 'trees', '*1300']
C. Assembly via Minimumstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSasha has an array a of n integers. He got bored and for all i, j (i < j), he wrote down the minimum value of a_i and a_j. He obtained a new array b of size \frac{n\cdot (n-1)}{2}.For example, if a= [2,3,5,1], he would write [\min(2, 3), \min(2, 5), \min(2, 1), \min(3, 5), \min(3, 1), min(5, 1)] = [2, 2, 1, 3, 1, 1].Then, he randomly shuffled all the elements of the array b.Unfortunately, he forgot the array a, and your task is to restore any possible array a from which the array b could have been obtained.The elements of array a should be in the range [-10^9,10^9].InputThe first line contains a single integer t (1\le t\le 200) — the number of test cases.The first line of each test case contains a single integer n (2\le n\le 10^3) — the length of array a.The second line of each test case contains \frac{n\cdot (n-1)}{2} integers b_1,b_2,\dots,b_{\frac{n\cdot (n-1)}{2}} (−10^9\le b_i\le 10^9) — the elements of array b.It is guaranteed that the sum of n over all tests does not exceed 10^3 and for each array b in the test, there exists an original array.OutputFor each test case, output any possible array a of length n.ExampleInput 531 3 121047 5 3 5 3 352 2 2 2 2 2 2 2 2 253 0 0 -2 0 -2 0 0 -2 -2Output 1 3 3 10 10 7 5 3 12 2 2 2 2 2 0 -2 0 3 5NoteIn the first sample, Sasha chose the array [1,3,3], then the array b will look like [\min(a_1,a_2)=1, \min(a_1,a_3)=1, \min(a_2,a_3)=3], after shuffling its elements, the array can look like [1,3,1].In the second sample, there is only one pair, so the array [10,10] is suitable. Another suitable array could be [15,10].
531 3 121047 5 3 5 3 352 2 2 2 2 2 2 2 2 253 0 0 -2 0 -2 0 0 -2 -2
1 3 3 10 10 7 5 3 12 2 2 2 2 2 0 -2 0 3 5
2 seconds
256 megabytes
['greedy', 'sortings', '*1200']
B. Maximum Roundingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a natural number x. You can perform the following operation: choose a positive integer k and round x to the k-th digit Note that the positions are numbered from right to left, starting from zero. If the number has k digits, it is considered that the digit at the k-th position is equal to 0.The rounding is done as follows: if the digit at the (k-1)-th position is greater than or equal to 5, then the digit at the k-th position is increased by 1, otherwise the digit at the k-th position remains unchanged (mathematical rounding is used). if before the operations the digit at the k-th position was 9, and it should be increased by 1, then we search for the least position k' (k'>k), where the digit at the k'-th position is less than 9 and add 1 to the digit at the k'-th position. Then we assign k=k'. after that, all digits which positions are less than k are replaced with zeros.Your task is to make x as large as possible, if you can perform the operation as many times as you want.For example, if x is equal to 3451, then if you choose consecutively: k=1, then after the operation x will become 3450 k=2, then after the operation x will become 3500 k=3, then after the operation x will become 4000 k=4, then after the operation x will become 0 To maximize the answer, you need to choose k=2 first, and then k=3, then the number will become 4000.InputThe first line contains a single integer t (1\le t\le 10^4) — the number of test cases.Each test case consists of positive integer x with a length of up to 2 \cdot 10^5. It is guaranteed that there are no leading zeros in the integer.It is guaranteed that the sum of the lengths of all integers x over all test cases does not exceed 2 \cdot 10^5.OutputFor each set of input data, output the maximum possible value of x after the operations. The number should not have leading zeros in its representation.ExampleInput 101599913198020444204456094741986040862016542130810467Output 1 10 100 1000 2000 20444 21000 100000 420000 41000000000000000000 NoteIn the first sample, it is better not to perform any operations.In the second sample, you can perform one operation and obtain 10.In the third sample, you can choose k=1 or k=2. In both cases the answer will be 100.
101599913198020444204456094741986040862016542130810467
1 10 100 1000 2000 20444 21000 100000 420000 41000000000000000000
2 seconds
256 megabytes
['greedy', 'implementation', 'math', '*1100']
A. Array Coloringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array consisting of n integers. Your task is to determine whether it is possible to color all its elements in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored.For example, if the array is [1,2,4,3,2,3,5,4], we can color it as follows: [\color{blue}{1},\color{blue}{2},\color{red}{4},\color{blue}{3},\color{red}{2},\color{red}{3},\color{red}{5},\color{red}{4}], where the sum of the blue elements is 6 and the sum of the red elements is 18.InputThe first line contains an integer t (1 \le t \le 1000) — the number of test cases.Each test case begins with a line containing an integer n (2 \le n \le 50) — the length of the array a.The next line contains n integers a_1,a_2, \dots, a_n (1 \le a_i \le 50) — the elements of the array a.OutputFor each test case, output "YES" (without quotes) if it is possible to color the array in two colors in such a way that the sums of the elements of both colors have the same parity and each color has at least one element colored, and "NO" otherwise.You can output "Yes" and "No" in any case (for example, the strings "yES", "yes", and "Yes" will be recognized as correct answers).ExampleInput 781 2 4 3 2 3 5 424 733 9 821 755 4 3 2 144 3 4 5250 48Output YES NO YES YES NO YES YES NoteThe first sample is described in the statement.In the second sample, there are only two colorings [\color{blue}{4},\color{red}{7}] and [\color{red}{4},\color{blue}{7}] , but in both cases the parity of sums is different.In the third sample, you can color [\color{blue}{3},\color{blue}{9},\color{red}{8}] and 12 and 8 are both even.
781 2 4 3 2 3 5 424 733 9 821 755 4 3 2 144 3 4 5250 48
YES NO YES YES NO YES YES
1 second
256 megabytes
['greedy', 'math', '*800']
E2. PermuTree (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the hard version of the problem. The differences between the two versions are the constraint on n and the time limit. You can make hacks only if both versions of the problem are solved.You are given a tree with n vertices rooted at vertex 1.For some permutation^\dagger a of length n, let f(a) be the number of pairs of vertices (u, v) such that a_u < a_{\operatorname{lca}(u, v)} < a_v. Here, \operatorname{lca}(u,v) denotes the lowest common ancestor of vertices u and v.Find the maximum possible value of f(a) over all permutations a of length n.^\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 n (2 \le n \le 10^6).The second line contains n - 1 integers p_2,p_3,\ldots,p_n (1 \le p_i < i) indicating that there is an edge between vertices i and p_i.OutputOutput the maximum value of f(a).ExamplesInput 5 1 1 3 3 Output 4 Input 2 1 Output 0 Input 6 1 2 2 1 5 Output 7 Input 4 1 1 1 Output 2 NoteThe tree in the first test: One possible optimal permutation a is [2, 1, 4, 5, 3] with 4 suitable pairs of vertices: (2, 3), since \operatorname{lca}(2, 3) = 1 and 1 < 2 < 4, (2, 4), since \operatorname{lca}(2, 4) = 1 and 1 < 2 < 5, (2, 5), since \operatorname{lca}(2, 5) = 1 and 1 < 2 < 3, (5, 4), since \operatorname{lca}(5, 4) = 3 and 3 < 4 < 5. The tree in the third test: The tree in the fourth test:
5 1 1 3 3
4
3 seconds
512 megabytes
['bitmasks', 'dfs and similar', 'dp', 'fft', 'greedy', 'implementation', 'math', 'trees', '*2700']
E1. PermuTree (easy version)time limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is the easy version of the problem. The differences between the two versions are the constraint on n and the time limit. You can make hacks only if both versions of the problem are solved.You are given a tree with n vertices rooted at vertex 1.For some permutation^\dagger a of length n, let f(a) be the number of pairs of vertices (u, v) such that a_u < a_{\operatorname{lca}(u, v)} < a_v. Here, \operatorname{lca}(u,v) denotes the lowest common ancestor of vertices u and v.Find the maximum possible value of f(a) over all permutations a of length n.^\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 n (2 \le n \le 5000).The second line contains n - 1 integers p_2,p_3,\ldots,p_n (1 \le p_i < i) indicating that there is an edge between vertices i and p_i.OutputOutput the maximum value of f(a).ExamplesInput 5 1 1 3 3 Output 4 Input 2 1 Output 0 Input 6 1 2 2 1 5 Output 7 Input 4 1 1 1 Output 2 NoteThe tree in the first test: One possible optimal permutation a is [2, 1, 4, 5, 3] with 4 suitable pairs of vertices: (2, 3), since \operatorname{lca}(2, 3) = 1 and 1 < 2 < 4, (2, 4), since \operatorname{lca}(2, 4) = 1 and 1 < 2 < 5, (2, 5), since \operatorname{lca}(2, 5) = 1 and 1 < 2 < 3, (5, 4), since \operatorname{lca}(5, 4) = 3 and 3 < 4 < 5. The tree in the third test: The tree in the fourth test:
5 1 1 3 3
4
2 seconds
512 megabytes
['dfs and similar', 'dp', 'trees', '*1800']
D. More Wrongtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.The jury has hidden a permutation^\dagger p of length n.In one query, you can pick two integers l and r (1 \le l < r \le n) by paying (r - l)^2 coins. In return, you will be given the number of inversions^\ddagger in the subarray [p_l, p_{l + 1}, \ldots p_r].Find the index of the maximum element in p by spending at most 5 \cdot n^2 coins.Note: the grader is not adaptive: the permutation is fixed before any queries are made.^\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).^\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. For example, the array [10,2,6,3] contains 4 inversions. The inversions are (1,2),(1,3),(1,4), and (3,4).InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 100) — the number of test cases.The only line of each test case contains a single integer n (2 \le n \le 2000) — the length of the hidden permutation p.It is guaranteed that the sum of n over all test cases does not exceed 2000.InteractionThe interaction for each test case begins by reading the integer n.To make a query, output "? l r" (1 \le l < r \le n) without quotes. Afterwards, you should read one single integer — the answer for your query.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 exceed 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.When you are ready to give the final answer, output "! i" (1 \le i \le n) without quotes — the index of the maximum of the hidden permutation. After solving a test case, your program should move to the next one immediately. After solving all test cases, your program should be terminated immediately.After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. HacksTo hack, use the following format:The first line contains an 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 2000) — the length of the hidden permutation p.The second line of each test case contains n integers p_1,p_2,\ldots, p_n (1 \le p_i \le n), p must be a permutation.The sum of n over all test cases should not exceed 2000.ExampleInput 2 4 1 0 2 1Output ? 1 3 ? 3 4 ! 4 ? 1 2 ! 1NoteIn the first test, the interaction proceeds as follows:SolutionJuryExplanation2There are 2 test cases.4In the first test case, the hidden permutation is [1,3,2,4], with length 4.? 1 3 1The solution requests the number of inversions in the subarray [1,3,2] by paying 4 coins, and the jury responds with 1.? 3 4 0The solution requests the number of inversions in the subarray [2,4] by paying 1 coin, and the jury responds with 0.! 4 The solution has somehow determined that p_4 = 4, and outputs it. Since the output is correct, the jury continues to the next test case.2In the second test case, the hidden permutation is [2,1], with length 2.? 1 2 1The solution requests the number of inversions in the subarray [2,1] by paying 1 coin, and the jury responds with 1.! 1 The solution has somehow determined that p_1 = 2, and outputs it. Since the output is correct and there are no more test cases, the jury and the solution exit.Note that the line breaks in the example input and output are for the sake of clarity, and do not occur in the real interaction.
2 4 1 0 2 1
? 1 3 ? 3 4 ! 4 ? 1 2 ! 1
2 seconds
256 megabytes
['divide and conquer', 'interactive', '*2100']
C. To Become Maxtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of integers a of length n.In one operation you: Choose an index i such that 1 \le i \le n - 1 and a_i \le a_{i + 1}. Increase a_i by 1. Find the maximum possible value of \max(a_1, a_2, \ldots a_n) that you can get after performing this operation at most k times.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 100) — the number of test cases. The description of the test cases follows.The first line of each test case contains two integers n and k (2 \le n \le 1000, 1 \le k \le 10^{8}) — the length of the array a and the maximum number of operations that can be performed.The second line of each test case contains n integers a_1,a_2,\ldots,a_n (1 \le a_i \le 10^{8}) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 1000.OutputFor each test case output a single integer — the maximum possible maximum of the array after performing at most k operations.ExampleInput 63 41 3 35 61 3 4 5 14 131 1 3 1795 34 3 2 2 25 66 5 4 1 52 173 5Output 4 7 179 5 7 6 NoteIn the first test case, one possible optimal sequence of operations is: [\color{red}{1}, 3, 3] \rightarrow [2, \color{red}{3}, 3] \rightarrow [\color{red}{2}, 4, 3] \rightarrow [\color{red}{3}, 4, 3] \rightarrow [4, 4, 3].In the second test case, one possible optimal sequence of operations is: [1, \color{red}{3}, 4, 5, 1] \rightarrow [1, \color{red}{4}, 4, 5, 1] \rightarrow [1, 5, \color{red}{4}, 5, 1] \rightarrow [1, 5, \color{red}{5}, 5, 1] \rightarrow [1, \color{red}{5}, 6, 5, 1] \rightarrow [1, \color{red}{6}, 6, 5, 1] \rightarrow [1, 7, 6, 5, 1].
63 41 3 35 61 3 4 5 14 131 1 3 1795 34 3 2 2 25 66 5 4 1 52 173 5
4 7 179 5 7 6
2 seconds
256 megabytes
['binary search', 'brute force', 'data structures', 'dp', '*1600']
B. Good Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array of positive integers a of length n.Let's call an array of positive integers b of length n good if: a_i \neq b_i for all i from 1 to n, a_1 + a_2 +\ldots + a_n = b_1 + b_2 + \ldots + b_n. Does a good array exist?InputEach test contains multiple test cases. The first line of input 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, \dots, a_n (1 \le a_i \le 10 ^ 9) — the elements of the array a.It is guaranteed that the sum of n over all test cases does not exceed 10^5.OutputFor each test case, output "YES" (without quotes) if there exists a good array, 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 636 1 221 143 1 2 411751 2 1 1 13618343152 819343431 1000000000Output YES NO YES NO NO YES NoteIn the first test case, a possible good array is [3, 3, 3]. Some examples of not good arrays are: [8, 0, 1] — the array does not consist of only positive integers, [5, 2, 4] — the array does not have the same sum as the given array, [5, 2, 2] — the third element is equal to the third element of the given array. In the second test case, [1, 1] is the only array of positive integers of length 2 that has the sum of it's elements equal to 2. Since [1, 1] is not a good array, the answer is "NO".
636 1 221 143 1 2 411751 2 1 1 13618343152 819343431 1000000000
YES NO YES NO NO YES
1 second
256 megabytes
['implementation', 'math', '*900']
A. Tales of a Sorttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlphen has an array of positive integers a of length n.Alphen can perform the following operation: For all i from 1 to n, replace a_i with \max(0, a_i - 1). Alphen will perform the above operation until a is sorted, that is a satisfies a_1 \leq a_2 \leq \ldots \leq a_n. How many operations will Alphen perform? Under the constraints of the problem, it can be proven that Alphen will perform a finite number of operations.InputEach test contains multiple test cases. The first line of input contains a single integer t (1 \le t \le 500) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (2 \le n \le 50) — the length of the array a.The second line of each test case contains n integers a_1, a_2, \dots, a_n (1 \le a_i \le 10 ^ 9) — the elements of the array a.OutputFor each test case, output a single integer — the number of operations that Alphen will perform.ExampleInput 731 2 352 1 2 1 243 1 5 427 754 1 3 2 552 3 1 4 531000000000 1 2Output 0 2 5 0 4 3 1000000000 NoteIn the first test case, we have a=[1,2,3]. Since a is already sorted, Alphen will not need to perform any operations. So, the answer is 0.In the second test case, we have a=[2,1,2,1,2]. Since a is not initially sorted, Alphen will perform one operation to make a=[1,0,1,0,1]. After performing one operation, a is still not sorted, so Alphen will perform another operation to make a=[0,0,0,0,0]. Since a is sorted, Alphen will not perform any other operations. Since Alphen has performed two operations in total, the answer is 2.
731 2 352 1 2 1 243 1 5 427 754 1 3 2 552 3 1 4 531000000000 1 2
0 2 5 0 4 3 1000000000
1 second
256 megabytes
['implementation', '*800']
B. Longest Divisors Intervaltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven a positive integer n, find the maximum size of an interval [l, r] of positive integers such that, for every i in the interval (i.e., l \leq i \leq r), n is a multiple of i.Given two integers l\le r, the size of the interval [l, r] is r-l+1 (i.e., it coincides with the number of integers belonging to the interval).InputThe first line contains a single integer t (1 \le t \le 10^4) — the number of test cases.The only line of the description of each test case contains one integer n (1 \leq n \leq 10^{18}).OutputFor each test case, print a single integer: the maximum size of a valid interval.ExampleInput 1014099099042044745601699589137065729723659882203458280803877017195378264306201968835781298538648023412808056621000000000000000000Output 1 2 3 6 4 22 3 1 2 2 NoteIn the first test case, a valid interval with maximum size is [1, 1] (it's valid because n = 1 is a multiple of 1) and its size is 1.In the second test case, a valid interval with maximum size is [4, 5] (it's valid because n = 40 is a multiple of 4 and 5) and its size is 2.In the third test case, a valid interval with maximum size is [9, 11].In the fourth test case, a valid interval with maximum size is [8, 13].In the seventh test case, a valid interval with maximum size is [327869, 327871].
1014099099042044745601699589137065729723659882203458280803877017195378264306201968835781298538648023412808056621000000000000000000
1 2 3 6 4 22 3 1 2 2
2 seconds
256 megabytes
['brute force', 'combinatorics', 'greedy', 'math', 'number theory', '*900']
A. Dalton the Teachertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputDalton is the teacher of a class with n students, numbered from 1 to n. The classroom contains n chairs, also numbered from 1 to n. Initially student i is seated on chair p_i. It is guaranteed that p_1,p_2,\dots, p_n is a permutation of length n.A student is happy if his/her number is different from the number of his/her chair. In order to make all of his students happy, Dalton can repeatedly perform the following operation: choose two distinct students and swap their chairs. What is the minimum number of moves required to make all the students happy? One can show that, under the constraints of this problem, it is possible to make all the students happy with a finite number of moves.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 contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 1000). The description of the test cases follows.The first line contains a single integer n (2 \le n \le 10^5) — the number of students.The second line contains n integers p_1, p_2, \ldots, p_n (1 \le p_i \le n) — p_i denotes the initial chair of student i. 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 the minimum number of moves required.ExampleInput 522 131 2 351 2 5 4 341 2 4 31010 2 1 3 6 5 4 7 9 8Output 0 2 2 1 1 NoteIn the first test case, both students are already happy, so Dalton can perform 0 moves.In the second test case, Dalton can swap the chairs of students 1 and 2 to get the array [2, 1, 3]. Then he can swap chairs of students 2 and 3 to get the array [2, 3, 1]. At this point all the students are happy, and he performed 2 moves. It is impossible to perform the task with fewer moves.In the third test case, by swapping the chairs of students 1 and 2 and then swapping the chairs of students 4 and 5, Dalton gets the array [2, 1, 5, 3, 4] in 2 moves.
522 131 2 351 2 5 4 341 2 4 31010 2 1 3 6 5 4 7 9 8
0 2 2 1 1
1 second
256 megabytes
['greedy', 'math', '*800']
F. Mark and Spaceshiptime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputMark loves to move fast. So he made a spaceship that works in 4-dimensional space. He wants to use the spaceship to complete missions as fast as possible. In each mission, the spaceship starts at (0, 0, 0, 0) and needs to end up at (a, b, c, d). To do this, he instructs the spaceship's computer to execute a series of moves, where each move is a unit step in one of the eight cardinal directions: (\pm 1, 0, 0, 0), (0, \pm 1, 0, 0), (0, 0, \pm 1, 0), (0, 0, 0, \pm 1).Unfortunately, he also moved fast when building the spaceship, so there is a bug in the spaceship's code. The first move will be executed once, the second move will be executed twice, the third move will be executed thrice, and so on. In general, the i-th move will be executed i times.For any four integers a, b, c, d, let f(a, b, c, d) be the minimum number of moves of a mission that ends up at (a, b, c, d). Compute the sum of f(a, b, c, d) over all points (with integer coordinates) such that -A\le a\le A, -B\le b\le B, -C\le c\le C, -D\le d\le D.InputThe only line of the input contains the four integers A, B, C, D (0\le A,B,C,D\le 1000).OutputPrint the sum of f(a, b, c, d) over the set of points described in the statement.ExamplesInput 1 0 0 0 Output 2 Input 1 1 0 1 Output 82 Input 3 2 4 1 Output 4616 NoteIn the first sample, one has to compute f(-1, 0, 0, 0)+f(0, 0, 0, 0) + f(1, 0, 0, 0) = 1 + 0 + 1 = 2.In the second sample, one has to compute the sum of f(a, b, c, d) over 27 different points (a, b, c, d). Let us describe the value of f(a, b, c, d) for some of them: It holds f(-1, 0, 0, -1)=3 and it may be achieved with the following sequence of moves (an arrow \xrightarrow{\pm i} denotes that the move is performed on the i-th coordinate): (0, 0, 0, 0) \xrightarrow{-1} (-1, 0, 0, 0) \xrightarrow{+4} (-1, 0, 0, 2) \xrightarrow{-4} (-1, 0, 0, -1). It holds f(1, 1, 0, 1) = 5 and it may be achieved with the following sequence of moves: (0, 0, 0, 0) \xrightarrow{+1} (1, 0, 0, 0) \xrightarrow{-2} (1, -2, 0, 0) \xrightarrow{+2} (1, 1, 0, 0) \xrightarrow{-4} (1, 1, 0, -4) \xrightarrow{+4} (1, 1, 0, 1). In the third sample, one has to compute the sum of f(a, b, c, d) over 7\cdot5\cdot 9\cdot 3 points. One of them is (3, 2, 4, 1). It holds f(3, 2, 4, 1) = 4 and it may be achieved with the following sequence of moves: (0, 0, 0, 0) \xrightarrow{+4} (0, 0, 0, 1) \xrightarrow{+2} (0, 2, 0, 1) \xrightarrow{+1} (3, 2, 0, 1) \xrightarrow{+3} (3, 2, 4, 1).
1 0 0 0
2
3 seconds
512 megabytes
['brute force', 'dp', '*3500']
E. Game Bundlestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRishi is developing games in the 2D metaverse and wants to offer game bundles to his customers. Each game has an associated enjoyment value. A game bundle consists of a subset of games whose total enjoyment value adds up to 60.Your task is to choose k games, where 1 \leq k \leq 60, along with their respective enjoyment values a_1, a_2, \dots, a_k, in such a way that exactly m distinct game bundles can be formed.InputThe input is a single integer m (1 \le m \le 10^{10}) — the desired number of game bundles.OutputThe first line should contain an integer k (1 \le k \le 60) — the number of games.The second line should contain k integers, a_1, a_2, \dots, a_k (1 \le a_1, a_2, \dots, a_k \le 60) — the enjoyment values of the k games.ExamplesInput 4 Output 4 20 20 20 20 Input 722 Output 15 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1Input 1 Output 1 60 NoteIn the first sample, any subset of size 3 is a game bundle. There are 4 such subsets.
4
4 20 20 20 20
3 seconds
512 megabytes
['brute force', 'constructive algorithms', 'dp', 'greedy', 'math', '*3000']
D. Michael and Hoteltime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMichael and Brian are stuck in a hotel with n rooms, numbered from 1 to n, and need to find each other. But this hotel's doors are all locked and the only way of getting around is by using the teleporters in each room. Room i has a teleporter that will take you to room a_i (it might be that a_i = i). But they don't know the values of a_1,a_2, \dots, a_n.Instead, they can call up the front desk to ask queries. In one query, they give a room u, a positive integer k, and a set of rooms S. The hotel concierge answers whether a person starting in room u, and using the teleporters k times, ends up in a room in S.Brian is in room 1. Michael wants to know the set A of rooms so that if he starts in one of those rooms they can use the teleporters to meet up. He can ask at most 2000 queries.The values a_1, a_2, \dots, a_n are fixed before the start of the interaction and do not depend on your queries. In other words, the interactor is not adaptive.InputThe input contains a single integer n (2 \leq n \leq 500).InteractionTo ask a query, print a line in the format "? u k |S| S_1 S_2 ... S_|S|" with 1 \leq u, S_1, \ldots, S_{|S|} \leq n, all the S_i distinct, and 1 \leq k \leq 10^9.As a response to the query you will get "1" if the answer is yes, and "0" if the answer is no.To output an answer, you should print "! |A| A_1 A_2 ... A_|A|" with 1 \leq A_1, \ldots, A_{|A|} \leq n all distinct. Printing the answer doesn't count as a query.See the interaction example for more clarity.If you ask too many queries or you ask a malformed query, you will get Wrong answer.After printing a query do not forget to output the end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages. Hack formatFor the hacks use the following format.The first line should contain n — the number of rooms.The second line should contains n integers a_1, a_2, \dots, a_n — the teleporter in room i leads to room a_i.ExampleInput 5 0 1Output ? 3 5 2 2 3 ? 2 5 2 2 3 ! 3 1 3 4NoteIn the sample test, there are n=5 rooms and the (hidden) array describing the behavior of the teleporters is [1, 2, 1, 3, 2]. The first query asks whether starting from room number a=3, and using the teleporters 5 times, one ends up in one of the two rooms S=\{2, 3\}. This action results in ending up in the room 1, so the answer is 0. The second query asks whether starting from room number a=2, and using the teleporters 5 times, one ends up in one of the two rooms S=\{2, 3\}. This action results in ending up in the room 2, so the answer is 1.
5 0 1
? 3 5 2 2 3 ? 2 5 2 2 3 ! 3 1 3 4
2 seconds
256 megabytes
['binary search', 'interactive', 'trees', '*3000']
C. Expected Destructiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a set S of n distinct integers between 1 and m.Each second you do the following steps: Pick an element x in S uniformly at random. Remove x from S. If x+1 \leq m and x+1 is not in S, add x+1 to S. What is the expected number of seconds until S is empty?Output the answer modulo 1\,000\,000\,007.Formally, let P = 1\,000\,000\,007. It can be shown that the answer can be expressed as an irreducible fraction \frac{a}{b}, where a and b are integers and b \not \equiv 0 \pmod{P}. Output the integer equal to a \cdot b^{-1} \bmod P. In other words, output an integer z such that 0 \le z < P and z \cdot b \equiv a \pmod{P}.InputThe first line contains two integers n and m (1 \leq n \leq m \leq 500) — the number of elements in the set S and the upper bound on the value of the elements in S.The second line contains n integers S_1,\,S_2,\,\dots,\,S_n (1 \leq S_1 < S_2 < \ldots < S_n \leq m) — the elements of the set S.OutputOutput a single integer — the expected number of seconds until S is empty, modulo 1\,000\,000\,007.ExamplesInput 2 3 1 3 Output 750000009 Input 5 10 1 2 3 4 5 Output 300277731 Input 5 10 2 3 6 8 9 Output 695648216 Input 1 100 1 Output 100 NoteFor test 1, here is a list of all the possible scenarios and their probabilities: [1, 3] (50% chance) \to [1] \to [2] \to [3] \to [] [1, 3] (50% chance) \to [2, 3] (50% chance) \to [2] \to [3] \to [] [1, 3] (50% chance) \to [2, 3] (50% chance) \to [3] \to [] Adding them up, we get \frac{1}{2}\cdot 4 + \frac{1}{4} \cdot 4 + \frac{1}{4} \cdot 3 = \frac{15}{4}. We see that 750000009 \cdot 4 \equiv 15 \pmod{1\,000\,000\,007}.
2 3 1 3
750000009
1 second
256 megabytes
['combinatorics', 'dp', 'math', 'probabilities', '*2500']
B. Earn or Unlocktime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputAndrea is playing the game Tanto Cuore. He has a deck of n cards with values a_1, \ldots, a_n from top to bottom. Each card can be either locked or unlocked. Initially, only the topmost card is unlocked. The game proceeds in turns. In each turn, Andrea chooses an unlocked card in the deck — the value written on the card is v — and performs exactly one of the following two operations: Unlock the first v locked cards in the deck from the top. If there are less than v locked cards in the deck, then unlock all the locked cards. Earn v victory points. In both cases, after performing the operation, he removes the card from the deck.The game ends when all the cards remaining in the deck are locked, or there are no more cards in the deck.What is the maximum number of victory points Andrea can earn?InputThe first line contains a single integer n (1 \leq n \leq 10^5) — the number of cards in the deck.The second line contains n integers a_1, \ldots, a_n (0 \leq a_1, \ldots, a_n \leq n) — the values of the cards in the deck.OutputOutput a single integer — the maximum number of victory points Andrea can earn.ExamplesInput 2 1 2 Output 2 Input 5 2 4 5 0 1 Output 9 Input 4 0 4 4 4 Output 0 NoteIn the first sample test, the deck starts as [unlocked, locked]. Then, Andrea uses the first card to unlock the second card. Then he uses the second card to earn 2 victory points.In the second sample test, Andrea can use the first card to unlock the second and the third card. Then he uses the second and the third card to earn 4+5=9 victory points.In the third sample test, Andrea can't unlock any cards or gain any victory points with the first card.
2 1 2
2
3 seconds
512 megabytes
['bitmasks', 'brute force', 'dp', '*2200']
A2. Dual (Hard Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPopskyy & tiasu - Dual⠀The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.You are given an array a_1, a_2,\dots, a_n of integers (positive, negative or 0). You can perform multiple operations on the array (possibly 0 operations).In one operation, you choose i, j (1 \leq i, j \leq n, they can be equal) and set a_i := a_i + a_j (i.e., add a_j to a_i).Make the array non-decreasing (i.e., a_i \leq a_{i+1} for 1 \leq i \leq n-1) in at most 31 operations. You do not need to minimize the number of operations.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line contains a single integer n (1 \le n \le 20) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (-20 \le a_i \le 20) — the array before performing the operations.OutputFor each test case, output your operations in the following format.The first line should contain an integer k (0 \le k \le 31) — the number of operations.The next k lines represent the k operations in order. Each of these k lines should contain two integers i and j (1 \leq i, j \leq n) — the corresponding operation consists in adding a_j to a_i.After all the operations, the array a_1, a_2,\dots, a_n must be non-decreasing.ExampleInput 1022 141 2 -10 352 1 1 1 180 0 0 0 0 0 0 051 2 -4 3 -101011 12 13 14 15 -15 -16 -17 -18 -1971 9 3 -4 -3 -2 -1310 9 8201 -14 2 -10 6 -5 10 -13 10 7 -14 19 -5 19 1 18 -16 -7 12 820-15 -17 -13 8 14 -13 10 -4 11 -4 -16 -6 15 -4 -2 7 -9 5 -5 17Output 1 2 1 3 4 4 4 4 3 4 4 2 1 3 1 4 1 5 1 0 7 3 4 3 4 5 4 5 4 5 4 5 4 5 4 15 6 1 6 1 6 1 7 2 7 2 7 2 8 3 8 3 8 3 9 4 9 4 9 4 10 5 10 5 10 5 8 3 4 3 4 2 4 2 4 2 4 2 4 1 4 1 4 3 2 1 3 1 3 1 31 14 1 18 7 13 11 15 11 6 4 5 17 19 6 19 12 10 5 11 12 1 17 15 19 16 10 14 2 16 11 20 7 7 6 9 5 3 6 6 14 17 18 18 14 12 3 17 16 8 18 13 16 9 8 14 8 16 2 11 8 12 7 31 5 12 19 13 9 1 5 17 18 19 6 16 15 8 6 9 15 14 7 10 19 7 17 20 14 4 15 20 4 3 1 8 16 12 16 15 5 6 12 10 11 15 20 3 20 19 13 14 11 14 18 10 7 3 12 17 4 7 13 2 11 13 NoteIn the first test case, by adding a_1 = 2 to a_2, we get the array [2, 3] which is non-decreasing.In the second test case, the array changes as: [1, 2, -10, 3] [1, 2, -10, 6] [1, 2, -10, 12] [1, 2, 2, 12] In the third test case, the final array is [2, 3, 3, 3, 3].
1022 141 2 -10 352 1 1 1 180 0 0 0 0 0 0 051 2 -4 3 -101011 12 13 14 15 -15 -16 -17 -18 -1971 9 3 -4 -3 -2 -1310 9 8201 -14 2 -10 6 -5 10 -13 10 7 -14 19 -5 19 1 18 -16 -7 12 820-15 -17 -13 8 14 -13 10 -4 11 -4 -16 -6 15 -4 -2 7 -9 5 -5 17
1 2 1 3 4 4 4 4 3 4 4 2 1 3 1 4 1 5 1 0 7 3 4 3 4 5 4 5 4 5 4 5 4 5 4 15 6 1 6 1 6 1 7 2 7 2 7 2 8 3 8 3 8 3 9 4 9 4 9 4 10 5 10 5 10 5 8 3 4 3 4 2 4 2 4 2 4 2 4 1 4 1 4 3 2 1 3 1 3 1 31 14 1 18 7 13 11 15 11 6 4 5 17 19 6 19 12 10 5 11 12 1 17 15 19 16 10 14 2 16 11 20 7 7 6 9 5 3 6 6 14 17 18 18 14 12 3 17 16 8 18 13 16 9 8 14 8 16 2 11 8 12 7 31 5 12 19 13 9 1 5 17 18 19 6 16 15 8 6 9 15 14 7 10 19 7 17 20 14 4 15 20 4 3 1 8 16 12 16 15 5 6 12 10 11 15 20 3 20 19 13 14 11 14 18 10 7 3 12 17 4 7 13 2 11 13
1 second
256 megabytes
['constructive algorithms', 'math', '*1900']
A1. Dual (Easy Version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPopskyy & tiasu - Dual⠀The only difference between the two versions of this problem is the constraint on the maximum number of operations. You can make hacks only if all versions of the problem are solved.You are given an array a_1, a_2,\dots, a_n of integers (positive, negative or 0). You can perform multiple operations on the array (possibly 0 operations).In one operation, you choose i, j (1 \leq i, j \leq n, they can be equal) and set a_i := a_i + a_j (i.e., add a_j to a_i).Make the array non-decreasing (i.e., a_i \leq a_{i+1} for 1 \leq i \leq n-1) in at most 50 operations. You do not need to minimize the number of operations.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 500). The description of the test cases follows.The first line contains a single integer n (1 \le n \le 20) — the length of the array.The second line contains n integers a_1, a_2, \ldots, a_n (-20 \le a_i \le 20) — the array before performing the operations.OutputFor each test case, output your operations in the following format.The first line should contain an integer k (0 \le k \le 50) — the number of operations.The next k lines represent the k operations in order. Each of these k lines should contain two integers i and j (1 \leq i, j \leq n) — the corresponding operation consists in adding a_j to a_i.After all the operations, the array a_1, a_2,\dots, a_n must be non-decreasing.ExampleInput 1022 141 2 -10 352 1 1 1 180 0 0 0 0 0 0 051 2 -4 3 -101011 12 13 14 15 -15 -16 -17 -18 -1971 9 3 -4 -3 -2 -1310 9 8201 -14 2 -10 6 -5 10 -13 10 7 -14 19 -5 19 1 18 -16 -7 12 820-15 -17 -13 8 14 -13 10 -4 11 -4 -16 -6 15 -4 -2 7 -9 5 -5 17Output 1 2 1 3 4 4 4 4 3 4 4 2 1 3 1 4 1 5 1 0 7 3 4 3 4 5 4 5 4 5 4 5 4 5 4 15 6 1 6 1 6 1 7 2 7 2 7 2 8 3 8 3 8 3 9 4 9 4 9 4 10 5 10 5 10 5 8 3 4 3 4 2 4 2 4 2 4 2 4 1 4 1 4 3 2 1 3 1 3 1 31 14 1 18 7 13 11 15 11 6 4 5 17 19 6 19 12 10 5 11 12 1 17 15 19 16 10 14 2 16 11 20 7 7 6 9 5 3 6 6 14 17 18 18 14 12 3 17 16 8 18 13 16 9 8 14 8 16 2 11 8 12 7 31 5 12 19 13 9 1 5 17 18 19 6 16 15 8 6 9 15 14 7 10 19 7 17 20 14 4 15 20 4 3 1 8 16 12 16 15 5 6 12 10 11 15 20 3 20 19 13 14 11 14 18 10 7 3 12 17 4 7 13 2 11 13 NoteIn the first test case, by adding a_1 = 2 to a_2, we get the array [2, 3] which is non-decreasing.In the second test case, the array changes as: [1, 2, -10, 3] [1, 2, -10, 6] [1, 2, -10, 12] [1, 2, 2, 12] In the third test case, the final array is [2, 3, 3, 3, 3].
1022 141 2 -10 352 1 1 1 180 0 0 0 0 0 0 051 2 -4 3 -101011 12 13 14 15 -15 -16 -17 -18 -1971 9 3 -4 -3 -2 -1310 9 8201 -14 2 -10 6 -5 10 -13 10 7 -14 19 -5 19 1 18 -16 -7 12 820-15 -17 -13 8 14 -13 10 -4 11 -4 -16 -6 15 -4 -2 7 -9 5 -5 17
1 2 1 3 4 4 4 4 3 4 4 2 1 3 1 4 1 5 1 0 7 3 4 3 4 5 4 5 4 5 4 5 4 5 4 15 6 1 6 1 6 1 7 2 7 2 7 2 8 3 8 3 8 3 9 4 9 4 9 4 10 5 10 5 10 5 8 3 4 3 4 2 4 2 4 2 4 2 4 1 4 1 4 3 2 1 3 1 3 1 31 14 1 18 7 13 11 15 11 6 4 5 17 19 6 19 12 10 5 11 12 1 17 15 19 16 10 14 2 16 11 20 7 7 6 9 5 3 6 6 14 17 18 18 14 12 3 17 16 8 18 13 16 9 8 14 8 16 2 11 8 12 7 31 5 12 19 13 9 1 5 17 18 19 6 16 15 8 6 9 15 14 7 10 19 7 17 20 14 4 15 20 4 3 1 8 16 12 16 15 5 6 12 10 11 15 20 3 20 19 13 14 11 14 18 10 7 3 12 17 4 7 13 2 11 13
1 second
256 megabytes
['constructive algorithms', 'math', '*1400']
B. Fibonaccharsistime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNtarsis has received two integers n and k for his birthday. He wonders how many fibonacci-like sequences of length k can be formed with n as the k-th element of the sequence. A sequence of non-decreasing non-negative integers is considered fibonacci-like if f_i = f_{i-1} + f_{i-2} for all i > 2, where f_i denotes the i-th element in the sequence. Note that f_1 and f_2 can be arbitrary.For example, sequences such as [4,5,9,14] and [0,1,1] are considered fibonacci-like sequences, while [0,0,0,1,1], [1, 2, 1, 3], and [-1,-1,-2] are not: the first two do not always satisfy f_i = f_{i-1} + f_{i-2}, the latter does not satisfy that the elements are non-negative.Impress Ntarsis by helping him with this task.InputThe first line contains an integer t (1 \leq t \leq 2 \cdot 10^5), the number of test cases. The description of each test case is as follows.Each test case contains two integers, n and k (1 \leq n \leq 2 \cdot 10^5, 3 \leq k \leq 10^9).It is guaranteed the sum of n over all test cases does not exceed 2 \cdot 10^5.OutputFor each test case output an integer, the number of fibonacci-like sequences of length k such that the k-th element in the sequence is n. That is, output the number of sequences f of length k so f is a fibonacci-like sequence and f_k = n. It can be shown this number is finite.ExampleInput 822 43 955 1142069 669420 469 14341 31 4Output 4 0 1 1052 11571 0 1 0 NoteThere are 4 valid fibonacci-like sequences for n = 22, k = 4: [6,8,14,22], [4,9,13,22], [2,10,12,22], [0,11,11,22]. For n = 3, k = 9, it can be shown that there are no fibonacci-like sequences satisfying the given conditions.For n = 55, k = 11, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] is the only fibonacci-like sequence.
822 43 955 1142069 669420 469 14341 31 4
4 0 1 1052 11571 0 1 0
2 seconds
256 megabytes
['binary search', 'brute force', 'math', '*1200']
A. Desortingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputCall an array a of length n sorted if a_1 \leq a_2 \leq \ldots \leq a_{n-1} \leq a_n.Ntarsis has an array a of length n. He is allowed to perform one type of operation on it (zero or more times): Choose an index i (1 \leq i \leq n-1). Add 1 to a_1, a_2, \ldots, a_i. Subtract 1 from a_{i+1}, a_{i+2}, \ldots, a_n. The values of a can be negative after an operation.Determine the minimum operations needed to make a not sorted.InputEach test contains multiple test cases. The first line contains the number of test cases t (1 \le t \le 100). The description of the test cases follows.The first line of each test case contains a single integer n (2 \leq n \leq 500) — the length of the array a.The next line contains n integers a_1, a_2, \ldots, a_n (1 \leq a_i \leq 10^9) — the values of array a.It is guaranteed that the sum of n across all test cases does not exceed 500.OutputOutput the minimum number of operations needed to make the array not sorted.ExampleInput 421 141 8 10 1331 3 231 9 14Output 1 2 0 3 NoteIn the first case, we can perform 1 operation to make the array not sorted: Pick i = 1. The array a then becomes [2, 0], which is not sorted. In the second case, we can perform 2 operations to make the array not sorted: Pick i = 3. The array a then becomes [2, 9, 11, 12]. Pick i = 3. The array a then becomes [3, 10, 12, 11], which is not sorted. It can be proven that 1 and 2 operations are the minimal numbers of operations in the first and second test cases, respectively.In the third case, the array is already not sorted, so we perform 0 operations.
421 141 8 10 1331 3 231 9 14
1 2 0 3
1 second
256 megabytes
['brute force', 'greedy', 'math', '*800']